How would you interpret this result of ANOVA and the interaction plot, where the picture seems to contradict the output of ANOVA?

Question: Let's see the two interaction plots below. It's the same design, just "orthogonally" displayed:
The ANOVA says:
<code>> car::Anova(model_chg, type=3)
Anova Table (Type III tests)

Response: chg
                  Pr(>F)
(Intercept)       0.011894 *
AB                0.983652
XY                0.001262 **
AB:XY             0.123200
</code>
which means, that there is the main effect of XY (the effect at all levels of AB) and no interaction.
But the picture says, that there exists an interaction, quite visible, and it's dis-ordinal (crossing) one, so the main effect can be hardly found. Instead, we can see a partial effect, a simple effect between X and Y of the variable XY at the level of B of variable AB.
In other words: ANOVA says: no interaction, main effect of XY, picture says: interaction exists, no main effects, simple effect of XY at B exists.
When I did an analysis of contrasts (X vs Y at A and at B), it confirmed this finding: no effect except X vs. Y at B.
How can I interpret that little "discrepancy" between the ANOVA and the picture?

EDIT:
the data:
<code>data <- structure(list(chg = c(0.2, 0.4, -0.0999999999999996, 0.9, 0,
0.5, 0.5, 0, 0.3, 1.3, -0.2, 0.5, 0.5, 0.2, 0.2, 0.2, 0, 2.1,
0.3, 0.5, 0.2, 0.5, 0.1, 0, -0.1, 0, 0.4, 0.5, 0.4, -0.2, 0,
0, 0.5, 0.1, -0.2, 0.2, 3, 0.3, 0, 0.8, 0.1, 0.8, -0.1, 0.3,
-0.1, -0.2, 0.2, 0.6, 0.4, 0.3, -0.0999999999999996, 0, -0.3,
0.3, 0.2, 0.9, -0.1, 0.9, -0.1, -0.1, 0.3, 0.8, 0.6, 0, -0.5,
0.5, -0.3, 0, 0.1, -0.8, 0.2, 0.6, 0.6, 1.1, 0.4, 0.7, 0.399999999999999,
2.4, 0.3, 0, -0.2, 0.2, 1.1, 0.5, 0.1, -0.21, -0.3, 0.0399999999999996,
0.6, 0.0499999999999998, 0.31, 0.47, 0.0499999999999998, 0.52,
-0.12, 0.0499999999999998, 0.13, 0.35, 0.15, 0.44, -0.66, 1.18,
0.69, 0.4, 0.38, 0.63, 0.96, 0.26, 0.12, 0.13, 0.24, -0.0799999999999996,
-0.0699999999999998, 0.27, 0.2, 0.33, 0.0600000000000001, 0.0499999999999998,
0.32, 0.18, 0.38, 0.12, 0.62, 0.47, 0.33, -0.81, 1.31, 0.42,
-0.0800000000000001, 0.7, 0.4, 0.5, 0.2, 0, 0.4, -0.3, 0.2, 0.4,
0.5, 0, 0.3, 0.6, 0, -0.1, 0.6, 0.2, 0.8, 0.3, 0.8, 0.3, 0.4,
0.3, 1.1, 1.6, -0.2, 0.4, 0.3, -0.3, 1, 0, 0, 0, 0.1, 0.4, 0.1
), XY = c("A", "B", "B", "A", "B", "B", "B", "B", "B", "B", "A",
"B", "B", "B", "B", "B", "B", "A", "B", "B", "B", "A", "B", "A",
"A", "A", "A", "B", "B", "A", "B", "B", "A", "A", "A", "A", "B",
"A", "B", "B", "A", "B", "A", "B", "A", "A", "B", "A", "B", "A",
"B", "A", "B", "A", "A", "B", "A", "B", "A", "B", "A", "B", "A",
"B", "A", "B", "B", "A", "A", "B", "B", "B", "A", "B", "B", "B",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "A", "A", "B", "A",
"A", "A", "A", "A", "A", "A", "A", "B", "A", "A", "A", "A", "A",
"A", "A", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A",
"B", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A",
"B", "B", "B", "B", "A", "A", "B", "A", "A", "B", "B", "A", "A",
"B", "A", "A", "B", "A", "A", "B", "A", "B", "B", "B", "A", "B",
"A", "A", "A", "A", "B", "A", "A", "A", "A", "B", "A"), AB = c("X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
"X", "X", "X", "X", "X", "X", "X", "Y"), Baseline = c(-3.1, -3.5,
-2.7, -2.7, -3.5, -3.1, -2.6, -4.1, -3.3, -3.5, -2.7, -2.9, -3.4,
-3.2, -2.9, -4, -3.7, -1.4, -3.7, -3.6, -3.2, -2.5, -2.7, -2.7,
-3.3, -1.5, -2.8, -3.4, -3.8, -2.8, -2.7, -3.3, -3, -3, -2.8,
-2.2, -2.5, -2.5, -3.9, -3.8, -2.5, -2.8, -2.4, -3.1, -2.8, -2,
-2.6, -2.3, -3.3, -1.4, -2.7, -2.3, -3.3, -2.6, -3.9, -4, -2,
-3.1, -1.9, -2.4, -1.8, -3.3, -2.3, -4.1, -3.4, -3.2, -2.7, -3.1,
-3.9, -2.8, -4.5, -4, -2.6, -2.7, -4, -3.5, -4.1, -3.2, -4.3,
-4.2, -4.5, -3.9, -2.9, -3.7, -4, -3.24, -2.48, -2.51, -5.08,
-3.09, -3.29, -2.37, -3, -2.54, -2.67, -3.46, -3.28, -2.64, -3.81,
-3.17, -2.71, -2.98, -3.49, -2.56, -2.92, -2.63, -3.56, -3.78,
-2.56, -1.97, -3.61, -2.18, -2.75, -2.14, -3.31, -2.41, -2.71,
-3.15, -2.1, -2.86, -0.99, -3.57, -1.22, -3.08, -2.35, -2.4,
-4.6, -2.56, -2.65, -4.3, -2.7, -2.7, -2.5, -3.5, -2.5, -3.1,
-2.7, -3.2, -2.6, -2.9, -2.9, -2.9, -2.4, -3.1, -3.1, -2.8, -3,
-2.2, -2.8, -3.1, -1.8, -3.4, -2, -3.1, -2.9, -2.6, -3.3, -2.8,
-2.7, -2.5, -2.7, -2.7, -3, -2.6, -2.9)), row.names = c(NA, -165L
), class = "data.frame")
</code>
Model:
<code>> library(emmeans)
> options(contrasts=c('contr.sum','contr.poly'))
> model_chg <- lm(chg ~ XY * AB + Baseline, data = data)
> car::Anova(model_chg, type=3)
Anova Table (Type III tests)

Response: chg
            Sum Sq  Df F value   Pr(>F)
(Intercept)  1.471   1  6.4739 0.011894 *
XY           2.449   1 10.7778 0.001262 **
AB           0.000   1  0.0004 0.983652
Baseline     0.198   1  0.8694 0.352519
XY:AB        0.546   1  2.4014 0.123200
Residuals   36.357 160
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> car::Anova(model_chg, type=2)
Anova Table (Type II tests)

Response: chg
          Sum Sq  Df F value  Pr(>F)
XY         1.906   1  8.3862 0.00431 **
AB         0.003   1  0.0123 0.91167
Baseline   0.198   1  0.8694 0.35252
XY:AB      0.546   1  2.4014 0.12320
Residuals 36.357 160
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> joint_tests(model_chg)
 model term df1 df2 F.ratio p.value
 XY           1 160  10.778 0.0013
 AB           1 160   0.000 0.9837
 XY:AB        1 160   2.401 0.1232

em_chg <- emmeans(object = model_chg, specs = ~XY * AB, mode = "df.error", data=data, adjust="mvt")

# Adjusted for multiplicity
> contrast(em_chg,
+          list(X_AB = c(1, 0, -1, 0),
+               Y_AB = c(0, 1, 0, -1),
+               A_XY = c(1, -1, 0, 0),
+               B_XY = c(0, 0, 1, -1)
+          ), adjust = "mvt")
 contrast estimate    SE  df lower.CL upper.CL t.ratio p.value
 X_AB        0.133 0.122 160   -0.170   0.4361  1.090  0.6383
 Y_AB       -0.130 0.112 160   -0.408   0.1482 -1.156  0.5937
 A_XY       -0.150 0.090 160   -0.373   0.0723 -1.672  0.2830
 B_XY       -0.414 0.145 160   -0.773  -0.0543 -2.849  0.0183

Confidence level used: 0.95
Conf-level adjustment: mvt method for 4 estimates
P value adjustment: mvt method for 4 tests

# Unadjusted (nominal)
> contrast(em_chg,
+          list(X_AB = c(1, 0, -1, 0),
+               Y_AB = c(0, 1, 0, -1),
+               A_XY = c(1, -1, 0, 0),
+               B_XY = c(0, 0, 1, -1)
+          ), adjust = "none")
 contrast estimate    SE  df lower.CL upper.CL t.ratio p.value
 X_AB        0.133 0.122 160   -0.108   0.3750  1.090  0.2775
 Y_AB       -0.130 0.112 160   -0.352   0.0920 -1.156  0.2493
 A_XY       -0.150 0.090 160   -0.328   0.0273 -1.672  0.0966
 B_XY       -0.414 0.145 160   -0.701  -0.1269 -2.849  0.0050

Confidence level used: 0.95
</code>
Answer: The fact that the lines on the first plot cross is not in and of itself proof of an interaction at significance 0.05 (or any significance level). A p-value of 0.12 might be said to suggest that there is "probably" some type of interaction, which we can eye-ball from plot one. But is it for sure an interaction? No.
Same thing on plot 2. Is the fact that one slope is positive and one is negative in and of itself proof of an interaction. No. This is, in fact, a good example of why statistics exist. Our visual intuitions fail us and suggest to us a pattern when really there is not sufficient evidence to distinguish the pattern from random noise.
Comment: Yes, but then how it's possible, that the ANOVA reports the main effect, while the contrast analysis (either the dummy Tukey HSD for all pairs, or the specific subset if contrasts I provide to the program) shows *only* the one simple effect (at p<0.001), which immediately points to the interaction? Can it be that the contrast analysis supports the graph, while the overall ANOVA is fooled by something? I mention this contrast analysis in my post. Moreover, the graph doesn't support the claim that the main effect even exists. That drove me to ask this question: more contradicting results.
Comment: In other words - how is that possible, that a single simple effect confirmed by the contrast analysis (adjusted for multiplicity using the multivariate t distribution) agrees with the picture, is able to "force" the ANOVA to report the whole main effect (at both levels of the second variable - by the definition of the main effect) and invalidates the interaction at the same time. This is something that I wanted to consult.
Comment: Can you edit the post to include actual numerical results for your contrast analysis? Just looking at graphs isn't really useful.
Comment: I added the data and the calculations I made. I use type 3 (or 2 for no interaction) ANOVA-like analysis - a sequence of the likelihood ratio tests to assess the main and interaction effects. I analyse change from baseline (in my industry it's the only allowed method for non-randomized trials) adjusted for the baseline (it's required by the industry). If you omit the baseline, results are slightly different, but the overall outcome (in terms of significance) is exactly the same.
Comment: So, as we can see, the LR test over lm() (pretty equivalent to the type 3 ANOVA) finds the main effect and no interaction (which by definition means, that XY must differ on both levels of AB, A and B). But the analysis of contrasts finds only the partial (simple) effect. And the graph seems to reflect the analysis of contrasts. I reported also the unadjusted analysis - it doesn't change much, the results are consistent.
Comment: There is too much black-and-white reasoning in this discussion. You do not have proof that there is no interaction, you only have insufficient data to prove an interaction exists. Absence of proof is not the same as proof of absence. I think the P value for interaction is low enough here that I'd consider doing comparisons of simple effects.


