Prove that $P(X \le a) + P\{Y \le \frac{1}{a}\} = 1$

Question: Prove that if $X$ has the F-distribution with $(m, n)$ d.f. and $Y$ has the
F-distribution with $(n, m)$ d.f., then for every $a > 0$,
$$
P(X \le a) + P\left\{Y \le \frac{1}{a}\right\} = 1
$$
I tried solving  $P(X \le a)$ by integration but it was too difficult for me.
How do I approach questions like these in general?
Comment: Use the properties of the F-distribution. In particular, if $X \sim F_{m,n}$, what is the distribution of the reciprocal $Y=\frac{1}{X}$?
Comment: Welcome to Cross Validated! Please add the self-study tag, read it's wiki, and post what progress you've made so far with your homework assignment.
Answer: I will give you some clues toward a proof and, I hope, some idea why
this equality is of interest.
Definition and simulation. First, the distribution $\mathsf{F}(m,n)$ is defined as the distribution
of the ratio of two independent chi-squared random variables, each divided
by its degrees of freedom (so that numerator and denominator both have mean $1).$
It follows that $Y = 1/X \sim \mathsf{F}(n,m).$
set.seed(2020)
Num = rchisq(10^6, 10)/10
Den = rchisq(10^6, 15)/15
F.rat = Num/Den
summary(F.rat)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
 0.02225  0.65241  0.97911  1.15450  1.45158 21.39064

The graph below shows the simulated values of F.rat along with the
density function of $\mathsf{F}(10, 15).$ The positions of quantiles .025 and
0.975 are shown by vertical dotted lines.
hdr="Simulated Values of F(10,15) with Density"
hist(F.rat, prob=T, br=50, col="skyblue2", ylim=c(0,.9), main=hdr)
 curve(df(x,10,15), add=T, col="brown", lwd=2, n=1001)
 abline(v=qf(c(.025,.975), 10, 15), col="red")

Motivation: Printed tables of F-distributions. Typically, printed tables
of F-distribution give just a few 'percentage points' for each pair of degrees
of freedom: in my table. 'percentage points' $.25, .1, .05, .025, .001,$ which
cut those percentages of probability from the upper tail of each distribution.
These amount to quantiles $.75, .9, .95, .975, .999.$ These vaues are chosen
because of their frequent use to make confidence intervals and for tests involving
F-distributions.
However, values that cut particular values from the lower tails of F-distributions
are often of use, even though they are not provided in most printed F-tables.
(Nowadays, this is hardly causes difficulty because statistical calculators and
computer software provide almost any quantiles of practical interest.)
Suppose that for $X \sim \mathsf{F}(10, 15),$ I want to know the value $q$ such that
$P(X \le k) = 0.025,$ which is not in my F-table. From R, I can find that $k = 0.2840.$
k = qf(.025, 10, 15);  k
[1] 0.2839559
pf(k, 10, 15)
[1] 0.025

Now let's look at some additional values for relevant F distributions. The following
information is in my table: percentage point 0.975 is 3.52. In R, this is equivalent to
the following (where some extra decimal places are available):
h = qf(.975, 15, 10);  h
[1] 3.521673
pf(h, 15, 10)
[1] 0.975

Your equation $P(X \le a) + P\left(\frac{1}{X} \le \frac 1a\right) = 1$ can be
illustrated in R as follows:
pf(h, 15, 10) + pf(1/h, 10, 15);  1/h
[1] 1
[1] 0.2839559    # 1/h

Notice that the information from the second term, $P\left(\frac{1}{X} \le 1/h\right)$ is
not available in a printed table because it involves the 'lower half' of
$Y = 1/X \sim \mathsf{F}(10,15).$
pf(1/h, 1, 15)
[1] 0.398074

It follows that we can find the value that cuts probability $0.025$ from the lower
tail of $\mathsf{F}(10,15)$ from a printed table. It can be found as the reciprocal of the value that cuts
$0.025$ from the upper tail of $\mathsf{F}(15, 10).$
 1 / qf(.975, 15,10)
 [1] 0.2839559       # can be found from table
 qf(.025, 10, 15)
 [1] 0.2839559       # not explicitly printed in table

