Having problems understanding following simple algorithm

Question: public class Test1
{
    public static void main (String[]args)
    {
        int number = 0;
        for (int i = 0; i < 5; i++)
        {
            if (number != 0)
            {
                number = i * number;
            }
            else
            {
                number = i;
            }
        }
        System.out.println (number);
    }
}

I'm not quite sure how this algorithm works. My thought process is:

We set number to 0 by default.
In the for loop we are just saying, continue counting i till it's no longer smaller than 5.
We say that if number isn't 0, we update number by multiplying it with i. So in our case, i is 0,1,2,3 and 4.
Else we are saying the number is i and i is what we were counting.
Lastly, we print number.

Am I missing something? Am I wrong somewhere?
If I run this code why do I get 24 as output? I cannot understand how this simple program works.
Comment: You end up with `4!`. It might help to add `System.out.println(number);` in the loop.
Comment: Your thinking seems to be correct. How about imagining that you are the computer running this code, and think about what you would output?
Comment: the point is that 0 * `x` is equal to  0 for all integers `x`, hence if we would not initialize `number` to something else than `0`, the answer would always be `0`. That is what the `else` branch (i.e. `if (number == 0)`) does. I personally would have chosen another approach (initialize `number` with `1`, start the iteration at `i = 1`, since [0! is 1](https://www.wolframalpha.com/input/?i=0%21)).
Comment: @Goof If you feel your question has been answered, you may mark one of the answers as accepted (The green tick ✔ symbol near the voting options).
Comment: Poor title. Rewrite to summarize your specific technical issue.
Answer: Executing the algorithm step by step will help understanding it.
Let's start with the first line. As you said, this line just sets number to 0.
int number = 0;    | number: 0

I included the value of the variable on the right side after the bar.
Second step is to start with the loop. Before the loop starts, the counter variable i is set to zero.
int i = 0;    | number: 0, i: 0

As a second step we have to check if the loop criterion is fulfilled, so that the body of the loop will be executed.
The criterion of the loop is i < 5 and since the current value of i is 0 and 0 < 5, the body of the loop is executed:
if (number != 0) {
    number = i * number;
} else {
    number = i;
}

Since it is an if statement, we have to see if the if-condition is fulfilled. number is currently 0, so number != 0 is not true. This means we go to the else branch with is:
number = i;    | i = 0 -> number = 0

Since i is zero, number continues to be zero after this statement was executed.
This is the end of the first execution of the loop. Last thing the loop does before restarting is incrementing the counter:
i++;    | number = 0, i = 1

Now i < 5 is still true, so the loop body runs again.
We still have number = 0 therefore number != 0 is still false.
Note that i was updated to 1, but number was not until now. Now:
number = i;    | i = 1 -> number = 1

Now the loop increments the counter and starts anew:
i++;    | i = 2

Still i < 5, so the body of the loop is executed again.
For the first time number != 0 is true, because number = 1.
So now we execute:
number = i * number;    | i = 2 -> number = 2

number used to be 1, i is to, so i * number = 2
Again the loop body ends, the counter is incremented and the loop restarts, since 3 < 5:
i++;     | i = 3

Here again number != 0, so we execute
number = i * number;

which yields number = 6 since 2 * 3 = 6.
The same process continues one more time with i = 4.
Now number = 4 * 6 = 24.
We increment the counter
i++;    | i = 5, number = 24

Now i < 5 is no longer true, the loop exits and
System.out.println(number);

prints the current value of number, 24 to the screen.
Answer: public class Test
{
    public static void main (String[]args)
    {
        int number = 0;
        for (int i = 0; i < 5; i++)
        {
            if (number != 0)
            {
                number = i * number;//For i=2, 3, 4
            }
            else
            {
                number = i;//This is executed twice - for i=0 and i=1
            }
        }
        System.out.println (number);
    }
}

Let's understand this program.

Execution begins from the main() method.
A variable named number is defined and initialized to 0.
A loop control variable named i is defined. Its initial value is 0 and it is increased by 1 at the end of every iteration till it reaches 5. Note that i is never modified inside the loop body.
For i = 0, the condition number != 0 is false, the else block is executed. number = i. The value of number remains 0.
For i = 1, the condition number != 0 is false, the else block is executed. number = i. The value of number changes to 1.
For i = 2, the condition number != 0 is true, the if block is executed. number = i * number. The value of number changes to 2.
For i = 3, the condition number != 0 is true, the if block is executed. number = i * number. The value of number changes to 6.
For i = 4, the condition number != 0 is true, the if block is executed. number = i * number. The value of number changes to 24.
Since i = 5, the loop breaks. The value of number is printed.

This is how we end up getting 24 as the output.
Comment: I would suggest to write-up an answer completely before posting it.
Answer: Your thought process was good, but it wasn't exact or detailed enough because the meshing/merging of the sequence of the multiplication (of number) with the sequence of incrementing i is important.
Work it out on paper with a table, one column per variable, one line per instruction executed:
i      number

null   0     int number = 0; // i has not been initialized yet.
0      0     int i = 0;
0      0     number = i;  // it took the else branch
1      0     i++
1      1     number = i;
2      1     i++
2      2     number = i * number
3      2     i++
3      6     number = i * number
4      6     i++
4      24    number = i * number
5      24    i++
5      24    falls out of loop since i < 5 is now false


How to run logistic regression accurately

Question: I am interested in understanding the specific relationships between an dependent variable (low birthweight), which is binary and various independent variables (which are also binary). So far, the way I have been doing the logistic regression is to run the regression with low birthweight and all of the independent variables.
My question is: Is running the regression with all of the variables the same as running the regression with each independent variables one by one? I ran both of them (one by one, and all at once) and I received different coefficients. So which one is more accurate?
Comment: Welcome to CV. Since you're new here, you may want to take our [tour], which has information for new users. No, they are not the same. When you have multiple predictors, the coefficients are partial (I am sure you heard the expression: "holding all other variables constant"). Which one is more accurate? It depends on your aim. If you want to control the effect of some variables while estimating the effects of others' (which is most probably the case), you should include all these variables in the model.
Comment: I recommend reading this question (and answers) to get a better idea about control: https://stats.stackexchange.com/questions/17336/how-exactly-does-one-control-for-other-variables
Answer: (This is not specific to logistic regression; it is true of any kind of regression model.)
Both are presumably accurate.  But they give an accurate answer different questions, so it shouldn't be surprising that the answers differ.  In general, regression models do not estimate the direct association between a covariate and a response unless the units (e.g., patients) were randomly assigned and the levels of the covariate were independently manipulated (i.e., the data are drawn from a true experiment).  If the data are from a true experiment, the coefficient from the treatment variable should be (approximately) the same in both the simple regression model and the multiple regression model.
In any model, for any variable that was not independently manipulated and randomly assigned to the study units, the coefficient is an estimate of a marginal association.  The only question is which marginal association is being estimated.  There are potentially infinite margins to consider.  You need to decide which you care about and why.
For a clearer sense of the relevant issues, there are a few of my existing answers that may be helpful:

For a conceptual overview of 'marginal': Intuition behind the names 'partial' and 'marginal' correlations
The most directly relevant for your question: Is there a difference between 'controlling for' and 'ignoring' other variables in multiple regression?
For additional visuals that may help to clarify the ideas: Alternatives to three dimensional scatter plot


When calculating a meta-analytic prediction interval is it appropriate to report the back-transformed mean of that distribution?

Question: The Problem
I have been working on an epidemiological meta-analysis of prevalence values, measured as proportions but analyzed in logit-space. The conditions I study are quite rare (<5%) so all estimates are close to 0. Due to the presence of heterogeneity across samples, it is important that I report both the mean as well as the prediction interval for my estimates. I am using a Bayesian approach, which means that I have a logit-transformed posterior representing the mean of the latent "true" prevalence distribution as well as a posterior representing variability within this latent "true" prevalence distribution from which individual study estimates are derived. This corresponds to a standard random-effects model. To calculate a confidence interval around the mean, I back-transform the posterior for the mean value into probability space (e.g., using the plogis function in R) and then calculate a highest density interval on the back-transformed distribution. To calculate a prediction interval, I generate a "new" study for each sample within my joint-posterior distribution using the appropriate mean and variance estimates. I then back-transform those values and calculate a highest density interval. This works fine and generally agrees with other standard approaches (e.g., the metafor in R).
However, in doing so I realized that the mean of the back-transformed predictive distribution no longer matches the back-transformed mean that I had estimated and used to generate the predictive distribution. The cause is easy to determine – it is the difference between taking the mean of a distribution on the logit scale or on the probability scale. It is a simple result of the back-transform changing the shape of the distribution overall and can be demonstrated (in R for the sake of simplicity) as follows:
set.seed(12345)
logit_var = rnorm(1000, -3,1) # Sample from a variable in logit-space
plogis(mean(logit_var))       # Mean on the logit-scale produces .05
mean(plogis(logit_var))       # Mean on the probability scale produces .07

Note: For those interested, this problem is most pronounced for logit- or probit-transformed variables that are close to the lower (p = 0) or upper (p = 1) boundary and becomes less pronounced as the variable approaches p = .5.
Generally, I have only ever seen people report the former. Specifically, they report an estimate of the back-transformed mean, its confidence interval and then the back-transformed prediction interval without recognizing that the expected means do not match.
The Question

In a scenario similar to the one depicted above, is ever appropriate to report the mean of the prediction distribution in probability space either in lieu of or in combination with the more traditional mean estimate?
If so, how could one best conceptualize the difference between each mean with respect to their interpretation?
Answer: This is due to Jensen's inequality, that is, for a convex function $f()$, $$f(E(X)) \le E(f(X))$$ (and vice-versa for a concave function). For values below 0, plogis() is in fact convex and most values simulated here are below 0.
This is indeed often ignored in meta-analysis. The proper interpretation of the back-transformed value is that it is the median of the back-transformed distribution. To use your example:
set.seed(12345)
logit_var = rnorm(1000, -3,1)
plogis(median(logit_var))
median(plogis(logit_var))

Both yield the same value.
Comment: Another informative and impressively concise answer. Thanks, @Wolfgang!


AWS X-Ray not initializing a new segment

Question: I'm using OpenTelemetry with AWS X-Ray to trace E2E messaging between:
Producer (JVM) -> Kafka Broker -> Consumers (Multiple, Python-based)
Generated traces are then send to AWS OTEL Collector which forwards them to AWS X-Ray.
However when I see them from X-Ray consumer trace is displayed as a sub-segment of producer:

I'm expecting to see consumer as a separate segment.
I've also tried to use AWS X-Ray SDK in the consumer side to explicitly initialize a new segment as following:
val traceId = TraceIdData(String(record.headers().headers("X-Amzn-Trace-Id").first().value()))
logger.debug("Trace Id {}, Parent Id {}", traceId.root, traceId.parent)
AWSXRay.beginSegment("Simple Kafka Consumer", traceId.root, traceId.parent)
... some processing ...
AWSXRay.endSegment()

However this is still shown as a sub-segment in AWS X-Ray even though I'm beginning a new segment and specifying: trace_id and parent_id. I have confirmed that both attributes are not null and valid.
How can I generate a new segment in AWS X-Ray for this ongoing trace? Preferably, I'd like to do this using OpenTelemetry (agent/sdk/collector), but using AWS X-Ray SDK is also a possibility.
Answer: I had a chat with AWS X-Ray team and they helped me solve my issue.
The reason for this issue is that awsxray exporter only creates new segments for Spans when kind=SpanKind.SERVER.
I have implemented this (in Python) using OpenTelemetry SDK and explicitely declaring kind=SpanKind.SERVER when creating a new span
processing_span = self.tracer.start_span(self.service_name, context=current_context, kind=SpanKind.SERVER)

Which gives me my desired result of seeing multiple consumers in the Service Map

Unfortunately OpenTelemetry java instrumentation for Kafka on consumer side is automatically creating a new span where kind=CONSUMER which cannot be modified (as part of automatic instrumentation) so the only way to get my desired result is through manual instrumentation.


Checkbox e PHPMailer

Question: Olá, pessoal!
Não estou conseguindo enviar valores do checkbox através do PHPMailer. Alguém poderia me dar uma dica?
$precisa = implode(",", $_POST['precisa[]'] );

O QUE VOCÊ PRECISA?

                        <input type="checkbox" class="check" name="precisa[]" value="Site">Site
                        <input type="checkbox" class="check" name="precisa[]" value="App">App
                        <input type="checkbox" class="check" name="precisa[]" value="Logomarca">Logomarca

                        <input type="checkbox" class="check" name="precisa[]" value="Catálogo">Catálogo de produtos

                        <input type="submit" class="button" value="Enviar contato" />

Answer: Quando um campo do seu form é um array (o atributo name precisa de conchetes), ao receber ele no php não é necessário utilizar conchetes no nome.
Mude:
$precisa = implode(",", $_POST['precisa[]'] );

para:
$precisa = implode(",", $_POST['precisa'] );

Exemplo - phpfiddle
Comment: e  quando o checkbox tem names diferentes como poderia fazer?
Comment: @allanaraujo como assim?
Comment: esse é minha pergunta teria como responder ela ? http://pt.stackoverflow.com/questions/178790/como-enviar-checkbox-com-names-diferentes-para-o-mysql
Comment: tenho uma tela de pedido com um input  text e dois checkbox com names diferentes e outros dois input text para colocar a quantidades , e também com names diferentes para enviar eles para o mysql ,mas eu não sei como usar mais de um implode para inserir no banco de dados .

Checkbox e PHPMailer


alias hello='echo Hello' - why doesn't this work after a restart?

Question: All over the internet you see this commands
alias hello='echo Hello'

Yes, I know the above is a lame example, but it's beside the point. If I execute that, it works. But when I restart my computer, it is lost. Why? a bug with the alias command? Why would it only work until a restart is executed?
Thanks
Answer: You will need to write it into your ~/.bashrc like
echo "alias hello='echo hello'" >> ~/.bashrc

This appends the string to your .bashrc and will be read when you start a bash in xterm or even pure command line.
Comment: You are welcome. It will be remembered as long as your bash-session is valid. This is why there is `.bashrc` to make your bash "remember" after power-off ;)
Comment: @Nadine Yes, bash is not that important on OSX, as for example on Linux. Now you can spent these typed characters somewhere else :)
Comment: Excellent, thanks. But what is the point of the Alias command if it doesn't remember anything? By itself, it seems a dumb command :/
Comment: So is ~/.profile and ~/.bash_profile just used to store variables? and ~/.bashrc for aliases? Like currently in mine, I use the export VAR=Var_value command to remember a var.
Comment: Have a look at `~/.bashrc` using `less` or `cat`; there is usually some other stuff in there. You can put all `bash`-relevant stuff in there, like environment-variables or define scripts.
Comment: There's nothing in mine (using OSX, that might be why). http://stackoverflow.com/questions/415403/whats-the-difference-between-bashrc-bash-profile-and-environment told me though. Thanks for your answer, no more re-typing alias commands :)
Comment: this answer did not work any more in my MACBOOK AIR.