Bayesian Inference Formulation

Question: I am new to Bayesian inference so I apologise in advance if this seems a basic or poorly described question.
I am trying to perform the fusion of probabilities of multiple data points. To do this I am trying to formulate how I can do this with Bayesian inference. I understand how Bayesian inference can obtain a probability for two data points on the same distribution.
However, I now have two separate datasets of priors for two separate sources. I am given to understand that Bayesian inference must be conducted with independent and identically distributed variables. The two sets of priors in my case are not identically distributed.
Can I still perform Bayesian inference? I have considered a normalisation approach to get them on the same distribution but this seems like a poor solution.
Comment: Bayesian inference does not require independent and identically distributed variables.   It is really unclear what your objective is and what data etc. you have; perhaps you could clarify?
Comment: Ignoring the math and statistics, how would you explain what you were trying to do to someone and what would success look like?
Comment: @jbowman I essentially have two distributions of data that represent two separate prior sensor measurements when a hypothesis is true. The distributions are different for each sensor. Given a future sample from each sensor I am trying to work out the belief in the two sensor scores given the prior readings.
Answer: Let us assume we have some unobserved variable $\theta$ that represents a state, e.g., $\theta \in \{0,1\}$.  We have two sensors, label them $s_1$ and $s_2$, and each produces a random measurement $x_i, i\in \{1,2\}$ that is dependent upon the state, with possibly different probability distributions $p_i(x_i;\theta)$.  We'll further assume the random parts of the measurements are independent of each other.
Now, if $\theta = 0$, the probability distribution for the measurements $(x_1, x_2)$ is just the product of the sensor-specific probability distributions conditional upon $\theta=0$ (thanks to that independence assumption made in the previous sentence):
$$p(x_1,x_2; \theta = 0) = p_1(x_1;\theta=0)p_2(x_2;\theta=0)$$
and similarly for $\theta=1$.  If we have a prior distribution on $\theta$, say $P(\theta)$, we can form our posterior distribution in the usual Bayesian way:
$$p(\theta;x_1,x_2) \propto p(x_1,x_2;\theta)P(\theta) = p_1(x_1;\theta)p_2(x_2;\theta)P(\theta)$$
ETA: For concreteness, let us assume we are monitoring a piece of equipment that produces power, e.g., a solar panel that tracks the sun.  Something happens that may have damaged it, in which case it would a) produce less power, and b) consume more power trying to track the sun.  So we have two different sensors reporting measurements, the sensor $s_1$ that tracks power production and the sensor $s_2$ that tracks power consumption.
If the tracker is good, power production ($x_1$) is distributed $\text{Normal}(100,10)$.  If it is bad, power production is distributed $\text{Normal}(90,10)$.
If the tracker is good, power consumption ($x_2$) is distributed $\text{Gamma}(\mu=5,\sigma=2)$.  If it is bad, power consumption is distributed $\text{Gamma}(\mu=10,\sigma=3)$.  I am parameterizing the Gamma using the mean and standard deviation respectively for ease of interpreting the numbers.
If we define a parameter $\theta$ which equals 1 if the tracker is good and 0 if it is bad, we can write the probability distributions for $x_1$ and $x_2$ as follows:
$$p_1(x_1;\theta) = \text{Normal}(90 + 10\theta, 10)$$
$$p_2(x_2;\theta) = \text{Gamma}(10-5\theta,3-\theta)$$
Our prior probability is on whether or not the tracker is good, i.e., on $\theta$.  We doubt it was damaged; let's set $P(\theta = 1) = 0.75$.
Now we look at our sensor readings.  $x_1 = 97$ and $x_2 = 6.7$.  On to the Bayesian calculation engine!  The likelihood function for $\theta$ is just the product of the individual probability distributions $p_1$ and $p_2$:
$$L(\theta; x_1,x_2) = p_1(x_1;\theta)p_2(x_2;\theta)$$
and some calculation gives us the following results:
$$L(\theta=0; x_1=97, x_2=6.7) = 0.00281$$
$$L(\theta=1; x_1=97, x_2=6.7) = 0.00364$$
and our posterior probability that the tracker is good is:
$$P(\theta = 1) = {0.00364*0.75 \over 0.00364*0.75 + 0.00281*0.25} = 0.795$$
Note that it is not, strictly speaking, necessary that we construct a numeric parameter $\theta$ for this example.  We could have just done everything using "Good" and "Bad" as conditions for selecting, in the case of sensor 1, which of two Normal distributions to use in the calculation, and similarly for sensor 2, and we would have gotten the same result.
Comment: Thank you for your explanation! The one this I am still a little lost on is how we deal with the fact that our x values for different sensors may have different probability distributions? You say we have a prior distribution $P(\theta)$. In practice though we will have a prior for each sensor. Therefore don't we need to combine the two priors? The priors for the x values for the current sensors have different means and standard deviations.
Comment: Well, in the example I gave above, they do have different probability distributions.  One has probability distribution $p_1$ and the other has probability distribution $p_2$; they can be completely different.  Furthermore, your prior isn't on data from the sensor, it's on some parameter your sensors are giving you information about.  If that parameter is different between the two sensors, then you have two completely separate problems.  If the parameter is the same, and you have measurements from two different sensors, then the parameter is just $\theta$ above.
Comment: Ah, I think I understand that! Thank you for the explanation!
Comment: Does this mean that given the parameter is the same, the prior scores from *both* sensors form the prior $P(\theta)$ even if they have different means, etc?
Comment: Let me expand the answer with an actual example, just to make things clearer.  It'll take a little while to work it out.
Comment: Sure -- I really appreciate the help understanding this and your patience.
Comment: Just wanted to say thank you. Reading it in conjunction with the Bayesian inference formula now makes perfect sense!

Bayesian Inference Formulation


Verify trigonometric equation $\frac{(\sec{A}-\csc{A})}{(\sec A+\csc A)}=\frac{(\tan A-1)}{(\tan A+1)}$

Question: How Would I verify the following  identity.
$$\frac{(\sec{A}-\csc{A})}{(\sec A+\csc A)}=\frac{(\tan A-1)}{(\tan A+1)}$$
I simplified it to
$$\frac{(\sin{A}-\cos{A})}{(\sin{A} \cos{A})}\div\frac{(\sin{A}+\cos{A})}{(\sin{A}\cos{A})}$$
Comment: I edited your question to include LaTeX formatting, and in your statement of the identity I changed "Tan+1" to "$\tan A+1$". Please Verify that this is correct. Unfortunately, for the life of me I was unable to understand what you simplified "it" too (or what "it" is).
Comment: As a first step in situations like this, try writing everything in terms of $\sin A$ and $\cos A$, then simplify the fractions and try to use the fact that $\sin^2 A +\cos^2 A = 1$.
Comment: you edit it correctly
Comment: @AlexBecker: I think the "it" in the question text indicates the left-hand side. So, Papi, that's a good start; notice that your simplified quotient simplifies further to $(\sin A - \cos A)/(\sin A + \cos A)$. Can you get the right-hand side to the same place?
Answer: $$\frac{\sec x- \csc x}{\sec x + \csc x}$$  $$=\frac{\frac{1}{\cos x} - \frac{1}{\sin x}}{\frac{1}{\cos x} + \frac{1}{\sin x}}$$ $$ = \frac{\frac{\sin x}{\cos x} - 1}{\frac{\sin x}{\cos x} + 1}$$ $$ = \frac{\tan x - 1}{\tan x +1}.$$
Answer: Hint: Start by multiplying top and bottom on the left by $\sin A$.
Comment: Try the hint and see what happens, then ask another question.
Comment: @Papigrande: When you multiply $\csc A$ by $\sin A$, you will get $1$. When you multiply $\sec A$ by $\sin A$, then since $\sec A=\frac{1}{\cos A}$, you will get $\frac{\sin A}{\cos A}$, which is $\tan A$.
Comment: I did that already I the question Is do I also have to multiply cos to csc=1/sin?


Complex quadratic equation always comes out as wrong

