How to show $\nabla (\Delta A) -\Delta(\nabla A)=\nabla Rm *A+Rm*\nabla A$?

Question: $A$ is a tensor field, $\nabla A(X,...)=(\nabla_XA)(...)$. Besides, $R$ is curvature operator and
$$
Rm(X,Y,Z,W)= \langle R(X,Y)Z,W\rangle
$$
and
$$
\Delta A = g^{ij}(\nabla _{X_i}\nabla _{X_j}A - \nabla_{\nabla_{X_i}X_j}A)
$$
For any tensor field $A,B$, $A*B$ is linear combination of tensor fields, each formed by starting with the tensor field $A\otimes B$, using metric to switch the type of components or to contractions.  Then, how to show
$$
\nabla (\Delta A) -\Delta(\nabla A)=\nabla Rm *A+Rm*\nabla A
~~~?
 \tag{1}
$$
PS: I know how to show $R(\cdot,\cdot)A=A*Rm$, for example $A=A_{ij}dx^i\otimes dx^j$, I can get
$$
[R(\cdot,\cdot)A]_{abcd}=-g^{lk}R_{abck}A_{ld}-g^{lk}R_{abdk}A_{cl}
$$
therefore, there is
$$
R(\cdot,\cdot)A=A*Rm
$$
But I fail to show (1).
Comment: After I posted my answer, I noticed that your question was essentially a duplicate of [this one](https://math.stackexchange.com/q/2471877/2002). Anthony's [answer](https://math.stackexchange.com/a/2471943/2002) is equivalent to what I've tried to express, but, perhaps, is more accessible for you.
Answer: Firstly, let me restate the definition of the notation $A*B$ as a linear combination of various compatible contractions of $A \otimes B$. This notation is very permissive and absorbing, e.g.:
$$
- A*B \equiv A*B \tag{1}
$$
and
$$
A*B + A*B \equiv A*B \tag{2}
$$
where by $\equiv$ here I mean "can be renamed as".
Secondly, for the sake of easier calculations, let me switch to the abstract index notation (see e.g. R.Wald, General relativity, for an accessible introduction).
Thus, the Ricci calculus is presented by the following identities.
$$
2 \nabla_{[a} \nabla_{b]} X^c = R_{a b}{}^{c}{}_{d} X^d \tag{3}
$$
and
$$
2 \nabla_{[a} \nabla_{b]} \omega_d = - R_{a b}{}^{c}{}_{d} \omega_c \tag{4}
$$
You may be wondering about the sign conventions for the curvature, but for our needs it does not really matter, as we are going to rewrite the above equations as
$$
\nabla_a \nabla_b X^c = \nabla_b \nabla_a X^c + (R*X)_{a b}{}^c \tag{5}
$$
and
$$
\nabla_a \nabla_b \omega_c = \nabla_b \nabla_a \omega_c + (R*\omega)_{a b c} \tag{6}
$$
Since any tensor $A$ is can be presented as a linear combination of simple terms, that is tensor products of some amount of vectors and covectors, by the virtue of the linearity of the covariant derivative and using the Leibniz rule, we can see that
$$
\nabla_a \nabla_b A = \nabla_b \nabla_a A + (R*A)_{a b} \tag{7}
$$
for any tensor $A$ (this is the Ricci identities in disguise).
Now, down to the calculation.
$$
(\nabla \Delta A)_a - (\Delta \nabla A)_a  = \nabla_a \Delta A - \Delta \nabla_a A = \\
\nabla_a (g^{b c} \nabla_b \nabla_c A) - g^{b c} \nabla_b \nabla_c \nabla_a A = \\
g^{b c} ( \nabla_a \nabla_b \nabla_c A - \nabla_b \nabla_c \nabla_a A ) \equiv \\
g^{b c} ( \nabla_b \nabla_a \nabla_c A + (R*\nabla A)_{b a c} - \nabla_b \nabla_c \nabla_a A ) \equiv \\
g^{b c} ( \nabla_b \nabla_a \nabla_c A + (R*\nabla A)_{b a c} - \nabla_b ( \nabla_a \nabla_c A + (R*A)_{a c}) ) \equiv \\
g^{b c} ( \nabla_b \nabla_a \nabla_c A + (R*\nabla A)_{b a c} - \nabla_b \nabla_a \nabla_c A + (\nabla R*A)_{b a c} + (R * \nabla A)_{b a c} ) \equiv \\
(\nabla R*A)_a + (R*\nabla A)_a
$$
Let me emphasize, that the $*$-notation should be understood as
$$
\nabla \Delta A - \Delta \nabla A \equiv \nabla R*A + R*\nabla A
$$
Comment: @Malkoun yes, this is one of the quirks that the abstract index notation has inherited from the classical Ricci calculus (in order to keep the equations look the same). Using the parentheses is a pedantic way to mitigate this confusion. Reading Wald's book really helps. You could also compare my answer with the [Antony's one](https://math.stackexchange.com/a/2471943/2002).
Comment: Nice, but I think you forgot an $R*A$ term in the 2nd line, because the Laplacian also has a first order term, and the difference between the first order term coming from the derivative of the Laplacian of $A$, and that coming from the Laplacian of the derivative of $A$, should give you an $R*A$ term (unless I am mistaken somewhere).
Comment: @Malkoun Thank you. I think that I just expand the definition there. This is the so-called "connection Laplacian", which in the abstract index notation is defined as $\Delta A := g^{a b} (\nabla \nabla A)_{a b}$, where the indices, coming from tensor $A$ are suppressed (not shown).
For a discussion of the second covariant derivative $\nabla \nabla A = \nabla^2 A$ please check [this Wikipedia article](https://en.wikipedia.org/wiki/Second_covariant_derivative).
Comment: @Malkoun Also, I have to mention that it is an unfortunate tradition to write $\nabla_a \nabla_b A$ instead of $(\nabla \nabla A)_{a b}$, but I assume that it is well known.  Actually, this is why I use the parentheses to clarify the meaning of the indices, like in the first line of the calculation.
Comment: I see. I must admit it is a somewhat confusing abuse of notation. Is this part of the abstract index notation? I should know these things better (but I haven't computed with curvature in a while).
Comment: Thank you so much. It makes sense to me now. I should have spent more time in the past understanding the conventions for second order covariant derivatives :). But I guess it is better late than never. Thanks!
Comment: Shouldn't $\nabla_a \nabla_b A=(\nabla \nabla A)_{ba} $ to mimic $\nabla_a\nabla_b A=A_{|b|a}$?
Comment: @ContraKinta sorry, I don't understand what you mean. You can check out how I use the notation from [this answer](https://math.stackexchange.com/a/1269095/2002), for instance.
Comment: I'm just curious about the order of the slots. I interpret your notation $(\nabla \nabla A)_{ab}$ as $A$ is a tensor with an unknown number of suppressed indices. Each time you form a covariant derivative you add another lowered index. First you form the covariant derivative (adding the slot $A_{|b}$) and then you form the covariant derivative adding slot $A_{|b|a}$. For a torsion free connection we can express the lack of symmetry of the tensor $A^j_{|b|a}$ in the indices $b$ and $a$ as $(\nabla_a\nabla_b-\nabla_b\nabla_a)A=A^j_{|b|a}-A^j_{|a|b}=K_{l\,\,ba}^{\,\,j}A^l$
Comment: @ContraKinta Ah, I see. Thank you for the details. Simply put, you are using a different set of conventions for the index placement. There is a variety of traditions in differential geometry and mathematical physics in this regard. I stick to the convention that $\nabla_a \nabla_b A_{\dots}$ is a "traditional" notation for the second covariant derivative $(\nabla \nabla A)_{a b \dots}$, where $\dots$ denote the suppressed indices of $A$. Beware that there is much more sloppiness in this notation. In my thesis I made a humble attempt to clarify this a little further.
Comment: Thanks your help.  Does $\nabla_a \nabla_b X^c$ mean $\nabla_a \nabla_b X^c dx^a \otimes dx^b \otimes \partial_c$ ?
Comment: @lanse7pty no, the abstract index notation works differently. It means the tensor (field) $\nabla \nabla X$, where the indices show which tensor space (or bundle) it is taken from. In contrast, the notation $\nabla_a \nabla_b X^c dx^a \otimes dx^b \otimes \partial_c$ assumes a choice of coordinates, and $\nabla_a \nabla_b X^c$ denotes the components of this tensor in the chosen coordinates.
Please take a look at [this answer](https://math.stackexchange.com/a/1269095/2002).
Comment: @lanse7pty This is why I write $\nabla_a \nabla_b X^c = (\nabla \nabla X)_{a b}{}^{c}$ interchangeably, and even can drop (suppress) the indices completely, when the space is clear from the context.
Comment: I have read your other answer before I ask question.  But I misunderstood you.  Besides, I use to the definition $R(X,Y)Z = \nabla _Y\nabla _X Z - \nabla_X \nabla _Y Z$.  And only from this point , I can get (5).  I don't know how to from the abstract index notation to get (5). Could you talk it ? Thanks.
Comment: @lanse7pty I will try to give you more explanations in my answer to your [another related question](https://math.stackexchange.com/q/4259943/2002) which I am planning to write.
Comment: I like you. Thanks very much.
Comment: I have get (5) from the traditional notation, namely,  $R(X,Y)Z = \nabla _Y\nabla _X Z - \nabla_X \nabla _Y Z$.  And I think I understand abstract index notation by reading it in Wiki. But I can't get its advantage. In contrast, the trace and Einstein summation are confused in my view. Besides, I think an important thing for using abstract index notation is that the order of abstract indices is fixed. Thanks again.
Comment: @lanse7pty The [Riemann curvature operator](https://en.wikipedia.org/wiki/Curvature_of_Riemannian_manifolds) is a tensor, defined as $R(X,Y)Z = \nabla _Y\nabla _X Z - \nabla_X \nabla _Y Z - \nabla_{[ X, Y]} Z$. Your formula is valid only for coordinate vector fields. Because it is a tensor (field), we can write it as $R_{a b}{}^{c}{}_{d}$ where the indices only *indicate* the space, this field is a section of. This is why they are called "abstract" in this case. The trace and the Einstein summation appear (in disguise) as contraction, e.g. $\omega_a X^a$ means $\omega(X)$.
Comment: @lanse7pty There are advantages and disadvantages in using the abstract index notation, as any other notation, in general. We make choices and trade offs. For me, using abstract indices, saves a lot of space and gives a lot of freedom for being less careful, but still being correct. You just need to grasp their value. Also, Anthony has already given an [answer](https://math.stackexchange.com/a/2471943/2002) in a more traditional way.


Question: Can I conduct likelihood ratio test with robust linear regression?

Question: I'm using robust linear regression in R (the rlm function from MASS package that uses the Huber M estimator by default). I'm wondering if I can conduct a likelihood-ratio test after running the nested and full model. I wanted to test if c1+c2+c3 combined improves the fit of the model. Can anyone answer from a statistical perspective? Here are the example code:
mod_nest=rlm(y~x,data=dat,maxit=200)
mod_full=rlm(y~x+c1+c2+c3,data=dat,maxit=200)
lrtest(mod_nest,mod_full)

Comment: I am not sure what form of robust regression the rlm function uses.  The likelihood ratio test assumes a form of a model which is a function of certain parameters.  Robust regression does not make such assumptions. It attempts to fit a model that avoids the normality assumption.
Comment: rlm uses the M-estimation by default, does this violate the assumption of the likelihood ratio test? Thank you~
Comment: Given that some function names occur in more than one package, can you explicitly say which package the function `rlm` you're using is in? Do you mean the one in `MASS`? Further, your code isn't  reproducible (since we don't have your x and y) -- a [small reproducible example](http://stackoverflow.com/a/5965451/330679) might be useful for potential answerers to illustrate their answers.
Comment: Yes! It's the one in MASS.
Comment: That information would be a good thing to edit into your question. If you're stuck for a small reproducible example you might be able to organize one from one of the built in data sets in R or in MASS
Answer: You can use a likelihood ratio test when the model is fitted by maximum likelihood (indeed, you need the likelihood under the null and alternative).
In the cases where the estimator you use does correspond to ML for some distributional assumption, under that same assumption you could generally get a likelihood ratio test.
In the case of M-estimators, it depends on the M-estimator. For example, a Huber M-estimator corresponds to ML for a particular distribution (one with a normal center and exponential tails) but the Hampel 3-part redescending M-estimator doesn't.
Note that this would assume either a known scale or a consistent estimator of it (which I think by applying Slutsky's theorem would then leave us still with the usual asymptotics for the LR test).
Even in cases where you use an estimator which wouldn't correspond to an ML estimator there are often tests that should have fairly good properties. In many cases, one could choose a permutation test based on some robust estimator, for example. In cases where you're testing all the regression coefficients at once, that should yield a distribution-free test. In the cases where you're only testing some of them, I think you would have an approximate test (you don't get exchangeability of residuals under the null -- except perhaps asymptotically, if your estimator is consistent). Alternatively, in many cases a parameter estimate might be shown to be asymptotically normal and so give a large sample test.
There's also the possibility that you might use a bootstrap test in large samples; I think that should work pretty well with the Huber psi function.

Note that even when a likelihood ratio test is possible, I'm not at all sure that rlm will return a (log-)likelihood (or something from which you can easily compute it) -- you might have to evaluate the (log-)likelihood yourself. I haven't checked that it doesn't though.
Comment: +1 for a good answer.  It seems the OP is unaware of which psi function he is using.   Your other points are well taken but doesn't fit in with the OPs constraints.  Still it is worth including.


Monotonicity described by barrier function

Question:
Let $f : [a,b] \to \mathbb R$ be a continuous function such that for all $c\in [a,b]$, there is a continuous function $f_c : [a,b] \to \mathbb R$ so that
  $$\begin{cases} f_c(c) = f(c), \\ f_c(x) \ge f(x) &\text{for all } x\in [a,b], \\ f'_c(c) \ge 0.\end{cases}$$
  show that $f$ is then non-decreasing. That is $f(y)\ge f(x)$ if $y\ge x$.

If the last condition is changed to $>0$, then it is easy to check that using the continuity of $f$ and some open/close argument. However when one only have $\ge 0$, that $f_c$ might not be nondecreasing locally at $c$.
Any ideas/thoughts/hints are appreciated.
Answer: Suppose by contradiction that $f$ is not non-decreasing, so there exist two points $x,y \in [a,b]$ such that $x<y$ and $f(x)>f(y)$. Now take
$$c=\sup \{ z \in (x,y) : f(z)> f(y) \}$$
Clearly $f(c)=f(y)$. Now, we have that for every $\epsilon>0$ there exists $z\in (c,c-\epsilon)$ such that $f(z)>f(c).$ Recalling that $f_c'(c)\ge0 $, by definition of derivative, we can choose an $\epsilon_1>0$ so that $f_c(c-h)\le f_c(c)$ for every $h\le \epsilon_1$. We know from before that there exists $z \in (c,c-\epsilon_1)$ such that $f(z)>f(c)$. Hence,
$$f(z)>f(c)=f_c(c)\ge f_c(z)$$
 a contradiction.
Comment: Actually I do not assume that $f$ is differentiable.
Comment: You are right, but this just makes the proof a bit longer, i'll fix it now.
Comment: @JohnMa it should be correct now.
Comment: Actually $f_c(c) \ge 0$ alone does not imply that $f_c(c) \ge f_c(c-h)$ for all $h$ small. $f(x) = x^2 \sin(1/x)$ at $x=0$ is a counterexample.
Comment: You're again right, I'm missing a step to complete the proof.


Viewpager with Youtube Player API

Question: I have used ViewPager. And In some of the items, I have used Youtube Player Fragment.
I used PageTranformers from this Android Dev Page
public class DepthPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.75f;

    public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            view.setTranslationX(0);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // (0,1]
            // Fade the page out.
            view.setAlpha(1 - position);

            // Counteract the default slide transition
            view.setTranslationX(pageWidth * -position);

            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

The problem is,
If I used DepthPageTranformer,
when I move to that page(which has youtube fragment) , I am getting warning

W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to
  unauthorized overlay on top of player. The YouTubePlayerView is
  obscured by android.widget.RelativeLayout{28896be5 V.E..... ........
  39420,0-39960,850}. YouTubePlayerView is completely covered, with the
  distance in px between each edge of the obscuring view and the
  YouTubePlayerView being: left: 0, top: 0, right: 0, bottom: 510..

But it works if I didn't use any transformer or with ZoomPageTranformer.
I debugged the code with custom ViewPager to check which view is
android.widget.RelativeLayout{28896be5 V.E..... ........ 39420,0-39960,850}
It is the previous page of the page which has Youtube Player Fragment .
I tried all the solutions like,

removing padding and margins
setting background as black
setting all the view's visibility  which overlaps as View.GONE

Everything works fine if I don't use DepthPageTranformer.
EDIT
As we know, Viewpager's OFFSCREEN_PAGES=1 by default. So the next and previous page will be in cache. Consider, If player view is in 5th page, If I move to 7th page and move back to 5th page , then video is playing. It clearly says that the "previous page of video page overlays" . Is there any way to refresh this page or remove previous page from OFFSCREEN_PAGES LIST.
Can anyone help me?
Comment: I don't think inflating different layout is the problem. Now it's become harder to debug without seeing how it's covered. Some options you can do for now: Change the `RelativeLayout` background color, disable any alpha setting so you can see where it is after the transformation. Use `Android Studio` Tools>Layout Inspector or `Stetho` to inspect your layout and see how the views are positioned.
Comment: it looks like the animation coveres YouTube player with some other view, which is not allowed by the YouTube player. So basically you can't use this animation
Comment: @VladyslavMatviienko I accept your point, But I am trying to make app like "inshorts" , in that app , they have used DepthPageTranformer. And it works fine. That's why I am thinking that, there will be a solution for it
Comment: It will be easier if you share the code in `DepthPageTranformer` and anything related so we can see how you translate, show/hide the pages
Comment: @TamHuynh please check , I edited the post
Comment: @JyotiJK I try your `Transformer` on my ViewPager with `YouTubePlayerView` on each item and it works fine. Each video can be played without being covered. I doubt that the `RecyclerView` mentioned in the error is not the previous item in `ViewPager`. Try to add id to some of the `RecyclerView`, the error usually show the view's id too
Comment: @TamHuynh I am not using recyclerview. Just **Viewpager without fragments**. And I am using videoview in some of the pages
Comment: My bad, I mean `RelativeLayout` instead of `RecyclerView`. The `RelativeLayout` that mentioned in the Youtube error message said it cover your view. Try to put `android:id` in some of `RelativeLayout` in the app to see if its id shown up in the error message
Comment: @TamHuynh thanks let me check it
Comment: @TamHuynh I checked, It is the previous page relative layout id. I am inflating different layouts based on the type in `instantiateItem()` . is Inflating different layout  a problem???? But it works fine without the tranformer
Answer: Just implement this interface YouTubePlayer.OnFullscreenListener Activity or Fragment. It overrides below method,
override fun onFullscreen(isFullScreen: Boolean) {
    if (isFullScreen)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
    else
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
}

Why is this happening?
When playing youtube videos using YouTubePlayerFragment or YouTubePlayerView, we need to hide the Status Bar because of no more views will not be added above YouTubePlayerFragment or YouTubePlayerView.
I had also this issue and found a solution.
Just try this one.

Viewpager with Youtube Player API


laravel latest post sort by category

Question: i have a model setup in Eloquent of a many to many relationship of Pages and Articles. My users have the ability to order these articles per page.
So my question is, can i order the relationship with sync...
<code> $page->articles()->sync($specificOrderOfArticleIds)
</code>
And it sync the relationships in the order of that passed array.
so when i query the page
<code>  $page->articles() // in specified order
</code>
It's in the specified order.
Maybe i'm missing something obvious here?
Answer: In order to do that, you'll need some kind of column in the pivot table that defines an order. For example, an "order" column on the pivot table could be given a value using:
<code>$page->articles()->sync([1 => ["order" => 1], 42 => ["order" => 6]]);
</code>
Then on the read, you can pass a closure into your query to specify the order be by this column.
<code>$page = Page::whereId($id)->with(['articles' => function($query) {
    $query->orderBy('pivot.order', 'asc');
}])->get();
</code>
The "pivot" keyword is used in relationship queries to point to the middle table.
However, you can use the closure ability shown above to order by anything you like, not just the pivot table. Depending on how you define the order, you may not even need the new pivot table column.

laravel latest post sort by category


Confidence interval that starts with 0

Question: I have a confidence interval that starts with 0 (0, 0.8) at the 95% interval. would this be considered significant?
Comment: What do you think and why?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: It is important to define your null and alternative hypotheses. For instance, if the null hypothesis is that the parameter equals a billion, that is a different story than if the null hypothesis is that the parameter equals $0.2$. // However, people often sling around this terminology with it implied that the null hypothesis is that the parameter equals zero. If that is the case, what is your concern, that the lower endpoint is exactly equal to zero?
Comment: If suppose you tossed a biased coin $4$ times and saw tails every time, your 95% confidence interval for the probability $p$ of heads might be $[0,0.75]$ using the "rule of three".  That is not a significant result if your null hypothesis is $H_0:p=0.5$ and even less so with $H_0:p=0$ but it is significant for $H_0:p=0.9$
Answer: The confidence interval starts only with a rounded value of zero. Here's how to get a more precise value using an example of a regression coefficient with a label 'a':
MODEL:
y on x (a);
MODEL CONSTRAINT:
new(a_big);
a_big = a*10000;
OUTPUT: cinterval;
Now the output for the parameter a_big will have a CI that is 10,000 times as big as the original 'a' parameter. This CI will not start at zero most likely... if it does then just multiply 'a' by 1,000,000 :-)
Comment: Many CI's beginning with 0 do so because the underlying numeric procedure produced a negative value, but the parameter has been restricted to be non-negative.  There's no rounding issue then.  For more precision simply print the original result more precisely: there's no need for any additional calculation.

Confidence interval that starts with 0


Chi square statistic and contingency coefficients

Question: I need some advice on explaining $\chi^2$ as a contingency measure from a pedagogical perspective.
I usually introduce the individual terms in the $\chi^2$ sum as scaled deviations from independence; my argument claims that $d_{ij} = (n_{ij} - E_{ij})^2$ is an absolute measure but we want relative measures that are independent of the units so we should divide by $E_{ij}$.  However, the natural question raised is why we do not divide by $E_{ij}^2$ which would truly normalize the counts in the numerator.
In addition, it is difficult to find good, intuitive explanations for the final form of the contingency coefficient which is $\sqrt{\chi^2/(\chi^2 + N)}$
Comment: You're dealing with counts -- which are already dimensionless. The purpose of dividing by $E_{ij}$ is to correct for the variance.
Answer: There are two standard accounts of $\chi^2$ as applied to a multinomial distribution, both of which show why the denominator should not be squared:

After expanding the logarithm through second order and doing some algebra, the likelihood ratio statistic for the multinomial distribution, $-2\log(l) = 2\sum_{i=1}^k n_i \log(n_i / e_i)$, equals $\chi^2(1 + O(n^{-1/2}))$, so at least asymptotically, $\chi^2$ gives a likelihood ratio test.  (I have replaced the double indexing by a single index, without any loss of generality.)
Fisher showed that the multinomial distribution arises as the conditional distribution of  $k$ independent Poisson variates of intensities $e_{i}$, conditioned on their sum, $n$.  Because the variances are $e_{i}$, the standardized values $(n_i - e_i)/\sqrt{e_i}$ are asymptotically Normal for large $n$, whence $\chi^2$ approaches the sum of squares of $k$ independent Normals, subject to the single condition $n_1 + \cdots + n_k=n$, giving it $k-1$ degrees of freedom.

Both arguments clearly show the sense in which $\chi^2$ is valid only asymptotically.
Accounts of both these points of view are found in chapter 30 of Stuart & Ord, Kendall's Advanced Theory of Statistics, Fifth Edition (1987).
I do not know the historical answer to the second question--the contingency coefficient $C$ goes back to Pearson over 100 years ago--but clearly $C$ is an analog of an absolute correlation coefficient, computed as the root of (residual variance / total variance).  Indeed,
$$\chi^2 + n = \sum\frac{(n_i-e_i)^2 + e_i^2}{e_i} = \sum\frac{n_i^2}{e_i},$$
which looks exactly like an inverse variance-weighted total sum of squares.  In effect, $n$ is the variance "explained" by the fit and $\chi^2$ is the residual variance.  Note that $\chi^2$ small implies the fit is good with $C \approx 0$, corresponding to almost no association in a contingency table, while $\chi^2$ large implies the fit is terrible, corresponding to almost perfect association with $C \approx 1$.
Comment: Comments about how to improve this reply would be appreciated.
Answer: I don't know what is "more true" or "less true" form of normalization. Any normalization that makes a particular sense will do. The quantity $(n_{ij}-E_{ij})^2/E_{ij}$ is called squared standardized residual in a cell, and overall Chi-square of a table is the sum of those across all cells. Chi-square can be viewed therefore as the weighted euclidean distance (weight$=1/E_{ij}$) between observed and expected frequencies [this notion of chi-square as the distance is realized in correspondence analysis].
Also, standardized residual follows Poisson distribution, and  with large $E_{ij}$ approaches normal distribution. This opens the possibility to infer whether the residual in a cell is significantly large.
Standardized residual is not the only way to normalize residual in a cell. Adjusted residual is another useful form.
Answer: An intuitive explanation for why
$$
d_{ij}=(n_{ij}−E_{ij})^2/E_{ij}^2
$$
would not be a good test statistic is to notice that it doesn't scale with the size of the sample:  Suppose we increase our sample by 10 fold.  Then if the null-hypothesis is false, we should be much more likely to reject -- that is, the test statistic $d_{ij}$ should be much larger.  Yet if we multiply $n_{ij}$ and $E_{ij}$ by 10 (to get an idea of the scale of the new $d_{ij}$), we see that the value of $d_{ij}$ doesn't change.
To summarize, even though $d_{ij}$ is a very fine and intuitive measure of the difference between two probability distributions, it doesn't reflect anything about how confident we are that the sample distribution is different from the null hypothesis.
Answer: About the contingency coefficient, I want to take the opportunity to leave a remark.
Consider the "theoretical chi-square statistic"
$$
v= \sum_{i,j}\frac{(p_{i,j}-p_ip_j)^2}{p_ip_j}
$$
and the theoretical contigency coefficient
$$
C_0 = \sqrt{\frac{v}{v+n}}.
$$
It is called the effect size in power calculations. As far as I know, there is no general and precise definition of the effect size.
However, considering $C_0$ as the effect size yields something similar to the power of $F$-tests in linear models, which are exact (non-asymptotic) likelihood ratio tests up to an elementary transformation.
Indeed, denoting by $E$ the effect size for such a test (for example $E=\mu/\sigma$ in the case of a simple Gaussian ${\cal N}(\mu, \sigma^2)$ sample and $H_0\colon\{\mu=0\}$), the test statistic under $H_1$ is a non-central $F$-distribution with non-centrality parameter $\boxed{\lambda=nE^2}$. In this situation we do not perform an asymptotic test because it is possible to get the exact law of the test statistic $F$. Asymptotically,  $F \approx df_1\times\chi^2$ where $\chi^2$ is the test statistic of the asymptotic likelihood-ratio test. If we used the asymptotic likelihood ratio instead of the exact $F$-test, we would get a non-central Chi-square under $H_1$ instead of a non-central $F$ distribution : $F_{df_1,df_2}(\lambda) \approx \frac{1}{df_1}\chi^2_{df_1}(\lambda)$ when $df_2$ is large.
Similarly, in the context of contingency tables, when $n$ is large, the $\chi^2$ test statistic under $H_1$ is approximated by a non-central $\chi^2$ distribution with non-centrality parameter $\boxed{\lambda=n C_0^2}$, as we can check by this example of power calculation:
<code>C0 <- 0.3 # theoretical effect size
n <- 100 # total count
alpha <- 0.05 # type I error
#--- Power calculcation with the pwr package ---#
library(pwr); pwr.chisq.test(C0, N=n, df=1, sig.level=alpha)
##
##      Chi squared power calculation
##
##               w = 0.3
##               N = 100
##              df = 1
##       sig.level = 0.05
##           power = 0.8508388

#--- Direct power calculation ---#
threshold <- qchisq(1-alpha, df = 1) # the critical value of the test statistic
lambda <- n*C0^2 # non-centrality parameter
1 - pchisq(threshold, df = 1, ncp = lambda) # we get the same result
## [1] 0.8508388
</code>
Thus each of these examples ($F$-tests in Gaussian linear models and $\chi^2$ tests for contingency tables) asymptotically give a likelihood ratio test (see @whuber's answer about the Pearson $\chi^2$), and their test statistic under $H_1$ is approximated, for large $n$, by a non-central $\chi^2$ distribution with non-centrality parameter $\boxed{\lambda=n\times\text{effect size}^2}$.


Understanding SVN error : Reintegrate can only be used if

Question: Doing a SVN merge from pre_prod branche to b1 branche I get following error:
D:\Web\projet\branches>svn merge svn://10.10.10.10/projet/branches/pre_prod b1
svn: E195016: Reintegrate can only be used if revisions 239 through 259 were previously
merged from svn://10.10.10.10/projet/branches/b1 to
the reintegrate source, but this is not the case:
  branches/pre_prod
    Missing ranges: /branches/pre_prod:241,245
  branches/pre_prod/src/Type
    Missing ranges: /branches/pre_prod/src/Type:245

I want to try this answer from SO.
But I've a difference with his case, his error says:
branches/bronze_services/occl
    Missing ranges: /trunk/occl:650-693

Which are two different branches, whereas my error says me to merge pre_prod branches with itself. How is it possible?
Moreover my error message says to merge missing revisions from svn://10.10.10.10/projet/branches/b1.
I don't understand it, what should I merge and from where?
Answer: Ok actually I just need to re-use the initial command which throws the error, and add manually the revision missing as says in the error message:
The following command throws an error:
svn merge svn://10.10.10.10/projet/branches/pre_prod b1
svn: E195016: Reintegrate can only be used if revisions 239 through 259 were previously [...]

So just replay the merge as following:
svn merge -r 239:259 svn://10.10.10.10/projet/branches/pre_prod b1

Comment: You got lucky (or you had to resolve conflicts); the second merge is not the same as the first merge and is not the solution.  If you read the error message more carefully you would have seen that it actually asked you to merge r239:259 from b1 to pre_prod, not the other way around.
Comment: Interesting. This worked for me, unlike all others solutions.
Answer: I've managed to work around the same error message by:

Making a fresh check-out of trunk: svn co ${SVN_URL}/trunk
Merging the branch from the repository into the fresh check-out: cd trunk && svn merge ${SVN_URL}/branches/the_branch

You should of course commit the merged check-out.


React Native Expo Managed App doesn't launch/start on iOS simulator

Question: I've been having hard times with my old Windows laptop while developing React Native apps so I moved to MacOS laptop. I installed Android Studio and Xcode (including Xcode command line tools). Then I initialized a blank expo managed project. I started both on Android Emulator and iOS simulator. Android one worked out with an ádb´ error (or maybe warning). But on the other hand, iOS simulator did nothing. There's no Expo Go app installed on iOS device, so it can not launch my app using it. I don't get any error or warning related to this problem, so I can't trace the problem.

I have tried deleting global expo folder located at ´~/.expo/´, I also tried to give 777 (all permissions) on that folder to my current user.
I tried uninstalling and reinstalling expo package globally.
I made sure I have selected Xcode command line tools on ´Xcode -> Preferences -> Locations -> Xcode 13.2.1 (13C100)´
I tried to launch different iOS devices like (iPhone 6, 8, 13, iPod etc.)
I tried clearing cache and starting expo with ´sudo npm start --clear-cache´

I have been trying to solve this for at least 2 hours tried everything possibly related to my problem but none of them did work. There's one thing I don't understand though. Even though I used different iOS device simulators the Expo Metro Bundler showed this ´› Opening exp://10.42.33.15:19000 on iPhone 8´ output. I have tried iPhone 13, iPhone 6, iPod etc. but this was the same output for different devices. Here's some screenshot related to probem:
Comment: 1st time you have to agreee "installing Expo Go" in console by pressing Y when asked :)
Comment: @Engazan Well, I can't really say but I don't remember I've asked to install Expo Go on console. Can I playback to that moment and answer "yes" if possible? :D
Comment: i. sure y can but idk how, maybe try opening NEW simulator for example iPhone 12 and try run it there
Comment: @Engazan Unfortunately I have tried creating new simulator at least 3 times but none worked out.
Comment: @Engazan I found out what was cousing me so much yet little trouble. You can check out my answer to my own question. Thanks!
Answer: https://www.youtube.com/watch?v=dvuZn6gX_Q4
This tutorial video on YouTube helped me solve my problems. I think I was missing a few things:

I haven't granted required privacy permissions on my Mac for Xcode, Android Studio and VS Code. Open System Preferences > Security & Privacy > Go Privacy Tab > Give Full Disk Access to Xcode, VS Code, Android Studio, Terminal and Watchman (Watchman is not required, but I have also installed it for solving a problem before)
You should to launch both your Android and iOS simulators before starting your expo application. Simply go to Android Studio and launch your device. To launch iOS device use bash and type open -a simulator.
If you don't have Expo Go app installed on your iOS simulator then you should first install it before starting your expo app. To install it use expo client:install:ios command.
Start your app by using expo start command. Type i and a or click on Run on iOS simulator and Run on Android device/emulator buttons to launch your app on devices.

NOTE: If you app gets stuck at New update available, downloading... stage then you can start your expo app with cleaned cache using expo start -c command. It was helpful for me.
NOTE 2: You may need to use sudo command on some of the commands I've mentioned, I'm not sure which ones are required or not.
Answer: I fixed similar issue by hard restarting simulator
Top menu -> Device -> Erase All Content And Settings...
Answer: I run into the same issue every time when I tried to set it up on a new laptop.
Its fixed after the installation of xCode cli.
Take a look at this - https://docs.expo.dev/workflow/ios-simulator/
Answer: You can now install the Expo Go client on the simulator via:
npx expo client:install:[ios|android]
https://docs.expo.dev/archive/expo-cli/
Answer: I tried the above answers without success and after some research I noticed that MacBooks with M1/M2 (if you are concerned) are not yet compatible with Expo Go. So I installed Rosetta and that solved the problem, Expo Go on iOS simulator works now.
To install Rosetta (which is not an application), you must launch  a software for intel chip on your Mac (vlc for example) and a popup will ask you if you want to install Rosetta.
Comment: You can also run `softwareupdate --install-rosetta` in terminal to install Rosetta.


The limit: $\lim_{x\rightarrow0}\frac{1-\cos2x}{\sin3x\cdot\ln(1+\sin4x)}$

Question: $$\lim_{x\rightarrow0}\frac{1-\cos2x}{\sin3x\cdot\ln(1+\sin4x)}$$
My steps
$\lim_{x\rightarrow0}\frac{1-\cos2x}{\sin3x\cdot\ln(1+\sin4x)} = \lim_{x\rightarrow0}\frac{1-\cos2x}{2x}\cdot2x\cdot\frac{3x}{\sin3x}\cdot\frac{1}{3x}\cdot\frac{1}{\ln(1+\sin4x)}\cdot\frac{4x\sin4x}{4x\sin4x}\\= \lim_{x\rightarrow0}\frac{2x}{3x\cdot4x}\cdot\frac{1-\cos2x}{2x}\cdot\frac{3x}{\sin3x}\cdot\frac{4x}{\sin4x}\cdot\frac{\sin4x}{\ln(1+\sin4x)} = \lim_{x\rightarrow0}\frac{2}{12x}$
I'm so close to the right answer $\frac{1}{6}$.
What did I do wrong?
Edit 1: So apparently, $\lim_{x\rightarrow0}\frac{1-\cos2x}{2x} = 0 \not=1$ and so the limit would be $\lim_{x\rightarrow0}\frac{2x}{3x\cdot4x}\cdot\frac{1-\cos2x}{2x}\cdot\frac{3x}{\sin3x}\cdot\frac{4x}{\sin4x}\cdot\frac{\sin4x}{\ln(1+\sin4x)} = 0\cdot\frac{2}{12\cdot0}$
And so now the limit is $[\frac{0}{0}]$. I'm not sure how to fix this.
Comment: Actually, you could do it by rearranging the term with $\cos$ and the term with $\frac{2x}{3x\cdot4x}$ to $2\cdot\frac{1-\cos(2x)}{(2x)^2}$ which can be shown to be $2\cdot\frac{1}{2}$ without L'Hospital (see this link http://www.enotes.com/homework-help/calculate-limit-1-cosx-x-2-231157 ). Then the limits should all be $1$ & you'll be left with $\frac{1}{6}$
Comment: I managed to get $\frac{1}{6}$ by using L'Hospital twice then substituting $x=0$. The terms get quite big and messy but it works.
Comment: Yeah, but I haven't learnt L'Hopitals rule yet :/
Comment: I don't really understand your reasoning though. I'll agree that you can cancel the $\frac{3x}{\sin(3x)}$ terms but how have you taken out the term with $\frac{2x}{3x\cdot4x}$ & the term with the log?
Comment: $\lim_{x\rightarrow0}\frac{\ln(1+x)}{x} = 1$. And the thing is, $\frac{2x}{3x\cdot4x}$ **is** my problem right now.
Comment: See that's where the problem is: that part is $\frac{1}{6x}$ which would be undefined. I think you might have to take a different approach but I can't suggest what.
Answer: We have $1-\cos(2x)\sim \frac{(2x)^2}{2}=2x^2$ as $x\to 0$; $\sin(3x)\sim 3x$, $\ln(1+\sin(4x))\sim \sin(4x)\sim 4x$ as $x\to 0$. Thus
$$\mathop {\lim }\limits_{x \to 0} \frac{{1 - \cos \left( {2x} \right)}}{{\sin \left( {3x} \right).\ln \left( {1 + \sin \left( {4x} \right)} \right)}} = \mathop {\lim }\limits_{x \to 0} \frac{{2{x^2}}}{{3x.4x}} = \frac{1}{6}.$$
Comment: No. $1-cos(2x)\sim \frac{(2x)^2}{2}$ as $x\to 0$ means that $\mathop {\lim }\limits_{x \to 0} \frac{{1 - \cos \left( {2x} \right)}}{{\frac{{{{\left( {2x} \right)}^2}}}{2}}} = 1$. In fact $\mathop {\lim }\limits_{x \to 0} \frac{{1 - \cos \left( {2x} \right)}}
{{\frac{{{{\left( {2x} \right)}^2}}}
{2}}} = \mathop {\lim }\limits_{x \to 0} \frac{{2{{\sin }^2}x}}
{{2{x^2}}} = \mathop {\lim }\limits_{x \to 0} \frac{{{{\sin }^2}x}}
{{{x^2}}} = \mathop {\lim }\limits_{x \to 0} \frac{{\sin x}}
{x}.\mathop {\lim }\limits_{x \to 0} \frac{{\sin x}}
{x} = 1.$
Comment: Definition: $f(x)\sim g(x)$ as $x\to a$ if $\mathop {\lim }\limits_{x \to a} \frac{{f\left( x \right)}}{{g\left( x \right)}} = 1$.
Comment: I'm not sure I understand how $\lim_{x\rightarrow0}(1-\cos2x) = \frac{(2x)^2}{2}$, or the others for that matter. I appreciate the work, but I'm trying to use the common limits: http://en.wikipedia.org/wiki/List_of_limits


When people say that viola and double bass are too small for their range, what does it mean?

Question: I'll stick to the viola example, though I've heard similar arguments made about the double bass.
I've seen the following reasoning: the viola is tuned one fifth lower than the violin. A perfect fifth means a frequency ratio of 3:2, which means a wavelength ratio of 2:3, which (if we assume that the violin has the perfect size for its pitch) means what the viola should be one and a half times as big as the violin. Normally, it's smaller than that, which means it's too small.
My problem with this explanation is that the ranges of the two instruments mostly overlap. If the viola's body is too small to play e.g. the D3 note properly, then surely the violin, whose body is even smaller, must be even less suitable for producing the same pitch.
What am I missing?
Comment: I think at least the strings need consideration. If they are heavier, the pitch should be lower without the length changing. That why the four strings are different in pitch despite being the same length. I imagine viola strings are heavier than violin.
Comment: Playability concerns also limit the size of the bass: you can't get much bigger and still finger and bow. Well, not without some [very inventive measures](https://en.wikipedia.org/wiki/Octobass).
Comment: The problem with your problem is that the actual problem is about the part where the ranges *don't* overlap. It is about the inadequacy of the scale to the lowest notes produced by the viola, which the violin doesn't produce at all.
Comment: @user207421 your answer implies that the C string behaves differently than the other strings. I haven't ever tried it myself, but after a quick search, I've found many posts that confirm that, e.g. at https://www.reddit.com/r/Viola/comments/ysh727/ the top comment says: "the C string has a very different bow response than anything on the violin, and is different from the upper three strings of the viola".
Answer: A violin doesn't resonate to just ONE particular pitch.   The wood and the air in the body cavity certainly have resonant peaks, but there are lots of them, and a good violin is designed so that any one resonance doesn't predominate.
We COULD design a viola 1.5 times as big as a violin, but it probably wouldn't fit under the chin too well! It won't necessarily reproduce the same resonance plot as a violin.  Why should it?  It isn't a violin, it's a viola, with its own characteristic sound.
A similar, but not identical, question is discussed here:
Why do lower pitched string instruments have a larger body?
Answer: The explanation of instrument size with relation to pitch is mostly relevant for the lowest notes it plays, not as much for overlapping notes. Also instrument size goes hand in hand with instrument scale length, the distance of the open vibrating string. That is also a big factor in the sound an instrument produces.
Assuming the size in approximate body length of the violin (~360mm) was conceived perfectly hundreds of years ago then yes, scientifically the body length of a viola is small (~432mm as opposed to ~540mm) for the lowest pitch it produces based on the 1.5x model for an instrument a P5 lower. I and some others believe the low notes on a viola do lack some depth and power due to its size. The reason for its size is ease of playing since it was designed to be held like a violin and this was also conceived and decided hundreds of years ago. Fortunately we have the cellos in quartets and chamber groups, not to mention cellos and basses in orchestras to beef up the low end in the music.


Flask-Login and Heroku issues

Question: I have a sample web application (flask with flask-login running on heroku) at this URL: http://twittaclone.herokuapp.com.
When I run it on my localhost the login functionality works fine. When I push to heroku it freaks out and does not allow users to login (it does allow user registration). Database modifications are being made.
Why would flask login not work on heroku?
<code>app = Flask(__name__)
mysql = MySQL()

app.config['MYSQL_DATABASE_HOST'] = os.environ['MYSQL_DATABASE_HOST'] if 'MYSQL_DATABASE_HOST' in os.environ else config.MYSQL_DATABASE_HOST
app.config['MYSQL_DATABASE_PORT'] = os.environ['MYSQL_DATABASE_PORT'] if 'MYSQL_DATABASE_PORT' in os.environ else config.MYSQL_DATABASE_PORT
app.config['MYSQL_DATABASE_USER'] = os.environ['MYSQL_DATABASE_USER'] if 'MYSQL_DATABASE_USER' in os.environ else config.MYSQL_DATABASE_USER
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['MYSQL_DATABASE_PASSWORD'] if 'MYSQL_DATABASE_PASSWORD' in os.environ else config.MYSQL_DATABASE_PASSWORD
app.config['MYSQL_DATABASE_DB'] = os.environ['MYSQL_DATABASE_DB'] if 'MYSQL_DATABASE_DB' in os.environ else config.MYSQL_DATABASE_DB

mysql.init_app(app)

if 'SECRET_KEY' in os.environ: app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
else: app.config['SECRET_KEY'] = os.urandom(24)

def connect_db(): return mysql.connect()

###
# Routing for your application.
###

login_manager = LoginManager()
login_manager.login_view = "login"

@login_manager.user_loader
def load_user(username):
    g.db = connect_db()
    return get_user(username)

login_manager.init_app(app)

@app.route('/')
def home(): return render_template('home.html')

def connect_db(): return mysql.connect()

@app.before_request
def before_request():
    g.user = current_user
    g.db = connect_db()

@app.teardown_request
def tear_down(exception):
    g.db.close()

@app.route('/main/')
@login_required
def main():
    print("in main")
    tweets, user = get_main()
    follower_count, followee_count = get_follower_info(g.user.username)
    return render_template('main.html', user=user, tweets=tweets, followercount =      follower_count, followeecount = followee_count)

@app.route('/login/', methods=['GET', 'POST'])
def login():
    """Logs the user in."""
    if request.method == 'GET':
        if current_user is user_logged_in: logout_user()

    error = None
    if request.method == 'POST':
        user = get_user(request.form['username'])
        if user is None:
            error = 'Invalid username'
        elif not check_password_hash(user.password, request.form['password']):
            error = 'Invalid password'
        else:
            flash('You were logged in')
            login_user(user)
            return redirect(url_for('main'))

    return render_template('login.html', error=error)
</code>
Comment: The issue was that I had gunicorn in my Procfile. When I changed it to: web: python app.py. Heroku now serves the content fine. Not sure why gunicorn made the sessions None each request...
Comment: i'm not fluent in heroku, but i do use gunicorn to serve client projects.  it'll swallow exceptions unless you fire it up with the `--debug` flag.  that may give you some insight into why your session is getting trashed.
Comment: app.secret_key shouldn't be random.
 [This answer solved my problem](https://stackoverflow.com/a/31002236/3811582)
Comment: What does running `heroku logs` show? (See http://stackoverflow.com/questions/2671454/heroku-how-to-see-all-the-logs)
Comment: What do you mean by 'freaks out'?
Comment: It keeps redirecting you to login multiple times.
Comment: try registering with a dummy name like username a, email: a@a, password: a. It will redirect you to login multiple times
Comment: Can I remote debug flask apps with heroku?
Comment: Here are my logs for when the crash happens. It seems to be crashing from login to main. https://dl.dropbox.com/u/10021156/logs.txt
Comment: You don't have a route named `main` in your code - how is your redirect working on localhost?
Comment: In heroku it looks like the request is being tore down before the call to main leaving the current user object unauthenticated
Comment: why is the session being destroyed during each call to before_request?
Comment: @SeanVieira I removed flask login, the sessions are still not persisting on each get/post..
Comment: by looking at the code, what does get_user() return in heroku? I think if load_user() returns None, login page will be shown normally.
Answer: Many years later but this solves your issue: Heroku gunicorn flask login is not working properly
Updated Procfile:
web: gunicorn app:app --preload
Documentation on preloading for gunicorn: https://docs.gunicorn.org/en/stable/settings.html
Answer: I'm pretty sure that Heroku uses PostgreSQL. Try referring to their documents https://devcenter.heroku.com/articles/heroku-postgresql

Flask-Login and Heroku issues


formal partial complex derivatives and symmetry

Question: This is probably a silly question but let me ask.
As it is well known for a general function $f:\mathbb R^2\to \mathbb R$ which posesses partial derivatives of second order it is not necessarily true that
$$\frac{\partial}{\partial x}(\frac{\partial f}{\partial y})=\frac{\partial}{\partial y}(\frac{\partial f}{\partial x}) $$ and one concrete example is
$$f(x,y)=\frac{xy^3}{x^2+y^2},$$
for $(x,y)\neq (0,0)$ nad $0$ at the origin. My question is about formal complex partial derivatives
$$\frac{\partial}{\partial z}=\frac{1}{2}\left(\frac{\partial}{\partial x}-i\frac{\partial}{\partial y}\right)$$
$$\frac{\partial}{\partial \bar z}=\frac{1}{2}\left(\frac{\partial}{\partial x}+i\frac{\partial}{\partial y}\right)$$
in the complex plane $\mathbb C\cong \mathbb R^2 (x+iy\cong z)$.
Is it always true that
$$\frac{\partial}{\partial z}(\frac{\partial f}{\partial \bar z})=\frac{\partial}{\partial \bar z}(\frac{\partial f}{\partial z}), $$
when both sides make sense or there exists an example of the above type (of course it can not be too regular)?
Comment: What do you mean by "formal complex derivative making sense"? Do you mean that $\partial_x f$ makes sense and $\partial_y f$ makes sense and you just define $\partial_z f$ to be the complex linear combination of the two? Then wouldn't the example you gave already work as a counterexample?
Comment: Yes that is exactly what  "formal complex derivative making sense" means.
Answer: Willie essentially answered the question, but here is the explicit computation in case someone finds it amusing:
$$
\frac{\partial }{\partial z}\frac{\partial f}{\partial \bar z}
 = \frac14 \Delta f +\frac{i}{4}\left(\frac{\partial }{\partial x}\frac{\partial f}{\partial y} -\frac{\partial }{\partial y}\frac{\partial f}{\partial x}\right)
$$
and
$$
\frac{\partial }{\partial \bar z}\frac{\partial f}{\partial z} = \frac14 \Delta f  - \frac{i}{4}\left(\frac{\partial }{\partial x}\frac{\partial f}{\partial y} -\frac{\partial }{\partial y}\frac{\partial f}{\partial x}\right)
$$
This means that the $z$- and $\bar z$- derivatives commute if and only if $x$- and $y$- derivatives commute. For real-valued $f$ the failure of commutativity is expressed as the presence of an imaginary term in the formal partials.


Code impact inside click event?

Question: element.onclick = function() {
    myFunction();
};

function myFunction() {
    // 100, 500 or 1000 lines of code
}

Does and if yes, how does code inside the click event impacts the weight of click event?
PS! Im interested in code impact in event listener overall, not just a function like in my example. What if there was 500 lines of code instead of function?

Does it matter how big is myFunction() code?
Does it get processed before click event is triggered?

I do not mean the impact on the moment it's pressed but before this: if event is attached to element.

Im asking this because I need to attach the same click event to many elements and the code inside is pretty big. Event delegation is not an option in my situation. An example:
for(i = 0; i < 500; i++) {
    //Just for the sake of this example
    var element = document.createElement('div');

    element.onclick = function() {
        myFunction();
    };
}

function myFunction() {
    // 100, 500 or 1000 lines of code
}

Based on this example, should I be thinking about or worried about the size of myFunction()?
Comment: it should be processed well in advance unless theres an eval.
Comment: No more than any other function.
Comment: @PM77-1 Does it get _processed_ before event is triggered? What if there was 500 lines of code inside the event instead of function?
Comment: @DanielA.White So.. Big code inside the event listener has pretty big performance impact even before event is triggered, especially if there are many identical?
Comment: If it's a viable option try using jQuery  to attach on the click event, this way you will avoid creating multiple function objects for every element
$('element').click(eventHandler)
and outside the loop
var eventHandler = function() {
        myFunction();
    }
Answer: You function will be processed by the JavaScript runtime when it reads in the file. It will be invoked when you call it in the callback. The time for the callback to invoke the function will be no different if the function is 10 lines or 1000 lines.
Edit:
You may notice the execution time of the function change, as the amount of code increases, but invocation shouldn't change. Things that change invocation speed are looking up nested functions in objects: obj1.obj2.obj3.obj4.obj5.func() would be slower than a top-level func() definition (shouldn't be drastically different if it is not nested deep in large objects).
Answer: First, Javascript is a single threaded ecosystem.
There is a big eventloop which executes one event after another.
In case your onclick takes ages, you might see the prominent "A script is not responding"
The processing happens when you click it.
The "big event loop" reads the click event and calls all your event handlers for it. So the clicking triggers all the click event handlers being processed. (for the elements that are under your click area)
In case your problem is a not responding script, you could try WebWorkers. I never played with those, as it´s rather new.

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Regarding your 500 elements with the same click handler... You can only click one item at a time, no?
Maybe try
event.stopPropagation();

Code impact inside click event?


Identificar o nome das ruas contidas em um polígono

Question: Tenho o seguinte polígono abaixo:

function initialize() {
  var bounds = new google.maps.LatLngBounds();
  var i;

  var polygonCoords = [
     new google.maps.LatLng(-23.554548, -46.607911),
     new google.maps.LatLng(-23.556043, -46.595058),
     new google.maps.LatLng(-23.564403, -46.593942),
      new google.maps.LatLng(-23.567884, -46.604757)
  ];

  for (i = 0; i < polygonCoords.length; i++) {
     bounds.extend(polygonCoords[i]);
  }

  var map = new google.maps.Map(document.getElementById("map_canvas2"), {
    zoom: 14,
    center: bounds.getCenter(),
    mapTypeId: "roadmap"
  });

  var sp_mooca = new google.maps.Polygon({
    paths: polygonCoords,
    strokeColor: '#0000ff',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#0000ff',
    fillOpacity: 0.35
  });
  sp_mooca.setMap(map);

}
#map {
  height: 100%;
}

É possível identificar o nome de todas as ruas contidas em um polígono no Google Maps? Se sim, como?!
Answer: Acredito que a API não possua um método que retorne endereços num polígono.
Tem o containsLocation que verifica se a coordenada está dentro do polígono. Se a sua intenção é extrair os endereços do polígono para verificar se bate com algum endereço que você tem, pode fazer o caminho contrário: verifique se os seus endereços pertencem ao polígono.
E tem o geocode que retorna o endereço a partir de uma coordenada. Então você pode fazer um loop percorrendo coordenadas dentro do polígono obtendo os endereços. Mas dessa forma você pode atingir o limite de queries facilmente. Exemplo de código.
Acho que de certa forma, dependendo do tamanho do polígono, isso caracterizaria extração em massa da API, o que é proibido pelos termos de uso. Você pode usar o OpenStreetMap para isso, e até baixar o database (dá pra selecionar apenas uma região) e fazer as manipulações de geodata sem restrições.


Well-defined way to quotient by a relation involving an infinite sum

Question: Take a unital (*-)algebra $\mathcal A$ generated by a finite set of generators, $e_n$, and relations. We can require the generators to be (self-adjoint) projections. Some of the relations are of the form $\sum_{n\in S} e_n = 1$ for various finite sets $S$. This is okay so far.
Now I'd like to define an analogous algebra when there are countably many generators, and the sets $S$ involved in the sum-to-one relations are no longer finite.
Inherent in defining an object by generators and relations is selecting an axiomatic meaning for all symbols used (you have to know, for example, whether you are defining a group or a unital algebra over the complex numbers, etc.). My problem is with the infinite sum in a relation. It seems that the possible interpretations are to use infinite sums formally, or to impose some kind of topology.
What kind of mathematical object could work here?
(The eventual goal of defining this object is to consider representations in the bounded operators $B(\mathcal{H})$ on some Hilbert space $\mathcal H$, and to think about traces.)
Comment: The answer here might me somewhat useful: https://mathoverflow.net/questions/152355/free-c-algebra
Comment: It is important to notice that in the MO question, the generators are assumed to be contractions (this may or may not fit what the OP has in mind). In general, there are no free $C^\ast$-algebras.
Comment: Thank you both - I suppose this question may be too open-ended for this site.

@MaoWao I do want to assume my generators are self-adjoint projections (so indeed contractions). I have added that to the post.
Comment: Not necessarily so. The problem is that infinite sums of projections do not converge in norm to $1$ (unless all but finitely many are zero), so $C^\ast$-algebras are not the right way to formulate it. Von Neumann (or $W^\ast$-algebras) would be the natural objects, but I have never seen anyone studying universal von Neumann algebras with given generators and relations. I would suspect this is the case because they rarely exist, but it would be interesting to get a confirmation (or, even better, some good results for universal von Neumann algebras).
Comment: On von Neumann algebras you have an additional topology, the weak$^\ast$ topology. If you have a sequence of projections on a Hilbert space $H$, then $\sum_n p_n=1$ in the weak$^\ast$ topology holds iff the ranges of the projections are pairwise orthogonal and their direct sum is $H$. So this seems like the correct topology for this problem. Morever, the weak$^\ast$ topology on a von Neumann algebra does not depend on the (weak$^\ast$ continuous, faithful) representation, but is really an inherent property.
Comment: @MaoWao This is exactly the problem I'm running into. What I'd like is to have an object that doesn't "decide" which of the projections are zero until a representation is chosen, but I suppose that initial object does not behave like a $C^*$-algebra. I'm curious why you say that Von Neumann algebras would be the natural objects? (I'm not as familiar with VN algebras.)
Answer: There is a new preprint on arxiv that addresses your question: Infinite sum relations on universal $C^\ast$-algebras
For the relations from your question, their construction goes as follows: They start with the free unital $\ast$-algebra $\mathcal{A}$ generated by the projections $e_n$, just as in your OP. A unital $\ast$-representation of $\mathcal{A}$ on a Hilbert space $H$ is called a representation of the defining relations if $\sum_{n\in S}e_n=1$ in the strong operator topology for all defining sets $S$.
They then define the following seminorm on $\mathcal{A}$:
$$
\lVert x\rVert=\sup_{\pi}\lVert \pi(x)\lVert,
$$
where the infimum is taken over all admissible representations $\pi$. Since every element of $\mathcal{A}$ is a finite linear combination of finite products of elements $e_n$, this supremum is indeed finite for every $x\in \mathcal{A}$ (in general, they require a property called admissibility to guarantee that this supremum is finite).
The associated $C^\ast$-algebra $A$ is then defined as the completion of $\mathcal{A}/\{x\in \mathcal{A}: \lVert x\rVert=0\}$. It is universal in the following sense: Whenever there is a unital $C^\ast$-subalgebra $B$ of $B(H)$ for some Hilbert space $H$ with projections $f_n\in B$ such that $\sum_{n\in S}f_n=1$ strongly for all $S$, then there exists a unique unital $\ast$-homomorphism $\phi\colon A\to B$ such that $\phi(e_n)=f_n$.
Also, $A$ has a faithful representation on a Hilbert space $H_u$ in which the defining relations hold in the strong operator topology. However, in their general construction it may happen that the $C^\ast$-algebra has faithful representations that don't satisfy the defining relations in the strong operator topology. In other words, the validity of $s$-$\sum_{n\in S}\pi(e_n)=1$ depends on the representation $\pi$ (in contract to universal $C^\ast$-algebras that involve only "finite" representation).
In the simple example when you only have one relation $\sum_{n=1}^\infty e_n=1$, then $A$ is isomorphic to $c_0+\mathbb{C}1$. Indeed, if projections $p_n$ on a Hilbert space $H$ satisfy $\sum_n p_n=1$ strongly, then they are mutually orthogonal. Thus $A$ is a commutative $C^\ast$-algebra, the linear combinations of the projections $e_n$ and $1$ are dense in $A$, and it suffices to compute its character space.
If $\chi\colon A\to \mathbb{C}$ is a character, then $\chi(e_n)$ is a projection, that is, $\chi(e_n)\in \{0,1\}$. Moreover, since $\sum_{n=1}^N e_n\leq 1$ for all $N\in \mathbb{N}$, for every character $\chi$ there is at most one $n\in \mathbb{N}$ such that $\chi(e_n)=1$. The universal property of $A$ implies for every $n\in \mathbb{N}$ the existence of a character $\chi_n$ such that $\chi_n(e_n)=1$, and it is not hard to see that the weak$^\ast$-topology on $\{\chi_n\mid n\in\mathbb{N}\}$ is discrete. As this space is not compact, the character space of $A$ must be homeomorphic to the one-point compactification of $\mathbb{N}$.


Writing sheet music on your smartphone

Question: This is my first question so sorry if its a poor one for this style of forum.
I regularly write and sight-read standard notation but there are plenty of times im caught without pen and paper or a computer. When that happens I usually just record the idea on my phone using my voice if at all possible. However, if im on a plane, for example, that's not practical. So my question is:
Is there any good android applications that allow you to write your own sheet music?...Preferably with audio playback.
Answer: I don't know if this fits all the criteria you are looking for, but there is NotateMe which is available on Google Play and App Store. It allows you to write music sheets with your finger (or a pen) and is 'translated' into sheet music.
Here is a video demonstration:

There is also Ensemble Composer.

And there is Maestro

And there is Music Notation
Answer: I just found out there's also a smartphone version of Guitar Pro. That might especially be of interest to all you tabbers out there who are unable to sight-read standard notation. GuitarPro

Writing sheet music on your smartphone


How to save outputs in every step using while_loop with tensorflow?

Question: I want to build a RNN with thousands of timesteps, so the proper way is to use the while_loop function since the GPU will be out of memory in for loops.
But I could not find a way to save rnn outputs in every step. I tried using a global list or using tf.concat() to accumulate the output. Neither worked. It seems like while_loop() can only be used to get the final output.
Is there any solution to get all the outputs?
Answer: Try tf.nn.dynamic_rnn which does exactly this using while_loop and TensorArray objects.


Is there a way to iterate through all Child Views of ListView and cast them to TextView

Question: Am building an app for exploring files and am using the android native resource layout for data population called android.R.simple_list_item_1, i have tried going through the methods of a listview to see if i can add a drawable to the left of each item in my list but didn't manage. So the only way i get to access a view from a listview is on event OnItemClick where the view tapped is passed as parameter to the method and then i can format it this way for the drawable
public class MainActivity extends AppCompatActivity {
//Define a listview for holding the data mined from storage
     public ListView mydata;
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          //Define the listview
           mydata=findViewById(R.id.data);
           mydata.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
               //Cast view to TextView at position
                  TextView r=(TextView)view;
              //get the drawable and set to textview
                    Drawable mydraw= ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_file_copy_24,null);
                    r.setCompoundDrawables(mydraw,null,null,null);
            }
      }
}

Is there in which i can get all the views in the listview, create a loop, iterate through all of them and cast to  TextView array and then set my drawable to the TextView(s)?
Comment: You need to extend ListView's ArrayAdapter and manage to call "setCompoundDrawables()" from there.
Comment: I will try to do that thanks, does array adapter got that method?
Comment: That is a TextView method. The extended Adapter is used just to inflate "android.R.simple_list_item_1" and then set its Drawable using THAT method.
Comment: Can you post an answer on the same?
Answer: final static class YourItemClass {
    ...
}
final static class ViewHolder {
    TextView mTextView;
    private ViewHolder(@NonNull final View simpleListItem1) {
        if (!(simpleListItem1 instanceof TextView)) throw new IllegalArgumentException("TextView was expected as root of Layout");
        this.mTextView = (TextView)simpleListItem1;
    }
}
final class CustomArrayAdapter extends ArrayAdapter<YourItemClass> {
    private final Drawable mDrawable;
    private final LayoutInflater mLayoutInflater;
    public CustomArrayAdapter(@NonNull final Context context, @NonNull final List<YourItemClass> objects) {
        super(context, resource, objects);
        this.mDrawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_file_copy_24,null);
        this.mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull final ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = this.mLayoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        final YourItemClass cYourItemClassAtSpecificPosition = this.getItem(position);

        holder.mTextView.setCompoundDrawables(this.mDrawable, null, null, null);

        return convertView;
    }
}

Then from your Activity/Fragment:
private void setItemsToListView(@NonNull final List<YourItemClass> items) {
    mListView.setAdapter(new CustomArrayAdapter(getActivity(), items));
}

This code will run "setCompoundDrawables()" for each row displayed in the ListView.


How to properly tune drum heads?

Question: I would like to know if there are any tips on tuning drumheads; I keep hearing harmonics.
Comment: What do you mean by "listening an harmonic"?  I also suggest maybe just asking how to tune a drum, rather than for "tips", since the latter could lead to random items of information.
Comment: Matthew: When I tune both heads and I hit the top one, I can't find a clear sound since I hear a subtle harmonic. Do I need a relation between the tones of the bottom and the top heads?
Comment: Welcome to Music SE! I've removed the signature and tagline in your post per the [FAQ](http://music.stackexchange.com/faq#signatures). Your posts are always pre-signed, so no use re-signing them. As for, the tagline, the best way to show appreciation for a post is to upvote it and accept the best answer. Great question. +1
Answer: Dave Weckl has a great video for tuning drums
http://www.youtube.com/watch?v=pH_RoUQyv5A&feature=player_embedded
In response to your harmonic problem.
I'v always found it handy to look at the top and bottom heads of the drum as providing 2 different functions. Tune the top head, so that its tight enough to get a nice rebound from
your stick and try to make sure that the drum ring is evenly placed on the drum. While tuning you might want to look at the drum from its side to make sure its even.
Now use the bottom to fine tune the sound of your drum. The tighter the bottom the higher-pitched it gets. That should get rid of your harmonics or help you find it and tune it out. If your still getting a slight ring then listen to which head its coming from. Once you find the ringing head then its usually 2 tuner bolts that are right next to each other that are too tight. You need to re-balance the tuner bolts by loosening and tightening them. Play around with it until the ring goes away.
Comment: I have also found the Bob Gatzen series very useful: http://www.youtube.com/watch?v=hIdehfzpWcc
Answer: I can't believe nobody has mentioned the Drum Tuning Bible yet.
Comment: @Stunner: Done... Unfortunately; I don't have a permanent, "official" link, but googling for "Drum Tuning Bible" should return something in case the link breaks again.
Answer: The best way I found to tune drums is a technique that I have appropriated from many years of watching others, videos, etc.  It involves adjusting one lug to the pitch you want (eg, relative low or high, depending on which tome/drum it is) and then matching each additional lug to that by going around the drum.  It takes practice, but I have found it to be a great method.
I have also met others who actually use a tuner to get the exact frequency they want on a section of the head, and then use a round-about or criss-cross pattern to tune.  I prefer my method but both seem to have merit.
Regarding top and bottom heads.  I usually start with tuning them the same.  If this is good for general playing, I leave it alone.  If I need something different for the tune or piece, I change.  For instance, my snare typically runs a very tight diplomat because I want that pop.  I can't stand the round, loose sound of a snare drum.  I like tight, piccolo sounds with a deep-dish girth.
The thing with technique from pros, etc, like Dave Weckl (who, I should add, is in my top three favorite drummer list) is that you end up modifying it as you go anyway.  So these instructional viedos are good for hints, and tips, but in the end, you are going to develop your own method.
Answer: A tip for getting the levels right on your toms and snare is tune the top and bottom drums to the same pitch and use the stick to tap adjacent to each of the tuning keys individually, if they have the same tone near each tuning key the drum will be tuned evenly and will make the drum sound a lot cleaner.

How to properly tune drum heads?


How do I create a user relationship to show author name in Views?

Question: I want to show node title and it's author but I'm not able to find how to show the author name. I don't see Content:Author in Relationship.
How do I configure Views to show it?
Comment: I believe this has been answered before:
http://drupal.stackexchange.com/questions/5868/drupal-7-2-views-adding-authors-name-of-a-node
Comment: No it does not seem to apply for D6 as I've mentioned(Content:Author)
Answer: In Drupal 6 you don't need a relationship for the author name of a node, it is directly available in the fields' list.


Update in PyMongo with "." in key

Question: I have to find the value of attribute "8.jpg" in collection with "job_id":"0". I have written the following query. "8.jpg" is an Object type.
db.collection.findOne({"job_id":"0"})."8.jpg"
I am getting following error:
2020-10-11T23:18:39.812+0530 E QUERY    [thread1] SyntaxError: missing name after . operator @(shell):1:42
Also how to find the type of an attribute?
I am also trying to update a key in attribute "8.jpg"
db.collection.update({"job_id": "0"},{ $set:{"8.jpg.name":"abc"}})
but this is coming all wrong
Answer: You getting this error because you are doing ."8.jpg". you can not have a string after a dot operator.
You can try this:
db.collection.findOne({"job_id":"0"})["8.jpg"]

Comment: But this will treat jpg as attribute of 8. But that's not the case. "8.jpg" is a key name
Comment: I have updated my answer, can you see if that works?
Comment: Yes, this works. ThankYou!!
And can you tell how to update if "8.jpg" is a dict type?
Have to update a key of "8.jpg".
Comment: You can try `.update({"8.jpg" : value},{$set : {}}) `
Comment: Please mark it as accepted answer if it helped you, it will help others, and it motivates me as well!

Update in PyMongo with "." in key


Given $(x+3)(y−4)=0$, what is the relationship between $xy$ and $-12$?

Question: Given
$(x+3)(y−4)=0  $
Quantity $A = xy  $
Quantity $B = -12  $
A Quantity $A$ is greater.
B Quantity $B$ is greater.
C The two quantities are equal.
D The relationship cannot be determined from the information given.
How is the answer D and not C ?
Please help.
Comment: You are given an equation on the form $ab = 0$. This requires $a = 0$ *or* $b = 0$.
Answer: $(x+3)(y-4)=0 ...(I)\Rightarrow$ either $x=-3$ OR $y=4$ OR  $ x=-3$ AND $y=4$.
If $x=-3$, then $y$ can assume any value and when $y=4$, $x$ can assume any value to satisfy eqn (I)
In both the cases $A=xy$ can be anything, so we can not be sure about $A$ being greater than or less than -$12$.
Only when $x=-3$ AND also, $y=4$, we get $A=-12$, but such condition is not specified in the problem.
Answer: Because the first equation says either $x=-3$ or $y=4$ or both and only in last case C is correct.
for example
$$\begin{cases}
x=-3\\y=0\end{cases}\rightarrow \begin{cases}
A=0\\B=-12\end{cases}$$


Function não altera a variável

Question: Estou aprendendo a usar functions no php. Criei este html, que irá pegar 3 informações, Nome, raça e classe do jogador:

<input type="hidden" name="decicsion" value="0">

<form method="POST">

Name:<input type="text" name="n1">

Race:<select name="n2">
<option value="H">Humano</option>
<option value="O">Orc</option>
<option value="E">Elfo</option>
</select>

Class:<select name="n3">
<option value="W">Guerreiro</option>
<option value="M">Mago</option>
<option value="A">Arqueiro</option>
</select>

<input type="submit" name="Enviar" value="Enviar"></form>

';

No php, começei criando um algoritmo que salva cada valor, fiz o teste e ele funciona, mostrando todos os valores já definidos.
Cada escolha na classe e raça tem uma alteração em outras variáveis que não citei porque ficaria um trecho de código muito grande.
Basicamente, quando os valores do html forem escolhidos, isso irá aumentar algum atributo do personagem, e dar dois itens para ele
if($equip==0)
{
//Define os atributos da classe
if($race=="H")      {$mana=$mana+20; $race="Humano";     }
elseif($race=="O")  {$health=$health+20;    $race="Orc";}
elseif($race=="E")  {$dextery=$dextery+20; $race='Elfo';}

//Adiciona um item de acordo com a classe
if($class=='W'  )   {$sword=1;  $plate=1; $staff=0; $cape=0; $bow=0;    $vest=0; $classe='Guerreiro';}
if($class=='M') {$staff=1;  $cape=1; $plate=0; $sword=0; $bow=0;    $vest=0; $classe='mago';}
if($class=='A') {$bow=1;    $vest=1; $sword=0; $plate=0;    $cape=0; $classe='arqueiro';}

}

Eu criei então, vários if e elseif para aumentar valores do personagem se o item fosse igual a 1. Como esse exemplo:
if($sword==1)
{
    $damage=$damage+3; $weapon='Sword'; $sword=3;
}
elseif($sword==2)
{
    $damage=$damage-3;$sword=3;
}

Eu fiz isso para cada item que coloquei no trecho das classes, então o código ficou muito extenso e complicado. eu queria transformar esses trechos de código em functions, para poder usar novamente caso eu precisasse. então criei a function (equipSword) e passei o código para dentro:

//Trecho do código alterado no if
if($class=='W'  )
{
    equipSword(1);
    $plate=1;
    $staff=0;
    $cape=0;
    $bow=0;
    $vest=0;
    $classe='Guerreiro';
}

//defini essa função abaixo do if($equip==0)
function equipSword($sword)
{
if($sword==1){$damage=$damage+3; $weapon='Sword'; $sword=3;}
elseif($sword==2){$damage=$damage-3;$sword=3;}
if($sword == 3 ){echo'

Weapon	Sword

';}
return $sword;
return $damage;
return $weapon;
}

O problema que estou passando, é que mesmo fazendo os returns, as minhas variáveis não mudam, continuam com o mesmo valor. Gostaria de saber o que estou fazendo de errado para retornar esses valores.
Answer: Você tem que passar como parâmetro os novos valores que você deseja.
Pois do jeito que você esta fazendo os valores já estão definidos na função.
exemplo:
$sword = 5;
$damage = 33;
$weapon = "Tword";

$dados = equipSword($sword, $damage, $weapon);
print_r($dados);

Função PHP
function equipSword($sword, $damage, $weapon){

   if($sword==1){
       $damage = $damage + 3;
       $weapon = $weapon;
       $sword = $sword;
   }
   elseif($sword == 2){
       $damage = $damage-3;
       $sword = 3;
   }

   if($sword == 3 ){
       echo'

       Weapon	Sword

';
   }

   $dados = [];
   $dados["sword"] = $sword;
   $dados["damage"] = $damage;
   $dados["weapon"] = $weapon;

   return $dados;
}

Comment: Testei seu algoritmo para ver se iria funcionar, o programa enviou o seguinte erro `FATAL ERROR Uncaught Error: Using $this when not in object context in /home4/phptest/public_html/code.php70(5) : eval()'d code:73 Stack trace: #0 /home4/phptest/public_html/code.php70(5): eval() #1 {main} thrown on line number 73number 73`
Comment: foi por causa do  **$this** na chamada da função. tente novamente código editado.
Comment: Ele agora só exibe a seguinte mensagem: `Array ( [sword] => 1 [damage] => 5 [weapon] => 0 ) `   As variáveis continuam com o valor original
Comment: Você tem que mandar os novos valores como parâmetro, repare como eu fiz la no primeiro exemplo onde eu defini os novos valores para **sword, damage e weapon**. E a partir do momento que a função recebe esses valores você pode trabalhar eles do jeito que você quiser. dai você pode definir um padrão dentro da função onde ela vai realizando sempre.
Comment: Sim, eu fiz exatamente igual
Comment: agora você tem olhar como você está tratando elas dentro da função
Comment: Funcionou depois que eu fiz as variáveis fora dos dados serem iguais ao array. Não era bem isso que eu queria, pois eu queria uma forma que me permitisse chamar a function de um outro lugar com poucas linhas de código. Mas já ajudou, obrigado
Answer: Há alguns erros conceituais na sua implementação
1 - funções e métodos retornam no primeiro return executado, logo, tudo que vem abaixo de return $sword não será executado
2 - o return não retorna a variável e sim o valor dela, por isso, vc precisar desse valor, vc deve armazenar o retorno em uma variável, algo do tipo: $sword=equipSword($sword);
3 - existe o escopo de variáveis, de forma resumida: as variáveis declaradas fora da função  não são as mesmas que vc chamou dentro, para serem as mesmas vc precisa declarar elas como globais dentro da função, tipo:
function equipSword()
{
    global $sword;
    global $damage;
    global $weapon;

    if($sword==1){$damage=$damage+3; $weapon='Sword'; $sword=3;}
    elseif($sword==2){$damage=$damage-3;$sword=3;}
    if($sword == 3 ){echo'

Weapon	Sword

';}

}

Comment: Eu fiz as alterações no código conforme você explicou, mas os valores não mudam mesmo assim

Function não altera a variável


Solving two variables system equations with parameter above $\mathbb{Z}_7$

Question: Let:
$$(1+5a)x +y = 1$$
$$a^2x + y = 2$$
Eliminating the $y$ variable we have:
$$(-a^2 +5a +1)x = 6$$
Now, I should have find $y$ such that $(-a^2 +5a +1)y = 1$, but obvoiusly I can't do that because the parameter $a$.
What should I do instead?
Answer: First off, you need to solve $$(-a^2+5a+1)x=6\tag{$\star$}$$  instead of $(-a^2+5a+1)y=1.$ I'm not sure where that equation could have come from.
You'll need to proceed casewise, as the value of $a$ will make a difference. For example, one readily sees that if $a=0,$ then $(\star)$ becomes $x=6,$ from which it follows that $y=2.$ On the other hand, note that you can equivalently rewrite $(\star)$ as $$(-a^2+5a-6)x=-1\\(a^2-5a+6)x=1\\(a-2)(a-3)x=1$$ Clearly, then, if $a=2$ or $a=3,$ then there is no solution. There are $4$ cases left to consider. I leave them to you.
Nota Bene: If you are supposed to give a solution that is independent of $a,$ then something probably went wrong in the process of obtaining this system of equations. If you let me know how the problem was presented, and what you've done so far, I may be able to help you isolate any errors you've made.
Comment: Yes, you should. Apologies for the delayed response. For whatever reason, I just now got the notification.
Comment: Thanks. Should I check the 4 left options of $a$ manually?


In every polygon circumscribed about a circle, there exist three sides that can form a triangle.

Question: How can one show that in every polygon circumscribed about a circle, there exist three sides that can form a triangle?
(This was posted by another user and then deleted while I was typing my answer.)
Comment: It's a perfectly good question, of course. Perhaps the previous poster deleted it because he found the answer and then decided that he didn't need to ask it.
Answer: Look at the very longest side and the two sides adjacent to it.
Say the longest side has vertices $B$ and $C$ and touches the circle at $Y$.  One of the adjacent sides shares vertex $B$ and touches the circle at $X$.  The other shares $C$ and touches at $Z$.
Notice that the distances $BY$ and $BX$ are equal, and the distances $CX$ and $CZ$ are equal.
So a segment of length more than $BY$ and one of length more than $CZ$ have a sum of lengths more than $BY+YC$, thus satisfying the triangle inequality.
Comment: Why are the distances between CX and CZ equal?
Comment: Through every point (such as $C$) exterior to the circle, one can draw two lines tangent to the circle.  The distances from $C$ to the two points of tangency are equal.
Comment: All right, let's try a slightly less intuitive approach: Let $C$ be exterior to the circle; let $X$ and $Z$ be the points of tangency on the two lines through $C$ that are tangent to the circle; let $P$ be the center.  The two radii $PX$ and $PZ$ have equal lengths (by definition of "circle") and meet the tangents at right angles. So we have the two triangles $\triangle CPX$ and $\triangle CPZ$, with two side lengths in common and each with a right angle. Thus "S.S.A.", with the "A." begin a right angle. The Pythagorean theorem then says $CX^2 = CP^2 - PX^2 = CP^2 - PZ^2 = CZ^2$. ${}\qquad{}$


Increasing Heap Space of Grails Application Deployed on Tomcat Server in Windows OS

Question: I have created an extensive Grails Web Application using lot of Plugins. I deployed this application on Tomcat Server (version-08), But as the records started growing, I get Java Heap Memory errors such as:

OutOfMemoryError occurred when processing request
JobExecutionException: java.lang.OutOfMemoryError: Java heap space
java.lang.IllegalStateException: Already value for key bound to thread
Error processing GroovyPageView: Error executing tag : Java heap space

I have tried lot of things available on web regarding increasing heap space allocated to my Tomcat Server, such as:

Creating file 'setenv.bat' in tomcat/bin directory with content 'setx JAVA_OPTS="-server -Xmx1024m"'
Setting System Environment Variable. Name:CATALINA_OPTS Value:-Xms256m -Xmx1024m
setting these variables using 'set' and 'setx' command.
Added the following line as very first line in my BuildConfig.Groovy file:
grails.tomcat.jvmArgs= ["-Xms512m", "-Xmx1024m", "-XX:PermSize=512m", "-XX:MaxPermSize=1024m"]

I am Using Java-Melody to monitor the requests, memory, thread processes. I use this to check this:

P.S. In my Server Machine there are multiple Tomcat Server Installed on which different multiple applications are deployed.
Secondly, I succeeded to increase my permGen Memory by writting: -XX:PermSize=512m
-XX:MaxPermSize=1024m in Tomcat Java Configurations.
Any Help regarding this will be highly appreciated.
Answer: You can set memory limits with bin/tomcat7w.exe tool, in the Java tab.
However, I have not tried it with Tomcat 8 or with multiple Tomcat instances on the same server.
Hope this helps...


How can I make my site stop adding  tags in textareas?

Question: For a current project I have a content type's textarea set to Full HTML. But where I've added a  tag, Drupal will go ahead and enclose it within a
 tag which is definitely not what I want!
It's also adding an empty
 tag at the bottom of said container.
How and where can that be turned off? Where is the mechanism or module that is doing that?
Answer: Sounds like maybe you need to disable the "Convert line breaks into HTML (i.e.
 and
)" filter on your Full HTML text format.
This can be done by navigating to Configuration > Content authoring > Text formats and editors, then editing the Full HTML configuration and un-checking the box for "Convert line breaks into HTML (i.e.
 and
)" under "Enabled filters". Assuming this is Drupal 8 anyway. Drupal 7 has the same setting but the exact location might be different.
Comment: thanks Joe!, why i was just watching one of your video tuts this a.m......


Check if file-path is set in cron

Question: I am setting a cron from bash script
I want to check  if file path is set in CRON
I checked this code to create cron but this code does not help with random time
(crontab -l; echo "${MIN} ${HOUR} * * * /temp/filepath") | awk '!x[$0]++' | crontab -

Note: ${MIN} ${HOUR} are random values
This creates multiple entry for changed variable values
I want single entry created based on file path /temp/filepath if not there
Answer: I don't know your exact crontab content so some of this is presumptive. The problem is related to your awk program.. I generated a "fake" crontab and simulated trying to re-add /tmp/filepath_7 .... Here is what worked for me:
$ for K in $(seq 0 10) ; do printf  '%2d %2d * * * %s_%d\n' "$((RANDOM % 61))" "$((RANDOM % 25))" /tmp/filepath $K ; done > $HOME/fakeCrontab.txt
$ (cat $HOME/fakeCrontab.txt ; printf  '%2d %2d * * * %s_%d\n' "$((RANDOM % 61))" "$((RANDOM % 25))" /tmp/filepath 7) | awk ' !x[$6]++ { print $0 }'
17  2 * * * /tmp/filepath_0
13 19 * * * /tmp/filepath_1
59  9 * * * /tmp/filepath_2
56 13 * * * /tmp/filepath_3
59 22 * * * /tmp/filepath_4
55 19 * * * /tmp/filepath_5
33  5 * * * /tmp/filepath_6
17 14 * * * /tmp/filepath_7
58  5 * * * /tmp/filepath_8
51 19 * * * /tmp/filepath_9
18  8 * * * /tmp/filepath_10
$

Answer: If you don't care about the exact time, don't include the exact time in the string you check.
Assuming the other time fields are significant (day, month, weekday) try
crontab -l; echo "${MIN} ${HOUR} * * * /temp/filepath") |
awk '{ y = $0; sub("^[ \t ]*" $1 "[\t ]*" $2, "", y }
    !x[y]++' | crontab -

Depending on how thorough you want to be, you might want to perform additional whitespace normalization on the y value. The main beef is to use the part you care about as the index into x.

Check if file-path is set in cron


What are the "Sprint" and "Sprint Shootout" in F1 Grand Prix?

Question:
In the above F1 Azerbaijan Grand Prix 2023 schedule, I cannot understand what Sprint and Sprint Shootout mean.
Is this kind of practice or qualifier?
Answer: As of 2023, the F1 "sprint race weekends" are effectively two entirely separate races:

The sprint race, which takes place on the Saturday of the race weekend. This is a short race (100km) with 8 points available for the winner, 7 for second place and so on down to 1 point for 8th place.

The grid for this race is set by the "sprint shootout" session earlier on the Saturday.

The main race, which takes place on the Sunday. This is a full length race (305km) with up to 26 points available for the winner.

The grid for this race is set by the qualifying session on the Friday.

This is a significant change from the sprint format used in 2021/22, where the sprint race set the grid for the main race (and gave 3-2-1 points for the first three places). The change was made on 25th April 2023, just five days before the first sprint race of the 2023 season in Azerbaijan, in response to criticisms of the 2021/22 sprint format (source: BBC News).
Answer: From the 2021 season, the F1 introduced a new format.
They introduced Sprint which set the grid for the main race.
In the 3 days of F1 event weekend from Friday to Sunday the old schedule (2021 and 20220 are as follows:

Friday: Practice One, Qualifying
Saturday: Practice Two, Sprint Race
Sunday: Grand Prix

From the 2023 season, the F1 introduced another new format.
Fhe Friday schedule remains unchanged.
The Sprint shootout are held in saturday from 2023.
The new weekend schedule are as follows:

Friday: Practice, Qualifying
Saturday: Sprint Shootout, Sprint race
Sunday: Grand Prix

The sprint shootout will set the grid for the sprint race itself.
Reference:

https://www.espn.co.uk/f1/story/_/id/36280380/f1-adds-sprint-shootout-qualifying-event-sprint-weekends

https://www.espn.com/f1/story/_/id/36288097/what-sprint-shootout-f1-new-sprint-race-weekend-format-explained
Comment: That directly contradicts what is written in the first link you posted: "The starting grid of Sunday's grand prix [...] will be determined by the standard qualifying session on Friday."
Comment: So what _is_ a sprint shootout? Repeating the name of something doesn't tell me anything about what it actually is.
Comment: @PhilipKendall   The sprint shootout set the grid for the sprint race, and the sprint set the grid for the main race. Is it clear now?


How to have aspect ratio by parent height?

Question: I want to have aspect ratio controlled by parent height.
Every example I search in stackoverflow and codepen are examples of aspect-ratio by width size.
In my example I have two div. there height is controlled by wrap div. so in the first div there is a div inside that should display in 16:9 aspect-ratio.
This is mean if the height is 200px then the width should be 355px (200*(16/9)).
Please keep in mind that height can change because I use vh.
How to do that with css?
Here is my example code in codepen

.wrap { display:grid;grid-template-columns:1fr;grid-template-rows:30vh 70vh; }

.item { border:1px solid red; }

.aspect-ratio { background:blue; height: 100%; }

aspect ratio should be 16:9

Answer: you can use css calc();

.wrap { display:grid;grid-template-columns:1fr;grid-template-rows:30vh 70vh; }

.item { border:1px solid red; }

.aspect-ratio { background:blue; height: 100%; width: calc(30vh * 16 / 9); }

aspect ratio should be 16:9


Can I use binary variables in logistic glm in R?

Question: Can I use binary variables in R's glm function with a binomial outcome (logistic regression)?
Comment: You mean as predictors? Yes.
Comment: Yes you definitely can.
Answer: The short answer is yes you can.
Here is a minimal working example of a logistic regression with one binary predictor variable.
set.seed(4)

###Creat some psuedo data
n = 100
x = rbinom(n,1,0.5)
y = x
y[sample(1:n,10,replace=FALSE)] = 1
y[sample(1:n,10,replace=FALSE)] = 0

model = glm(y~x,family="binomial")

and so y is my binary output, and x is my binary predictor variable. The code runs with no error (so clearly you can include a binary predictor variable) and the example output from running this code would be:
> model

Call:  glm(formula = y ~ x, family = "binomial")

Coefficients:
(Intercept)            x
      -3.02         5.16

Degrees of Freedom: 99 Total (i.e. Null);  98 Residual
Null Deviance:      138.3
Residual Deviance: 54.54        AIC: 58.54

Comment: What if you skip the sample lines and leave x = y, so we get a perfect separating predictor. Why in that case is the model becoming bad and resulting in a p-value of 1?
Comment: @Ansjovis86 you can read about it here: http://stats.stackexchange.com/questions/11109/how-to-deal-with-perfect-separation-in-logistic-regression


Is $F_p^{l}[t]$ is a UFD

Question: I'm stuck here.
Let $F_{p}$ be a finite filed. Is  $F_{p^{l}}[t]$ a Unique factorization Domain.
Can anyone explain? Thank you very much
Answer: I presume $F_{p^l}$ denotes the finite field of order $q^l$.
The polynomial ring $k[t]$ is a UFD for any field $k$.
The proof is via the Euclidean algorithm for polynomials.

Is $F_p^{l}[t]$ is a UFD


Condicional na API em Java Script

Question: sou novato em NodeJs com JavaScript, peguei um exemplo pronto e quero apenas adicionar uma condição no corpo da API do tipo: Caso aquele valor exista mostra a mensagem na chamada da API via Insonmia ou Postman e não deixa incluir.
Código no VSCode

const express = require('express')
const server = express()

server.use(express.json())

const users = ["aa", "bb", "cc", "ddd"]

server.get('/users', (req, res) => {

return res.json(users)
})

server.post('/users', (req, res) => {
    const { name } = req.body
    users.push(name)
       if (name == "aaaa") {
        console.log("Registro existente.")

      return res.json(users)

})

server.listen(3000)

Chamada API
{
"name": "aa"
}

via

Comment: Isto responde à sua pergunta? [Verificando se valor existe em um array através de campo de busca](https://pt.stackoverflow.com/questions/173589/verificando-se-valor-existe-em-um-array-atrav%c3%a9s-de-campo-de-busca)
Comment: Esse código não compila.
Answer: Você poderia fazer a verificação antes de incluir o elemento no array.
Ao detectar que o elemento já existe, basta fazer o envio da mensagem de erro.
server.post('/users', (req, res) => {
    const { name } = req.body
    if (name && users.includes(name)) {
        res.json({"msg": "Registro existente"})
        return
    } else if (name) {
        users.push(name)
    }
    res.json(users)
})

O else if é necessário para prevenir a inserção do valor null no array users, caso não seja enviado a chave name no request.body
Documentação do Array.includes
Comment: Muito agradecido... Deu super certo..

Condicional na API em Java Script