How to exponentiate the vector field $v$?

Question: i didn't succed to exponentiate these vector field
$$\boxed{v=\sqrt{x}\sqrt{y}\frac{\partial}{\partial x}-\sqrt{x}\sqrt{y}\frac{\partial}{\partial y}+2b\sqrt{x}\sqrt{y}u\frac{\partial}{\partial u}}$$
where $x,y,t$ are independents variables and $u$ is an dependant variable .
this vector field is one of the basis element of a Lie algebra of symmetry associated to a certain pde .the solution of the pde is of the form $u(x,y,t)$
Remark:
i succeded to exponentiate the vector field $$w=\sqrt{x}\sqrt{y}\frac{\partial}{\partial x}-\sqrt{x}\sqrt{y}\frac{\partial}{\partial y}$$
it gives $$\exp \left(\varepsilon w\right)(x,y, t, u)=(\tilde{x},\tilde{y},\tilde{t}, \tilde{u})=\left(\sqrt{x}\sqrt{y}\sin(\varepsilon)+(\frac{x-y}{2})\cos(\varepsilon)+(\frac{x+y}{2}),-\sqrt{x}\sqrt{y}\sin(\varepsilon)-(\frac{x-y}{2})\cos(\varepsilon)-(\frac{x+y}{2}),t,u\right) $$
where $exp : \mathfrak{g}\longrightarrow G$ and $\mathfrak{g}$ is the Lie algebra of $G$ .
to exponentiate a vector field of the form $\mathbf{v}=\displaystyle{\sum_{k=1}^{p}\xi_{k}(x,u)\frac{\partial}{\partial x_{k}}+\sum_{i=1}^{q}\phi_{i}(x,u)\frac{\partial}{\partial u_{i}}}$we solve the system of odes  $ \displaystyle{\frac{d\tilde{x_{i}}}{d\varepsilon}=\xi_{i}(\tilde{x_{i}})\,\,,\,\, \frac{d\tilde{u}}{d\varepsilon}=\phi(\tilde{x},\tilde{t},\tilde{y})}$ with initial conditions $\tilde{x_{i}}(0)=x_{i}$  , $\tilde{u}(0)=u$
Or we can just develop this Lie series for the flow, given by
$$
\exp (\varepsilon \mathbf{v}) \cdot x = x+\varepsilon \xi(x)+\frac{\varepsilon^2}{2} \mathbf{v}(\xi)(x)+\cdots=\sum_{k=0}^{\infty} \frac{\varepsilon^k}{k !} \mathbf{v}^k(x)
$$
where $\xi=\left(\xi^1, \ldots, \xi^m\right), \mathbf{v}(\xi)=\left(\mathbf{v}\left(\xi^1\right), \ldots, \mathbf{v}\left(\xi^m\right)\right)$,
I tried to develop the serie but it's getting more and more complicated from order 3 i guess
Thanks for the help !:)
Comment: What is the question exactly?
Comment: @TravisWillse what is the exponentiation of "v"?how to do it ?
Answer: For readability, denote the initial condition by
$$(x(0), y(0), t(0), u(0)) = (x_0, y_0, t_0, u_0),$$ so that
$$(x(\tau), y(\tau), t(\tau), u(\tau)) = \exp(\tau V)(x_0, y_0, t_0, u_0) .$$
Hint Since the $\partial_x$ and $\partial_y$ components of the vector field $V$ depend only on $X, Y$, we may as well first solve for the integral curves $(x(\tau), y(\tau))$ of the projection of $V$ to the $xy$-plane, namely, $W$---that is, solve
$$x' = \sqrt{x y}, \qquad y' = -\sqrt{x y}$$
---then lift the solution curve to $xytu$-space.
We can simplify our computation some by observing that $x' + y' = 0$, hence
$x + y = x_0 + y_0$, which reduces our system to a single, separable o.d.e. in $x(t)$:
$$x' = \sqrt{x (x_0 + y_0 - x)} .$$
As in the edited question statement, solving gives
\begin{align*}
x(\tau) &= \frac{1}{2}\left[x_0 + y_0 + 2 \sqrt{x_0 y_0} \sin \tau + (x_0 - y_0) \cos \tau\right] \\
y(\tau) &= \frac{1}{2}\left[x_0 + y_0 - 2 \sqrt{x_0 y_0} \sin \tau - (x_0 - y_0) \cos \tau\right] .
\end{align*}
To compute $u(\tau)$ efficiently, we can compare coefficients of the vector find and observe that
$$u' = 2 b u x'.$$