Question: For some reason I always get the wrong answer and I don't understand why:
$$4z^2-12z+19=0$$
I got  $z= \frac{12 \pm \sqrt{260}i}{8}  $ and the answer is supposed to be $z=\frac{3 \pm \sqrt{10}i}{2} $ where is my mistake?
Comment: They are the same thing, only a factor of $4$ was cancelled.
Comment: Note that $ \sqrt{260} $ (is that is what you meant) is typeset as `\sqrt{260}` .
Answer: Your mistake is that the discriminant should be $12^2 - 4\times 4\times 19 = -160$, not $-260$, and then dividing top and bottom by $4$ gives the correct answer.
Comment: In applying the quadratic formula … it might help to divide all coefficients by the original *a* of 4 so that the *a* drops out or the adjusted *a=1* and the adjusted *b=-3* and adjusted *c=19/4* ... although it's best to keep it as simple as possible in order to minimize the likelihood of adding a mistake caused by extra cleverness … it's useful to understand the root cause of the error, eg b^2=44? rather 144 which lead to the -260 … in order to eliminate the likely missteps in one's problem-solving process.
Answer: When the $x$ coefficient is even, say $ax^2+2bx+c=0,$ there is an equivalent version of the quadratic equation which automatically cancels that extra factor of $4.$
Instead of the usual discriminant $D=b^2-4ac$ with this setup one calculates what might be called the "other" discriminant (for want of a better word) $E=b^2-ac$ as the thing under the radical. As usual if that's negative the complex number $i$ is used when square root of discriminant is taken.
Then the roots are $$\frac{-b \pm \sqrt{E}}{a}.$$
For the re-written example you have: $4z^2-2(-6)z+19=0,$ we get $E=(-6)^2-4\cdot 19=36-4\cdot 19=36-76=-40.$ Then roots are $(6 \pm \sqrt{-40})/12.$ This simplifies again in this case.
Comment: When you write "$ax^2+2bx+c=0$" and "$D=b^2-4ac$", those are two different $b$s. You should pick another letter for the first one.
Comment: @coffeemath It's not clear. The traditional discriminant would be $D = (2b)^2 - 4ac$.
Comment: @coffeemath Yes, but this answer claims that  $D = b^2 - 4ac$, which is wrong. The coefficient of the first degree term is $2b$ here, not $b$.
Comment: @A.Howells That is clear from my explanation, and is why $E$ was used for $b^2-ac$ instead of the traditional $D$ for the discriminant (when no built-in multiplier of $2$ before $x$-coefficient.
Comment: @JiK And that, divided by $4,$ is $b^2-ac.$
Comment: No, this answer claims that (more accurately, *defines*) $E=b^2-ac.$ Read it more closely. I made it clear that $D$ was the "usual" discriminant, and that $E$ was for the case of $x$ coefficient $2b$ instead of usual $b.$


error while writing file after adonis analysis

Question: I am trying to write output from permutation analysis by using below code but it shows error, could you please suggest how I can resolve this error?
R code

###adonis_calculation
BC <- phyloseq::distance(phyloseq_prop, "bray")
pmv =adonis(BC ~Season*Region, as(sample_data(physeqN3), "data.frame"),permutations = 5000)
pmv

write.table(pmv, "permutation.16s.Root.txt")

Error:

              Df SumsOfSqs MeanSqs F.Model      R2 Pr(>F)
Season          1    1.2435 1.24348  17.229 0.07405  2e-04 ***
Region          2    5.3491 2.67457  37.058 0.31855  2e-04 ***
Season:Region   2    1.3222 0.66110   9.160 0.07874  2e-04 ***
Residuals     123    8.8773 0.07217         0.52866
Total         128   16.7921                 1.00000
---

Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
  cannot coerce class '"adonis"' to a data.frame
Calls: write.table ... data.frame -> as.data.frame -> as.data.frame.default
Execution halted

Many thanks
Comment: Can you try `library(broom); write.table(tidy(pmv), "permutation.16s.Root.txt")`
Answer: The output is not in data.frame format, an option is to capture the output with capture.output
capture.output(pmv, file = "permutation.16s.Root.txt")

Using a small reproducible example
library(vegan)
data(dune)
data(dune.env)
pmv <- adonis(dune ~ Management*A1, data = dune.env)
capture.output(pmv, file  = "/Users/akrun/tmp/permutation.16s.Root.txt")

-output
Answer: The element you want is the aov.tab. You can tidy the output with broom . There are some 'NA' that can be easily eliminated.
library(broom)
fit_adonis_before$aov.tab %>% broom::tidy()

As an extra step you can print to the screen an almost ready table with formattable
library(formattable)
fit_adonis_before$aov.tab %>% broom::tidy() %>%
    formattable::formattable()


Renomear arquivos em massa a partir de uma lista do bloco de notas

Question: Preciso renomear muitas (muitas!!!) fotos dentro de algumas pastas, pra isso decidi utilizar o método os.rename dentro de um laço a partir de uma lista auxiliar no bloco de notas que contém em cada linha o nome antigo da foto, e um ponto e vírgula separando para qual é o nome novo de cada uma.
Exemplo de como está o bloco de notas:
*nomeantigo1;nomenovo1*

*nomeantigo2;nomenovo2*

*nomeantigo3;nomenovo3*

A princípio o código roda certinho substituindo os nomes, principalmente em pastas menores com poucas fotos. Mas em pastas maiores ele começa a rodar parcialmente e às vezes nem roda!
Não sei se é algum erro de lógica no loop ou de alguma permissão do sistema!
Como são muitos arquivos estou rodando o código direto no HD externo, e utilizando Python 3.6.5 no Windows 10
Meu código:
import os
import string
import re
from os import rename
from os import replace
from os import listdir

lista_principal = os.listdir('.')
arquivo = open('lista_auxiliar.txt')
sublista = [linha.strip() for linha in arquivo]
arquivo.close()

nome_antigo = list()
nome_novo = list()
nomeacoes = list()
nomeacoes_separadas = list()

for i in range(len(sublista)):
    nomeacoes.append(sublista[i].split(';'))

for i in range(len(nomeacoes)):
    if (type(nomeacoes[i]) is list):
        nomeacoes_separadas = nomeacoes[i];
        nome_antigo.append(nomeacoes_separadas[0])
        nome_novo.append(nomeacoes_separadas[1])

for nome in lista_principal:
    nome_tratado = nome.split('.jpg')
    nome_tratado_teste = str(nome_tratado[0])
    for i in range(len(nome_antigo)):
        if nome_tratado_teste == nome_antigo[i]:
            os.rename(nome, str(nome_novo[i]) + '.jpg')

Desculpem se a lógica não for muito limpa, sou iniciante em programação!
Agradeço desde já
Comment: Os nomes dos arquivos que estão nesse txt são de um mesmo diretório?
Comment: sim, estou rodando tudo no mesmo diretório!
Answer: Se entendi bem, o que você precisa fazer é apenas:
import os

with open('nomes.txt') as nomes:
    for nome in nomes:
        antigo, novo = nome.strip().split(';')
        os.rename(antigo, novo)
        print(f'Arquivo {antigo} renomeado para {novo}')

Veja funcionando no Repl.it
Isto é, percorre todas as linhas do arquivo que possui os nomes dos arquivos e renomeia um a um.
Comment: Seu código tá mais limpo e curto, mas continua dando no mesmo resultado que o meu! (o meu tratava as extensões do arquivo também)

Agora eu vi que ele para de renomear quando acha na lista um arquivo que já foi renomeado ou não está na mesma pasta, pois rodo o mesmo script e mesma lista em diversas pastas, está tudo em um só.

Saberia me dizer como faço pro laço continuar rodando mesmo depois de dar um "erro" de "arquivo X não encontrado na pasta"?


@setup vs background reference in final report

Question: The duplicate post reference helped me solve the issue, but now I see the setup being counted as a test scenario in 1.3.0. Moving to 1.3.1 has fixed that issue as well, but the @setup reference only shows on the first scenario, and no further entries, along with no background reference, but the background shows in subsequent tests. Is this expected?
Answer: Yes. The Background does not apply to the @setup as explained in the design.
And the @setup body will appear only once. It could possibly be duplicated in the report, but right now that's how it is implemented. This should normally not be a concern because the point of the @setup is to move some setup logic out of the actual business flow you are testing.
Code contributions are welcome to improve how it works.
Comment: So should the background step appear in the steps list of the first scenario item rather than just the subsequent ones, since I believe it is being executed as a part of the first run itself?
Comment: @mike opened an issue: https://github.com/karatelabs/karate/issues/2290


Menu transparente com mudança de cor ao mover o mouse

Question: Como faço o efeito do menu no topo aparecer transparente mostrando uma imagem e quando mover o mouse aparece uma barra com cor igual esse template.
Alguém poderia me dar uma dica?
Exemplo:
http://themes.semicolonweb.com/html/canvas/
Answer: Basta colocar ou não um background-color nas divs. Se vc não colocar um background na div, vai mostrar o que tem por debaixo dela. Pra colocar cor vc usa background-color (OU somente background), pra colocar imagem vc usa background-image.
Dá uma olhada nesta página e aprenda a usar fundos (backgrounds): https://www.w3schools.com/css/css_background.asp
Comment: Eu não entendi como que eu faço para quando ele subir a imagem até o topo ficar transparente e quando ele mover pra baixo ficar branco.
Comment: Então. Quando a janela está no topo da página (scroll), o elemento está sem fundo, e quando a página desce, é atribuído ao elemento um fundo branco.
Answer: Como o @DavidSamm disse, basta não atribuir uma cor de fundo ao elemento alvo, e depois ao fazer scroll definir-lhe uma cor.

var el = document.getElementById('menu'); // elemento alvo
var numPx = '250'; // Quantidade de pixels a contar do TOP até definir a cor

window.addEventListener('scroll', function() {
    if (window.scrollY > numPx) {
     el.classList.add('mudaCor'); // adiciona classe "mudaCor"
    } else {
      el.classList.remove('mudaCor'); // remove classe "mudaCor"
    }
});
html {
    background: url(https://i.stack.imgur.com/NsOce.jpg) no-repeat center center fixed;
    background-size: cover;
    font-family: sans-serif;
    color: #fff;
}
.section{height:100vh;}

/* Define o menu */
#menu {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    border-bottom: 1px solid #fff;
    transition: background-color 0.3s ease-in-out;
}

/* Nova classe a ser atribuída ao elemento com os estilos desejados */
.mudaCor{
    background-color:#fff;
    color:#000;
}
#menu .item{display:inline-block;padding:15px;}
#body-wrapper{margin-top:70px;}

Inicio

Sobre

Primeira Secção

Segunda Secção

Terceira Secção

No entanto se precisares mesmo de adicionar uma cor de fundo por alguma razão ou preferência, podes utilizar uma cor rgba qualquer e remover-lhe a opacidade toda por completo. Mas nota que também vai ser preciso adicionar um !important para sobrescrever a cor anteriormente aplicada.
#menu {
    background-color: rgba(0,0,0,0);
}
.mudaCor{
    background-color:#fff !important;
}

Exemplo ao vivo: https://jsfiddle.net/2jkupaz4/
Answer: Veja assim, criando um ul.active com background de cor diferente. Assim, você pode usar o método addClass e removeClass quando usar o scroll. Dê uma olhada se desta forma resolve pra você:

$(window).scroll(function(event){

  var yOffset = window.pageYOffset;
  var breakpoint = 50;
  if (yOffset > breakpoint){
    $("nav ul").addClass('active');
  }else{
    $("nav ul").removeClass('active');
  }

});
body{
 background:#eee;
 padding: 0;
 margin:0;
}
nav ul{
  margin-top: 0p;
  position:fixed;
  z-index:1000;
  width:100%;
  color:#333;
  list-style:none;
  -webkit-transition:.5s;
  -moz-transition:.5s;
  transition:.5s;
  font-size: 18px;
}
nav ul.active{
  background:#fff;
  color:#212121;
}
nav ul li{
  display:inline-block;
  padding:20px 30px;
}
section{
  padding:100px 50px 50px;
  line-height:140%;
}
p{
  margin-bottom:20px;
}

Jon Snow

Jack Sparrow

George Harrison

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at libero nunc. Ut nec maximus leo, et tristique lacus. Praesent condimentum eleifend gravida. Phasellus pharetra finibus sapien, in ullamcorper orci imperdiet at. Phasellus vel arcu suscipit, pellentesque massa nec, tincidunt neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus tristique nunc nec finibus commodo. In hac habitasse platea dictumst. Vivamus mattis nec lorem sed sollicitudin. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec tristique, orci a feugiat vulputate, enim risus egestas mi, ac efficitur purus est placerat justo. Vestibulum ex erat, facilisis at quam quis, euismod vehicula magna. Aliquam faucibus laoreet sapien nec vulputate. Etiam a sapien sit amet risus fermentum vehicula eu et velit.


Range validation

Question: Suppose I have a table like:
create table
{
id numeric(5,3),
code varchar(10)
}

I have two text boxes in my form for the two fields.
Suppose if I type 1234578 in the first text box the error has been thrown in ASP.NET because I crossed the limit.
How can I validate in JavaScript or some other way for that particular range validation?
Answer: Let's take one textbox only. Attach an 'onchange' event handler to your textbox like this:
<input type="text" onchange="handleChange(this);" />

Then declare a script for validation like this:

Please note that the alert pop-up used here should not be actually used. Use a more subtle reminder at a more appropriate moment. The alert here is only to make things simple.
Comment: script>  function handleChange(input) {    if (input.value > 5,3) alert ("Invalid input");  }