Comment: The right tail of F(m,n) tells you much about the left tail of F(n,m) because of the reciprocal relationship from the definition of an F distribution.
Comment: This gave me the intuition for the question but I still don't know how to proof this mathematically.
Answer: I will share three general techniques for working with density functions that are remarkably simple and useful: normalization, scaling, and identifying symmetries.  (A fourth general technique, recentering, often is useful but isn't applicable in this situation.)
By following these principles, along with a healthy application of the "principle of mathematical laziness," you can just look at a formula for the F-Ratio density and deduce the symmetry relationship expressed in the question.
Normalization
The Normalization Principle
Any function $f$ that is never negative, can be integrated, and has a finite integral $I[f]$ corresponds to a density: all we need do is divide all the values of $f$ by its integral and the result satisfies all the properties of a density.
When you are examining any mathematical expression for $f,$ then, it often is convenient just to ignore any constant multiplicative factors that may appear.  ("Constant" means they don't depend on the argument of $f$ -- but often they may depend on other quantities, usually known as "parameters.")  Those factors will be determined by the integral of all the other factors.  Let's call this the "Normalization Principle."
In this case, one expression for the F-Ratio density (from the Wikipedia article) is
$$f(x;d_1,d_2) = \color{blue}{\frac{1}{B\left(\frac{d_1}{2},\frac{d_2}{2}\right)} \left(\frac{d_1}{d_2}\right)^{\frac{d_1}{2}}}\, x^{\frac{d_1}{2}-1}\left(1 + \frac{d_1}{d_2}x\right)^{-\frac{d_1+d_2}{2}}.\tag{1}$$
I have colored some terms that do not depend on the argument $x:$ we are free to ignore these, because they are determined by the Normalization Principle.
You have choices
There is always more than one way to partition a density's expression into a constant factor and the other factors.  Indeed, you may even introduce new factors in the expression if that helps you simplify or understand it -- so long as they don't depend on the function's argument.  I will illustrate this in the next section, where I expand the blue factors to include more terms that appear.
Scaling
Distributions are best analyzed by examining the entire expression that you would integrate.  This expression is sometimes called the probability element: it is the product of the density $f_X(x)$ (representing the height on its graph) and the differential element $\mathrm{d}x$ (representing small distances along the base of the graph of $f_X$).  The product has units of probability -- and it's the probability, not the density, that behaves most simply under analysis.
Consider, then, a probability element $f_X(x)\,\mathrm{d}x$ and suppose you were to change the units of measurement in which $x$ is expressed.  For instance, if $x$ represents a length in centimeters and you prefer to work in inches, you would divide $x$ by $2.54$ centimeters per inch.  This obviously doesn't change anything about any probabilities: it merely reflects how you choose to write down numbers.
Mathematically, when we divide $x$ by a positive number $\lambda$ to produce $y=x/\lambda,$ the new probability element $f_Y$ is therefore written
$$f_Y(y)\,\mathrm{d}y = f_X(x/\lambda)\,\mathrm{d}( x / \lambda ) = f_X( x)\,\mathrm{d}(\lambda x/ \lambda ) = f_X(x/ \lambda )\,\left(\mathrm{d}x\right)/ \lambda  = \frac{1}{\lambda} \left(f_X(x/ \lambda )\,\mathrm{d}x\right).$$
If now, as is conventional, we omit writing the differential elements $\mathrm{d}y$ and $\mathrm{d}x,$ the preceding equation reads
$$f_Y(y) = \frac{1}{\lambda} f_X(x/ \lambda ).\tag{2}$$
The appearance of the factor of $\lambda$ is a mystery until you appreciate it is the last visible trace of the now-vanished differential element.  Let's call this the "density scaling law."  (Understanding how $f_X$ changes when $x$ is transformed also permits us to drop the subscripts from $f$ from now on.)
Exploit the density scaling law by working backwards. Whenever you look at the mathematical expression of a density, look for constant terms that multiply the argument: these are candidates for the scale factor $1/\lambda.$
Let's re-examine the F-Ratio density $(1)$ from this perspective.  It contains two terms with "$x$" in it.  Focus on the simplest one:
$$f(x;d_1,d_2) = \frac{1}{B\left(\frac{d_1}{2},\frac{d_2}{2}\right)} \left(\frac{d_1}{d_2}\right)^{\frac{d_1}{2}}\, x^{\frac{d_1}{2}-1}\left(1 + \color{red}{\frac{d_1}{d_2}x}\right)^{-\frac{d_1+d_2}{2}}.$$
There it is in red, all by itself, multiplied by a constant $d_1/d_2 = 1/\lambda.$  What you want to do is replace $x/\lambda$ by $y$ or, equivalently, just plug $\lambda y = d_2/d_1 y$ into the formula everywhere in place of $x.$  In so doing you will be neglecting that ghostly $\lambda$ factor that appeared in $(2),$ but the Normalization Principle tells us this doesn't matter.
This is a perfectly routine substitution, requiring only basic algebra to simplify:
$$\begin{aligned}
f(y;d_1,d_2) &\propto \frac{1}{B\left(\frac{d_1}{2},\frac{d_2}{2}\right)} \left(\frac{d_1}{d_2}\right)^{\frac{d_1}{2}}\, (d_2/d_1\, y)^{\frac{d_1}{2}-1}\left(1 + \color{red}{\frac{d_1}{d_2}(d_2/d_1\, y)}\right)^{-\frac{d_1+d_2}{2}}\\
&= \color{blue}{\frac{1}{B\left(\frac{d_1}{2},\frac{d_2}{2}\right)} \left(\frac{d_1}{d_2}\right)^{\frac{d_1}{2}}\, \left(\frac{d_2}{d_1}\right)^{\frac{d_1}{2}-1}}\,  y^{\frac{d_1}{2}-1}\left(1 + \color{red}{y}\right)^{-\frac{d_1+d_2}{2}}
\end{aligned}
.$$
Although there is an obvious nice cancellation of the fractions involving $d_1/d_2$ and $d_2/d_1,$ I didn't bother to go further with the simplification because the Normalization Principle tells us we don't have to do any more work: these new factors merely contribute to the multiplicative "fluff" that we may freely ignore.  That's why I am showing all of it in blue.
Notice the appearance at the outset of the "$\propto$" ("is proportional to") relation: it acknowledges that I neglected to divide the right hand side by $\lambda = d_2/d_1.$
These last two steps are examples of what I call the Principle of Mathematical Laziness: don't do calculations until you have to, because often you will discover you don't have to do them at all.
Invoking the Normalization Principle once more, let's look at what's left of $f:$
$$f(y;d_1,d_2)\ \propto\ y^{\frac{d_1}{2}-1}\left(1 + y\right)^{-\frac{d_1+d_2}{2}}.\tag{3}$$
Let's call this the "nucleus" of $f:$ any factors multiplying its argument $y$ have been stripped away and any constant factors multiplying its value have been ignored.  Typically, you can just look at the formula of a density and see its nucleus.  It usually takes no work at all.
Symmetry
The appearance of $-1$ in the power of $y$ in the nucleus $(3),$ along with the fact that $f$ is supported on the positive numbers $(0,\infty),$ hints at a multiplicative symmetry.  (For more on the $-1$ terms in the powers, see https://stats.stackexchange.com/a/263842/919.)
Symmetry is a powerful, general concept that I can only hint at here by showing how it applies to the F-Ratio distribution.
The beautiful thing about the differential element $\mathrm{d}y/y$ is how it transforms when we take powers of $y:$
$$\frac{\mathrm{d}(y^p)}{y^p} =\frac{py^{p-1}\mathrm{d}y}{y^p} = p\frac{\mathrm{d}y}{y}\ \propto\ \pm\frac{\mathrm{d}y}{y}.$$
This is, after invoking the Normalization Principle, $\mathrm{d}y/y$ does not change when we take a positive power of $y$ and otherwise, for negative powers, it is merely negated.  The negation reflects the fact that transforming $y$ to a negative power of $y$ reverses order: when $x \gt y \gt 0$ and $p\lt 0,$ $0 \lt x^p \lt y^p.$  We need to keep track of any such reversals because they subtly change the interpretation of $f:$ more about this at the end.
Take the appearance of "$-1$" in the power of $y$ in the nucleus $(3)$ as an invitation to rewrite the density as a differential element in terms of $\mathrm{d}y/y.$  This is the final simplification:

$$f(y;d_1,d_2)\,\mathrm{d}y\ \propto\ y^{\frac{d_1}{2}}\left(1 + y\right)^{-\frac{d_1+d_2}{2}}\,\frac{\mathrm{d}y}{y}.\tag{4}$$

Upon applying the transformation $y = u^{-1}$ in the question, without any work at all we immediately see
$$f(u;d_1,d_2)\,\mathrm{d}u\ \propto\ -(u^{-1})^{\frac{d_1}{2}}\left(1 + u^{-1}\right)^{-\frac{d_1+d_2}{2}}\,\frac{\mathrm{d}u}{u} = \frac{(u^{-1})^{\frac{d_1}{2}}}{\left(1 + u^{-1}\right)^{\frac{d_1+d_2}{2}}}\,\left(-\frac{\mathrm{d}u}{u}\right).$$
Simplifying the fraction (in the usual manner) by multiplying numerator and denominator by a suitable power of $u$ (namely, the $(d_1+d_2)/2$ power) yields
$$f(u;d_1,d_2)\,\mathrm{d}u\ \propto\ \frac{u^{\frac{d_2}{2}}}{\left(1 + u\right)^{\frac{d_1+d_2}{2}}}\,\left(-\frac{\mathrm{d}u}{u}\right) =u^{\frac{d_2}{2}}\left(1 + u\right)^{-\frac{d_1+d_2}{2}}\,\left(-\frac{\mathrm{d}u}{u}\right).\tag{5}$$
Comparing $(5)$ to $(4)$ shows that upon transforming $y$ to $1/y,$ the kernel with parameters $(d_1,d_2)$ becomes the kernel with parameters $(d_2,d_1)$ with a negative sign.
Conclusion
The appearance of the negative sign means that at some point we transformed the variables in an order-reversing way.  Originally, to compute the probability of an interval $(-\infty, a]$ we would have integrated the probability element over the interval $(0, a].$  Because of the transformations we made, we must transform its endpoint $a$ appropriately to some new value $a^\prime$ and, due to the order reversal, we must now integrate over the interval $[a^\prime, \infty).$
Because the integral will be the same whether or not we include $a^\prime$ in that interval, the conclusion in the question follows immediately: when $X$ has an F-Ratio distribution with parameters $d_1,d_2$ we may compute $\Pr(X\le a)$ either by integrating $f_X$ from $0$ to $a$ or by integrating $f_U = f_{1/X},$ which has an F-Ratio distribution with parameters $d_2,d_1,$ from $a^\prime = 1/a$ to $\infty,$ which of course is just $1 - \Pr(U \le 1/a).$

If you would like to practice these techniques further, virtually every distribution (over 40 of them) in the Wikipedia list of continuous distributions supported on semi-infinite intervals) can be analyzed in the same way.


How is $\chi^2$ value converted to p-value?

Question: I'm brand new to statistics and am studying the math behind split testing (A/B and multivariate). I've learned how to calculate $\chi^2$ with given test data, and I understand how to translate this into a probability via a table, but I'd like to be able to calculate the probability myself. I've read through a couple of explanations online, but I'm not getting it.
Does anyone know of a resource or book that breaks this down?
Answer: The $p$-value is the area under the $\chi^2$ density to the right of the observed test statistic. Therefore, to calculate the $p$-value by hand you need to calculate an integral.
In particular, a $\chi^2$ random variable with $k$ degrees of freedom has probability density
$$f(x;\,k) =
\begin{cases}
  \frac{x^{(k/2)-1} e^{-x/2}}{2^{k/2} \Gamma\left(\frac{k}{2}\right)},  & x \geq 0; \\ 0, & \text{otherwise}.
\end{cases}$$
Suppose you observe a test statistic $\lambda$. Then, the $p$-value corresponding to $\lambda$ is
$$
p = \int_{\lambda}^{\infty}
\frac{x^{(k/2)-1} e^{-x/2}}{2^{k/2} \Gamma\left(\frac{k}{2}\right)}
dx $$
After trying to evaluate this integral by hand, it may become clear to you why people use tables (and computers) for calculating such things.
Edit: (This was in the comments but seemed important enough to add here) Note that you can write the $p$-value using special functions:
$$ p = 1−\frac{γ(k/2,λ/2)}{Γ(k/2)} $$
where $\gamma(\cdot,\cdot)$ is the lower incomplete gamma function.
Comment: Well, if you're hoping to find an exact solution that doesn't involve special functions(e.g. the gamma function), I think you're going to remain stuck. The actual solution is $p = 1 - \frac{ \gamma(k/2, \lambda/2) }{\Gamma(k/2)}$, where $\gamma(\cdot,\cdot)$ denotes the lower incomplete gamma function. Both $\Gamma$ and $\gamma$ are defined in terms of integrals, so any calculator you program for your website will need to involve a numerical integration routine.
Comment: Thanks for your reply Macro, your response is helpful. I think the place I'm stuck is the gamma function. I can push through the integration (though my calculus is rusty), but I don't understand the gamma function. I'll do some research on that. My goal is to build a web page that does these calculations. I know that a handful of these exist already, my main goal in doing this is fully understanding the math behind the results.
Comment: This has been a really fun exercise and I've learned a ton in the process. I've constructed my web page calculating the probability through linear interpolation. Thanks for your help Marco.
Comment: No problem, Lenwood. What kind of error do you incur? Do you have a link to the website?
Comment: I've been running the page on my own system, but I'll put it up for a few days. You can see it here, http://chisq.nfshost.com/. As I've spent more time with this, I realize that my values for $\chi^2$ are consistent with other calculators that I've seen, but not with R. I believe the difference is in the calculation of expected values. I'll post that as a separate question.


Loop through dataframe to change a columns values - python

Question: I have a df with a column of Months. The months are in their numeric values, i.e 1 through to 12. I need these to read as their actual text equivalent, such that 1 would be replaced with January and 2 would be replaced with February and so on.
At the minute I'm doing it the long way by declaring each month separately:
cntryPerMonth.loc[cntryPerMonth['Month'] == 1.0, 'Month'] = 'January'
cntryPerMonth.loc[cntryPerMonth['Month'] == 2.0, 'Month'] = 'February'
cntryPerMonth.loc[cntryPerMonth['Month'] == 3.0, 'Month'] = 'March'
cntryPerMonth.loc[cntryPerMonth['Month'] == 4.0, 'Month'] = 'April'
cntryPerMonth.loc[cntryPerMonth['Month'] == 5.0, 'Month'] = 'May'
and so on for the remaining months

Is there a more efficient way?
Thanks.
Answer: You can use a dictionary to replace the values:
replace_dict = {
    1:'Jan', 2:'Feb'
}

df = pd.DataFrame({'month': [1,2]})

df['month_names'] = df['month'].replace(replace_dict)


Can Git merge changes from a disk copy (not a clone) of a personal repository?

Question: I started using Git Extensions with no prior knowledge of Git. I created a personal repository for a project I was given that was not under source control. I made a bunch of commits, and then copied (instead of cloning, which I now see is what I should have done) the source directory and gave it to the person who gave me the project in the first place.
Since then we have both made further changes to our respective local repositories, and we are planning to merge them in the near future. Is this possible, given that I didn't properly clone my repository before giving it to the other person?
Answer: Cloning and copying are the same thing (assuming you included the .git directory in the copy) except that remotes are not configured. You can merge them exactly as you would a cloned repository, save that you'll have to configure a remote to fetch from in one of your copies.
Answer: One of you wants to make a patch and give it to the other.  Then you need to create a central repo of the patched repository and both clone it and start working from that.  Keep in mind that when you perform that patch you may have conflicts that you will have to resolve.
Here's a tutorial on patching.
http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git
Answer: Yes and no. A clone (that is a clone with a working directory) is almost a copy. I say almost, because a clone will not create a copy of any untracked files.
So, for discussion's sake, if we assume that your working tree did not have any untracked files, or that your .gitignore file was tracked (and that it included all the necessary entries), then a copy is the same as a clone.
That said, from a merging point of view you can merge between the two repositories.


Mysql skip-name-resolve

Question: I had recently purchased a new server, and transferred all my accounts via WHM Transfer.
The problem is that when WHM takes a daily backup, it outputs are message such as
DBD::mysql::st execute failed: There is no such grant defined for user 'abc' on host 'myhostname'

The problem is solved when I remove skip-name-resolve from my my.cnf file. Tough I dont find any differences in the speed (when I dont add it), it is often mentioned in forums that adding skip-name-resolve optimizes Mysql Performance.
Does adding skip-name-resolve really help, if one has a Dedicated server?
Answer: It really depends on how many clients are connecting to the server and how often. If you only have one server connecting to MySQL (e.g. the local host) there is really no benefit by setting this option because MySQL does cache the result from the DNS lookup for some time, so you only really incur the performance penalty at the start.
If you have lots of hosts connecting to your MySQL server, and many connections, you can certainly see a benefit (I have seen benefits in environments where we have 25 web servers hitting a DB server that is handling 500 q/sec, with a new connection for each web request).
You do have to adjust all the grants to use IP addresses instead of host names if you go this route, e.g. to fix your above issue:
SHOW GRANTS FOR 'abc'@'myhostname';

Take the output of that and change the host name to IP address to create all the same grants based on the IP address. You can then revoke the host-based grants.
Comment: In case, if we add grants for IP address, while connecting to the DB, do you need to specify the IP address instead of the 'DB name'/'DB user'
Comment: Nope, since the grants by IP deal with the *client's* address it shouldn't affect the way the clients are connecting to the server (they can continue to specify `localhost` as before and should work).
Comment: If you connect specifying localhost in the host parameter then your MySQL user should have rights as localhost.

Mysql skip-name-resolve


Difference in floating point arithmetics between x86 and x64

Question: I stumbled upon a difference in the way floating point arithmetics are done between MS VS 2010 builds for x86 and x64 (both executed on the same 64 bit machine).
This is a reduced code sample:
float a = 50.0f;
float b = 65.0f;
float c =  1.3f;
float d = a*c;
bool bLarger1 = d<b;
bool bLarger2 = (a*c)<b;

The boolean bLarger1 is always false (d is set to 65.0 in both builds).
Variable bLarger2 is false for x64 but true for x86!
I am well aware of floating point arithmetics and the rounding effects taking place. I also know that 32 bit sometimes uses different instructions for floating operations than 64 bit builds. But in this case I am missing some information.
Why is there a discrepency between bLarger1 and bLarger2 on the first place? Why is it only present on the 32 bit build?
Comment: my guess is that the x86 version is using the FPU registers for that and x64 is using SSE registers for that. But you probably need to look at IL code and also at the machine code.
Comment: Certainly x86 is using x87 unit, and x64 is using SSE unit. But it doesn't really explain the difference. They should both get the same answer. @Oliver can you show how you are compiling the code because my quite attempt at a repro failed. Both bools are `false` for both x86 and x64 for me.
Comment: It's going to be the way a*c is treated in the expression for `bLarger2`. I guess it will be a float mult in one and a double mult in the other, or something like that
Comment: The real question is why is this surprising, knowing full well that floating point isn't exact.  Depending on compiler, compiler options, etc. results can differ.
Comment: @PaulMcKenzie Whilst floating point arithmetic does not exactly represent all real values, it is repeatable and well-defined. It is not unreasonable to hope for consistency between different compilers.
Comment: OK, now I got a repro!
Comment: Well the difference between two comparision operations on the same platform that look the same was especially confusing for me
Comment: Related questions: [Does any floating point-intensive code produce bit-exact results in any x86-based architecture?](https://stackoverflow.com/questions/27149894/does-any-floating-point-intensive-code-produce-bit-exact-results-in-any-x86-base) and [this one](https://stackoverflow.com/questions/33789476/is-boostrandomuniform-real-distribution-supposed-to-be-the-same-across-proce)
Answer: The issue hinges on this expression:
bool bLarger2 = (a*c)<b;

I looked at the code generated under VS2008, not having VS2010 to hand. For 64 bit the code is:

000000013FD51100  movss       xmm1,dword ptr [a]
000000013FD51106  mulss       xmm1,dword ptr [c]
000000013FD5110C  movss       xmm0,dword ptr [b]
000000013FD51112  comiss      xmm0,xmm1

For 32 bit the code is:

00FC14DC  fld         dword ptr [a]
00FC14DF  fmul        dword ptr [c]
00FC14E2  fld         dword ptr [b]
00FC14E5  fcompp

So under 32 bit the calculation is performed in the x87 unit, and under 64 bit it is performed by the x64 unit.
And the difference here is that the x87 operations are all performed to higher than single precision. By default the calculations are performed to double precision. On the other hand the SSE unit operations are pure single precision calculations.
You can persuade the 32 bit unit to perform all calculations to single precision accuracy like this:
_controlfp(_PC_24, _MCW_PC);

When you add that to your 32 bit program you will find that the booleans are both set to false.
There is a fundamental difference in the way that the x87 and SSE floating point units work. The x87 unit uses the same instructions for both single and double precision types. Data is loaded into registers in the x87 FPU stack, and those registers are always 10 byte Intel extended. You can control the precision using the floating point control word. But the instructions that the compiler writes are ignorant of that state.
On the other hand, the SSE unit uses different instructions for operations on single and double precision. Which means that the compiler can emit code that is in full control of the precision of the calculation.
So, the x87 unit is the bad guy here. You can maybe try to persuade your compiler to emit SSE instructions even for 32 bit targets. And certainly when I compiled your code under VS2013 I found that both 32 and 64 bit targets emitted SSE instructions.
Comment: @OliverZendel There's no compiler setting that will change the control word. That is a runtime property and so has to be managed at runtime. And it's a total minefield FWIW with modules left right and centre screwing with the control word. Compile with `/arch:SSE2` and you'll avoid all that x87 pain. But your program will only run on machines with SSE2 units.
Comment: Actually I'm not even sure that /arch:SSE2 will necessarily get it done. Anyway, I think we do at least understand the cause for the behaviour.
Comment: Interesting, so I assume the difference between the way bLarger1 and bLarger2 are computed is the precision of the ALU. For bLarger2 the result with the higher precision is kept in the ALU for comparision while bLarger1 will first load the single precision values and compare those.
Comment: @OliverZendel Correct
Comment: Hm, neither changing "Enable Enhanced Instruction Set" nor "Floating Point Model" resulted in a different behaviour (VS2010 x86); _controlfp does the trick, but I'm still curious if there is a compiler setting itself that results in the same behaviour
Comment: That's a limitation I can live with (in this case). Thanks!
Comment: I tried it out and in combination with "Fast" Floating Point Model (/fp:fast) the sample behaviour is consistent (both booleans are false on both platforms)
Comment: Excellent. You program will be a little faster too with SSE2.
Comment: Note that the solution references _controlfp(_MCW_PC, _PC_24); however, the Microsoft documentation and Intellisense in VS2017 indicates that the mask is the *second* parameter.

https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/control87-controlfp-control87-2

Which means, that this line should read:
_controlfp(_PC_24, MCW_PC)

Here are the docs for 2008, which state the same.
https://msdn.microsoft.com/en-us/library/e9b52ceh(v=vs.90).aspx
Comment: @Markus You are correct. I have changed the answer accordingly. Thanks.
Answer: Floating points operations are always imprecise, and comparing two floats this close (or equal) almost never return the correct output.
Floating point numbers are stored and processed differently on 32bit and 64bit machines (as also suggested by comments). If I remember correctly, in VC 32bit floats are saved on the stack and FPU (Floating-Point Unit) processes them, whereas floats on a 64bit machine can be stored in specialized registers (SSE) and are calculated using other Units in the CPU.
I have no definite source to my answer, but please look at this page or this.
Comment: There is no difference in storage. These are IEEE754 floats. A standard format.
Comment: But floats are not necessarily stored on the stack. The x87 unit has its own register stack of 8 extended precision floating point registers ST(0) to ST(7). They are specialized registers for sure. And the SSE unit has its own specialized registers.
Comment: @DavidHeffernan, They are stored the same way, but different locations is what I'm trying to say.


How to find infimum of below set

Question:
Let $F$ be a non-zero continuous linear map from $X$ to $Y$ (both normed linear space). Let $\alpha$ be positive, then show that infimum of the set $\inf\{\|x\|:\|F(x)\|=\alpha\}$ is $\alpha/\|F\|$.

I have done one inequality as every member in set must satisfy  $\|F(x)\| =  \alpha$  therefore
$\alpha$ $\leq $ ||F|| ||x||  hence ||x|| $\geq$$\alpha$/ ||F|| hence infimum must be greater than or equal to . But I stuck in other way pleaz help... thank you
Answer: Recall that $$||F||=\sup_{||x||=1}||F(x)||.$$ Take a sequence $x_i$ in the unit ball such that $||F(x_i)||\to ||F||$. It follows that $$\left|\left|F\left(\frac{\alpha}{||F(x_i)||}x_i\right)\right|\right|=\frac{\alpha}{||F(x_i)||}||F(x_i)||=\alpha.$$ Also, for all $i$, we have $$\left|\left|\frac{\alpha}{||F(x_i)||}x_i\right|\right|=\frac{\alpha}{||F(x_i)||}\to\frac{\alpha}{||F||}$$ as $||x_i||=1$ and $||F(x_i)||\to ||F||>0$. Thus, the infimum is less than or equal to $\frac{\alpha}{||F||}$.
Comment: Why this $$\left|\left|\frac{\alpha}{||F||}x_i\right|\right | $$ is in the set. Note it not satisfy the required condition
Comment: Please reply if i miss something
Comment: Ooops, you are right. I'll update my answer when I figure out how to fix this.
Comment: I have fixed my solution.
Comment: No problem! If my answer was what you are looking for, please feel free to accept it.

How to find infimum of below set


addTextChangedListener doesn't work for space or backspace etc

Question: I'm writing an android app that sends your inputs to the pc via socket programming. I can send all the characters that you write in a textarea such as 'a','1','+' etc. but cannot send "space" or "backspace" when i touch the space on the keyboard from the screen it shuts down the app. anyone can tell why ? or any other function suggestions that i can use ?
This is the code i wrote for the situation.
etTextArea.addTextChangedListener(new TextWatcher() {
            int x =0;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                char characters ;
                MessageSender messageSender = new MessageSender();
                characters = etTextArea.getText().charAt(x);
                messageSender.execute(String.valueOf(characters));

                /*if (characters == ' ')
                {
                    Toast.makeText(KeyboardActivity.this, " space ", Toast.LENGTH_SHORT).show();
                }
                else{
                    messageSender.execute(String.valueOf(karakterler));
                }*/

            }

            @Override
            public void afterTextChanged(Editable editable) {
                x++;
            }
        });

Any help would be great, thanks guys.
Answer: If text has changed it should work. Also for key events you can use for example:
view.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                presenter.onBackClicked()
                return@setOnKeyListener true
            }
            return@setOnKeyListener false
        }