Integrating gives $$u(\tau) = u_0 \exp \left[2 b \left(x(\tau) - x_0\right)\right] = u_0 \exp \left[ b \left(2 \sqrt{x_0 y_0} \sin \tau + (x_0 - y_0) (\cos \tau - 1)\right) \right] .$$

Of course, since the vector field $V$ does not have a $\partial_t$-component, $t(\tau) = t_0$.
Comment: I've tweaked the answer to make the algebraic role of the initial conditions more transparent.
Comment: For any (admissible) time $\epsilon$, $\exp(\epsilon w)$ is a (possibly only local) diffeomorphism, not a vector field, and $\exp(0)$ is the identity map on the manifold. The property that you might have in mind is $\left.\frac{d}{d\epsilon} \exp(\epsilon w)\right\vert_{\epsilon = 0} = w$.
Comment: The result that I found in w is true no $exp(\epsilon w)(x,y,t,u)$ using Taylor formula instead of solving the system for ODEs ?  you used the notation $\phi$ and $\tau$  so I am little bit lost because I used them already in my work to define the vector field "the infinitesimal symmetry " associated to the pde $v=\xi(x,y,t,u)\frac{\partial}{\partial u}+\gamma(x,y,t,u)\frac{\partial}{\partial u}+\tau(x,y,t,u)\frac{\partial}{\partial u}+\phi(x,y,t,u)\frac{\partial}{\partial u}$  in the end I think you mean by $tau$ just $\epsilon$ using the notation that I introduced in the beginning
Comment: ,also to verify we need just to derive the flow with respect to $\epsilon$ then taking $\epsilon=0$ so we can find the vector field ,from the results that you found you mean that $$\exp(\epsilon w)(x,y,t,u)=\left(\frac{1}{2}(x+y).(1+\sin(\epsilon+c),\frac{1}{2}(x+y).(1-\sin(\epsilon+c),t,e^{-b}u\exp((x+y)b(1+\sin(\epsilon+c))\right)???????.$$.                                                                       with $x(0)=x$ and $y(0)=y$ also $u(0)=u$ and $\phi=c$((if we use my notations))
Comment: i made a mistake the vector field v that I defined in the first comment is $$v=\xi(x,y,t,u)\frac{\partial}{\partial x}+\gamma(x,y,t,u)\frac{\partial}{\partial y}+\tau(x,y,t,u)\frac{\partial}{\partial t}+\phi(x,y,t,u)\frac{\partial}{\partial u}$$
Comment: normally if we derive the flow $\exp(\epsilon w)$ that you found and taking $\epsilon=0$ we need to find the vector field w , which is not the case I think !!!??   I think we need to find some $\sqrt{x}\sqrt{y}$ somewhere in the solution that you found .
Comment: ah okay I see , now I understand more well done !Thanks
Comment: Cheers, I'm glad you found the answer helpful.
Comment: yes yes it's local , yes it's the exact property that I have in mind , I'am used to Olver's book notation that's why .


Custom thread started in Application_Start

Question: I have to deal with legacy ASP.NET application written in .NET Framework 1.1. When checking the application code I found interesting part. The application starts custom thread in Application_Start event handler (Global.asax). This thread must run whole life of the application.
Long time ago I read that this should be never used but I don't remember why. What are the problems related to such application design? Is it possible to start thread again when it crashes? Will the crash be logged somewhere automatically (event log)? Can ASP.NET runtime kill the thread for any reason?
At the moment I'm not interested in AppPool recycling. It restarts application, all sessions and creates new thread.
Comment: The only issue I can think of is that the thread will be terminated when the app pool recycles -- but then it will start again.  Clearly the thread code should be written robustly and not terminate due to unexpected exceptions.
Answer: The main problem is that the thread may be terminated at any time by ASP.NET. If the thread's running the whole time, there is presumably some work it should be doing, and getting terminated may not make your application happy the next time it starts up.
Modern solutions include using asynchronous pages and the built-in thread pool.
If you do choose to upgrade, remember that in .NET 1.1, threads throwing a top-level exception just exit; in .NET 2.0, threads throwing a top-level exception crash. If you upgrade, it would probably be better to make the leap to async pages rather than keeping a separate thread.
Comment: This is what I'm affraid of. I know ASP.NET 2.0 handles it threads in thread pool but I'm not sure how it works in ASP.NET 1.1. The thread is actually very important because it handles expired locks in in-memory pesimistic locking. One of the issues I have to solve is that locks are sometimes not released ...
Comment: Since the locking is in-memory, it should all be recycled along with the thread when the application restarts. The first thing to determine is if the thread is dying for some unexpected reason; wrap the whole thread procedure in a try/catch and log the error. Reproduce the problem and see what shows up in the log (if anything).
Comment: Yes that is what I'm planing to do. I'm just curious if this is a good practice and what are reasons to not to use it.
Comment: It's generally discouraged (modern approaches use async pages). In your *particular* situation, it sounds like it *might* be OK. I would prefer using something like [Session_OnEnd](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatemodule.end.aspx) rather than a separate thread.


Difference between "there exists at most one" and "there exists only one"

Question: What is the difference in proof of this type?
I know that for "there exists only one" existence
and uniqueness must be demonstrated but for
"there exists at most one" I don't understand very well.
Comment: "there exists only one"  means "there exists (exactly) one". Whereas "there exists at most one" means either "there exists (exactly) one" or "there exists (exactly) none". So the statement, "there exists at most one integer between $0.5$ and $0.6$" is True, whereas the statement, "there exists only one integer between $0.5$ and $0.6$" is False.
Comment: there could exist none; then "there exists at most one" would be true but "there exists only one" would not
Comment: @AdamRubinson That should be an answer.
Answer: "there exists only one"  means "there exists (exactly) one". Whereas "there exists at most one" means either "there exists (exactly) one" or "there exists (exactly) none". So the statement, "there exists at most one integer between $0.5$ and $0.6$" is True, whereas the statement, "there exists only one integer between $0.5$ and $0.6$" is False.


React can and will sometimes call your components multiple times?

Question: I read this article React Hook to Run Code After Render and came across this line:

React can and will sometimes call your components multiple times before actually rendering them to the screen, so you can't rely on "one call == one render".

What did he mean?
I wrote this code
function x() {
  console.log("x");
}

function y() {
  console.log("y");
  return "y";
}

function Silicon() {
  console.log("silicon");
  return

;
}
function useDarko() {
  const [count1, setCount1] = useState(0);
  console.log("useDarko");
  return [count1, setCount1];
}

export default function Test0022() {
  const [darko, setDarko] = useDarko();
  const [count1, setCount1] = useState(0);

  x();

  useEffect(() => {
    if (count1 !== 200)
      setTimeout(() => {
        setCount1((e) => ++e);
      }, 100);
  }, [count1]);

  return (
    <>
      <Silicon />
      {y()}
    </>
  );
}

I always see "804 console.log". It works as expected, one call == one render.
Comment: `I always see 804 console.log, it works as expected one call == one render.` Your example is too simple to see the behavior. They're talking about [concurrent mode](https://reactjs.org/docs/concurrent-mode-intro.html), where react may abort a render part way through to handle a more important update.
Comment: JULY 17, 2020 ? When the article came out, there was no parallel mode yet
Answer: For about four years, React has been working to implement a feature called "concurrent mode" (yes, it had been announced long before that article was released). It will be in version 18 of React, which is currently in a release-candidate state.
Concurrent mode allows React to abort a long-running render part way through in order to handle a more important update. This new approach has implications for lifecycle hooks and for the behavior of side effects, and as a result the React team has been training the community to start writing their code in a way that works with concurrent mode. For example, they deprecated several class component lifecycle hooks that would not be safe with the new approach.
And as the article mentions, one of the mental models we need to get used to is that a component may be called multiple times before it actually makes it on to the screen. Your component may get called, run all the way through, and then React realizes it needs to throw out that work and start over. These cases are rare, but to help you catch problems you can use strict mode. Among other things, it will deliberately double-render your components in development builds, to make it easier to spot bugs that only occur when these double-rendering cases occur.
Note that in React 17 this strict-mode double-render overwrites the console.log function so that it has no effect, and as a result it's difficult to see that it's happening.


Finding the minimal polynomial and its conjugates without a matrix

Question: Let $K=\mathbb Q\left(^3\sqrt{5}\right)$ and $\alpha=a+b\left(^3\sqrt{5}\right)+c\left(^3\sqrt{5}\right)^2$. How do I find the minimal polynomial $f_\alpha$ of $\alpha$ over $\mathbb Q$?
I am already aware of the method that involves using a matrix of $m_\alpha$, I want to be able to find the polynomial without use of matrices.
I have tried cubing $\alpha$ in an attempt to multiply out the cube root terms, however this gets messy quickly and creates as many terms in powers of $^3\sqrt{5}$ as it eliminates. Does the fact that the minimal polynomial of $^3\sqrt{5}$ over $\mathbb Q$ is $x^3-5$ help here since $\alpha \in K=\mathbb Q\left(^3\sqrt{5}\right)$?
The reason I want to find the minimal polynomial is to compute the Norm $N_{K/\mathbb Q}(\alpha)$ and the Trace $Tr_{K/\mathbb Q}(\alpha)$ from it, using its conjugates. Is there an easier way to do this (again, without using matrices)?
Answer: When you know the conjugates of the element in question, you can write out the Norm, Trace, and characteristic polynomial without resorting to matrices. For instance, in the case you mentioned, $\xi=a+b\lambda+c\lambda^2$, where $\lambda^3=5$, we have $\xi'=a+b\omega\lambda+c\omega^2\lambda^2$ and $\xi''=a+b\omega^2\lambda+c\omega\lambda^2$, for the conjugates of $\xi$. (Here, of course, $\omega$ is a primitive cube root of unity, so a root of the polynomial $X^2+X+1$.) Then the Trace is $\xi+\xi'+\xi''$, the Norm is $\xi\xi'\xi''$, and the characteristic equation is $(X-\xi)(X-\xi')(X-\xi'')$. All of these are computable by hand, and the exercise of working slowly and checking each step is very valuable.
Comment: Could you possibly start me off with the process of expanding these? I don't understand how I would represent $\omega$ in the expansions. Would I have to substitute in that $\omega=e^{\frac{2\pi i}{3}}$?
Comment: It's high-school algebra. DON'T use $\omega=\exp(2\pi i/3)$. Simply use the identities $\lambda^3=5$ and $\omega^2+\omega+1=0$. Every time you get an $\omega^2$, replace it by $-\omega-1$, and every time you get a $\lambda^3$, replace it by $5$.
Answer: $(x-a)^3=5(b+c\sqrt[3]5)=5b^3+15bc(x-a)+25c^3$. The key is noticing the reappearance of $(x-a)$ in the expansion of the cube. Unfortunately, this doesn't seem to work so well for fifth roots.


Probability and Variance--Bernoulli, Binomial, Negative Binomial

Question: I am taking a course in probability and I have trouble computing the variance of a random variable.
There are 2 cases we saw in class that I would like to understand:
First I will state the definition of variance of expected value:

If $X$ is a random variable who's values are in $\mathbb{N}$, then $$\mathbb{E}(X) = \Sigma_{n≥0}\mathbb{P} (X > n)$$
If $X$ is a random variable and $\mathbb{E}(X)$ exists, then the variance of X is: $$Var(X) = \mathbb{E}\Big((X-\mathbb{E}(X))^2\Big)$$

Now here are the examples I'd like to understand:

binomial distribution: If $X$ is a random variable that follows a binomial distribution of parametres $n$ and $p$ then we can write $X = X_1+X_2+X_3+...+X_n$ where the $X_i$'s are bernoulli variables of parametre $p$. Then $$Var(X) = np(1-p)$$
negative binomial distribution (Pascal law): If X is a random variable that follows a pascal law of parameters $r$ and $p$ the $X+r= X_1+...+X_r$ where $X_i$'s are independant geometric variables. Then $$Var(X)=Var(X+r) = r\dfrac{1-p}{p^2}$$

I don't understand how one comes up with such results using the defintion of variance.
Comment: 1 ) By using $\text{Var}(X_1+\cdots+X_n)=\text{Var}X_1+\cdots+\text{Var}X_n$. This is not true in general, but it is true if the $X_i$ are uncorrelated (wich is the case if they are independent). Secondly $Var{X_i}=p(1-p)$ for every $i$ (wich is easy to find) so the summation gives $np(1-p)$. Sortlike on 2) with the addition that $\text{Var}(X+r)=\text{Var}(X)$ if $r$ is a constant.
Comment: A useful formula for variance is $V (X)=E (X^2)-(E (X))^2$
Comment: Showing that the above formula is equivalent to the definition of variance is a good exercise, as well.
Answer: If $X$ is Bernoulli, with $P(\text{Success}) = p,$ then $E(X) = (0)(1-p) + 1p = p.$ Because $0^2 = 0$ and $1^2 = 1$, we also have $E(X^2) = p.$
From @Dave's hint $Var(X) = p - p^2 = p(1-p).$
Binomial: Then for $Y \sim Binom(n, p),$ we have
$$E(Y) = E\left(\sum_{i=1}^n X_i \right) = \sum_{i=1}^n E(X_i) = np.$$
Also, direct proofs, with
$$E(Y) = \sum_{i=0}^n i{n \choose i}p^i(1-p)^{n-i} = \sum_{i=1}^n i{n \choose i}p^i(1-p)^{n-i} = \cdots = np(1) = np,$$ (with a change in index $j = i-1$)
are given in many elementary texts.
Similarly, using independence,
$$Var(Y) = Var\left(\sum_{i=1}^n X_i \right) = \sum_{i=1}^n Var(X_i) = np(1-p).$$
Again here, proofs using about the same method as above to find $E(Y(Y-1)),$ and then
$Var(Y)$ from that and $E(Y),$ are given in many elementary texts.
For the negative binomial, it seems intuitive that the avarage waiting time
for the $r$th Success should be $r/p.$ A rigorous derivation of the expectation
of a negative binomial random variable often uses some sort of trick involving
differentiation of a sum. Probably the easiest route is to find the moment generating
function and differentiate it to get the mean and variance.
Note: You may find
some useful details on Wikipedia 'negative binomial distribution'. But if you
are looking at various references on negative binomial, be aware that
some parameterizations count trials until the $r$th Success and others count
only the Failures before the $r$th Success.