is it right
Comment: No, if you want the range to be within 3 and 5, use this if clause: if(input.value < 3 || input.value > 5) alert(...

Range validation


Trouble running Excel Add In macro from MS Access 2010 procedure

Question: I'm using VBA code in MS Access to export a query as an Excel workbook. I have a separate procedure that should open the workbook from MS Access and run a macro to format the workbook. The macro is stored in a separate Excel Add-In (.xlam) workbook.
My problem: I'm getting a 1004 can't run macro error, because "the macro can't be found or macros have been disabled." I tried enabling all macros in the Excel Trust Center options and I opened the Add-In workbook separately and re-ran the procedure. I'm getting the same error.
I've searched online for an answer, but I haven't found anyone who has successfully ran a macro stored in a separate Add-In workbook from a MS Access procedure. Anyone care to try and help?
Here's my MS Access procedure that's giving me problems:
 Private Sub RunExcelTrackerMacro(strFileName As String)
    Dim xl As Object
    ' Create excel app.
    Set xl = CreateObject("Excel.Application")

    ' Open workbook to be formatted via a macro.
    xl.Workbooks.Open (strFileName)
    xl.Visible = False

    ' Run the macro, stored in a separate add-in (.xlam) workbook.
    ' This procedure fails to run the public Call_FormatTracker macro, which
    ' is stored in an Add-In in a module called "MacroCalls."
    xl.Run "MacroCalls.Call_FormatTracker"

    ' Save and close the workbook.
    xl.ActiveWorkbook.Close (True)
    ' Close excel app.
    xl.Quit
    Set xl = Nothing
End Sub

Answer: What about changing the xl.Run line to something like xl.Run "Sales.xlam!Orders"
Not sure what your xlam is called, but just change to suit.
Answer: I had a similar problem running a macro in an add on. Although the addin was available when I opened Excel directly it was not when Excel was called from Access.
After you create the Excel object add the line below.
Call ReloadXLAddins(xl)

Function ReloadXLAddins(oExcel) ' As Boolean

  '  Dim CurrAddin As Excel.AddIn

For Each CurrAddin In oExcel.AddIns
    If CurrAddin.Installed Then
        CurrAddin.Installed = False
        CurrAddin.Installed = True
    End If
Next CurrAddin

End Function


how to directly open the doc page of a s4 class?

Question: Is there a way to directly open the doc page of a s4 class? for example the mle-class:
http://127.0.0.1:16875/library/stats4/html/mle.html
I have tried the followings, none seem to work:
<code>?mle-class
?`mle-class`
?"mle-class"
</code>
Answer: You must load the package first.  This does work:
<code>library(stats4)
?"mle-class"
</code>
as does these, also assuming you have done it after loading the package:
<code>?`mle-class`

class?mle
</code>
Comment: Thanks. I confirm that stats4::"mle-class" notation also works. only if I place the cursor in the class string and I press F1 in rstudio!!


Como fazer para utilizar ActionBarActivity em aplicação que rode com android 2.2 ou maior?

Question: Quero utilizar Action Bar em minha aplicação que vai rodar também em dispositivos com Android 2.2 ou maior. Sei que devo utilizar a Classe ActionBarAcitivity, que é a API disponibilizada pela Google. Já baixei o Android Support Library e Repository e importei a classe android-support-v7-appcompat. Nesta classe android-support-v7-appcompat  adicionei ao build path os .jar e adicionei estes .jar na minha classe que especializa ActionBarActivity.
Na tela principal fiz ela especializar e importar a ActionBarActivity, mas no manifest não consigo mudar do tema android:theme="@style/AppTheme" para os temas da ActionBarActivity android:theme = "@style/Theme.AppCompat.Light".
Quando tento é gerado um erro:

"Error: No resource found that matches the given name (at 'theme' with
  value '@style/Theme.AppCompat.Light').

Observações: Quando adiciono os .jars da android-support-v7-appcompat à minha classe, a classe R some.
Como fazer para utilizar a ActionBarActivity em aplicação que rode com Android 2.2 ou maior?
Comment: Dá uma olhada nesta vídeo aula. http://www.thiengo.com.br/criando-suporte-actionbar-android-com-actionbarsherlock
Answer: Após você criar um novo projecto, a melhor forma que achei no eclipse foi fazer:

Arquivo->importar->código de Android existente->navegue ate "..\sdk\extras\android\support\v7"->seleccione o directório "appCompat"->Marque a opção "Copiar para a área de Trabalho"->terminar

Após fazer isso você terá um novo projecto com o nome android-support-v7-appcompat.
De seguida va para o projeto que você quer usar a biblioteca e:

Clique o botão direito->propriedades->android->addicionar e ira aparecer o projecto que você importou acima, seleccione ele e já poderá ir ao manifest e mudar o Theme para Theme.appCompat.Light.

Se você vai trabalhar com as versões mais recentes também sugiro que você vá ao directório values/styles.xml e reescreva os themes para a ActionBarCompat e para as versões mais recentes assim:

E assim você pode posteriormente customizar os seus temas tanto para as versões mais antigas como as mais antigas.
Comment: Ta certo Paulo. sem nenhum problema eu falo o PT-pt por isso assim a escrita. Valeu ai pela corecao.
Comment: Não sei ao certo o que eu estava fazendo de errado, ontem bati cabeça de mais com isso, mas hoje pela manhã fiz todos os passos novamente, juntando as dicas do Ramaral e as suas e deu tudo certo! Obrigado Paulo!
Answer: Você para puder utilizar esse Theme tem que definir o android:targetSdkVersion no mínimo para API Level 11.
No entanto é aconselhável que android:targetSdkVersion aponte sempre para a API mais recente.
android:targetSdkVersion=19

Isto, além de resolver o problema do Theme, irá também resolver o problema do R e qualquer outros erros relacionados com No resource found that matches the given name ....
Eu também me deparei com este problema.
Quando encontrei a solução, fiz uma pergunta/resposta no SO.com
Comment: Fazendo os testes aqui ramaral, por enquanto não obtive resultados. Talvez eu tenha deixado passar algum passo da configuração. Agradeço desde já a ajuda!
Comment: Ramaral suas dicas foram de grande valia, juntei as mesmas com as dicas do paulo e deu tudo certo. Não sei ao certo o que eu estava fazendo errado ou deixando de fazer, mas hoje pela manhã refiz todos os passos e obtive êxito. Obrigado mais uma vez Ramaral =)
Answer: Use a biblioteca ActionBarSherlock:.
ActionBarSherlock
Comment: Obrigado Carlos, mas consegui com a AppCompat mesmo!


Is every subspace of a infinite-dimensional vector space an intersection of hyperspaces?

Question: The corollary below is from Hoffman and Kunze's book, Linear Algebra.

Corollary. If $W$ is a $k$-dimensional subspace of an $n$-dimensional vector space $V$, then $W$ is the intersection of
  $(n-k)$ hyperspaces in $V$.

In the proof, they find $n-k$ linear functionals $f_{i}$ such that $W=\cap_{i=1}^{n-k}\ker (f_{i})$.
I want to know if the following is true: For all proper subspace $W$ of a infinite-dimensional vector space $V$ there are a set of linear functionals $\{f_{i}|i\in I\}$, where $I$ is a set of index such that $W=\cap_{i\in I}\ker (f_{i})$.
Thanks for your kindly help.
Comment: *hyperspaces* should be *hyperplanes* all over the place, no?
Comment: @MarianoSuárez-Alvarez: Yes!
Comment: I have a doubt, what about the converse of the lemma? Can you give hints?
Answer: Let $(w_i)_{i\in I}$ be a Hamel basis of $W$. Extended this basis to a basis of $V$, let us call it $(w_i)_{i\in I}\cup (v_j)_{j\in J}$. Now for each $j\in J$ defined $f_j(v_j)=1$ and zero elsewhere. It follows that $W=\bigcap_{j\in J} ker(f_j)$.
If you are interested in normed vector space then $W$ need to be a closed subspace and you can mimic the proof using Hahn-Banach.
Comment: You mean, if $W$ is a closed subspace of a normed vector space, the functionals can be chosen to be continuous.
Comment: Is $W \subset ker(f_i)$ also?
Answer: Yes.  For every $x \notin W$, there is a linear functional $f_x$ on $V$ such that $f_x = 0$ on $W$ and $f_x(x) \ne 0$.  Then $W = \bigcap_{x \notin W} \text{ker}(f_x)$.
Comment: Certainly not $=$ unless $\text{dim}(V/W) = 1$.
Comment: Yes, it does apply.  If $g$ is a linear functional on $V$ and $g(u) \ne 0$, then $\ker(g) + \text{span}(u) = V$.
Comment: Would this also prove that there exists a family of linear functionals $\{g_i\}$ such that $\text{ker} (g_i) = W$?
Comment: Does that apply in this case where the dimensions are infinite?
Comment: Thank you very much for your comments in this (old) post. Imagine that $V$ was uncountably infinite dimensional. Then, for a non-zero linear functional $g$, since $\text{dim}(V/\text{ker}(g))=1$, $\text{dim}(\text{ker}(g))$ must be also uncountable infinite. But $\text{dim}(\text{span}(u))$ must also de infinite, right?
Comment: No, of course not:  $u$ is a single vector, its span is one-dimensional.
Answer: The linear functionals on $V$ which are zero on every element of $W$ are precisely the linear functionals on the quotient $V/W$. So the question reduces to the case that $W = 0$, which follows by the axiom of choice because $V/W$ has a basis.
Without the axiom of choice, the result can be false. For example, it's consistent with ZF that the vector space $\prod_{i=1}^{\infty} \mathbb{R} / \bigoplus_{i=1}^{\infty} \mathbb{R}$ has no nonzero linear functionals on it (see this MO question).


Unity vs Udk vs CryEngine

Question: Which is the best to learn? What are there advantages and disadvantages?
Comment: Unity3d is now, probably, let's say ... 500 times? more popularly used than the other two.  if you want to work, learn Unity first.
Answer: In my experience, UDK is the easiest to learn with its fantastic UnrealScript where pretty much any environment variable can be controlled. It also is the most powerful with complemented tools with superb Autodesk 3ds Max / Maya integration. UDK is free by the way.
Unity is based on Mono which provides C# as the scripting language. If you know C# and want to have the absolute power of Visual Studio, Unity will fit the bill. On the other hand, Unity is not free.
CryEngine is the most fascinating of all in terms of graphics and it is bundled with a superb environment editor. On the other hand it is the most expensive of all. Plus it may not be extendable as UDK or Unity, especially if you want to use it in visualization.
Comment: UDK is free to play around with but for a commercial project you need to buy a license or a mix of a license+royality.

With Unity3D on the other hand you do have a free version and paid (Pro) version. Now free version of Unity3D is not restricted on how you can use - so you can use it for commercial projects. The Pro version is also quite cheap (compared to UDK license).

CryEngine is quite extendable, given you have the right license (again). But it is as you mentioned quite over the top in price.
Comment: and just as an update of the current situation, Unity "Personal Ed" is free if you (or your game dev company) make less than $100K per year. Unity Pro currently costs about $75/month as a service (they will stop providing updates to non-service licenses on March 3, 2017, as they want everyone on that service I guess). On another hand UDK is completely free until you start making $3000 (or more) per quarter revenue from your game, at which point the software costs 5% of that revenue. CryEngine on another hand is offered on "pay as much as you want" basis.
Comment: My personal opinion as someone just fresh into looking at a 3d engine is that crytek is the current best option but the other two are great as well with minor issues here and there.

Unity vs Udk vs CryEngine


defining typed constant numbers in C/C++

Question: In C/C++, is there a difference between saying (1U) vs. ((unsigned int)1) ? I prefer the second one, but I am concerned that the second one may be type-cast at run time (i.e. extra cpu cycles), whereas the first one gets the correct type at compilation. Thanks.
Comment: Even if it makes any difference, it would be optimized at compile-time by just about every modern compiler.
Comment: I am curios what instructions you think are used to covert int(1) to unsigned int(1).
Comment: I'm sure there are some technical differences, but no practical ones.
Answer: They're not equivalent. 1U is valid in #if preprocessing directives. (unsigned int)1 is a syntax error at the preprocessor level. You could however make it (unsigned)+1 and it would be valid in the preprocessor, but only because of an obscure rule few people know..
Comment: 'Pre-processor numbers' are plain weird!  ISO/IEC 9899:1999, §6.4.8 _Preprocessing numbers_ defines the syntax as (pipes indicating newlines):  `pp-number: digit | . digit | pp-number digit | pp-number identifier-nondigit | pp-number e sign | pp-number E sign | pp-number p sign | pp-number P sign | pp-number .`