Comment: what is the presenter here exactly?
Comment: and by the way i have tried to use setOnKeyListener before, it only works if use emulator on my pc and write from hardware keyboard otherwise it doesnt work
Comment: you can replace  presenter.onBackClicked() with your own code, it means that back key was jus pressed.


Translation mess up with fields which are not translatable used in views

Question: Example set up:
Content type news with fields

Body (translatable)
date (another date field beside node published date - translatable)
type of news (list field - not translatable, the news should be of the same type in every language)

View with filters:

Published: yes
Content type: news
Content language: currently activated interface language
field "type of news" -> exposed to the user

Default language in the project is German.
When I go to the view in German and choose a type of news in the exposed filter there is no problem - the expected news are listed. The problem appears when I enter the page in English and I choose a type of news -> no results are found although the same nodes are translated into English.
I found out that this is due to the fact that the "type of news" values in the fields table are saved with the language id of the original node which is 'de' but the full view query expects the field value to have a language code 'en' (like the currently activated language has).
See this query and especially the INNER JOIN:
<code>
SELECT node__field_date.field_date_value AS node__field_date_field_date_value, node_field_data.nid AS nid, node_field_data.langcode AS node_field_data_langcode
FROM
{node_field_data} node_field_data
INNER JOIN {node__field_news_typ} node__field_news_typ ON node_field_data.nid = node__field_news_typ.entity_id AND (node__field_news_typ.deleted = '0' AND node__field_news_typ.langcode = node_field_data.langcode)
LEFT JOIN {node__field_date} node__field_date ON node_field_data.nid = node__field_date.entity_id AND (node__field_date.deleted = '0' AND node__field_date.langcode = node_field_data.langcode)
WHERE (( (node__field_news_typ.field_news_typ_value = 'press') )AND(( (node_field_data.langcode IN  ('en')) AND (node_field_data.status = '1') AND (node_field_data.type IN  ('news')) )))
ORDER BY node__field_date_field_date_value DESC
LIMIT 10 OFFSET 0
</code>
You may see that the inner join expects the langcode field in node__field_news_typ to be the same value as node_field_data.langcode which is 'en' when I enter the view in English. But looking into the table of node__field_news_typ I do not find one entry with 'en' as the field is not set to be translatable and all the nodes are originally written in German.
Maybe I did not get some basics of the multilanguage architecture in Drupal 8 but I find it a little bit strange that fields which are not translatable filter out nodes in views where a filter is set to "current active language". Is there not UNDEFINED_LANGUAGE ('und') anymore? Why do fields get a fix languagecode when they are not translatable? How can I avoid this behavior?
It seems to me that there is no other way as setting the field to translatable although I want to assure that translated nodes have the same value?!
Answer: This is known core bug, see https://www.drupal.org/node/2451657. The patch there should work well.