Custom Options Value of Views Grouped Filter?

Question: How do I change the select values of a Views groups filter?
By default, they are 1,2,3...
Default
<select>
<option value="all">all</option>
<option value="1">Group A</option>
<option value="2">Group B</option>
</select>

Desired Result
<select>
<option value="all">all</option>
<option value="mycustomname">Group A</option>
<option value="mycustomname2">Group B</option>
</select>

Answer: I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).
To do this in the most efficient/easy way possible, you should create your own filter handler.
For a really simple example:
<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

Then, in your module's .info file, add the file containing this class (in this example, 'custom_handler_filter_countries.inc') to the .info file's files array (files[] = includes/custom_handler_filter_countries.inc).
To make your particular view use this views handler instead of the default handler, you should be able to change the handler in hook_views_pre_view(), I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.
This discussion may also have a possible solution:
Custom Options Value of Views Grouped Filter?
Comment: Thanks @jonathan. I was guessing there would be a UI based way to do this via Contextual fields but this may be the best option
Comment: I have not heard of any UI based way to do this, so as far as I know I would do it like this.


Acessar leitor biométrico no lado cliente - ASP.NET MVC - WEBFORMS

Question: Galera,
Desenvolvi uma aplicação ASP.NET MVC, utilizando uma página webforms, no qual é chamado dentro de uma página do MVC. Porque somente a partir dela eu consegui carregar as DLLs do SDK, para mandar requisições para um leitor biométrico, realizar a captura e fazer autenticação da biometria.
A página Webforms é chamada a partir de iFrame dentro de determinadas views, que em determinados momentos passo a identificação do usuário que precisa ser identificado em uma comparação 1x1, ou não passo nenhum parâmetro quando é 1xN.
Certo, quando eu disponibilizei a aplicação para acesso externo, e conectei o leitor biométrico no computador que fez acesso, a aplicação não busca o leitor no lado cliente, e sim no lado servidor. E eu preciso que ela busque no lado cliente. Alguma sugestão de como eu posso fazer isso?
Agradeço desde já, qualquer colaboração.
Comment: Você acabou de descobrir que aplicação Web só serve para algumas. Algumas funciona aos trancos e barrancos, embora quem desenvolveu acha que está ótimo, outras não tem como funcionar. A solução é não usar uma aplicação web.
Comment: Qual o modelo do leitor biométrico? Qual SDK ele usa?
Comment: @CiganoMorrisonMendez o leitor biométrico é fultronic fs80h, e utilizo o sdk megamatcher da neurotech.
Answer:
Alguma sugestão de como eu posso fazer isso?