That means a _pp-number_ can contain all sorts of alpha characters.

The `(unsigned)` is (probably) not defined as a number, so it gets translated to 0, and `(0)+1` is valid as an integer - though probably not as an unsigned value despite appearances to the contrary.
Comment: Good point about it not being unsigned. How does signedness work at the PP level anyway? All arithmetic takes place as if in a max-size integer type, but what about signed/unsigned comparison issues, overflow/wrapping of huge values, etc.?
Comment: Looking at §6.10.1 _Conditional inclusion_, ¶3: _After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers are replaced with the pp-number
0, and then each preprocessing token is converted into a token. The resulting tokens
compose the controlling constant expression which is evaluated according to the rules of
6.6, except that all signed integer types and all unsigned integer types act as if they have
the same representation as, respectively, the types `intmax_t` and `uintmax_t` defined
in the header ``._
Answer: I think you have it right.
(1U) I suspect will be recognised by the compiler's lexical analysis as "unsigned" while (unsigned int)1 will be a runtime operation.
As the comments say, chances are it will be optimised out for you anyway.
As a general rule, don't try to out think the compiler. Do what looks most readable to you and worry about performance optimization once it becomes clear you have a problem.
I can guarantee* this will never actually cause you a problem.
*guarantee void on days ending with a Y.
Comment: The chances of `(unsigned int)1` being a runtime operation are essentially nil, even in the least optimizing of non-optimizing compilers.
Answer: 11 characters. Otherwise, they are equivalent.


Hosting DHCP/PXE server on windows embedded

Question: I am trying to boot a device through pxe, this device is connected to a windows embedded 8 (industry/standard) host pc.
It should be possible I think and searches point me in the direction to using WDS. I just cant seem to find any references talking about running WDS on windows embedded.
I have included the modules for dhcp server and internet connection sharing in the image configuration editor. But I cannot find any configuration options for it.
If I run netsh in a cmd window it only gives me the command for dhcpclient, not dhcp (server).
Can anybody point me in the right direction?
Ow, and as a side note, I dont want to use any 3rd party dhcp server software.
Edit:
It is acceptable to use other versions of windows embedded if they do support this feature. But I am convinced it should be able to work on the latest generation of Windows Embedded
Comment: you might need to re-evaluate your goals and available means. I'm all for solving puzzles, but somewhere lines need to be drawn on what's possible
Comment: maybe using ICS? https://social.msdn.microsoft.com/Forums/office/en-US/b4338ff8-667b-4b92-ad9c-2d22a8a2e565/dhcp-server-on-wes7 I would not hold my breath. If you need a dhcp server and budget is a problem, a rasperry pi would work pretty well with dnsmasq.
Comment: I saw that link, but that only gets me part way there. I can share the connection and as a result the 2nd unit get an IP as if the 1st unit acts as a DHCP, but there ar no configuration options, let alone supplying PXE (or WDS) boot services over that DHCP. Ow and budget is not the issue, there are other constrains that prevent me from using something like pi :(
Answer: Unfortunately WDS is unavailable as a service to run from Windows Embedded. To get WDS on on your hardware you will have to run any version of Windows server from 2008 and up. Windows server 2003 has RIS which is for older OS (E.G. XP 200, etc...)
To answer your question, The only way to make your Windows Embedded system a PXE server is to run 3rd party tools. And if your going to run 3rd party tools and only use your hardware as a PXE server, then I would recommend Linux.

Links:
WDS - https://en.wikipedia.org/wiki/Windows_Deployment_Services
Windows Embedded - https://en.wikipedia.org/wiki/Windows_Embedded
Ubuntu Server -https://en.wikipedia.org/wiki/Ubuntu_(operating_system)#Ubuntu_Server
Ubuntu server PXE - https://help.ubuntu.com/community/PXEInstallServer

TL;DR:
No WDS on Win Embedded. Use Win Server for WDS. If you want to deploy older OSs (E.G. XP) or non MS OSs try Linux (E.G. Ubuntu Server).
Comment: Yeah unfortunately I am coming to the same conclusion. I do really need windows for the software that I have to run on it. And I really need Embedded for the UWF. But thanks for the assurance that It is infact not possible to combine those 2 features.
Comment: @Daanvl What are you running on your embedded system that needs windows?
Comment: Touch screen user interface application. With a healthy but large chunk of c# based code that took years to make.
Comment: @Daanvl Oh, ok. Why would you run a server on a system that people have access to? (no judgement, just wondering why)
Comment: well it is a composite system with multiple cpu boards, one for linux (because hardware) and one for windows (user interactions) But only space for 1 harddrive. so that is why i have the requirements for embedded plus server in one :P I am now trying to make it work with 3rd party pxe server software (serva)
"edit": ow and the hdd has to be on the windows side cus the (physical) space on the linux side is filled with hardware specific stuff
Comment: @Daanvl I just finished making my `Raspberry Pi 2` a pxe server. It boots `WIM` files like it is nobodies business. You can even have multiple bootable images in one `wim` using linux (storage space savings). I would recommend linux if you do not have WDS available. A `Raspberry Pi 2` is $35. The SD card (storage) can be big or small, it is up to you. I have tried `serva` out. It did not work for me. Although that was a while ago. They might have fixed their issues. Check out `wimboot`, a `pxelinux` compatible module.


Criar botões dinamicamente

Question: Estou fazendo uma tela onde cadastro alguns usuários. Nessa tela, tenho um ScrollView com um Gridlayout dentro, com 2 colunas. Cada coluna tem 1 botão, que ao clicar, abre um link, no caso, do Youtube.
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <Button
            android:layout_width="0dp"
            android:layout_height="90dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@drawable/bg_button"
            android:text="DemonDies"
            android:onClick="demondies"
            android:textColor="@color/textColorPrimary"
            android:id="@+id/demondies" />...

Aí no JAVA faço o resto:
 Button demondies,...
 demondies = (Button) view.findViewById(R.id.demondies);

demondies.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Uri uri = Uri.parse("https://www.youtube.com/channel/UCEWQoXe934RcJr04efPm9OQ");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });...

Até aí blz, só que agora tá começando a ter muitos botões, e tá ficando meio difícil de continuar criando botão assim. Teria um jeito de criar botões dinamicamente, recuperando o nome e url do link do banco de dados ou algo parecido?
Ia adicionar a imagem aqui pra ver como é o layout, mas ela fica muito grande.
Edit
O layout fica assim:
https://i.stack.imgur.com/Can2o.jpg
Comment: O uso de uma ListView não resolveria o problema?
Comment: Recycler View...
Comment: posta a foto num site de hospedagem de fotos
Comment: Edit: postei a imagem.
Comment: Como fazer botões clicáveis num listview?
Comment: Você vai ter que fazer uma listView customizada. Basicamente, você terá um xml que representará um único item da lista e terá também uma classe adaptadora que terá de receber uma lista de Strings com os nomes dos botões e também será a responsável por vincular os dados dessa lista de Strings nos botões que aparecem nas telas. Aguarde que posto o código.
Comment: entendi, faço isso com um listview de imagens atualmente, se tiver como fazer com botões, ótimo
Comment: Imagens voce usa ImageView no xml. Buttons é só usar Button no xml... É o mesmo princípio; só muda a aparencia do widget.
Comment: Mais fácil do que a ListView acredito que seja você usar o GridView. https://developer.android.com/guide/topics/ui/layout/gridview.html
Comment: O que você quer é pegar vários dados (URL, nome, etc) e criar os botões automaticamente, correto? Tem sim, primeiramente precisa puxar os dados de algum lugar (sqlite, banco remoto, webservice, json, etc) e rodar um script para isso. Já vi isso uma vez. Vou ver se acho e posto. Mas para te adiantar, tem sim como fazer.
Comment: Essa é uma pergunta parecida que fiz, e ainda não testei: [Pegar valores de EditText gerados programaticamente](https://pt.stackoverflow.com/questions/243338/pegar-valores-de-edittext-gerados-programaticamente) ... Dá para tirar uma ideia creio eu.
Answer: voce pode criar um layout para os botoes:
Arquivo btn_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button
   android:layout_width="0dp"
   android:layout_height="90dp"
   android:layout_columnWeight="1"
   android:gravity="center"
   android:layout_gravity="fill_horizontal"
   android:background="@drawable/bg_button"
   android:text="DemonDies"
   android:onClick="demondies"
   android:textColor="@color/textColorPrimary"
   android:id="@+id/demondies"
</Button>

Criar um adapter para esse button.
Arquivo GridButtonsAdapter.java:
public class GridButtonsAdapter extends BaseAdapter {
    private ArrayList<String> list;

    @Override
    publc int getCount() {
        return list.size;
    }

    @Override
    public String getItem(position: int) {
        return list[position];
    }

    @Override
    public long getItemId(position: int) {
        return (long)position;
    }

    private Context mContext;
    GridButtonsAdapter(Context context, ArrayList<String> btnsNames) {
        this.mContext = context;
        this.list = btnsNames;
    }

    @SuppressLint("ViewHolder")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate o view personalizado
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Button itemLayout = (LinearLayout) inflater.inflate(R.layout.btn_layout, null);

        Button cellBtn = itemLayout.findViewById<View>(R.id.demondies);

        String name = list[position]

        cellBtn.setText(name)
        cellBtn.tag(name)
        return row
    }
}

depois, na sua activity principal voce monta o adapter
//...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    // criar o metodo para preencher a sua lista de urls para o itemclick
    ArrayList<String> urlList = pegaSuaListaDeUrlsDoSeuDatabase();
    // criar o metodo para preencher a sua lista de nomes do seu database
    // voce pode criar um metodo void e criar esses dois campos no escopo
    // da classe e preencher os dois campos num unico metodo void onde
    // voce pega os valores para os nomes e para as urls, assim, simplifica
    // e diminui o codigo
    ArrayList<String> btnsNamesList = pegaSuaListaDeNomesDoSeuDatabase();
    // monta o adapter para a sua GridView
    GridLayout gridbtns = findViewById(R.id.suagrid);
    GridButtonsAdapter mAdapter = new GridButtonsAdapter(this, btnsNamesList);
    // cria um listener para o onItemClick de cada button dentro do adapter
    AdapterView.OnItemClickListener listener = (arg0, arg1, position, id) -> {
        // aqui voce pega um determinado item da lista de urls
        Uri uri = Uri.parse(urlList.get(position));
        // e passa ela para o intent
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    };
    // passa o listener paa o click do adapter
    gridbtns.setOnItemClickListener(listener);
    // passa o adapter para a grid
    gridbtns.setAdapter(mAdapter);
}

assim, voce vai conseguir criar seus botoes dinamicamente.
Logicamente, isso é apenas um exemplo.
Espero que te ajude

Criar botões dinamicamente


Rewriting simple directory looping C sharp code in vbscript?