Relationships between correlation and causation

Question: From the Wikipedia page titled correlation does not imply causality,
For any two correlated events, A and B, the different possible relationships include:

A causes B (direct causation);
B causes A (reverse causation);
A and B are consequences of a common cause, but do not cause each
other;
A and B both causes C, which is (explicitly or implicitly)
conditioned on.;
A causes B and B causes A (bidirectional or cyclic causation);
A causes C which causes B (indirect causation);
There is no connection between A and B; the correlation is a
coincidence.

What does the fourth point mean. A and B both causes C, which is (explicitly or implicitly) conditioned on. If A and B cause C, why do A and B have to be correlated.
Comment: Obligatory related xkcd: https://xkcd.com/552/
Comment: Despite the saying I would expect there to be a high correlation between correlation and causation...
Comment: http://www.tylervigen.com/spurious-correlations
Comment: Possibly see also the discussion at [Does no correlation imply no causality?](https://stats.stackexchange.com/questions/221936/does-no-correlation-imply-no-causality/222411#222411)
Answer: "Conditioning" is a word from probability theory : https://en.wikipedia.org/wiki/Conditional_probability
Conditioning on C means that we are only looking at cases where C is true. "Implicitly" means that we may not be making this restriction explicit, sometimes not even aware of doing it.
The point means that, when A and B both cause C, observing a correlation between A and B in cases where C is true, does not mean there is a real relationship between A and B. It's just conditioning on C (maybe unwillingly) that creates an artificial correlation.
Let's take an example.
In a country there exists exactly two sorts of diseases, perfectly independent. Call A : "person has first disease", B : "person has second disease". Assume $P(A)=0.1$, $P(B)=0.1$.
Now any person who has one of these diseases goes to see the doctor and only then. Call C : "person goes to see the doctor". We have $C=A \text{ or } B$.
Now let's calculate a few probabilities :

$P(C)=0.19$
$P(A|C)=P(B|C)=\frac{0.1}{0.19}\approx 0.53$
$P(A \text{ and } B|C)=\frac{0.01}{0.19}\approx 0.053$
$P(A|C)P(B|C)\approx 0.28$

Clearly, when conditioned on C, $A$ and $B$ are very far from being independent. Actually, conditioned on C, $not A$ seems to "cause" $B$.
If you use the list of persons who where recorded by their doctor(s) as a data source for an analysis, then there seems to be a strong correlation between diseases $A$ and $B$. You may not be aware of the fact that your data source is actually a conditioning. This is also called a "selection bias".
Answer: The fourth point is an example of Berkson's paradox, also known as conditioning on a collider, also known as the explaining-away phenomenon.
As an example, consider a young woman who is frequently asked on dates by young men, and she must decide whether to accept or reject each date proposal. The young men vary in how attractive and charming they are, and let's suppose that these two traits are independent in the population of date-proposing men. Naturally the young woman is more inclined to accept a date proposal the more attractive or charming the man is. So a causal model for this situation may look like:
$$
Attractive \rightarrow Accept \leftarrow Charming
$$
That is, $Attractive$ and $Charming$ both cause $Accept$, which takes on values of 0 or 1 if the woman rejects or accepts the date proposal, respectively.
We supposed above that $Attractive$ and $Charming$ are independent in the population of date-proposing men. But are they still independent if we consider only the men whose proposals the woman accepted? In other words, we condition on $Accept=1$. Now suppose I tell you about a man who the woman agreed to date, and I tell you that he is (in the woman's opinion) not attractive at all. Well, we know that the woman agreed to date him anyway, so we would reasonably infer that he must be quite charming indeed. Conversely, if we learn about a man whose date proposal was accepted and who is not charming, we would reasonably infer that he must be quite attractive.
Do you see what's happened here? By conditioning on $Accept=1$, we've induced a negative correlation between $Attractive$ and $Charming$, even though these two traits are (by assumption) marginally independent. From the perspective of the woman, the attractive men she dates tend to be less charming, and the charming men she dates tend to be less attractive. But this is because, by thinking only of the men she has dated, she is implicitly conditioning on $Accept$. If she would instead consider all the men who have proposed dates, regardless of whether she accepted the proposal, she would see that there is no statistical association between the two traits.
Answer: Simpson's paradox and Berkson's paradox can each give examples of "A and B both cause C, which is (explicitly or implicitly) conditioned on"
As an example suppose I have $1000$ stamps in my collection of which $100$ are rare ($10\%$) and $200$ are pretty ($20\%$).  If there is no intrinsic relationship between rarity and prettiness, it might turn out $20$ of my stamps are both pretty and rare.
If I now display my $280$ interesting stamps, i.e. those which are rare or pretty or both, there will be an apparent negative correlation between rarity and prettiness ($20\%$ of displayed rare stamps are pretty while $100\%$ of displayed common stamps are pretty) due entirely to conditioning on being interesting.
Comment: This is an example Berkson's paradox, not Simpson's paradox (see my answer).
Comment: @JakeWestfall You are probably right - I knew I had written the stamps example before somewhere but forgotten where and it turns out to be the Wikipedia page for Berkson's paradox
Answer: The paragraph starts with "For any two correlated events, A and B,...", so my guess is that correlation is assumed at the beginning. In other words, they need not be correlated to simultaneously cause C, but if they were correlated and they did both cause C, it does not imply that there exists a causal relationship between them.


How do I delete columns from a matrix based on a list in R?

Question: I have a very large matrix that looks like this:
        AGAG      AAGAA     AGTG     AGAT     AAGAT     AGTT
1001    14691      0          0        0        0        5
1002    13        12          0       5831     20473     4
1003    0        5831      20473       0        0        0
1004    0        7936       7936      7936      0        0
1005    16066      0         0         24       2        2

There are >8000 columns. I need to delete many (~3000) of these columns by the column name. I have abbreviated the column names here (genome sequences). Obviously, I can't type that many individually.
I made a separate table that has the column names I want to delete. For example:
AGAG
AGTG
AGTT
AGAT

I tried to use subset and %in% so far to no avail.
Comment: Rows are sample names. Yes, these are genomic sequences.
Comment: What is the meaning of the rows? Samples? Is this data the result of some sequencing experiment?
Comment: Don't you have a lot less samples than you have genomic sequences?
Answer: Here's an example with the iris dataset:
col_to_rm <- c("Sepal.Length", "Sepal.Width", "Petal.Length")
col_to_keep <- setdiff(colnames(iris), col_to_rm )
iris[, col_to_keep]

iris is a dataframe, but it will work as well if you have a matrix.
You should be probably thinking whether that data structure (matrix) is the best to save your data: you've got very many columns...
Comment: This example has typos for the iris dataset column names, but once I resolved that, and imported my csv file correctly (not as factors) it work great.  Thanks!
Comment: I downloaded iris and ran this and it did not work. Also, I have no choice - I have to leave the data structure as a matrix for downstream processing.
Comment: You do not need to download `iris`. `iris` comes with R. I am not challenging  your choice of having a matrix, but perhaps it is more easy to handle your data if you transpose it (I am guessing you have a few samples...)
Comment: @BrianAiken: what typos?


Best practice to implement stores

Question: I want to allow my site users to create stores,, in which each store can contain content.
so the store is basically a page which contain specific content.
what's the best way to implement this in Drupal?
Comment: Do you need each store to have credit card checkout?
Answer: We used OG extensively in many sites with stores that are auto-created when a user registers.  You can check out one of them here - www.craftsaid.com - each "store" is an OG.  We also did the same thing on Bandromeda.com.
Install Organic Groups Module - http://drupal.org/project/og
Install Rules Module - http://drupal.org/project/rules
After you have created a content type for your Group type (this can be anything you want it to be - if you're not familiar with OG it is an incredibly powerful platform that allows users to create groups to which other members may subscribe - essentially you create one content type as the "group" type itself and then any other content type can be set as "group content" that may be added to a given group) go to /admin/workflow/rules and add a rule for Event = After saving a new user account with an Action = Create a new entity with parameters of Entity type: Node, Content type: Your Group Content Type, Title: [use tokens to create your title configuration]
This will auto-create a Group upon registration.  Otherwise you could simply create a link to node/add/store (or whatever your group content type is) from wherever makes the most sense in your site.
That is a very basic explanation - there are probably 50 ways you could implement this to accommodate your general description of your need.  Hope that helps!
Answer: If each store is just a page, with no checkout process, then you could

Create a "Product" content type, add required fields
Configure role and permission to allow adding product node
Create a View listing products for a particular store ( by product author(s) )

Alternatively, you could look at a commerce solution such as Drupal Commerce or Ubercart, but that may be overkill in this situation when a core solution + Views may suffice.
Answer: You should check out the Organic Groups module. Also here is a link to all the projects associated with this module. Looks like there used to be a "store" feature, but that was back with Drupal 4.x. However if the store only holds pieces of content, not actual sales, then OG does a great job of managing multiple "stores" within the site.

Best practice to implement stores


Can't access element's class to change its name in JavaScript

Question: I'd like to change an element's class from score -box1 to score -box1.-active. I created a const $target to try to access the class score -box1 but its not working.
const $target = document.getElementByClassname('score -box1')
function PlayerScore(score = 0){
    if(score == 1){
        $target.toggle('-active');
    }else if(score == 2){
        $target.toggle('-active');
    }else if(score == 3){
        $target.toggle('-active');
    }

    return( /*html*/
    `

one

two

three

    `
    )
}

Comment: @Andy, I agree, but if this is intended to be jQuery it won't work anyway. jQuery can't act on native elements with methods like `toggle()`.
Comment: Why do the boxes have class `box[n]` at all? If you want to differentiate between them a data attribute is probably the better option.
Comment: This doesn't seem like a very React-ive way to go about this in the first place. You usually shouldn't be manipulating the DOM directly.
Comment: Oh, and if you're using React, this is the wrong approach. React has its own way of updating the DOM. jQuery will just get in the way, and you won't get the results you want. You should be using state to help update the element classes. https://reactjs.org/tutorial/tutorial.html
Comment: OP, if you could add in the rest of your component to your question, and add some details of what causes the classList to be updated, we can probably guide to you to a better solution.
Comment: @isherwood sure it can, if the actual jquery method was being called on them.
Comment: @KevinB, I'm not sure I get your point. As it's written above [it won't work](https://jsfiddle.net/isherwood/rsq1en0b).
Comment: @isherwood Yes, however, `toggle` in that case isn't jQuery's toggle method. it simply isn't a function at all.
Comment: Yep. We get that. The issue was the implication that it was _possibly_ jQuery.
Answer: The proper method is .querySelectorAll and it returns a node list , if you add a [0] at the end like below, you will get the first element of that  node list (which maybe what you want for now), but if you want all target elements use a for loop to loop over document.querySelectorAll('score -box1') array.
const $target = document.querySelectorAll('score -box1')[0]
function PlayerScore(score = 0){
    if(score == 1){
        $target.toggle('-active');
    }else if(score == 2){
        $target.toggle('-active');
    }else if(score == 3){
        $target.toggle('-active');
    }

    return( /*html*/
    `

one

two

three

    `
    )
}

Or you can replace the .querySelectorAll with with .querySelector, it will automatically rturn the first element: https://www.w3schools.com/jsref/met_document_queryselector.asp
Comment: If you use `querySelector` you won't have to grab the first element like that.


Hide 'configure block' for Omega theme?

Question: How can I hide the 'configure block' mouseover from appearing? Im using the Omega theme.
Its breaking parts of my site but I cant stop it from appearing with permissions as certain users need the permission to edit blocks.
Comment: Turn off the Contextual Links module maybe?
Comment: Disabling Contextual Links fixed it.
Answer: If you are using Omega theme version 7.x-3.1, you can go to the templates folder and edit region--content.tpl.php. In line 12 you will find the following:
   <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>

You can comment this line out, or delete it.
Answer: Disabling Contextual Links fixed it.

Hide 'configure block' for Omega theme?


Por que acha o valor maior?

Question: x=0

quantos=0

valor=int(input())

while valor>0:

    if valor>x:

        x=valor #Se aqui ele define o X pro valor inserido, por que ele armazena o maior número?
                #não deveria armazenar o último?
        quantos=1

    elif valor==x:

        quantos+=1

    valor=int(input())

print('X=', x, 'quantos = ', quantos)

Não entendi como o x armazena sempre o número maior. Se eu der input 1, 5, 3, x printa 5, se der 1, 3, 5, printa 5 também...
Answer: Repare que x = valor está dentro do if. Ou seja, x só recebe o valor se o valor for maior que x (ou seja, se valor foi maior do que o maior número encontrado até agora, x passa a ser esse maior).
Então se você digita 1, 5 e 3, nessa ordem:

x começa com valor zero
quando valor for 1, é maior que x (que é zero), então entra no if e x passa a ser 1
quando valor for 5, é maior que x (que agora é 1), então entra no if e x passa a ser 5
quando valor for 3, não é maior que x (que agora é 5), então não entra no if e x continua sendo 5

Repare que x sempre contém "o maior valor lido até o momento". E quando o loop terminar, ele terá o maior valor lido dentre todos os que foram lidos.

Vale lembrar que só funciona com números positivos, já que x começa em zero. Se quiser algo mais genérico, que aceite também números negativos, basta fazer com que x comece com "menos infinito", assim qualquer número digitado será maior que ele:
x = float('-inf')
qtd = 0
while True:
    try:
        valor = int(input())
        if valor > x:
            x = valor
            qtd = 1
        elif valor == x:
            qtd += 1
    except ValueError:
        break # sai do loop

print(f'O maior valor é {x}, e ocorre {qtd} vezes')

Nesse caso estou interrompendo o while quando for digitado qualquer coisa que não seja número (podendo ser "nada" - somente um ENTER), ou um texto qualquer, como "abc". Mas você pode colocar o critério de parada que quiser.

Aprenda a fazer o teste de mesa e a debugar o código, vai te ajudar muito a entender qualquer código.
Answer: Ele não armazena o maior magicamente, isto é um algoritmo, então há vários passos sendo executados com uma coleção de dados que vai sendo entrada.
Em um passo desses ele vai analisar se o que foi digitado é maior que x, então se for, nesse momento o que foi digitado é o maior valor, e dentro do if ele diz então que x é esse valor que foi digitado. A primeira vez qualquer número que foi digitado será maior que x porque essa variável vale 0 e só entra no laço se o que foi digitado é maior que 0.
Aí ele vai executar mais uma vez a mesma coisa, essa é a função do while. E novamente terá que verificar se o novo valor digitado é maior que x, que desta vez vale o valor anteriormente digitado. Mais uma vez só entrará no if se foi digitado um valor maior, e aí o x passaria ter um novo valor. Se não for uma valor maior ele ignora esse dado (na verdade se for igual tem algo a fazer ali no elif, mas isso não é o foco da pergunta).
E ele vai fazendo isso até que seja digitado 0 ou valor negativo. Então o valor de x será o último maior valor digitado, não importa se ele foi digitado por último, porque se você digitar valores menores depois de digitar um maior nunca entrará no if e não mudará o valor de x.
O segredo é o if que determina quando o valor de x será mudado ou não. E junto reinicia a quantidade de número repetidos sem interrupção tiveram pela última vez. Ele não guarda todos repetidos ou as outras vezes que ocorrem inclusive o maior e quantos foram repetidos não tem relação alguma, por isso não sei se era para acontecer isso ou é erro do algoritmo.
Eu aconselho aprender e fazer um teste de mesa e/ou aplicar a execução usando um sistema de debug para ver os dados sendo mudados passo a passo.
Eu acho que x é um nome ruim para o que essa variável faz e prejudica o entendimento. Ainda que o exercício fale em x, seria um nome melhor para entender o algoritmo.
Eu odeio ter que fazer a leitura de dados em dois lugares diferentes e acho mais legível fazer cada coisa na ordem certa, não parece ser um código tão clever, não estou dizendo que é necessariamente melhor, mas acho mais fácil de entender assim:
maior = 0
quantos = 0
while True:
    valor = int(input())
    if valor < 1:
        break
    if valor > maior:
        maior = valor
        quantos = 1
    elif valor == maior:
        quantos += 1
print('X =', maior, 'quantos = ', quantos)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que eu preferi colocar uma condição de fim do laço dentro dele, logo depois que digita um número ele decide se é para continuar ou quebrar (break) o laço.
preferi não fazer a validação de dados digitados, mas se digitar algo que não seja um número quebrará a aplicação.

Por que acha o valor maior?


I want to duplicate Folding (use extra cpu-cycles)

Question: I want to use extra-cpu cycles to do some of my own processing, and I was wondering if someone could point me in the right direction as to how to get started on this?
Answer: I would suggest writing a program that runs continuously (make sure it blocks occasionally), and then simply setting it to a low priority.  The OS Scheduler (Windows/*nix) should handle the rest automatically.
Answer: You can use extra CPU cycles by writing a program that runs in the background.
You can check the CPU usage to find out when the computer is idle (but it's not necessarily a good idea), or you can listen for mouse/keyboard activity.
To check CPU usage in C#, use the following code:
<code>float cpuUsage;    //Between 0 and 100
using (var cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total")) {
    cpu.NextValue();    //First call gives wrong values
    cpuUsage = cpu.NextValue();
}
</code>
To check for keyboard or mouse activity, you'll need to use a keyboard / mouse hook; see here for instructions.
Comment: I would advise against checking CPU Usage, as this polling itself takes CPU.
Answer: Write an application.  Set its thread priorities to "background".  Job done ;)


IF/AND/OR/THEN in Excel

Question: I'm stuck trying to crack an IF/THEN where a specific character is not in one column, and another does have a certain set of text. I'm starting to wonder if it can be done.
I've tried several juggled around versions of =If(AND(..., I've tried =IF(NOT(OR..., I've even tried breaking it apart with =IF(ISNUMBER(SEARCH... which really isn't right.
I'm looking for situations where AE2 does not contain "*/*", and B2 contains "*IND*".
The basic formula I keep coming back to is =IF(AND(AE2<>"*/*", B2="*IND*"), "DAF","") but this is showing all of the columns as DAF then, which isn't right. I feel like I'm close, but I'm missing some little critical thing.
Answer: Try this
=IF(AND(COUNTIF(AE2,"*/*")=0,COUNTIF(B2,"*IND*")=1),"DAF","")

Comment: That did it! I stayed away from COUNTIF because I narrowly thought of it only giving me a 1 or a 0. Thank you!

IF/AND/OR/THEN in Excel


Erro na instalação do Composer: 'não foi possivel encontrar o módulo especificado (php_intl.dll)'

Question: Estou usando windows 10, 64 bits. Ao tentar instalar o composer, exibe o erro:

O php que está sendo indicado na instalação do composer é o do Wamp (localizado em c:/wamp64/bin/php/php7.0.10), e eu já verifiquei que a dll php_intl está lá. Já tentei alterar o php.ini, na linha extension_dir, colocando o caminho completo, mas mesmo assim encontro esse problema. Se alguém puder me dar uma mãosinha por favor...
Answer: Descomentar  a extensão no seu php.ini apenas já resolveria o problema, após isso você deve reiniciar o serviço do Wamp. Caso não funcione , provavelmente será necessário baixar e instalar essa extensão.
Answer: A mensagem pode ser o problema:

A setting in your php.ini could be causing the problem: Either the 'extension_dir' value is incorrect or the dll does not exist.

A configuração do extension_dir pode talvez estar errada no teu php.ini, o que esta afetando carregar as extensões.
Se as extensões estiverem de fato dentro da pasta c:/wamp64/bin/php/php7.0.10/ext, então o caminho no php.ini deve ser
extension_dir="ext"

Ou:
extension_dir="c:/wamp64/bin/php/php7.0.10/ext"

Se ainda falhar é porque de alguma maneira o php_intl.dll não existe dentro da pasta ou foi movido para c:/wamp64/bin/php/php7.0.10/ ou esta usando uma versão incorreta da .dll (eu mesmo tive alguns problemas com extensões do PHP7 no Windows)
Se suas dlls estiverem fora da pasta ext você pode então ajustar o extension_dir para:
extension_dir="."

Ou:
extension_dir="c:/wamp64/bin/php/php7.0.10"

Ou então mover todos arquivos com prefixo php_ para dentro da pasta ext


How to Find PDF of Transformed Random Variables Numerically?

Question: Is there a way to compute and plot the transformed random variable in Python or R?
Let's say if $X_1$ and $X_2$ are independent and identically distributed random variable with PDF defined over non-negative values of $x$ as:
$$
f(x) = \frac{x^2e^{-x}}{2}
$$
Another random variable $Y$ is defined as $Y = X_1 + X_2$.
I know that for computing the PDF of $Y$, I can define a transformed tandom variable $T = \left(X_1+X_2, X_2\right)$ and use conservation of probability and Jacobian of the transformation.
However, what I am interested in is to know if there is a way to do this transformation and compute the PDF using any existing packages/modules of R/Python.
Comment: As far as I know, R has not this symbolic computation capability. Numerical computation through simulation is the only solution I can think of.
Comment: Distributions of the sums of independent variables are computed through convolution, which is most efficiently carried out with the Fast Fourier Transform as explained in [several threads here on CV](https://stats.stackexchange.com/search?q=sum+convolution+fft).  Other transformations require different methods.  Could you therefore please be more specific about what transformation you are interested in?
Comment: @utobi, I am not aware of numerical computation through simulation. How could I use it?
Answer: As far as I can tell, R doesn't have such symbolic computation capabilities; though R does have some limited symbolic computation capabilities (e.g. the command D computes symbolically the derivative of a user-provided function).
Nevertheless, when the analytical computation is hard/long, or you are sceptical about your computations, you can get an approximation via the Monte Carlo (MC) approach. The idea is pretty simple. Instead of computing the analytical PDF of $Z$, draw random numbers from its distribution. You can then use these draws to approximate whatever quantity of $Z$ you are interested in.
Example.
Suppose $X_1,X_2\sim \text{Exp}(1)$, independently. Then $Z = X_1+X_2 \sim \text{Gamma}(2, 1)$. The MC approach would be to draw $N$ values (i.e. $N\times 1$ vector) from the distribution of $X_1$ and other $N$ values (i.e. $N\times 1$ vector) from the distribution of $X_2$. The element-wise sum of these vectors is another $N\times 1$ vector drawn from $\text{Gamma}(2,1)$.
Here is the R code for this.
# number of samples, the larger the better
N <- 1e4

# draw from X1
x1 <- rexp(N)

# draw from X2 (using the same N!)
x2 <- rexp(N)

# apply your funtion; here is the sum
z = x1+x2

# Distribution of Z computed(approximated) via
# Monte Carlo
hist(z, breaks = 30, probability = T, ylim=c(0,0.4))

# The TRUE distribution of Z
plot(function(x) dgamma(x, shape = 2, rate = 1),
     n=100, xlim=c(0,12), lwd=2, add=TRUE)

Side note 1. For the MC method to be applicable, you must be able to take random draws from $X_1,X_2$. Sometimes, this is trivial (as in the example above) but sometimes it may be less trivial. This happens when $X_1$ and $X_2$ do not have known distributions (e.g. normal, gamma, Cauchy, etc.) not there are no standard methods for generating random numbers.
Side note 2. The MC method delivers a stochastic approximation. This means that, if you run the approximation again, you will likely get slightly different answers. Analytical computation doesn't have this issue, thus my advice is to use MC as last resort or as a method for double-checking your analytical calculations.
Comment: Thanks a lot for your answer! There may not be a package to verify the transformed variable as you said but Monte Carlo approach really helped me in double checking my analytical solution. Kudos!


Tanpura app during Bansuri Practice

Question: I am viewing this tutorial

and am unclear on
Please clarify two things
What is purpose of Tanpura (I got Tanpura Droid) playing in background. Is it to create an ambiance which practising, or is it much more?
How do I set Tanpura. I set the pitch to A-scale, since I have an A-scale flute, but what do I set first string?
Do I keep it at Sa, or do I change it every time I am going from one scale to the other, i.e. I start practice by doing 5 deep blows of Sa, 5 of Re, 5 of Ga .. Ma, PA, DHA, NI, SA
Answer: One plays the tanpura in the background to help
fix the pitch of your playing. Since you have a flute
that is set to the A-scale, set the tanpura to the pitch
A. Set the first string to Pa.
The reason for choosing Sa and Pa to be played on the tanpura
is that these notes are "fixed" in all ragas, so having
a constant drone playing these notes in the background gives
you a base which you can rely on to fix your pitch while
playing the flute.
I might add that @Rusi is not incorrect in saying that what
note is played on the first string of the tanpura depends
on the raga being played. However, it is enough to keep
this as a general rule as a beginner that the tanpura
is set to the pitch you are playing and that the first string
is set to Pa.
Do not change the tuning of the tanpura as per the notes you
are playing: that would defeat the purpose of having the tanpura.
The tanpura is not an accompaniment to your music, in the sense
that it does not follow the notes you play. It stays constant
in the background to provide a base for your playing. Use the
Sa and Pa played on the tanpura to understand the positions of
the remaining notes (Re, Ga, Ma, Dha, Ni) as well, in relation
to Sa and Pa.
This is the primary function of the tanpura. However, I do not
deny that playing the tanpura also lends a pleasant ambience.
Comment: Very comprehensive explanation ..... `gives you a base which you can rely on to fix your pitch while playing the flute.` Does this includes notes playing at higher octaves?
Comment: @Marium Yes, this includes playing notes at higher octaves as well.
Answer: In Indian classical the tanpura never changes (or should not).
A teacher of mine reminded me:

How utterly opposite are the words tanpura and it's supposed
  translation : drone
Drone signifies  boredom, monotony
Tan-pura literally means infinite fullness of sound

The first string depends on rag but is usually the fifth

Tanpura app during Bansuri Practice


Erro ao instalar requirements do rvm

Question: Esse erro ocorre para as duas coisas que tentei: 1 - instalar ruby e a partir disso, instalar rvm requirements.
Error running 'requirements_debian_libs_install gawk libreadline6-dev libyaml-dev sqlite3 autoconf libgdbm-dev libncurses5-dev automake libtool bison libffi-dev',
showing last 15 lines of /home/larissa/.rvm/log/1461870549/package_install_gawk_libreadline6-dev_libyaml-dev_sqlite3_autoconf_libgdbm-dev_libncurses5-dev_automake_libtool_bison_libffi-dev.log
is only available from another source

E: Unable to locate package gawk
E: Unable to locate package libreadline6-dev
E: Unable to locate package libyaml-dev
E: Unable to locate package sqlite3
E: Package 'autoconf' has no installation candidate
E: Unable to locate package libgdbm-dev
E: Unable to locate package libncurses5-dev
E: Unable to locate package automake
E: Package 'libtool' has no installation candidate
E: Package 'bison' has no installation candidate
E: Unable to locate package libffi-dev
+ return 100
+ return 100
Requirements installation failed with status: 100.

Alguem tem alguma solucao para isso?
Obrigada.
Answer: Provavelmente seu /etc/apt/sources.list está com repositórios quebrados.
Tente:
sudo apt-get install gawk libreadline6-dev libyaml-dev sqlite3 autoconf libgdbm-dev libncurses5-dev automake libtool bison libffi-dev

E veja o resultado.

Erro ao instalar requirements do rvm


Palavra com maior frequência em uma string a partir de um tamanho

Question: Estou tentando resolver um problema, onde eu preciso ver a palavra com maior frequência em uma String.
O problema é que essas palavras são montadas a partir de um tamanho dado.
Por exemplo:
"5tardenoitemanhãtardenoitetarde"

Eu precisaria pegar o primeiro número, que é o tamanho das palavras que preciso procurar na String que vem depois desse número, e devolver a palavra com maior frequência.
tarde
noite
manhã
tarde
noite
tarde

Nesse caso seria a palavra "tarde".
Alguém teria ideia de como poderia fazer, da forma mais "limpa" possível, além de ter uma verificação caso não haja palavras repetidas?
Comment: O que já testaste?
Comment: @AugustoVasques não é assim tão trivial :)
Comment: É o trivial, não tem muito o que fazer, ou itere pela lista de palavras buscando correspondências ou use expressões regulares.
Comment: @Sergio trivial que digo é não dá para abreviar o código usando algorítimos que gerem atalhos em problemas similares com por exemplo distancia lichtenstein para avaliar similaridades entre strings.
Comment: @AugustoVasques vou dar uma resposta, pensei que desse para usar uma regex tipo `/(\d+)(\D{\1})+` mas o grupo de captura não apanha o que procurava. Se tiveres outra ideia de resposta mais simples coloca também!
Comment: @Sergio estou acabando de escrever uma resposta, mas não vai sair muito diferente do que fez.
Answer: Isso precisa de vários passos...
Deixo uma sugestão. Basicamente:

separa a parte numérica do resto
interpreta o valor do numero
cria uma regex para apanhar o comprimento esperado
cria um objeto com um contador
usa um reduce para saber qual a palavra mais usada...

const string = "5tardenoitemanhãtardenoitetarde";
const numericPart = string.match(/\d+/)[0];
const rest = string.slice(numericPart.length);
const nrs = Number(numericPart);
const regex = new RegExp(`\\D{${nrs}}`, 'g');
const words = rest.match(regex);
const count = words.reduce((obj, word) => {
  if (!obj[word]) obj[word] = 0;
  obj[word]++;
  return obj;
}, {});

const max = Object.keys(count).reduce((mostCommonWord, word) => {
  if (!mostCommonWord) return word;
  return (count[mostCommonWord] < count[word]) ? word : mostCommonWord;
}, null);

console.log('Mais usada:', max);
console.log('Todas:', count);
Answer: Apenas obtive a quantidade de letras por palavra usando a expressão regular ^\d+ que busca um ou mais dígitos que iniciem a frase e então removi os dígitos da entrada com slice().
Criei uma expressão regular baseada no tamanho anteriormente obtido e então a usei para fraturar a entrada em palavras de tamanho fixo.
Então foi só catalogar e contar as palavras e depois verificar qual apareceu mais.

let str = "5tardenoitemanhãtardenoitetarde";

let tamanho = str.match(/^\d+/).join();       //Obtem a quantidade de letras
str = str.slice(tamanho.length);              //Remove a parte numérica
let reg = new RegExp(`.{1,${tamanho}}`, "g");
let palavras = str.match(reg);                //Quebra a string em palavras do mesmo tamanho

let resultados = {};

//Conta a ocorrencia de cada palavra
palavras.map((palavra) => {
  if (resultados[palavra] == null) resultados[palavra] = 0; //Se a palavra ainda não foi catalogada inicializa seu contador
  resultados[palavra] = resultados[palavra] + 1;            //A cada ocorrência incrementa o contador da palavra
});

let maximo = {
  palavra: "",
  ocorrencias: 0
};

//Obtém a palavra que mais se repetiu.
Object.entries(resultados).forEach((palavra) => {
  if (palavra[1] > maximo.ocorrencias) maximo = {
    palavra: palavra[0],
    ocorrencias: palavra[1]
  };
});

console.log("============ ocorrências ============");
console.log(resultados);
console.log("========= maior ocorrência ==========");
console.log(maximo);


Tremolo notation for Sixteenth note triplets

Question: I'm wondering if there's a tremolo notation (https://en.wikipedia.org/wiki/Tremolo) for a repeated Sixteenth note triplets like this one for example:

I've only seen the notation for regular rhythm figures like Sixteenth or eight notes.
Answer: This would have been notated differently in the 19th century, but contemporary practice is this:

If it's necessary to make the rhythmic subdivisions clear:
Answer: Yes, this is possible. This would then look like this:

But then, this would canonically be read as

so you might want to do

or maybe use sextuplets instead of triplets.
Comment: Those quarter note shouldn't be dotted, and there should be a '6' under them, not '3'.
Comment: That example is notated according to the practice of Schubert's time, although it's clear enough from the context. Modern practice is to write quarter notes (if you have the book: Gould p.220). It's the words "or maybe" that are wrong (the Schubert has a sextuplet example).
Comment: @PiedPiper Note the _or maybe use sextuplets instead of triplets_ at the end. Also the note should be dotted, as else it would correspond to 2/3 of a quarter. See for example here for a real example: https://s9.imslp.org/files/imglnks/usimg/6/67/IMSLP04047-SchubertStringQuartetNo14.pdf


9/10 as a 5-adic number

Question: Working with p-adic integers is really simple, and usually if you want to do rational numbers, it's fairly easy; you just use long-division.
But here in the case 9/10 when we're working in the 5-adics; I have no idea. I understand you can extend the p-adic integers to the p-adic numbers; but given $9 = 4 + 1 \cdot 5 + 0 \cdot 5^2 + ...$ and $10 = 0 + 2 \cdot 5 + 0 \cdot 5^2 + ...$ we can't do long-division. So it seems that we'd have to get it in p-adic number form; the issue here is though that I have no idea how to do this. Is it simply trial in error? If so, the question after this is $\frac{1234}{625}$ how the hell am I meant to do that!!!!!
Comment: Paradoxically 1234/625 is easy since $625=5^4$ and $1234 = 14414_5$ so the answer is $1.4414_5$
Comment: Cf. https://math.stackexchange.com/q/1186967/96384 and many similar questions on this site.
Comment: In particular https://math.stackexchange.com/q/3600639/96384.
Comment: In the set of 5-adics numbers, all primes different from 5 are invertible, while 5 is not invertible. In particular dividing by 5 is easy: it's simply shifting the point. For example $$\frac{2}{5}= 0.2$$ $$\frac{4}{5^3}= 0.004$$
Answer: Note that $1/5$ (or any power of it) is not a $5$-adic integer. It is just $\ldots0000.1$, a $5$-adic rational.
Since the geometric series gives $\ldots1111=\sum_n5^n=1/(1-5)=-1/4$, we have
$$\ldots2222=-1/2$$
$$\ldots2223=(-1/2)+1=1/2$$
so
$$9/10=(9/2)/5=(4+1/2)/5=(\ldots2232)/5=\ldots2223.2$$
For the second question, the key is that $625=5^4$ is a power of $5$. So
$$1234/625=0.1234$$
In general, you can simply shift the radix point for each factor of $5$ in the denominator; and the remaining factors in the denominator must be factors of some $(5^m-1)$, so you can move them to the numerator by using the geometric series $\sum_n5^{mn}=1/(1-5^m)$.
Comment: I think I found an easier way to calculate it, here I just noted that 9/10 = 2/5 + 1/2 and wrote 1/2 in 5-adic form, and I did similarly for 1234/625 by breaking it down, you're right though noting 625 = 5^4 really helped.
Comment: Oops, I forgot that $1234$ is in decimal. @Crostul is correct.
Comment: Another way is $\frac{9}{10}+\frac{1}{10}=1$ so $\frac{9}{10}=1-\frac{1}{2}*\frac{1}{5}$. Since $-\frac{1}{2}=...222$ like above, you just need to shift the decimal place and add $1$ to get $...223.2$

9/10 as a 5-adic number


Colocar uma legenda em um gráfico do chart.js

Question: Preciso colocar uma legenda em um gráfico do chart.js, porém não estou conseguindo fazer isso.
Alguém sabe como faço?

        <canvas id="myChart3" width="900" ; height="400"></canvas>

Answer: Para gerar a legenda, precisa retornar um objeto do tipo LegendItem, veja a documentação com a definição da Interface: https://www.chartjs.org/docs/latest/configuration/legend.html#legend-item-interface
Ou seja:
{
    // Label that will be displayed
    text: string,

    // Fill style of the legend box
    fillStyle: Color,

    // If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
    hidden: boolean,

    // For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
    lineCap: string,

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
    lineDash: number[],

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
    lineDashOffset: number,

    // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
    lineJoin: string,

    // Width of box border
    lineWidth: number,

    // Stroke style of the legend box
    strokeStyle: Color,

    // Point style of the legend box (only used if usePointStyle is true)
    pointStyle: string | Image,

    // Rotation of the point in degrees (only used if usePointStyle is true)
    rotation: number
}

Então precisa retornar um objeto desse tipo. O texto da legenda por exemplo é o "text":
return new { text: "Muito Insatisfeito" };
Mas o método recebe por parâmetro os dados do gráfico (chart). Na variável "chart" pode ler o chart.data.labels, e retonar os objetos com os labels corretos.
Veja esse exemplo:
generateLabels(chart) {
    const data = chart.data;
    if (data.labels.length && data.datasets.length) {
        return data.labels.map((label, i) => {
            const meta = chart.getDatasetMeta(0);
            const style = meta.controller.getStyle(i);

            return {
                text: label,
                fillStyle: style.backgroundColor,
                strokeStyle: style.borderColor,
                lineWidth: style.borderWidth,
                hidden: !chart.getDataVisibility(i),

                // Extra data used for toggling the correct item
                index: i
            };
        });
    }
    return [];
}

Ou seja, para cada label, vai returnar um objeto com os dados no formato daquela interface que coloquei acima. Esse exemplo foi tirado da documentação: https://github.com/chartjs/Chart.js/blob/master/src/controllers/controller.polarArea.js#L48


Capturar Header do SOAP com PHP

Question: Boa Tarde
Estou a consumir um WSDL de um Webservice onde após o login e após cada requisição conforme XML retornado abaixo me é apresentada as seguintes tags no head do Soap

<Sequencia> 1 </ Sequencia>
<SessionId> 4b4uc2536530-941f-44e6-ab95-8ee7179fb016 </ SessionId>

Como regra de segurança devo salvar estes e na próxima requisão usar os dados para a próxima requisição gravar, nesta nova requisição sera gerada nova sessão e sequencia e eu devo guarda-las para outra requisição e assim por diante.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <Sessao xmlns="http://dominio.com.br">
            <Sequencia>1</Sequencia>
            <SessionId>4b4uc2536530-941f-44e6-ab95-8ee7179fb016</SessionId>
            <Versao>
                <Id>1</Id>
                <SituacaoCache>Inalterado</SituacaoCache>
                <VersaoAtual>0</VersaoAtual>
                <ReleaseAtual>0</ReleaseAtual>
                <ProximaAtualizacao>0001-01-01T00:00:00</ProximaAtualizacao>
                <Minutos>0</Minutos>
                <VersaoDisponivel>
                    <VersaoRota>0</VersaoRota>
                    <VersaoBanco>0</VersaoBanco>
                    <ReleaseBanco>0</ReleaseBanco>
                    <Compilacao>0</Compilacao>
                </VersaoDisponivel>
                <QuantidadeReleases>0</QuantidadeReleases>
            </Versao>
        </Sessao>
    </soap:Header>
    <soap:Body>
        <LogOnResponse xmlns="http://dominio.com.br">
            <LogOnResult>
                <Excecoes />
                <DatabaseCount>0</DatabaseCount>
                <Retorno>
                    <Id>18659</Id>
                    <Nome>NOME</Nome>
                    <Email>email@example.com</Email>
                    <Endereco />
                    <Bairro />
                    <Cidade />
                    <Estado />
                    <Pais />
                    <Cep />
                    <LogOn>login</LogOn>
                    <DataNascimento>1984-09-17T00:00:00</DataNascimento>
                    <RG />
                    <Cpf>000.000.000-00</Cpf>
                    <Telefone />
                    <Celular />
                    <Configuracoes />
                    <Ativo>true</Ativo>
                    <Tema>Azul</Tema>
                    <Perfil>
                        <Id>12</Id>
                        <Nome>Sites Externos</Nome>
                        <Descricao />
                        <NiveisAcesso>
                            <CLPerfilNivelAcesso>
                                <Id>11</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <NivelAcesso>
                                    <Id>1</Id>
                                    <Nome>Usuário</Nome>
                                    <Codigo>1</Codigo>
                                    <Descricao />
                                </NivelAcesso>
                            </CLPerfilNivelAcesso>
                        </NiveisAcesso>
                        <Modulos>
                            <CLPerfilModulo>
                                <Id>19</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>9</Id>
                                    <Nome>Portais</Nome>
                                    <Codigo>256</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                            <CLPerfilModulo>
                                <Id>20</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>2</Id>
                                    <Nome>Processos</Nome>
                                    <Codigo>2</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                        </Modulos>
                        <Atividades />
                    </Perfil>
                    <Skype />
                    <EmpresaAtual>
                        <Id>0</Id>
                        <SituacaoCache>Inalterado</SituacaoCache>
                        <Nome />
                        <RazaoSocial />
                        <Cnpj />
                        <Endereco />
                        <Bairro />
                        <Cidade />
                        <Estado />
                        <Pais />
                        <Cep />
                        <SistemaWooba>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaWooba>
                        <SistemaSisav>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaSisav>
                        <Arquivo>
                            <Nome />
                            <Extensao />
                            <Hash />
                            <Conteudo />
                        </Arquivo>
                    </EmpresaAtual>
                    <DeveAlterarSenha>false</DeveAlterarSenha>
                    <SenhaNuncaExpira>false</SenhaNuncaExpira>
                    <DataAlteracaoSenha>2015-11-10T14:53:45.647</DataAlteracaoSenha>
                    <DataAlteracaoEmail>0001-01-01T00:00:00</DataAlteracaoEmail>
                    <DataAlteracaoCelular>0001-01-01T00:00:00</DataAlteracaoCelular>
                    <Perguntas>0</Perguntas>
                    <UsaBloqueioIP>false</UsaBloqueioIP>
                    <JornadaTrabalho>
                        <Id>0</Id>
                        <Nome />
                        <Prioridade>0</Prioridade>
                    </JornadaTrabalho>
                    <Sexo>Masculino</Sexo>
                    <TokenSSO />
                    <Arquivo>
                        <Nome />
                        <Extensao />
                        <Hash />
                        <Conteudo />
                    </Arquivo>
                </Retorno>
            </LogOnResult>
        </LogOnResponse>
    </soap:Body>
</soap:Envelope>

em testes o código PHP abaixo ao ser executado me apresenta a seguinte mensagem
XML não existe

$UrlWSLogin = new SoapClient('https://ws.dominio.com.br/integrador/integrador.asmx?WSDL', array('trace' => 1));
//print_r($UrlWS->__getFunctions());

$MetodoLoginWS = 'LogOn';

$DadosLoginWs = array(
    "Sequencia" => "0",
    "SessionId" => "0",
    "prUsuario" => "login",
    "prSenha" => "senha",
);

$ResultadoWS = $UrlWSLogin->$MetodoLoginWS($DadosLoginWs);

//$RespostaWS = '
'.print_r($ResultadoWS,true).'
';

if (isset($ResultadoWS)) {
    //echo '
'. print_r($UrlWSLogin->__getLastResponse());'
';

    $XMLws = $UrlWSLogin->__getLastResponse(); // usando __getLastResponse tenho acesso ao header do soap

    if (!$xml = simplexml_load_string("$XMLws")) {
        echo 'XML não existe';
    } else {
        echo $xml->Sessao->SessionId;
    }

    echo "Falha ao capturar xml do ws";
}

Teria algum tratamento para que eu possa converter as tags do objeto em variaveis assim podendo trabalhar mais fácil com eles como guardar os dados das tags em variaveis?
Comment: Você quer somente obter os nós `Sequencia` e `SessionId` ?
Comment: sim isso mesmo é o que preciso
Comment: Ninguém? Já vi que o bicho é mais difícil de domar do que pensei.

Pois o body do Soap eu consigo ler agora o Head é fogo
Comment: eu ia resnponder, mas vi no seu código algo assim: `// usando __getLastResponse tenho acesso ao header do soap`. Então isso parece contraditório e confuso, haja vista que você quer os header mas ao mesmo tempo diz que os obtêm.
Comment: Veja a resposta abaixo.
Answer: Bom, vamos lá...
A verdade é que você não deveria precisar de nenhum parser, reader XML para analisar os dados XML retornados pela consulta ao web service via SOAP.
O próprio SOAPClient deveria ser capaz de fazer isso sem análise extra da árvore XML.

Todos os exemplos abaixo é baseado no XML da resposta do autor da
  questão.

Isso deveria ser mais ou menos assim:
$client = new SoapClient('arquivo WSDL');
$response = $client->LogOn($DadosLoginWs);
print $response->Header->Sessao->Sequencia;
// ...

Até onde eu sei o código acima deveria servir muito bem. No entanto, caso você ainda queira analisar o XML, eis aqui como você deveria proceder:
DOMDocument / DOMDocument::DOMXPath()
# Registre corretamente o domínio namespace
$namespaceDomain = 'http://dominio.com.br';
# Isso na verdade é somente XML em string
$xmldata = file_get_contents('http://localhost/soap.xml');

$dom = DOMDocument::loadXML($xmldata);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('sessao', $namespaceDomain);
#retorna DOMNode (servirá de contexto)
$sessao = $xpath->query('//soap:Header/sessao:Sessao')->item(0);
$sessaoSeq = $xpath->query('sessao:Sequencia', $sessao)->item(0)->nodeValue;
$sessaoId  = $xpath->query('sessao:SessionId', $sessao)->item(0)->nodeValue;

SimpleXMLElement / SimpleXMLElement::xpath()
$reader = new SimpleXMLElement($xmldata);
$reader->registerXPathNamespace('sessao', $namespaceDomain);
$sessao = $reader->xpath('//soap:Header/sessao:Sessao');
$sessaoSeq = $sessao[0]->Sequencia;
$sessaoId  = $sessao[0]->SessionId;

Como tu podes perceber, é necessário registrar o namespace antes de analisar os nós na árvore XML, do contrário, não funcionará! Isso porque, no seu caso, o nó Sessao possui um  namespace, então para acessar seus descendentes você precisa informar o namespace prefix.
O prefixo de namespace pode ser qualquer nome.

Links úteis:

SimpleXMLElmenet
SimpleXMLElement::xpath
SimpleXMLElement::registerXPathNamespace
The DOMDocument class
The DOMXPath class
DOMXPath::registerNamespace

Capturar Header do SOAP com PHP


ReferenceError: submitForm is not defined at HTMLInputElement.onclick

Question: I'm trying to create a form with a submit button, but I keep getting an error:

submitForm is not defined.

<form action="/action.php" method="GET">
    Name:
        <input type="text" name="Name" id="Name">

    Email:
        <input type="email" name="user-email" id="email">

    <input id="contactSubmit" type="button" onclick="submitForm()" value="Submit">

Answer: "submitForm" in your message is a name of the function. It's called when someone is clicking on the button (click event; "onclick" in your input tag). The message tells that this function in not defined. Make sure that you defined it earlier in you JS-code.


hook_entity_presave() doesn't work

Question: I want to save some details before saving the node, and I tried with hook_node_presave().
function hook_node_presave(Drupal Core Entity EntityInterface $node) {
  if ($node->id() && $node->moderate) {
    // Reset votes when node is updated:
    $node->score = 0;
    $node->users = '';
    $node->votes = 0;
  }
}

Then with hook_entity_presave().
function hook_entity_presave(Drupal Core Entity EntityInterface $entity) {
  $entity->changed = REQUEST_TIME;
}

Both hooks don't work. Why?
Comment: If those are the function names you really used, they aren't considered hooks, except in the case the machine name of the module is hook.
Comment: When asking about code you are using, you should show the real code you are using, or it gets harder to answer the question, Also, you could know it, but it would not be the first time users make a _typo_ like that.
Answer: Your function should be named according to your module's name. If your module is called "foo", then:
function foo_node_presave(Drupal\Core\Entity\EntityInterface $node) {

Note also the use of backslashes, not spaces, to separate namespaces.
Comment: Yes i have done like that !
Comment: @IcecreamJelly I see spaces in the namespace, so the answer given here is correct. If you don't show the code you are using, in a question about code, or the shown code contains typos, don't expect a different answer.
Answer: You can do it like this.
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

http://drupal8.ovh/en/tutoriels/65/update-a-node-entity-programmatically-drupal-8
Comment: hook_entity_presave() is not working on my site. I am using hook_node_presave() function. Don't know what's the issue.

hook_entity_presave() doesn't work


Exibir PDF após chamada AJAX com TCPDF no Laravel 4

Question: Após eu salvar informações no banco de dados utilizando  o código a seguir.
$this->anamnese->create($input);

Eu chamo apenas para teste um código para gerar um PDF de teste com o código a seguir.
PDF::SetTitle('Hello World');
PDF::AddPage();
PDF::Write(0, 'Hello World');

$name = '/test.pdf';

$headers = array(
      'Content-Type: application/pdf',
    );

$filename = storage_path() . $name;

PDF::Output($filename);
return $filename;

E na callback da requisição AJAX exibo um alert de confirmação.
Porém analisando o inspecionar elemento, na aba network, recebo a response a seguir
%PDF-1.7
%����
7 0 obj
<< /Type /Page /Parent 1 0 R /LastModified (D:20141016181750-03'00') /Resources 2 0 R /MediaBox [0.000000 0.000000 595.276000 841.890000] /CropBox [0.000000 0.000000 595.276000 841.890000] /BleedBox [0.000000 0.000000 595.276000 841.890000] /TrimBox [0.000000 0.000000 595.276000 841.890000] /ArtBox [0.000000 0.000000 595.276000 841.890000] /Contents 8 0 R /Rotate 0 /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Annots [ 6 0 R ] /PZ 1 >>
endobj
8 0 obj
<</Filter /FlateDecode /Length 295>> stream
x���Qo�0���+Σ��ۖ���9]|r[�-Q_&H�`�d  ٿ_%AQ�1p�
�m���ˁ�6�s�_X��+�9����`* �Sp[<9Fw��p?�#]vM���[FG�j�a�c��1)؋z�%���E�u�U�2
&4�L��,G�i�x/�<�������:Z��R�-�/�*-���p����QUU�g��lyQf��j��|7�����
�CI�I����z�C nt��u��*�Bm��V�k�ȚV9��л���~��_�*�҈����8�D�p;�� ���|�o
endstream
endobj

Já tentei colocar os headers e não consigo exibir ou forçar o download do PDF, porém testando sem AJAX em uma requisição à uma rota com apenas o código para gerar o PDF, ele gera e exibe no navegador normalmente.
Gostaria que, após o insert no banco, fosse gerado um PDF e aberto em nova aba, com as informações para impressão.
Ou outra solução para gerar PDF ou impressão.
Comment: Já tentou na callback de sucess fazer um get em uma rota diferente que só baixa o pdf ?
Comment: Então pensei nisso, mas por exemplo, o arquivo está na pasta storage, como faria uma rota para ele ?
Comment: Seria algo parecido como isso, substituindo o caminho do $file - http://stackoverflow.com/a/20415796/2099835
Answer: Para que o navegador saiba que o conteúdo é para ser descarregado, deverás utilizar o cabeçalho Content-Disposition (Inglês):
Content-Disposition: attachment; filename="meuFicheiro.pdf"

Adicionalmente, de acordo com as regras, deverá preferencialmente ser enviado o cabeçalho:
Content-Type: application/octet-stream

Para basicamente indicar a navegador:

Eu não sei o que isto é, chama a caixa de diálogo Salvar como e usa se possivel o nome meuFicheiro.pdf.

Digo em cima "preferencialmente" porque supostamente o navegador ao ler a stream do PDF deverá identificar a mesma como um PDF, embora, por via das duvidas, como os dois cabeçalhos damos a indicação completa que é um documento para guardar no dispositivo do utilizador.
Cabeçalho de identificação do documento
Também podes no cabeçalho Content-Type indicar que é um documento PDF:
Content-Type: application/pdf

Laravel
Em alternativa, o Laravel contém um método para indicar que a resposta é um download:
return Response::download($caminhoParaFicheiro, $nomeFicheiro, $cabecalhos);

Ver a documentação em: Laravel: Special Responses (Inglês)
Comment: Tentei tudo isso, e quando dou o window.open no success do ajax aparece aqueles códigos ainda


French " ' " in variable blocks its presentation

Question: Vague language issue in french.
I am building a website with 5 languages. I have setup language files with among others French which i include using PHP

$lang['Description'] = 'Photos';
  $lang['cookie']= "En utilisant notre site Web, vous acceptez que nous utilisions des cookies pour stocker des informations temporaires concernant votre utilisation. Cette information ne sera jamais utilisée à d autres fins!";
  $lang['regio']='Region';
  $lang['Viewkalender0'] = "Vous avez une réservation en cours qui doit être traitée avant qu'une réservation ultérieure puisse avoir lieu.";

I ask for these variables with JS
function checkCookie() {
var regular=getCookie("Homecheznous-Roullens");
if (regular=="Accepted") {
    document.getElementById('cookie').innerHTML=regular;
} else {
   var x= '<?php echo $lang['cookie'] ?>';
   document.getElementById('cookie').innerHTML=x;
   }
}

I can switch between languages without problem, getting the right contents. BUT as soon as I correct the French in "d'autres" only adding the "'" the French contents do not show up. Everything else in the language files still comes up, so the language file is still accepted, and also furtheron in the file I use often the ' without problem. I know about the sensibility of PHP JS and so on on " or ' or vv.That is why you already see that i surrounded this variable with "". It works flawlessly with the variable Viewkalender0 with "qu'une" . ?? Somebody having a clue ?? Cookie is not set BTW. And  as soon as i remove the ',the text shows up.
Have a nice day, Johan
Comment: if you surrond that string `var x= '';` with `"` instead of `'` it should work.
Comment: because right now you'll get `var x='...d'autres...';`
Comment: but keep in mind, that any `"` in your strings will break that - unless you escape them with `\"`
Answer: i think the problem is in your declaration of the variable
var x= '<?php echo $lang['cookie'] ?>';

so this is replaced server side by for example
var x= 'qu'une';

so it's normal that  x doesn't get the right text.
Solition 1 :
escape the ' symbole using \
qu'une  should be qu\'une

solution 2 :
try and change
var x = "<?php echo $lang['cookie'] ?>";

or using escma6
var x = `<?php echo $lang['cookie'] ?>`;

Comment: Well, I didn't see that one. As always my own fault. And useful hints also. Learned again.