Sim, desenvolvendo uma extensão para o Google Chrome, ou para o Firefox, ou para outros navegadores que desejar.
O problema é que o seu leitor biométrico fica no cliente e sua aplicação é Web, portanto fica no servidor. Não são a mesma máquina.
Assim sendo, você terás que desenvolver uma comunicação entre seu plugin e sua aplicação desenvolvida em ASP.NET MVC. Um bom caminho pode ser este artigo.
Answer: Olá,
Sua aplicação é web e o leitor biométrico está na máquina cliente, logo, você precisa comunicar com o hardware através do browser, ou seja, de suas páginas web. O problema é que, por questões de segurança os browsers impedem que uma página acesse os recursos locais do computador, a não ser que o usuário instale um plugin.
O ruim do plugin é que você vai precisar desenvolver um para cada browser, a saída para isso é desenvolver uma pequena aplicação WindowsService que publica um serviço REST, seu WindowsService irá fazer toda a comunicação com o hardware, assim como você já fez no server, e irá publicar um serviço REST que será consumido pela sua página através do Javascript.
A requisição do seu javascript será sempre para LOCALHOST, pois a requisição sempre será para o serviço na máquina local onde o leitor estará instalado.
Uma dica, você vai precisar configurar o CORS para fazer a requisição para LOCALHOST.
Já fiz desta forma e funciona muito bem!