Question: I need to rewrite the following C sharp code in a language that does not require .NET due to such a wide spread of windows versions and .NET installations in our environment. I was thinking maybe VBScript, but I don't know how easily this would port over?
        try
        {
            string docsDir = Environment.GetFolderPath(Environment.SpecialFolder.Mydocuments);

            if (Directory.Exists(docsDir))
            {
                // get all folders
                DirectoryInfo dInfo = new DirectoryInfo(docsDir);
                DirectoryInfo[] dirs = dInfo.GetDirectories();

                // start process
                Process p = new Process();
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = "cmd.exe";
                info.RedirectStandardInput = true;
                info.RedirectStandardOutput = false;
                info.CreateNoWindow = true;
                info.UseShellExecute = false;

                p.StartInfo = info;
                p.Start();

                using (StreamWriter sw = p.StandardInput)
                {
                    if (sw.BaseStream.CanWrite)
                    {
                        foreach (DirectoryInfo dir in dirs)
                        {
                            sw.WriteLine("FixPerms.exe" + dir.Name);
                        }
                    }
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

Comment: Just a thought: can you maybe downgrade it to .NET 2.0 or even lower (to leverage fact, that usually machines with newer .NET can still run old code)? Or do you have some machines that don't have .NET at all?
Comment: What is your question? How easy is it to port over? This looks very simple...you can do it in batch/.cmd pretty easily.
Comment: @Gerino Unfortunately some machines do not have it installed at all, while others are running Windows 8 so will only (by default) run .NET 4.5 code.
Comment: @RufusL I'm trying to hide the process from view as it may take some time to complete and I dont want a cmd window open while it runs. I thought one of the native windows scripts might be best in this case, but I do not know whether you can use them to 'stream' commands to cmd.exe like in my code above.
Comment: you mean like (in a .bat file): `start /min cmd.exe ...`?
Answer: If you are asking for a simple vbscript solution, this might help
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(server.mappath(path))
Set sf = f.SubFolders
for each fo in sf

Do Something
next

Answer: This should do the trick using a .cmd (or .bat) file, and should work on any windows system:
@ECHO OFF
SETLOCAL

:: Set exit code to a failure code
SET /A EXITCODE=-1

:: Get the MyDocuments Folder
FOR /F "skip=2 tokens=3" %%A IN ('REG.exe query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Personal"') DO (
    CALL :SetDocuments %%A
)

:: If MyDocuments doesn't exist, exit
IF NOT EXIST "%MyDocuments%" GOTO :END

:: Run the FixPerms.exe tool on each directory
FOR /F "tokens=*" %%A IN ('DIR /B /AD "%MyDocuments%"') DO (
    CALL :RunProgramOnDirectory %%A
)

:: Set exit code to success
SET /A EXITCODE=0

:END
ENDLOCAL&EXIT /B %EXITCODE%

:SetDocuments
SET MyDocuments=%*
GOTO :EOF

:RunProgramOnDirectory
SET directoryName=%*
START /MIN CMD.exe /C FixPerms.exe "%directoryName%"
GOTO :EOF

Comment: Anyone know how I set the coloring for my code sample for .bat/.cmd?


How can I make window movement commands ignore a certain window?

Question: So I generally have 3 buffers open in Emacs.

One buffer for the actual code I am writing.
One buffer for the unit test for said code.
A third buffer that displays the results of the unit test. This buffer comes into being
below the two other buffers when I run my unit test C-x SPACE.

How do I disable this third buffer such that when I press C-x o I am only switching between buffer 1 and buffer 2? Currently, I switch between buffer 1, then buffer 2, then buffer 3, then buffer 1, etc. To be specific, I want C-x o to only switch between buffer 1 and 2.
Thank you.
Comment: window-number-mode is good for this.
Comment: Not an answer but a workaround that might help you: http://stackoverflow.com/questions/91071/emacs-switch-active-window
Comment: It sounds like you're asking to skip a *window* when it contains a particular buffer you don't want to switch into.  Correct?
Comment: Stephen, may I suggest you update the title and question to put window instead of buffer ? buffer/window/frame have a specific meaning in emacs: Frame is the equivalent of what a windows manager calls a window (the enclosure you can generally move around). window is what you're referring to: a subset of the frame that shows some text. a buffer is what represents the actual content shown. It's generally identified by a name, that shows in the modeline. You can show the same buffer on 2 windows, e.g.
Comment: Using smarter movement commands is also a good strategy; see http://github.com/jrockway/elisp/blob/master/_local/term-extras.el for example.
Comment: Ok, I will switch it to buffer.
Answer: A general solution to this (can look) something like the following:
(defvar ignore-windows-containing-buffers-matching-res '("\\*Help")
      "List of regular expressions specifying windows to skip (if window contains buffer that matches, skip)")

(defadvice other-window (before other-window-ignore-windows-containing activate)
  "skip over windows containing buffers which match regular expressions in 'ignore-windows-containing-buffers-matching-res"
  (if (and (= 1 (ad-get-arg 0)) (interactive-p))
      (let* ((win (next-window))
             (bname (buffer-name (window-buffer win))))
        (when (some 'identity (mapcar '(lambda (re)
                                        (string-match re bname))
                                     ignore-windows-containing-buffers-matching-res))
          (ad-set-arg 0 2)))))

Customize the variable to be a regular expression matching the buffer names you want to skip.
Comment: I copied this into my .emacs file. I then just replaced "*Help" with "*Ruby-Test*" (which was the name of the buffer that the ruby test were being run within). Now when I switch buffers, it only switches between buffer 1 and 2. Seems like a good solution. Thanks.
Answer: Trey's answer will do exactly what you want (at least it looks like it will; I haven't tried it).  A more generic solution would be to use swbuff with either swbuff-x or my own swbuff-advice.  Info about all three can be found on the Emacs Wiki swbuff page.


Trouble understanding two accidentals in Chopin's Nocturne Op 9 No 2

Question: I'm having trouble understanding the 2nd bar of Nocturne Opus 9, No.2. I'm still learning sheet music so I'm finding a certain section confusing; maybe I don't understand the music correctly.
The image below has a red arrow pointing to the section I don't understand.
The bass clef tells me to play F D Flat followed by B Flat D E. You can clearly see that the accidental on the D note is a flat, followed by a natural accidental cancelling the previous flat. However it doesn't sound correct, and every video I watch its played F D Flat followed by B Flat D Flat E, which sounds correct. To make it worse I find other versions of the sheet that doesn't have the natural accidental, so maybe the sheet music I have is wrong. I'm really confused, can anyone help me out? Thanks.
Comment: I'm voting to close this question because the image on which this question fundamentally depends is no longer available.
Comment: Don't you mean e flat, not e?
Comment: No, the E Flat denoted in the key signature is cancelled out by the E at the start of that bar.
Comment: The harmony repeats about 12 bars later.  What do you have there?
Answer: The second chord is definitely B♭ D♭ E, functioning as an applied (or "secondary") chord to the Fm in the next beat.
Considering the program that was used to transcribe this piece, it's just an error by the person that input the music. It should be a courtesy accidental on the E, but the individual misread it and put the accidental on the D instead.
Comment: "Considering the program that was used" - looks like an old version of Lilypond, from the shape of the treble clef. In that case, the user forgot that the second D really was a flat when typing the input, and didn't bother didn't look too hard at the output. The engraving quality of whole of the OP's image is fairly atrocious, apart from the typo. I agree a courtesy E natural, to prevent the misreading of an Eb7 chord Bb Db Eb, might have been intended.
Comment: Thanks, I'm guessing it was an error too. I'm new to sheet music, and self taught, so I thought I was interpreting the music wrong initially.  Lesson learned, don't use free sheet music off the internet.
Comment: It is definitely a mistake. Apart from the fact that a d natural here sounds bizarre, I own an Urtext edition which simply has the natural sign in front of the e instead of the d.
Comment: @alephzero Precisely my thought process; it's almost definitely a LilyPond input error.
Comment: In the [change history](https://www.mutopiaproject.org/ftp/ChopinFF/O9/chopin_nocturne_op9_n2/chopin_nocturne_op9_n2.log) for this score on the Mutopia Project, there is a wrong chord cited in m. 2 that is corrected in m. 6. This was corrected in 2014.
Answer: Difficult to say: the first edition (here) has what looks like a flat in front of the E, not a natural in front of the D, but there are signs that it was jammed in at the last moment, and there is a stroke that seems to indicate that an attempt was made to convert it into a natural sign on E. Mikuli's edition has no accidentals on that chord at all. Mikuli was Chopin's pupil and, later, assistant, so that is a fairly good indication.
Answer: I've looked a couple of websites and Paderewski's edition; all have no marking for that chord. Editions of Chopin's music are not as accurate as one would like. I did find a version arranged for clarinet and piano which has a Db.
I don't see (at a short glance, by a real amateur) any harmonic reason for a D there rather than a Db. I'm guessing the overall harmony in the second half of the measure is a Bb chord so a Db would be indicated. A D might have been meant if there were an ascending chromatic line; using a D would only give 3 notes C-Db-D and that's probably not enough to be important. There is a Bb-B-C-A pattern in the next bar. Had there been a Bb in the marked measure, there would be more of an argument for the D.
Comment: Thanks, its free sheet music I pulled offline. I have checked a few other versions too, some missing the accidental, I'm going to assume the sheet music is wrong and find another version.
Comment: Schirmer's 1881 edition (ed. Th. Kullak) also has D flat, with a courtesy natural before the E. Same in b.6, 14, 22. Likewise Augener's and Peters's editions.


Link to images(thumb) in a (block)view to the image(original) in another (page)view

Question: I have a  unlimited multivalue field image gallery.
Using views i created a page for file entity and got the list of files in the field. The page displays the default original images one by one with a pager.
Created a block for the same view with the files shown as thumbnails, so the user can view all images in the gallery and click on the image he/she wants to see. I can link the thumbnails to content or file which takes me to the original file.
Is it possible i can link them to the corresponding image in the page view.
Answer: In your block view, if the "Link image to " option doesn't give you what you need for the thumbnail image field, you can build your own link using "Rewrite Results". You would do something like this:

Add content:path or nid to your view, and exclude from display
Make sure content:path or nid is first in you list of fields
For the thumbnail image field, enable "Output this field as a link " under Rewrite Results
use the token for nid or content:path (i.e. [path]) to construct the link you need

Note: if you use content:path, you will probably want to enable "Use absolute path" for it's field settings, even though it is excluded from display.
Comment: Hey Dave, Thanks for your time. The view is a list of files not content so i'm not getting nid or content:path only file:path also i want the image file in the block view to link to the image file in the page view. Basically am looking to create a gallery like imdb site.[Ref here](http://www.imdb.com/title/tt0429493/mediaindex).
Comment: Right. You did mention that these were file entities, and I also somehow missed the views and pager part :) I'm not sure this would be a good solution, but assuming both views show the same content in the same order, then you could add a counter to the block view and construct a link (using rewrite results) to the paged view, something like: viewpath/?page=[counter].
Comment: No luck..looks i need to learn more about file entities. For now am going with nodes like you answered. Giving a vote up. :) Thanks.


How important is a teacher / tutor?

Question: I am doing fine in my classes and enjoy math. That is not the issue.
During my spare time, I am doing more advanced stuff than my class is currently doing. My question is though, would I benefit more from a tutor / teacher in learning stuff outside the current classes I am taking or is learning on my own the superior?
Especially since I am content with my current school marks and more interested in stuff outside the curriculum, I do not see a reason to pay substantial amounts of money for a tutor as it is more pleasure than work to me. But, would a tutor be of much benefit in this case? Would I have a hard time finding a teacher / tutor that would help me learn more advanced stuff without breaking the bank?
I should note I am still in high school. As such, most tutors in my area cater towards just showing people the stuff they need to pass final exams. I wish to know more than just cookie cutter explanations, where should I be looking for tutors if I choose to get one?
I guess one reason I ask is in Robert Greene's book "Mastery", he puts a heavy emphasis on the apprenticeship phase and how many "Masters" had someone teaching and devoting significant time to them along the way.
Comment: I don't have time to write a whole answer, so I'm just leaving a comment: In general, a tutor isn't really necessary for a lot of math.  It really does help to have someone who will look over proofs when you start writing those, but a lot of people on this site will do so... (so long as you don't swamp us with a lot of "check my proof" requests. `:)`)
Comment: It sounds to me like you don't have any particular area that you wish to explore. I'd encourage you to work on some of the problems on [Brilliant.org](https://brilliant.org/), and see if there are any particular areas in which you are interested in further study. That will also help guide you in finding a suitable mentor.
Comment: I have never heard of that website before, thanks for that!
Answer: Most people find some stuff pretty hard to study in their own, and having a tutor with knowledge and experience can't be bad. That's one of the main didactic reasons universities exist, otherwise most people would simply "learn on their own".
Anyway, as you advance in your studies, you'll find it easier to study and learn new stuff on your own.
Comment: I should of noted I am still in high school.
Comment: I think this only reinforces my point. @nitrous2...though I think it's always a good idea to try to learn new stuff by your own.
Answer: I think that the teacher problem has many sides but now you are interested only in some of them. :-)
For me the learning strategy (mainly) depends on seeker's or student's skill. I think that sooner or later you should find a good teacher free of charge and I wish you good luck at your way. :-D
I try to illustrate my ideas by my own mathematical way. By the way, :-)  you can overview it in my profile.
Personally I never had a tutor, never paid to teachers and I had the opposite problem: to free myself from the classes. :-) But I was powerful – I was one of the first students in my country in school math competitions.
But even already in my high school my school teacher,  Volodymyr Prokip said to us that if anybody wants to know a subject deeper, then catch me, grasp my button and ask. :-) I remember as we were walking together along some kilometers from the school and were talking about matrices. :-) Now we are working in one institute and his room is placed in a couple of steps from mine. :-)
Personally I think that a bad teacher tries to find followers, but a good teacher shares with you his methods and strategies which you can use for solving you own problems. :-) I was lucky to find good teachers in my university (but, despite I think that the teachers from my university are good mathematicians, I still avoided the classes, :-) because their level was too low for me and the curriculum was bounded). I am grateful to prof. Taras Banakh (who is now my scientific consultant for the "Doktor of Science" thesis), under the influence of which I was fathomed into the idea to understand instead of selecting through methods, as  jimmies, searching which of them can solve a problem. Banakh is still followed by apprentices observing his work and able to learn from the method «do as I». :-) Also I am grateful to my scientific advisor for my "Kandidat of Science" (PhD) thesis, dr. Igor Y. Guran. When I was working for the thesis, we tried to solve his mathematical problems, using my powers and his experience.  I.Y. recommended to me directions of development, helps me with advices and as a reference book. :-) And he still does these. For instance, recently I sent to him my «The referee confession». :-)
Further, there should be scientific mathematical schools consisting of teachers, masters and their disciples and apprentices. For instance, I am a mathematician from Lviv topological school, which has the genealogy going through Karl Weierstraß and Carl Gauss to 17th century. :-) And the line of the school is to be fathomed by a seeker.
Answer: The answer to your question depends very much on you.  Some people (including me) learn well in isolation.  Even if someone explains something to me, I often have to go away later by myself to review it and make sure of the details.  Other people (and I think they're the majority) learn better by interacting with others --- possibly teachers or tutors, possibly fellow students learning the same material.  Obviously, the answer to your question depends on which of these learning styles is yours.  If I had to guess, I'd guess the second, simply on statistical grounds; as I said, there seem to be more people of the second sort than of the first.  But you have lots of knowledge about your own learning style and can surely make a more informed guess than I can.
On another matter, raised in earlier comments, in my experience, university professors are generally willing to help sincere, intelligent students even if they are not enrolled in classes.  Of course, there are limits; I can't spend all day answering everybody's sincere, intelligent questions (though it might be more enjoyable than some of my real work), but I'm certainly willing to do it in moderation, and I think the same goes for most of my colleagues.
Answer: I think when you start studying a topic, a teacher will benefit you but once you get into it, self-study will become much easier as you would have the basic concepts covered.
Answer: I think it very much depends on the style of learning that suits you. I was very impatient when I studied high school and university and I couldn't listen to teachers. That's why for me, books were the best. But some people had problems reading and understanding books, and they indeed appreciated tutors.
I'd say try books first. There is a plenty of resources online nowadays, like this site. If you find that you don't understand something, ask your teacher. If that is not enough, maybe try a friendly university professor. If you are really into math, they won't send you away.
I don't know how it works in your country/school, but my university lectures are open to everyone. My math teacher at my elementary school (I studied in math class) was very much open to any extra lessons in breaks.
Also math competitions are a great place to meet friendly teachers who are willing to spend time with talented students. There are plenty of them in Cadana as well.
Comment: Canada, unfortunately not a free system here.
Comment: Could someone else confirm that? "try a friendly university professor. If you are really into math, they won't send you away." Especially since I am still in High school I fear most places wouldn't take me seriously unless I attended.
Comment: My country's education system is free for every citizen. Where do you study?
Comment: Do you have math competitions? That was a great place to meet friendly teachers who would spend extra time with talented students (no need to answer, this is just a comment :))
Comment: @nitrous2: In a reasonably large mathematics department you do stand a good chance of finding someone who'd be willing to work with an interested high school student, at least to the extent of being available to help out when you get stuck.
Comment: Truthfully I haven't explored that much. Thanks for the tip.
Comment: I have added a list of math competitions in Canada to my answer. I used to attend our version of Math Olympiad, Kangaroo (international) and something we called Math League. All of them very helpful. Actually teacher would take time to prepare me for the competition.

How important is a teacher / tutor?


Gram-Schmidt Procedure from "Linear Algebra Done Right"