Dynamically construct Select clause of a Linq query

Question: I'm using a LINQ to Entities, and I have a couple of queries for which I want to be able to specify the Select clause at runtime.
I figured I'd have to do it by building an Expression and adding it to the IQueryable, but I'm not sure how to do this. Can anybody give me a hint?
Comment: can you give a specific example of what you want to achieve? There might be another way of doing things.
Answer: I am not sure you could do what you want with expressions.  The select clause specifies the type of the object in the IQueryable collection, that has to be defined at compile time.  There is something called Dynamic Linq that can do what you want.
Comment: I am aware of dynamic Linq, but that's not really what I'm looking for. You make a good point about the generic type of the IQueryable, though, which makes me think the scenario I have in mind might not be possible. Thanks!
Answer: Something like this:
<code>IQueryable<cerberus_Ticket> matches = db.cerberus_Tickets;

 if (this.AgentIdField.Text.Trim().Length > 0)
 {
     matches = matches.Where(a => a.AgentId == criteria.AgentId);
 }

  if (this.TicketIdField.Text.Trim().Length > 0)
 {
     matches = matches.Where(a => a.TicketId.Contains(criteria.TicketId));
 }

var output = matches.ToList();
</code>


Get Assembly version on windows phone 7

Question: In my c# applications I usually get the version (to show the customer) using the following code:
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version

This does not work in Windows Phone 7 (it hangs the emulator, and phone crashing is a no-no for MS).
So, how do I get the version of the executing on a windows phone 7 device??
[Update] as noted in the comments below, calling GetName() in a wp7 app seems to be the problem.
Comment: I would definitely report this to Microsoft. Your code is correct, and the hanging is definitely caused by a bug either in the .NET in the emulator, or in the whole .NET for WP7!!
Answer: Try this:
    private static string GetVersionNumber()
    {
        var asm = Assembly.GetExecutingAssembly();
        var parts = asm.FullName.Split(',');
        return parts[1].Split('=')[1];
    }

Comment: @Sam this is working for me in apps in the Marketplace. I had to parse the version number out of the FullName as `Version` wasn't working for me. What error are you getting?
Comment: Well, this is essentially the same I wrote above, and it hangs the phone just like my version does.
Comment: Aah, I checked back, I did not use FullName, but GetName instead. And whenever I have a call to GetName in my app, the emulator, device and debugger just hang - not when the GetName is hit, but when the app is started!
Comment: So even when GetName is not called, just its existence in the code is enough to crash the program. #Strange
Comment: A post on it : http://www.jonathanantoine.com/2011/11/07/wp7-how-to-get-the-version-number-of-my-application/
Comment: `GetName()` is marked as `SecurityCritical` while `FullName` isn't.
Answer: Does parsing it out of
Assembly.GetExecutingAssembly().FullName
work for you?
example output: SomeApp, Version=22.214.171.124, Culture=neutral, PublicKeyToken=null
edit: don't need to go through ManifestModule
Comment: I don't even get that far: it seems use of reflection kills the phone.
Comment: Testing on Samsung Taylor prototype device           System.Diagnostics.Debug.WriteLine(Assembly.GetExecutingAssembly().FullName);... no probs.
Comment: Yeah, you were right, I mistakenly used GetName instead of FullName.
Answer: First, I think it's more apt to use the assembly's file version info for conveying the application version to the user. See http://techblog.ranjanbanerji.com/post/2008/06/26/Net-Assembly-Vs-File-Versions.aspx
Second, what about doing this:
using System;
using System.Linq;
using System.Reflection;

public static class AssemblyExtensions
{
    public static Version GetFileVersion(this Assembly assembly)
    {
        var versionString = assembly.GetCustomAttributes(false)
            .OfType<AssemblyFileVersionAttribute>()
            .First()
            .Version;

        return Version.Parse(versionString);
    }
}

Comment: Problem there is that it returns the particular string set in AssemblyInfo.cs, which means if you wildcard revision and build, you get something like "1.2.*" instead of "22.214.171.124"
Comment: According to MSDN (http://msdn.microsoft.com/en-us/library/system.reflection.assemblyfileversionattribute.assemblyfileversionattribute.aspx) wildcards are not supported for AssemblyFileVersionAttribute, and doing so will emit a compiler warning because it's meaningless in this context. Use of wildcards for the version is only applicable to AssemblyVersion (http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx)
Answer:  public static string GetVersion()
    {
        return Regex.Match(Assembly.GetExecutingAssembly().FullName, @"Version=(?<version>[\d\.]*)").Groups["version"].Value;
    }

is fairly clean as well.

Get Assembly version on windows phone 7


How do I alter webform values before submission?

Question: I am trying to add some values to a hidden field in my webform before submission. Is there any hooks to access webform submission in Drupal 8? I tried How do I modify a webform submission field right before it is saved? without luck.
Answer: The answer linked is mostly right, just a couple of updates to get it working. In a custom .module add:
<code>use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#validate'][] = 'MODULENAME_form_validate';
  }
}

function MODULENAME_form_validate($form, FormStateInterface $form_state) {
  $form_state->setValue('hidden_id', 'Value for Hidden field');
}
</code>
Answer: To alter webform values before submission -
In my code, I am changing the timestamp from "Y-m-d HH:MM:SS" to "Y-m-d" format and changing it before saving to DB. Also, i am creating a custom module name as "webform_presave"
<code>/**
 * Implements hook_ENTITY_TYPE_presave().
 */

function webform_presave_webform_submission_presave(\Drupal\webform\Entity\WebformSubmission $submission) {
  $submissionCreated = $submission->getCreatedTime();
  $submissionCreatedChnaged = format_date($submissionCreated, 'custom_date');
  $a = strptime($submissionCreatedChnaged, '%Y-%m-%d');
  $timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
  $submission->setCreatedTime($timestamp);
}
</code>


How can you show the results from substituting $x=a\cos{\theta}$ and $x=a\sin{\theta}$ are the same when finding $\int{\frac{16}{\sqrt{9-x^2}}}$?

Question: How can you show the results from substituting $x=a\cos{\theta}$ and $x=a\sin{\theta}$ are the same when finding $\int{\frac{16}{\sqrt{9-x^2}}}$?
I am learning trig substitution right now. I know from seeing this problem I should substitute x for $a\sin{\theta}$. After working this out:
$$\int{\frac{16}{\sqrt{9-x^2}}}$$
$$x=3\sin{\theta}$$
$$dx=3\cos{\theta}d\theta$$
$$=\int{\frac{16}{\sqrt{9-x^2}}}=\int{\frac{48\cos{\theta}d\theta}{\sqrt{9-9\sin^2}{\theta}}}$$
$$=\int{\frac{48\cos{\theta}d\theta}{3\sqrt{1-\sin^2}{\theta}}}$$$$=16\int{\frac{\cos{\theta}d\theta}{\sqrt{\cos^2}{\theta}}}$$
$$=16\int{\frac{\cos{\theta}d\theta}{\cos{\theta}}}=16\int{d\theta}$$
$$=16\theta=16\sin^{-1}\left({\frac{x}{3}}\right)+C_1$$
However, substituting $x=a\cos{\theta}$ yields a different result.
$$\int{\frac{16}{\sqrt{9-x^2}}}$$
$$x=3\cos{\theta}$$
$$dx=-3\sin{\theta}d\theta$$
$$=\int{\frac{16}{\sqrt{9-x^2}}}=\int{\frac{-48\sin{\theta}d\theta}{\sqrt{9-9\cos^2}{\theta}}}$$
$$=\int{\frac{-48\sin{\theta}d\theta}{3\sqrt{1-\cos^2}{\theta}}}$$$$=-16\int{\frac{\sin{\theta}d\theta}{\sqrt{\sin^2}{\theta}}}$$
$$=-16\int{\frac{\sin{\theta}d\theta}{\sin{\theta}}}=-16\int{d\theta}$$
$$=-16\theta=-16\cos^{-1}\left({\frac{x}{3}}\right)+C_2$$
$$\implies\quad{-16\cos^{-1}\left({\frac{x}{3}}\right)}+C_2={16\sin^{-1}\left({\frac{x}{3}}\right)}+C_1$$
Unless I did something incorrectly or there is something that prohibits different types of substitutions, how can this be true? I have tried to think it over how $-\cos^{-1}{x}$ can equal  $\sin^{-1}{x}$.
I thought about it being a negative angle, perhaps making the opposite leg of the triangle negative. This however leads to a contradiction that says $-\cos^{-1}{x}=\sin^{-1}{x}$ but $\cos^{-1}{x}\neq-\sin^{-1}{x}$.