Question: The following content is from "Linear Algebra Done Right" book by Sheldon Axler, 6.31.
There was a part of the proof what I don't understand is that
$\begin{align*}
\left\langle e_j, e_k\right\rangle &= \left\langle\frac{v_j - \left\langle v_j, e_1\right\rangle e_1 - ...... - \left\langle v_j, e_{j-1}\right\rangle e_{j-1}}{||v_j - \left\langle v_j, e_1\right\rangle e_1 - ... - \left\langle v_j, e_{j-1}\right\rangle e_{j-1}||}, e_k\right\rangle\\ &= \frac{\left\langle v_j, e_k\right\rangle  - \left\langle v_j, e_k\right\rangle }{||v_j - \left\langle v_j, e_1\right\rangle e_1 - ... - \left\langle v_j, e_{j-1}\right\rangle e_{j-1}||}\\
&= 0
\end{align*}$
How did he got from the first equation into the second equation?
Comment: I'm guessing the basis $\{e_i\}_i$ is orthonormal? First use the fact that the inner product $\langle \cdot, \cdot \rangle$ is bilinear to distribute it to each term in that sum. Then use that $\langle e_i, e_j \rangle = 0$ if $i \neq j$ and $1$ if $i=j$.
Answer: The inner product is bi-linear. This basically means that it can distribute across its inputs. For the purpose of my answer I am going to assume you are working in a real vector space; if the space is complex then the modifications necessary are very minor.
The bi-linearity of the inner product means that the following holds.
$$ \langle a V_1 + b V_2, c U_1 + d U_2 \rangle = ac \langle V_1, U_2\rangle + ad \langle V_2, U_1 \rangle + bc \langle V_2, U_1 \rangle + bd \langle V_2, U_2 \rangle$$
If your vector space is complex, then some of these coefficients will be complex conjugated.
Lets apply this identity to your problem.
$$\langle e_j, e_k \rangle = \Big\langle \frac{v_j - \langle v_j, e_1 \rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1}}{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}, e_k\Big\rangle$$
$$= \frac{\Big\langle v_j - \langle v_j, e_1 \rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1}, e_k\Big\rangle}{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
$$= \frac{\Big\langle v_j, e_k\Big\rangle - \langle v_j, e_1 \rangle \Big\langle e_1, e_k\Big\rangle - \dots - \langle v_j, e_{k}\rangle \Big\langle e_{k}, e_k\Big\rangle \dots- \langle v_j, e_{j-1}\rangle \Big\langle e_{j-1}, e_k\Big\rangle}{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
By construction the basis vectors $e_1 \dots e_k \dots e_{j-1}$ are ortho-normal. This means that $\langle e_i, e_k \rangle = 0$ when $i \neq k$ and $\langle e_k, e_k \rangle = 1$ for $1\leq i \leq j-1$.
$$= \frac{\Big\langle v_j, e_k\Big\rangle - \langle v_j, e_1 \rangle 0 - \dots - \langle v_j, e_{k}\rangle 1 \dots- \langle v_j, e_{j-1}\rangle 0}{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
$$= \frac{\Big\langle v_j, e_k\Big\rangle -  0 - \dots - \langle v_j, e_{k}\rangle  \dots-  0}{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
$$= \frac{\Big\langle v_j, e_k\Big\rangle - \langle v_j, e_{k}\rangle  }{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
$$= \frac{0 }{\| v_j - \langle v_j, e_1\rangle e_1 - \dots - \langle v_j, e_{j-1}\rangle e_{j-1} \|}$$
$$= 0$$


Erro file_put_contents() failed to open stream: No such file or directory

Question: Boa tarde!
Acredito ter deletado de forma incorreta uma das pastas STORAGE e agora meu projeto esta com o erro a seguir

file_put_contents(/Users/claudio/Desktop/laravel/projeto/storage/framework/sessions/cQfSldUOUGFEcnL3Z8INxCExQQW3s13Nb2kp5AT6): failed to open stream: No such file or directory

Já busquei pela internet e mandaram limpar cache do config.php do bootstrap/cache/ remover o arquivo etc.
Nada aparentemente tem funcionado.
Alguém já cometeu este erro ou sabe como fixar que não seja instalando um novo projeto?
Grato!
Answer: consegui fixar o projeto baixando a pasta do meu repositório e fazendo tudo que já tinha pesquisado antes
primeiro baixei a pasta e coloquei no lugar da storage que havia deletado.
rodei um php artisan config:cache e apliquei chmod -R 775 storage na storage da raiz e da public
nao consigo dizer ao certo o que foi que resolveu, sei que tudo junto solucionou.
Answer: Recrie as pastas.
Na raiz do seu projeto, crie a estrutura:
storage/
storage/app
storage/framework/cache
storage/framework/session
storage/framework/views
storage/framework/testing
storage/logs

Comment: fiz o processo mas infelizmente nao funcionou amigo, há o problema.
Comment: tem um truque q talvez resolva. uma vez fiz isso e tive q copiar um dos arquivos dentro da pasta: /Users/claudio/Desktop/laravel/projeto/storage/framework/sessions/ e pegar o arquivo q está ausente: cQfSldUOUGFEcnL3Z8INxCExQQW3s13Nb2kp5AT6 e colar no nome do que eu copiei e funcionou.


Finding closest element without jQuery

Question: I am trying to find the closest element with a specific tag name without jquery. When I click on a  I want to get access to the
 for that table. Suggestions? I read about offset but didn't really understand it too much. Should I just use:
Assume th is already set to clicked th element
th.offsetParent.getElementsByTagName('tbody')[0]

Comment: I think this is a very important and valid question. There's no reason for downvotes.
Comment: If you find that you must start traversing through the DOM this is one instance where the extra kbs attributed to jquery would be worth it.
Comment: try `parentNode` : https://developer.mozilla.org/en-US/docs/Web/API/Node.parentNode
Comment: `el.closest('tbody')` for non-ie browsers. See more elaborated answer + polyfill below.
Answer: Very simple:
el.closest('tbody')

Supported on all browsers except IE.
UPDATE: Edge now support it as well.
No need for jQuery.
More over, replacing jQuery's $(this).closest('tbody') with $(this.closest('tbody')) will increase performance, significantly when the element is not found.
Polyfill for IE:
if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector;
if (!Element.prototype.closest) Element.prototype.closest = function (selector) {
    var el = this;
    while (el) {
        if (el.matches(selector)) {
            return el;
        }
        el = el.parentElement;
    }
};

Note that there's no return when the element was not found, effectively returning undefined when the closest element was not found.
For more details see:
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
Comment: Why is this answer at the bottom of the page? Should be at the top. Thanks a lot
Comment: @stevemoretz. closest is native JavaScript now
Comment: That's called the best answer!
Comment: closest is in jQuery.But OP says no jQuery.
Comment: @LouiseEggleton Yup it is,oops
Answer: Little (very) late to the party, but nonetheless. This should do the trick:
function closest(el, selector) {
    var matchesFn;

    // find vendor prefix
    ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
        if (typeof document.body[fn] == 'function') {
            matchesFn = fn;
            return true;
        }
        return false;
    })

    var parent;

    // traverse parents
    while (el) {
        parent = el.parentElement;
        if (parent && parent[matchesFn](selector)) {
            return parent;
        }
        el = parent;
    }

    return null;
}

Comment: Great answer which works a treat. MDN also has a polyfill for element.closest(). Chrome includes element.matches() in the current release, so no prefix is needed. I've just added this to a lib I'm using in an app I'm developing, Clibu.
Comment: I've change the code so that it also tests element `el` which jQuery.closest() and also Element.closest() does.
`for( var parent = el ; parent !== null && !parent[matchesFn](selector) ; parent = el.parentElement ){
                el = parent;
            }
return parent;`
Comment: This code is fine, but it's missing a semicolon and also defining `parent` in global scope (!)
Comment: Might be worth mentioning: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest the native method for closest, though little low on support: Chrome41, FF35, IE-nope, Opera28, Safari9
Comment: Just a note on this, you may want to do `el.parentNode` or this will break when traversing an SVG in IE.
Comment: speed of execution will be the same as with `Element.closest()?`
Comment: This answer is now outdated. See @oriadam 's answer below
Comment: @nevf, The above solution didn't worked for me, but modifying the function with your suggestion did the trick. Cheers!
Answer: Here's how you get the closest element by tag name without jQuery:
function getClosest(el, tag) {
  // this is necessary since nodeName is always in upper case
  tag = tag.toUpperCase();
  do {
    if (el.nodeName === tag) {
      // tag name is found! let's return it. :)
      return el;
    }
  } while (el = el.parentNode);

  // not found :(
  return null;
}

getClosest(th, 'tbody');

Comment: I don't believe this would work. It only checks up the DOM tree. th->thead->table never considers siblings
Comment: You should've state that specific case in your question.
Comment: Look. This function traverses parentNodes to find the closest parent (even by extension) that uses the provided tag. This won't go "down" the document tree, only "up."
The average user would see the "closest" node most likely as the closest sibling. He just doesn't know the terminology he needed.
Comment: In fairness to @Jhawins your definition of closest is what jQuery terms closest. This is not a jQuery question. I can't attest to why jQuery decided closest meant closest ancestor, but a more reasonable definition would be closest element whether that be a parent, a previous sibling, a next sibling etc. Whatever is found "closest" to the target element.
Comment: @ryandlf But what if you had both a parent and a sibling at the same "distance"? jQuery's definition is clear in that it will return one match at most.
Comment: Your answer doesn't find the closest element node though. It finds the closest parent node in the chain. Just doing a recursive call checking if current nodeName matches return current else return search(parentNode) accomplishes the same task
Comment: This answer is just bogus.
Comment: @Hunter If you think that this only searches parentNode, you should know better before you speak. There is a reason I used do before while.
Comment: I'm fairly new to js, so please forgive my ignorance. Can you access and/or manipulate tag after el has been returned? If not, how would you do so?
Comment: is it possible to do that with input[type='whatever']?
Answer: There exists a standardised function to do this: Element.closest.
Most browsers except IE11 support it (details by caniuse.com). The MDN docs also include a polyfill in case you have to target older browsers.
To find the closest tbody parent given a th you could do:
th.closest('tbody');

In case you want to write the function yourself - here is what I came up with:
function findClosestParent (startElement, fn) {
  var parent = startElement.parentElement;
  if (!parent) return undefined;
  return fn(parent) ? parent : findClosestParent(parent, fn);
}

To find the closest parent by tag name you could use it like this:
findClosestParent(x, element => return element.tagName === "SECTION");

Answer: function closest(el, sel) {
    if (el != null)
        return el.matches(sel) ? el
            : (el.querySelector(sel)
                || closest(el.parentNode, sel));
}

This solution uses some of the more recent features of the HTML 5 spec, and using this on older/incompatible browsers (read: Internet Explorer) will require a polyfill.
Element.prototype.matches = (Element.prototype.matches || Element.prototype.mozMatchesSelector
    || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector
    || Element.prototype.webkitMatchesSelector || Element.prototype.webkitMatchesSelector);

Comment: It always goes to top first table.  not closest table .. see this link http://jsfiddle.net/guuy5kof/
Comment: nice catch! fixed, see here http://jsfiddle.net/c2pqc2x0/ please upvote me like a boss :)
Comment: ya i ill do ...Did you checked your fiddle result  , it shows error ..matches undefined
Comment: works great for me, which browser are you working in? this is not supported in older browsers
Comment: hey lets clear out that downvote what do you say bro
Answer: Here's the simple function I am using:-
function closest(el, selector) {
    var matches = el.webkitMatchesSelector ? 'webkitMatchesSelector' : (el.msMatchesSelector ? 'msMatchesSelector' : 'matches');

    while (el.parentElement) {
        if (el[matches](selector)) return el;

        el = el.parentElement;
    }

    return null;
}

Answer: To extend @SalmanPK answer
it will allow to use node as selector, useful when you working with events like mouseover.
function closest(el, selector) {
    if (typeof selector === 'string') {
        matches = el.webkitMatchesSelector ? 'webkitMatchesSelector' : (el.msMatchesSelector ? 'msMatchesSelector' : 'matches');
        while (el.parentElement) {
            if (el[matches](selector)) {
                return el
            };
            el = el.parentElement;
        }
    } else {
        while (el.parentElement) {
            if (el === selector) {
                return el
            };
            el = el.parentElement;
        }
    }

    return null;
}

Answer: Summary:
For finding a particular ancestor we can use:
Element.closest();
This function takes a CSS selector string as an argument. it then returns the closest ancestor of the current element (or the element itself) which matches the CSS selector which was passed in the arguments. If there is no ancestor it will return null.
Example:

const child = document.querySelector('.child');
// select the child

console.dir(child.closest('.parent').className);
// check if there is any ancestor called parent

Answer: Get closest DOM element up the tree that contains a class, ID, data attribute, or tag. Includes the element itself. Supported back to IE6.
var getClosest = function (elem, selector) {

    var firstChar = selector.charAt(0);

    // Get closest match
    for ( ; elem && elem !== document; elem = elem.parentNode ) {

        // If selector is a class
        if ( firstChar === '.' ) {
            if ( elem.classList.contains( selector.substr(1) ) ) {
                return elem;
            }
        }

        // If selector is an ID
        if ( firstChar === '#' ) {
            if ( elem.id === selector.substr(1) ) {
                return elem;
            }
        }

        // If selector is a data attribute
        if ( firstChar === '[' ) {
            if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) {
                return elem;
            }
        }

        // If selector is a tag
        if ( elem.tagName.toLowerCase() === selector ) {
            return elem;
        }

    }

    return false;

};

var elem = document.querySelector('#some-element');
var closest = getClosest(elem, '.some-class');
var closestLink = getClosest(elem, 'a');
var closestExcludingElement = getClosest(elem.parentNode, '.some-class');

Comment: Why not use a switch for the `firstChar` instead of all the `IF` conditions?
Comment: Why use an obscured `for` loop?
Answer: Find nearest Elements childNodes.
closest:function(el, selector,userMatchFn) {
var matchesFn;

// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
    if (typeof document.body[fn] == 'function') {
        matchesFn = fn;
        return true;
    }
    return false;
});
function findInChilds(el){
    if(!el) return false;
    if(el && el[matchesFn] && el[matchesFn](selector)

    && userMatchFn(el) ) return [el];
    var resultAsArr=[];
    if(el.childNodes && el.childNodes.length){
        for(var i=0;i< el.childNodes.length;i++)
        {
             var child=el.childNodes[i];
             var resultForChild=findInChilds(child);
            if(resultForChild instanceof Array){
                for(var j=0;j<resultForChild.length;j++)
                {
                    resultAsArr.push(resultForChild[j]);
                }
            }
        }

    }
    return resultAsArr.length?resultAsArr: false;
}

var parent;
if(!userMatchFn || arguments.length==2) userMatchFn=function(){return true;}
while (el) {
    parent = el.parentElement;
    result=findInChilds(parent);
    if (result)     return result;

    el = parent;
}

return null;

}
Answer: Here.
function findNearest(el, tag) {
    while( el && el.tagName && el.tagName !== tag.toUpperCase()) {
        el = el.nextSibling;
    } return el;
}

Only finds siblings further down the tree. Use previousSibling to go the other way
Or use variables to traverse both ways and return whichever is found first.
You get the general idea, but if you want to traverse through parentNodes or children if a sibling doesn't match you may as-well use jQuery. At that point it's easily worth it.
Comment: Slightly modified your suggestion to support deep-child traversal:

`function findNearest(el, tag) {
            while( el && el.tagName && el.tagName !== tag.toUpperCase()) {
                el = findNearest(el.firstElementChild, tag) || el.nextElementSibling;
            } return el;
        }
`
Answer: A little late to the party, but as I was passing by and just answer back a very similar question, I drop here my solution - we can say it's the JQuery closest() approach, but in plain good ol' JavaScript.
It doesn't need any pollyfills and it's older browsers, and IE (:-) ) friendly:
https://stackoverflow.com/a/48726873/2816279
Answer: I think The easiest code to catch with jquery closest:

<?php

for ($i = 1; $i <= 5; $i++) {
    echo'
'
        . '<form method="POST" action="">'
        . '
<input type="number" name="roll" placeholder="Enter Roll">
'
        . '
<input type="button" class="add" name = "submit" value = "Click">
'
        . '</form>
';
}
?>

Thanks much.

Finding closest element without jQuery