Any thoughts, answers, or corrections are appreciated.
Comment: There comes "+ arbitrary constant" in both of these indefinite integrals...
Comment: Thank you! I forgot.
Comment: Ok , when you changed it to "Something+C1=Something+C2" , you got "Something=Something+(C2-C1)=Something+C3" & this is entirely true in your Case. There is no contradiction : $\sin^{-1}(x)$ & $-\cos^{-1}(x)$ are same except for a Constant. Plot these two to check that Constant !
Comment: The 2 "C" Values are not the same ! The last line is "Something=Something+C" where this C is not the same ! Try using "C1" & "C2" & "C3" to make that rigorous !
Comment: I'll do that. Thanks.
Answer: If you do a simpler example of $\int \frac{1}{\sqrt{1 - x^2}} dx$, you will get $\sin^{-1}(x) + C$ and $-\cos^{-1}(x) + C$ respectively. If you draw the diagrams, you will see that $\sin^{-1}(x) + \cos^{-1}(x) = \frac{\pi}{2}$, since it's the two angles that's not a right angle. Therefore, you see that $\sin^{-1}(x)$ and $-\cos^{-1}(x)$ differ by a constant $\frac{\pi}{2}$.
Comment: $+C$ doesn't mean a specific constant, it means *a constant*. It's like $\int f'(x) dx = f(x) + C_1 = \left(f(x) + 1\right) + C_2$, they look different but they're the same.
Answer: Quite simply $$-(\cos^{-1}x)'=(\sin^{-1}x)'$$ so they differ by a constant.   And that constant is easily determined to be $$\pi/2$$.
Everything checks out in terms of symmetry on the unit circle.
Just remember that when you compute an indefinite integral, the answer only holds up to a constant.


Como gravar stream RTSP

Question: Estou utilizando o package node-rtsp-stream mais Websocket para fazer a transmissão de minha IP-Câmera, e a visualização ocorre bem, agora eu gostaria de saber como faço para gravar essa transmissão e não faço muita ideia de como fazer isso.
index.js no Server(NodeJS)

const Stream = require('node-rtsp-stream'),
  stream = new Stream({
    name: 'Camera-Garagem',
    streamUrl: `rtsp://${meu_ip}:1030/user=${user}&password=${pass}&channel=1&stream=0.sdp?`,
    wsPort: 5000
  })

index.html no Cliente

  <canvas id="videoCanvas"></canvas>

Answer: Podes dar uma olhada a esta biblioteca
https://www.npmjs.com/package/node-rtsp-recorder
const Recorder = require('node-rtsp-recorder').Recorder

var rec = new Recorder({
    url: 'rtsp://${meu_ip}:1030/user=${user}&password=${pass}&channel=1&stream=0.sdp?',
    timeLimit: 60, // time in seconds for each segmented video file
    folder: '/node-rtsp-recorder/videos',
    name: 'cam1',
})
// Starts Recording
rec.startRecording();

setTimeout(() => {
    console.log('Stopping Recording')
    rec.stopRecording()
    rec = null
}, 300000)

Permite fazer o record da gravação e armazenar no disco do servidor, depois podes implementar algum tipo de lógica/rota para fazer o download desse video se necessário.
Comment: os arquivos gravados estão com 0 bytes, tem alguma ideia do que poder ser?

Como gravar stream RTSP


How to implement cross-validation on my time series (leave one out and k-fold)?

Question: I am a software developer. I do not have a formal training in time series. I have started reading Chatfield and Brockwell. I have enough wisdom to reach out to professional statisticians in your field for insightful commentary so I can avoid doing something wrong.
Problem
How can I apply leave one out and k-fold cross validation on my time series?
Details
Technically, I have 10 independent time series that is comprised of 10 participants. For each series, we have participant id, timestamp (data taken in one second interval), heart rate, GIS location, GIS zone(The zone is a GIS polygon of special interest for fatigue), and a binary variable indicating if the user is fatigued or not. My goal is to do cross validation so I can build a model to detect the fatigue.
My data is something like as follows:

participant id, timestamp, heartrate, lat, long, zone, fatigue
1, 10:30, 130, 70, 38, 39, 1, 0
1, 10:30, 130, 72, 38, 39, 1, 0
...
10, 10:30, 138, 72, 38,39, 1, 0
...

where I can tell which time series I am in based on the participant.
Attempts
Let me divide my time series by participant id. I have [1,2,3,4,5,6,8,9,10]. Where 1 here represents all the data I have for participant 1. Thus, my time series 1.  We can consider each series independent from each other. So I can do something like:
Leave one out

1 Train: [2,3,4,5,6,7,8,9,10] Test: 1
2 Train: [1,3,4,5,6,7,8,9] Test: 2
3 Train: [1,2,3,4,5,6,7,9,10] Test: [3]
4 Train: [1,2,3,4,5,6,7,8,9,10] Test: [4]
5 Train: [1,2,3,4,6,7,8,9,10] Test: [5]
6 Train: [1,2,3,4,5,7,8,9,10] Test: [6]
7 Train: [1,2,3,4,5,6,8,9,10] Test: [7]
8  Train: [1,2,3,4,5,6,7,9,10] Test: [8]
9  Train: [1,2,3,4,5,6,7,8,10] Test: [9]
10 Train: [1,2,3,4,5,6,7,8,9] Test: [10]

2 - fold validation
I really have confused myself. I was thinking about this approach, but I was told by a colleague that I had it all wrong because I was doing a "within time series approach" and I needed to do a "across time series" approach.
I also checked out this which I think is again for the "within" time series approach because you are taking 1 time series and dividing it in m parts. I have 10 independent time series that supposedly observe the same/similar effect and are independent from each other. I am trying to detect
Answer: The biggest concern with this kind of thing would be having a data point from participant a at time x in the test set, and another point from participant a at time y in the training set, where y > x. In other words, predicting the past based on the future. In this case, even just having participant a's data split between the train and test set could be problematic, since the model might overfit to some peculiarities of that participant.
Your leave-one-out scheme avoids both these problems though.
I'm assuming that your goal is to predict the presence of fatigue at a particular instant in time, without any context about what came before, in which case what you've described is great.
If the problem you're trying to solve involves seeing a sequence of observations and identifying the onset of fatigue, then the "forward chaining" procedure described in this answer is appropriate. You would still want to do the leave-one-out thing you described. But when evaluating performance on the last participant, you would feed your predictor each data point in order, and record its ability to predict the next one, given what it's seen so far.
Comment: How about k-fold cross validation as well? Consider  could have train: [1,2,3,4,5,6,7,8] and test: [9, 10]. Then train: [1,2,3,4,5,6,9,10] test: [7,8] and so on.
Comment: I think the forward chaining procedure is interesting, but I don't know what it buys me over k-fold like I sorta outlined above? Excited to hear your reply. I will be sure to mark it as the answer once we hash out the last few points. Thanks!
Comment: There's very little difference between k-fold and leave-one-out in this case. The k-fold scheme you describe just results in fewer evaluations at the cost of having slightly less data to train on each time. Forward-chaining is only useful if the scenario you're trying to model involves prediction over sequences, rather than one-shot predictions. It's something to be used *with* leave-one-out/k-fold, not instead of.