Is it legitimate to specify a statement as a Theorem if it is proved using numerical methods (since it can't be proved analytically)?

Question: I have some statement, which is "proved" by numerical methods (particularly, using simulations), since it isn't possible to prove analytically. Is it legitimate to articulate this statement as a Theorem, if it isn't proved analytically. If no, what should I call it?
P.S. More details regarding the statement.
I have some data generating process and need to prove that the generated data as a function of some variable has some properties. For example, I have $x^1,...,x^n$ generated data (n=100000) and need to show that the function $x(\gamma)$ is positive defined  over the domain. Therefore, on the generated data I apply interpolation technique in order to construct the function and I check the property.
Comment: How is it *proved* by numerical methods? There are computer proofs that use reliable numerical methods based on interval arithmetic. See https://scicomp.stackexchange.com/a/1028/640
Comment: @sane How do you know that it cannot be proved?
Comment: Not really, no. You could call it a conjecture, and cite the computation as evidence towards it being true.
Comment: @sane It won't change things. It'll provide more evidence, but no (finite) number of points will constitute a proof in itself. You have no way of knowing whether the function ducks below zero at other points, maybe at a value much larger than the values tested, or maybe at one tricky point in between the points you've tested. Most numbers cannot be expressed by notation, let alone computers! That is, most numbers have absolutely no chance of being tested numerically. How do you know the function doesn't become negative there?
Comment: @sane This might be something that I'd have to see the specifics to comment on properly, but in general, if you want to call it a theorem, you'll need to have a proof attached. You might have sampled 100 000 points, but why that number? Could your opinion change if you sampled 100 000 0000 points? Why didn't you sample, say, 10 instead? What is it about this property that makes you absolutely certain that 100 000 points will tell you definitively whether a function has it or not, but sampling 10 won't? A proof should leave no room for doubt, when verified.
Comment: It is at best empirical evidence, possibly over-fitting, at worst cherry-picking. And "theorem" has a very specific meaning in mathematics. No theorem can be proven in the way you are thinking of.
Comment: How do you know for sure that what you have observed in your simulated data is not a fluke?
Comment: @sane, the argument you are giving to Noah Schweber is certainly not a proof that your statement can not be proven. There are many results (theorems) concerning objects that can not (yet?) be computed explicitly.
Comment: I can't believe no one posted it yet, but I can't see it here so: https://math.stackexchange.com/questions/514/conjectures-that-have-been-disproved-with-extremely-large-counterexamples
Comment: When you say,  it cannot be proved, Do you mean that it is not in our powers yet,  or it is proved that it cannot be proved?
Comment: There are ways that are not "numeric methods" that may be able to show that a polynomial is positive everywhere in the domain $[0,1],$ even for a polynomial of very high degree. You should not assume there is no analytic proof just because the degree is greater than $4.$ After all, you have no need to know where the zeros are, as long as you know they are not in $[0,1].$
Comment: @sane: Your comment suggests that you are in fact unaware of the pitfalls. I challenge you to numerically show that $x^{x+1/\ln(x)/e}-1>0$ for all $x∈[0,1]$.
Comment: @lhf I have edited the question, please have  a look.
Comment: @TheoBendit Thank you for your comment. Actually, I show in the prove of the statement that the only way to prove it is numerical techniques, since it can't be proved analytically.
Comment: @TheoBendit So I need to show that the function $x(\gamma)>0$ over the domain $\gamma \in[0,1]$. i take $m=100 000$ points $\gamma^1,...\gamma^m$, therefore construct the function based on $m$ points using interpolation techniques. Although I think that the specified $m$ observations are sufficient, nevertheless I can generate 100 000 000 points form $\gamma \in [0,1]$, if it will change something.
Comment: @littleO I am sure because I control the data generating process. In other words, manually I estimate the points $\gamma_i$ and specify the estimation error (tolerance).
Comment: Is there an axiom that makes rigorous a numerical proof?
Comment: @dmtri I mean that it is proved that it cannot be proved.
Comment: @NoahSchweber I obtain the data $x_i$'s from $n$ degree polynomial, therefore I can't solve for $x_i$'s for $n>4$. Instead I use numerical methods, to estimate $x_i$'s.
Comment: So you have the function explicitly available and it is a polynomial? Then you can definitly use numerical methods like interval arithmetic mentioned by @lhf, which give you a valid proof. You could also try something like SOS (sum-of-squares) programming. If you post the polynomial, maybe we can say more.
Comment: @user21820 Then, what should I call my findings?
Comment: Exactly as I said. If you understand **all** the pitfalls in such kind of evidence, then perhaps you can call it empirical evidence. If you do not, then most likely you can only call it over-fitting or cherry-picking.
Comment: @user21820 Actually, I do recognize all pitfalls in such kind of evidence, but from other hand I am pretty sure that here we can't have any pitfall, since as I mentioned the domain is $[0,1]$ and I pick up $100 000$ points from that interval. However, I am sure, but it isn't proof.
Comment: @sane So to get you right, the domain of $\gamma$ is $[0, 1]$ but what is the domain of $x$ and $y$? If you perform sampling, you also have to specify these. Are they bounded as well?
Comment: @sane Ok, and you want to show that $x > 0$ for all $\gamma \in [0, 1]$ and all $y \in [0, 1]$, correct?
Comment: Please update your question with the actual equation instead of putting them into different comments, because otherwise it is difficult to follow.
Comment: If we could the Riemann hypothesis would become a theorem by now.
Comment: (converted from an answer to a comment); perhaps not directly relevant to your precise question, but a famous result whose proof is based on (rigorous) numerical computations is Warwick Tucker's proof of the existence of Lorenz attractor, e.g. https://www.ensta-bretagne.fr/jaulin/swim13_slides_tucker.pdf
Answer: In general, numerical methods don't constitute proofs. If all we have is an unknown blackbox function $f:\mathbb{R} \to \mathbb{R}$ that we know nothing about, and all we can do is compute its value at (finitely) many points, then we simply can't prove that $f$ is positive.
However, in specific cases, we could have arguments based on numerical methods that are valid. Typically, we'd need to make a numerical approximation, and then prove, using non-numerical methods, that our numerical approximation is accurate enough for the theorem to follow. As such, how numerical methods can aid us in proving a statement is very statement-specific.
Take, for example the following problem: Prove that $f(x) = x^2 + 1 > 0 \ \forall x \in [-1, 1]$.
Invalid proof: We computed $f(x)$ at $10^{10^{10000}}$ random points and used linear interpolation between them. Here's a plot. We can see that $f(x)$ is always positive.
Valid proof 1: We computed $f(x)$ at points three points: $f(-1) = 2$, $f(0) = 1$, and $f(1)=2$. Let $g(x)$ be the linear interpolation of the points $(-1, 2)$, $(0, 1)$, and $(1, 2)$. $g$ attains its minimum at $g(0) = 1$. Since $f^{\prime \prime} = 2$, we can compute an error bound on our interpolation (see https://ccrma.stanford.edu/~jos/resample/Linear_Interpolation_Error_Bound.html): $|f(x) - g(x)| \leq \frac{2}{8}$. Therefore, we can conclude that $f(x) \geq \frac{3}{4} > 0$.
Note: Often, if we need to resort to numerical methods, if would be just as hard to compute derivatives. However, we don't need the actual derivatives, we just need an upper bound. The better the bound, the less points we would need to evaluate $f(x)$ at. Furthermore, bound to the first derivative is enough, but having second could also reduce the number of points needed.
Valid proof 2 (sketch): We know that $f(x)$ is convex. We use a numerical method to compute its minimum. find that $\min f(x) \approx 1.0000000075$. We also have an (true, non-numerical) error bound on our approximation: $|1.0000000075 - \min f(x)| < 0.001$. Therefore, $f(x) > 1.0000000075 - 0.001 > 0$.
Finally, it doesn't really matter whether analytical proofs exist or not. The validity of any proof is only determined by that proof and no others.
In fact, it has been proven that not all true statements can be proven. But that is no reason to reduce our standards of rigor.
Comment: @alephzero The point of the first proof was to explain how one would argue something "numerically" using a simple example. Of course one can show that $x^2+1$ is non-negative in a billion easier ways, but they would be totally irrelevant to the question.
Comment: @sane A guess. Because that's what it is. An educated guess with a reasonable amount of evidence behind it.
Comment: "Valid proof 1" is perverse (it belongs in the well known book "Mathematics made difficult" IMO) - if you know enough calculus to find the second derivative and understand use the result quoted, you know enough to show that the minimum value is when $x = 0$ without using the "numerical method" at all. Numerical method 2 is not a proof, unless you have a *non-numerical* proof that the error bound of your algorithm is guaranteed to be correct, when using approximate arithmetic (e.g. working to a fixed number of decimal places, or using IEEE floating point arithmetic on a computer).
Comment: Thank you for your answer. I have a question regarding "valid proof 1". You have computed the error bound of the interpolation, but this computation is affordable, when you have the functional form $f(x)$ (actually you have assumed it). But in my case I don't have the functional form, therefore how can I replicate Valid proof 1 to my statement?
Comment: @dmtri no, we don't like it because they're not actual proofs. Without the proper regularity arguments we can end up "proving" numerically things that are actually wrong.
Comment: @sane In that case it doesn't make much sense to talk about a function $x(y)$ - there would likely be infinitely many. If you have $y(x)$, you can bound partials $|\frac{\partial y}{\partial x_i}| < A_i$. Then you'd have $y(x_1 + \epsilon_1, \dots, x_n + \epsilon_n) > f(x_1, \dots, x_n) - \sum \epsilon_i A_i$. However, in practice that would only be useful in low dimensions, otherwise the number of points needed to have a tight enough grid would be prohibitively huge.
Comment: A numerical proof would lead thousands of mathematician to unemployment,  so far. That is why we do not like it?
Comment: @sane I'd need to know the full context to even attempt to answer that: what's the function (as best as you can describe it), where does it come from, how do you compute it? It's not always possible to replicate valid proof 1. Ultimately, you need to have some property that prevents the function from being, for example, positive everywhere except at x=5.3242463456343
Comment: Then what should I call my findings?
Comment: If you knew the function's relation to other functions, you could also squeeze it and obtain a proof that way.
Comment: "We sue a numerical method" - Poor method :(
Comment: @sane If we have $f(x) = g(y)$, we can use implicit differentiation to get $\frac{df}{dx}\frac{dx}{dy} = \frac{dg}{dy}$, therefore $\frac{dx}{dy} = \frac{g^\prime(y)}{f^\prime(x)}$ (note this is an expression of both $x$ and $y$). Then if we can compute a (non-numerical) upper bound $A$ on $|\frac{dx}{dy}|$, we have $f(x \pm \epsilon) \geq f(x) - \epsilon A$. From there we can find out how many points we need to get a good enough bound for the whole domain.
Comment: @TodorMarkov What if we have $f(x_1,...,x_n)=g(y)$?
Answer: Well, is it proven or is it not proven? The way you've phrased your question is "if I've proven something with numerical methods, have I proven it?". Well, yes - you just said you had.
Say you want to prove that $f(n)$ is a prime number for $n<10^7$. Well then if you loop through all the numbers less than $10^7$ and check that $f(n)$ is prime for all of them, you have a proof. It isn't somehow less of a proof just because it doesn't involve a bunch of algebraic symbols and words like "therefore" and "by contradiction".
However, if you want to prove that $f(n)$ is a prime number for all numbers, and you check for $n\leq10^7$, that simply isn't a proof. There's no sophisticated philosophical reason why it isn't, it just clearly isn't, is it? I mean, $f(10^7+1)$ might not be prime, for all you know.
So what you really should be asking is whether or not you actually have proven your statement.
Comment: @sane It's computations which suggest a result might be true.
Comment: Thank you for your answer. Actually, I pick up (finite) points, therefore according to your answer I can't consider it as a proof. Then, please suggest what should I call it?
Comment: @sane: In short, your claim must be as accurate as your proof. If you've run your number simulation on a set of numbers (which is obviously finite), then you can only claim that it if proven for that set of numbers. You cannot make any claims about untested numbers. What you should do is amend your claim. Instead of saying "f(n) is a prime", you should say "f(n) is a prime for 0 < n < 10^7" (for example).
Answer: And it turns out that with further analysis of your actual problem you could have found an exact proof with first semester calculus means. There is no need for speculative numerical explorations.
For your actual problem, to find solutions $x(γ,y)>0$ for the equation
$$
(γ^{n−1}y)^n+(γ^{n−2}y)^{n−1}+...+(γy)^2+y=A(γ,y)=x^n+x^{n−1}+...+x,
$$
it is rather easy to answer that there is exactly one positive root $x$ for fixed positive $y$ and $γ$.
The right side at $x=0$ is zero and grows monotonically and convexly towards infinity, thus there is a positive root of the equation by the intermediate value theorem. Further, there is a lower bound
$$
x>\frac{A}{1+A}\ge\frac{y}{1+y}
$$
for the positive root, as either $x\ge 1$ or, for $0<x<1$,
$$
A(1-x)=x(1-x^n)<x\implies x>\frac{A}{1+A}
$$

In general, there are methods to determine the number of positive roots like Descartes rule or the Hurwitz criteria of stability. Descartes rule counts the sign changes in the coefficient sequence. Here $x^n+...+x^2+x-A=0$ has exactly one sign change which proves the existence of exactly one positive root.
The polynomial equation has lower root bounds $a_nx^n+...+a_1x+a_0=0$
$$
|x|\ge\frac{|a_0|}{|a_0|+\max_{k=1..n}|a_k|}
 ~~ \text{ or } ~~
|x|\ge\frac{|a_0|}{\max(|a_0|,\,|a_1|+...+|a_n|)}
$$
which are lower bound for a single positive root.
Comment: @sane: This should be in your Question, not hidden in comments.  In your first equation, where are the transitions between $a$ and $a+1$ in the numerators on each side?  In your second equation, does the sum on the right terminate?
Comment: @sane : It belongs in your Question, because your question is an instance of an [XY problem](https://meta.stackexchange.com/a/66378).
Comment: @sane : Then please add the correct problem statement somewhere, preferably to the body of the question text. It is better to add relevant, essential information there than in comments. There are many elementary and not so elementary results on the location and bounds of real roots, starting with Descartes' rule.
Comment: Sorry, I had a typo, this isn't the problem that I consider.
Comment: Ok, it looks more difficult to decide on the positivity of $h$. Still, I do not see it as hopeless to try to derive theoretical results, the right sides are still monotonic and convex polynomials in $1/(1+x)$ resp. $1/(1+z)$ with a nice structure.
Comment: @EricTowers In the first equation for the last term ($n$-th), in the numerator we have $a+1$, instead of $a$. Regarding second equation, I haven't space in order to finish the expression, the last term is identical to the last term of the LHS expression with denominator $(1+z)^n$ instead of $(1+\gamma^{n-1}y)^n$. (P.S. I write this in the comments, since my question is slightly different)
Comment: We need to solve the polynomials for $1+x$ and $1+y$, then subtract 1. But since we have $n$ degree polynomial, we can't solve it analytically (for instance for $n=25$) or it can be solved with very huge efforts, which isn't reasonable. Therefore, I decided to proceed with numerical techniques. Do you see any other option?
Comment: @sane : Please open a new topic with that question, as the general question about the proof method has been answered exhaustively as "in this generality, NO, and if at all, then only with strict error bounds in all stages."
Comment: @LutzL I am trying to show that we can't prove the statement using approach, which identifies bounds on roots (I mean lower and upper bounds). I know only Cauchy's theorem and your approach. My question is: (i) whether I have to apply all techniques which identify lower and upper bounds of the root, or one of them is enough, in order to state that this technique doesn't give insight regarding comparison of roots of two polynomials (ii) and what are other methods I have to consider besides Cauchy's theorem and the approach that was suggested by you? Thank you.
Comment: I think that to get in any way close to an impossibility argument is more difficult than finding analytical root approximations with close error bounds and proving the claim for some part of the domain and carving out ever larger parts by improving the bounds.
Comment: @LutzL I would highly appreciate if you could give me some links about "root approximations with close error bounds". Actually, what does it mean? Thank you.
Comment: As I already said, you should open a new question asking for close approximations of $x,z$ or just bounding their difference away from zero, resp. alternatively the same for the quantities $\frac1{1+x}$ and $\frac1{1+z}$. Comments are not for extended discussions.
Answer: As other answers have said, a statement is either proven or unproven.  If it is proven, we call it a theorem, regardless of the methods used.  I'm answering separately to call attention to some of the pitfalls of trying to "prove" things with numerical methods.
The vast majority of real-world numerical computing (outside of the financial sector) uses IEEE 754 floating point to represent numbers which may not be integers.  In short, the floating point numbers are a finite (but large) subset of the dyadic rationals, which become sparser (at a roughly logarithmic rate) as we move away from zero.  There are also a few "special" values which are used to represent the results of invalid operations or arithmetic overflow.
Why does this matter?  It's important to understand the limitations of floating point arithmetic.  In particular:

It does not support irrational numbers whatsoever.  The Dirichlet function and its cousins cannot be usefully analyzed at all.
Numbers which are farther from zero have less precision, so functions with essential singularities will be difficult to work with in the neighborhoods of their singularities.
Limits are potentially an issue.  Normally, a limit only exists if it exists under any possible choice of epsilon, but the floating point numbers can only choose finitely many epsilons, all of which are dyadic rationals.  So if you take a limit of a function which behaves "specially" over the dyadic rationals (e.g. certain combinations of trigonometric functions), you may derive an incorrect value or incorrectly conclude that the limit exists at all.
The floating point numbers are non-associative under every operation that matters, because of intermediate rounding.  No useful algebraic manipulations will preserve equality.  So equality is basically useless and you have to approximate it by looking at whether numbers are "close enough" instead.  For some applications, this is a problem (e.g. proving that a value is never exactly zero is impossible if it comes arbitrarily close to zero).
Comment: And even for integers, a real world computer is probably really working with the integers modulo some power of 2.  In many cases, they silently overflow so considerable care is needed even if you expect that a solution exists within the available range.


Ajuda com Array e operações

Question: Array[1] previamente setado.
A lógica é, pegar o ultimo numero do Array, fazer a operação com o valor do display e retornar como ultimo numero do array.
Exemplo:
Digite 2 e aperte X, 2 * o ultimo item do array.  Retorna 2.
Então este valor é jogado para o final do Array.
Agora Array[1,2]. Aperte 4 e multiplique, Array[1,2,8].
Estou contente com isso pois posso manipular depois.
A questão é este Array previamente setado com 1 deveria estar vazio!!! Pois assim eu poderia reutilizar este calculo para divisão.
Já que se você testar a mesma coisa com o botao de divisao (Aperta A/C antes). Aperta 2 %, Ai está, o Array ficara Array[1,0.5]. pois 1/2= 0.5.
Daria certo se fosse 2/1, pois resultaria em Array[1,2], e daria certo.
Já tentei iniciar Array com valor null, 0 e ''. Sempre retorna NaN, undefined ou o proprio 0, obviamente.
Lembre de digitar o numero no display e so clicar em X, A/C para resetar o Array e %.

const buttonnum = document.getElementsByClassName('num');
    const inputdisplay = document.querySelector('#displayval input[type="text"]')
    var arrayhistory = [1];
    var resultado;
    Array.from(buttonnum).forEach(function(item) {
      item.addEventListener('click', function(e) {
        switch (e.target.value) {
          case "A/C":
            arrayhistory = [1];
            inputdisplay.value = "0";
            console.log(arrayhistory);
            break;
          case "C":
            inputdisplay.value = inputdisplay.value.slice(0, -1);
            if (inputdisplay.value == '') {
              inputdisplay.value = "0";
            }
            break;
          case "X":
            var arraylastnum = arrayhistory.slice(-1)[0];
            console.log(arraylastnum);
            resultado = (arraylastnum * inputdisplay.value)
            arrayhistory.push(resultado);
            inputdisplay.value = '0';
            console.log(arrayhistory);
            break;
          case ".":
            inputdisplay.value += '.';
            break;
          case "%":
            var arraylastnum = arrayhistory.slice(-1)[0];
            console.log(arraylastnum);
            resultado = (arraylastnum / inputdisplay.value);
            arrayhistory.push(resultado);
            inputdisplay.value = '0';
            console.log(arrayhistory);
            break;
          case "-":
            break;
          case "√":
            break;
          case "+":
            break;
          case "÷":
            break;
          case "=":
            break;
        }
      })
    })
    * {
      margin: 0;
      padding: 0;
    }

    header h1 {
      text-align: center;
      margin: 8px;
    }

    #div-caldisplay {
      background-color: rgb(51, 51, 48);
      width: 500px;
      height: 140px;
      margin: auto;
      margin-top: 20px;
      border-radius: 8px;
    }

    #displayval {
      display: flex;
      justify-content: center;
      height: 80px;
    }

    #text-view {
      height: 75px;
      width: 470px;
      font-size: 35px;
      border: 1px solid black;
    }

    .flexcontainer {
      display: flex;
      justify-content: space-around;
      align-content: space-around;
      background-color: rgb(18, 58, 18);
      flex-wrap: wrap;
      height: 350px;
      width: 300px;
      margin-left: 31.8%;
      border-radius: 8px;
    }

    .flexcontainer2 {
      display: flex;
      justify-content: center;
      align-content: space-around;
      background-color: rgb(158, 27, 27);
      border-radius: 8px;
      flex-wrap: wrap;
      height: 350px;
      width: 100px;
    }

    .flexcontainer3 {
      display: flex;
      justify-content: center;
      align-content: space-around;
      background-color: rgb(2, 2, 2);
      border-radius: 8px;
      flex-wrap: wrap;
      height: 350px;
      width: 100px;
    }

    #flex {
      display: flex;
    }

    #teste1 {
      width: 100px;
      height: 100px;
      background-color: darkmagenta;
    }

    #teste2 {
      width: 100px;
      height: 100px;
      background-color: chartreuse;
    }

    .num {
      width: 85px;
      height: 65px;
      font-size: 25px;
      cursor: pointer;
      border: none;
      border-radius: 5px;
      border-bottom: 2px solid black;
      transition-duration: 0.1s;
    }

    .num:active {
      opacity: 0;
    }

    .num:hover {
      font-size: 28px;
    }

    #mais {
      height: 195px;
      background-color: crimson;
    }

    #igual {
      height: 195px;
    }
<!DOCTYPE html>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Calculator</title>
    <link rel="stylesheet" href="calc.css">

CALCULATOR

            <input type="text" name="visor" value="0" id="text-view">

            <input class="num" type="button" value="A/C">
            <input class="num" type="button" value="C">
            <input class="num" type="button" value="X">
            <input class="num" type="button" value="1">
            <input class="num" type="button" value="2">
            <input class="num" type="button" value="3">
            <input class="num" type="button" value="4">
            <input class="num" type="button" value="5">
            <input class="num" type="button" value="6">
            <input class="num" type="button" value="7">
            <input class="num" type="button" value="8">
            <input class="num" type="button" value="9">
            <input class="num" type="button" value=".">
            <input class="num" type="button" value="0">
            <input class="num" type="button" value="00">

            <input class="num" type="button" value="%">
            <input class="num" type="button" value="-">
            <input class="num" id="plus" type="button" value="+">

            <input class="num" type="button" value="√">
            <input class="num" type="button" value="÷">
            <input class="num" id="equals" type="button" value="=">

Obrigado desde já.
Answer: Consegui !
A solução para % foi essa:
 case "%":
            var arraylastnum = arrayhistory.slice(-1)[0];
            console.log(arraylastnum);
            if (arraylastnum == 1) {
                resultado = (inputdisplay.value / arraylastnum);
            }
            else {
                resultado = (arraylastnum / inputdisplay.value);
            }
            arrayhistory.push(resultado);
            inputdisplay.value = '0';
            console.log(arrayhistory);
            break;

Com + e - da pra iniciar com o valor 0 No Array Array[0]. Porém vamos ver na radiciação e porcentagem.

Ajuda com Array e operações


Twig template print all comments but not the comment form

Question: For context:
in my template file node--some-node.html.twig i have a grid of items which have a custom comment form on them. The form creates a comment through an API. The form passes the ID of the grid item it is under to the API and the created comment then has a field_profile_id with the item's id in it. Now, in the template file I need to output JUST the comments that belong to that grid item.
When I write this into the template file:
    {{ content.field_comments }}
i get the output of all the comments that belong to this node and underneath I get the comment form (which I don't need). Ideally I would like to do everything in the same template file, so I could do something like this:

{% if entity.nid.value == content.field_comments.someComment.field_profile_id %}
{# output the comment here #}
{% endif %}

Here the entity.nid.value is the node id of the grid items I was talking about earlier.
EDIT:
Theoretically what I need to do is:

Iterate through all possible comments for this node.
Check if comment has some ID value (that a grid item might have)
If the IDs match, print out the comment, if it doesn't skip it
Answer: You must add a file to your template called
field--comment.html.twig
Use the following code.
{#
/**
 * @file
 * Theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'comment-wrapper',
  ]
%}
{%
  set title_classes = [
    'title',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}

Comment: Hello, I am not really sure how this would help. Vaguely speaking what I need to do is: iterate through comments and check if a comment has a certain ID value. If it does, print it, if it doesn't don't. I will update my question
Answer: So the node in question had a field field_comments, from which I was trying to access the comments. I found a different way of doing that - I created a MYMODULE_preprocess_template function, loaded all comments of the node in that function, created a variable "comments", where I stored the comment data I needed and passed it on to the twig template. Here's the code in MYMODULE_preprocess_template function:
$node = \Drupal::routeMatch()->getParameter('node');

$user_comments = [];
  $entity_manager = \Drupal::entityTypeManager();
  try{
    $storage = $entity_manager->getStorage('comment');
    $comment_field = $node->get('field_comments');
    $comments = $storage->loadThread($node, $comment_field->getFieldDefinition()->getName(),\Drupal\comment\CommentManagerInterface::COMMENT_MODE_FLAT);
    if(empty($comments)){
      return;
    }
    foreach($comments as $comment) {
  $user_comments[] = [
    'cid' => $comment->id(),
    'user_id' => $comment->get('field_prf')->value,
    'comment' => $comment->get('field_comment')->value,
    'alias' => $comment->get('field_alias')->value,
    'rating' => $comment->get('field_rating')->value
  ];
}

  } catch (\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException $e) {
  } catch (\Drupal\Component\Plugin\Exception\PluginNotFoundException $e) {
  }
  $variables['user_comments'] = $user_comments;


What does [2 whole steps down & b flat down] mean for the guitar?

Question: I know two steps down is C tuning, but what does the "b flat down" mean?
Comment: Give us an example of where you've seen this.
Comment: Is this about [B flat tuning](https://en.wikipedia.org/wiki/B%E2%99%AD_tuning)?
Comment: To me, that sounds like "C Standard Drop Bb" or just "Drop Bb", but I've never seen or heard it expressed that way
Comment: I'd be interested what songs play with this tuning
Answer: I'm not sure where you found this, but it sounds like a very roundabout way of describing drop Bb tuning. C Standard is CFBbEbGc, whereas Drop Bb lowers the bottom C a whole step to yield BbFBbEbGc. That's the only real sensible way I could think to interpret "b flat down".


2 websites hosted on same domain, 1 needs to look like a subfolder ( /blog)

Question:
I bought a VPS for my new project running apache.
On it I have 2 websites on the same domain.
The first one is Ruby on Rails /var/www/html
The second one is Wordpress /var/www/blog
I want Wordpress to act like a subdirectory of ruby ( /blog).
Ruby on Rails website works, but if i go to /blog it just says that the page im looking is not available(with RoR 404 template)
Conf for RoR:
<VirtualHost *:443>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/public
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/certificate/apache-certificate.crt
        SSLCertificateKeyFile /etc/apache2/certificate/apache.key

</VirtualHost>

Conf for Wordpress:
<VirtualHost *:443>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/blog
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/certificate/apache-certificate.crt
        SSLCertificateKeyFile /etc/apache2/certificate/apache.key
        Alias /blog /var/www/blog
</VirtualHost>

Maybe the solution is a htacces file in /var/www.
Can you pleasep point me?
Thank you !
Answer:
On it I have 2 websites on the same domain.

Well, you actually have 1 website (1 domain). It's just that you have WordPress in a subdirectory of that 1 website. Consequently, you should only have 1 <VirtualHost> container, not 2 - which is where you would seem to be going wrong here.
The second <VirtualHost> is not being used and should be removed.
You need to move the Alias /blog /var/www/blog directive into the first <VirtualHost> container and allow access to this directory by including the following inside the vHost container:
# WordPress
<Directory /var/www/blog>
    # Permit access to this area
    Require all granted

    # Allow per-directory overrides if want to use WP htaccess file
    AllowOverride All
</Directory>

I assume you must already have something similar for /var/www/html/public?
You should really include a ServerName directive inside this vHost container, otherwise, this is just acting as the "default" by being defined first. For example:
# Declare the hostname that this vHost defines
ServerName example.com

And then define a "default" vHost container before this that catches non-canonical requests.
Comment: This is my defaultconf:
Comment: This is my defaultconf:

ServerName fdcb.site
  Alias /blog /var/www/blog
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/public
        SSLEngine on
        SSLCertificateFile /etc/apache2/certificate/apache-certificate.crt
        SSLCertificateKeyFile /etc/apache2/certificate/apache.key
# WordPress

    # Permit access to this area
    Require all granted

    # Allow per-directory overrides if want to use WP htaccess file
    AllowOverride All
Comment: i created a file https://fdcb.site/blog/a.php and it is accesible, but index.php is not. i have disabled htaccess file, tried some things inside it, but again, i dont have the skills.
have to say i tried many methods just to bypass server settings. tried to make it run in public, installed wordpress from terminal. came here after many hours of failing.
Thank you for your help
Comment: @Adelle "i created a file fdcb.site/blog/a.php and it is accessible" - and `a.php` is physically located at `/var/www/blog/a.php`? In that case, this would seem to have answered your question. (In which case you should mark it as "accepted"  - tick/checkmark on the left below the voting arrows. Once you have 15+ rep then you can also upvote answers you find useful. Thanks, much appreciated. :)
Comment: @Adelle "but index.php is not" - presumably you mean when accessing the `/blog/` subdirectory? This is a different problem. For `index.php` to be served when requesting a directory, you need to set `DirectoryIndex index.php` in the appropriate `` container.
Comment: even if i type https://fdcb.site/blog/index.php it does not work . I have added DirectoryIndex index.php to default conf inside Directory /var/www/blog and rr but nothing.
Comment: What do you mean by "does not work" exactly? If `/blog/a.php` is accessible then so should `/blog/index.php` if you are putting the files in the same directory?
Comment: inside /blog/ directory i have a wordpress instalation. Yes, the file is there. The filepermision is 755 . The only time i got it to work was when the blog was configured by me to work in http, with different virtualhost.


The size of output binary is smaller by using gcc rather than g++

Question: I'm migrating my project from C to C++ and today I noticed something strange. I have two almost the same (the only difference is extern keyword in .cpp) main files (created for compilation testing purpose). The first one is main.c and the second one is main.cpp.
The source code of these files you can find below. I'm using libopencm3, which is compiled to the static library, and then it is linked anywhere it is needed. So what is the problem? In the scenario where I compile my project using main.c (using gcc), the output binary is much more smaller than the output binary produced by compiling using main.cpp (using g++). I can't figure out what causes this issue?
The code is compiled for the STM32F1C8T6 target.
//main.c
#include <libopencm3/stm32/rcc.h>

static void rcc_setup()
{
  //Clock setup
  rcc_clock_setup_in_hse_8mhz_out_72mhz();

  //Peripherals clock
  rcc_periph_clock_enable(RCC_GPIOA);
  rcc_periph_clock_enable(RCC_GPIOB);
}

int main()
{
  rcc_setup();

  while(1)
  {

  }
}

//main.cpp
extern "C" {
  #include <libopencm3/stm32/rcc.h>
}

static void rcc_setup()
{
  //Clock setup
  rcc_clock_setup_in_hse_8mhz_out_72mhz();

  //Peripherals clock
  rcc_periph_clock_enable(RCC_GPIOA);
  rcc_periph_clock_enable(RCC_GPIOB);
}

int main()
{
  rcc_setup();

  while(1)
  {

  }
}

The structure of my project looks basically like:
- root
  CMakeLists.txt
  - lib
    - libopencm3
  - src
    - app
      CMakeLists.txt
      - inc
      - src
        - main.c
        - main.cpp

Here is my root CMakeFile.txt. I think it is the most important because it contains compilation flags, etc. There are also some other things within it, like port dirs, port.cmake etc, but these are not important in this case, so please just ignore them.
cmake_minimum_required(VERSION 3.16)
project(stm32-template)

# COMPILER JUST TEMPORARY TODO: REMOVE!!!
set(CMAKE_ASM_COMPILER "/usr/bin/arm-none-eabi-gcc")
set(CMAKE_C_COMPILER "/usr/bin/arm-none-eabi-gcc")
set(CMAKE_CXX_COMPILER "/usr/bin/arm-none-eabi-g++")

# CMAKE MODULES
include(${CMAKE_ROOT}/Modules/ExternalProject.cmake)

# GENERAL PATHS
set(PORT_DIR ${PROJECT_SOURCE_DIR}/src/port/${PORT})

# PORT CONFIGURATIOM
include(${PORT_DIR}/port.cmake)

# COMPILER CONFIGURATION
set(COMPILER_CXX_FLAGS "-fno-use-cxa-atexit -Os")
set(COMPILER_FLAGS "-fdata-sections -ffunction-sections -O0 -DNDEBUG -Werror")
set(LINKER_FLAGS "-nostartfiles -specs=nano.specs -specs=nosys.specs --static -ggdb3 -Wl,--gc-sections -Wl,--start-group -lc -lgcc -lnosys -Wl,--end-group -Wl,-Map=output.map -T ${LD_SCRIPT}")
set(CMAKE_BUILD_TYPE Release)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

set(CMAKE_C_FLAGS "${COMPILER_FLAGS} ")
set(CMAKE_CXX_FLAGS "${COMPILER_CXX_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${LINKER_FLAGS}")

# LIBRARIES
set(LIBOPENCM3_PATH ${PROJECT_SOURCE_DIR}/lib/libopencm3)
set(LIBOPENCM3_INCLUDE ${LIBOPENCM3_PATH}/include)
set(LIBOPENCM3_BIN ${LIBOPENCM3_PATH}/lib/libopencm3_${MCU_FAMILY}.a)
ExternalProject_Add(libopencm3
    SOURCE_DIR "${LIBOPENCM3_PATH}"
    BUILD_IN_SOURCE true
    DOWNLOAD_COMMAND ""
    CONFIGURE_COMMAND ""
    INSTALL_COMMAND ""
    BUILD_COMMAND make
)

# ADD LIBRARY INCLUDES
include_directories(${LIBOPENCM3_INCLUDE})

# SUBDIRECTORIS
add_subdirectory(src)

# CUSTOM COMMANDS
add_custom_target(flash
  COMMAND JLinkExe -device STM32F103C8 -If SWD -Speed 1000 -CommandFile tools/jlink/FlashCommand.jlink
  COMMENT "asd"

  #DEPENDS {EXE_NAME}
)

Comment: The C standard library can lean a lot more on the OS for implementations, but the C++ standard library has a lot of things it has to have code for that aren't in the OS. Streams and locale stuff mostly.
Comment: Someone just before, posted the comment that suggested to use "-fno-exceptions", and it helped. The size of output binary is the same no matter I  use main.cpp or main.c. I totally forgot about this flag.
Comment: Yes it is bare metal. I didn't point it in the question, but it is of course kinda important.
Comment: @MooingDuck what OS? it is bare metal
Comment: You can also look at the output of `objdump` to see what's included. It will output the contents of an executable image. It can even disassemble it if you use -S.
Comment: And when you say binary what do you mean the elf output from the toolchain or after you do the equivalent of objdump -O binary (depending on your toolchain of course as to how you do this)?
Comment: By size of binary I mean, the output of size command on my .elf file, and especially the size of .text section.
Answer: The C++ language has a much larger runtime than the C language (because of things like exceptions, RTTI, <iostream>, <thread>, and so forth).
When you link an application statically, you link in the entire language runtime, or at least those parts that are referenced somewhere in your code, including objects of static and thread-local storage duration in headers you pull in (eg. std::cout).  Most desktop applications don't see this because it tends to be in DSOs.
Because of language interop, you'll find a good deal of the C++ runtime is actually in your system libc.  That includes exception handling and unwinding. If you see symbols like __cxa_* and Unwind* that's what's going on.


Validar campos com selects(Combobox)

Question: Tenho o código abaixo que gera quantidade de quartos nos meus selects.
 str += '<select class="select-group" id="selQuartos">';
 str += '<option>Qtd. quartos</option>';

 for (var i = 1; i < $("#Quartos").val() + 1; i++) {

     if (i == 1) str += '<option>' + i + ' quarto</option>';
     else str += '<option>' + i + ' quartos</option>';

     if (i == $("#Quartos").val()) break;
 }

 str += '</select>';

Tenho essa função javascript que valida se há checkboxes checados ou não. Gostaria de acrescentar nessa validação, se há quartos selecionados nos meus combos acima,  mas não estou conseguindo fazer. Checkboxes pegamos os valores checados e pronto. Agora como fazer com Combos? Tentei assim: if($("selQuartos").val() < 1)... Isso não funcionou, porque não consigo trazer o valor do Seletor(Combobox). Abaixo javascript para validar:
 function Submit() {
     var Apartmento = [];
     var retorno = false;
     for (var i = 0; i < filtroPesquisa.chkApartmento.length; i++) {
         if (filtroPesquisa.chkApartmento[i].checked) {
             Apartmento.push(filtroPesquisa.chkApartmento[i].value);
         }
     }
     if (Apartmento.length == 0) {
         for (var i = 0; i < filtroPesquisa.chkApartmento.length; i++) {
             filtroPesquisa.chkApartmento[i].style.color = "red";;
         }
         retorno = false;
     } else {
         retorno = true;
     }

Então, colmecei a fazer como o FS.DEV postou. Se eu comento o for e dou return false, não vai para outra página, mas se deixo o for mesmo com return false, ele vai para outra página. Como ele chama outra página, não consigo pegar se há ou não erro de javascript. Veja como eu estou fazendo. Coloquei o return false apenas para testes.
function Submit() {

    var _selSeguro = document.getElementById('selSeguro');
    var _selIngresso = document.getElementById('selIngresso');
    var _selPasseio = document.getElementById('selPasseio');

    var selecionados = new Array();
    for(var i = 0; i <_selIngresso.length; i++)
        if(_selIngresso[i].selected)
            selecionados.push({'id':i,'valor':_selIngresso.value});

        return false;

    }

Observei algo importante aqui. Quando a página entra, vem os sliders fechados. Quando eu abro um slider é que me apresenta os botões e combos para preencher. Com os sliders abertos, o botão para navegar a outra página obedece ao return da função. Isso só não acontece quando os sliders estão fechados. Alguém sabe o porque?
Fiz dessa form e não deu certo.
if ((_selIngresso.value == '') && (_selPasseio.value == '') && (_selSeguro.value == ''))
        return false;

Se eu fizer uma a uma, dá certo, mas todas não dão, porque quando abro um slider, os denais se fecham e essa validação só acontece quando os sliders estão abertos. Alguém tem alguma idéia de como fazer isso?
Eu falei slider, mas agora vi que se chama ACCORDION os efeitos, ou seja, quando um abre o outro se fecha. Quando está fechado é que não consigo mais pegar nada nele, nada mesmo. Aí dá erro de javascript e o botão chama a página.
Comment: De onde vem o `filtroPesquisa` ? Pode fazer por favor um jsFiddle com o seu código recriando o problema?
Comment: filtroPesquisa é o form do html. O que é jsFiddle?
Comment: A função do FS.DEV está certa. Eu é que estou apanhando na lógica aqui.
Answer: Não está muito claro o que você perguntou, o que eu entendi e que você quer saber se está selecionado ou num um select, se for isso você pode fazer da seguinte forma... vou utilizar o javascript puro, se necessário faça as adaptações.
A primeira seria o seguinte.
Substitua o a linha
str += '<option>Qtd. quartos</option>';

por
str += "<option value=''>Qtd. quartos</option>";

e faça a seguinte validação:

Validar campos com selects(Combobox)


Finding a quadrature rule for symmetric integral

Question: I have to find a quadrature rule that approximates the integral of $f(x)$ such that
$$\int_{-h}^{h} f(x) = w_1f(x_1) + w_2f(x_2) + w_3f(x_3) + E$$ where the weights $w_i$ and points $x_i$ are to be found. I also have the extra condition:
$$\int_{-h}^{h} f(x) = \int_{-h}^{h} f(-x)$$
I'm not sure how this extra condition factors into finding the required constants; usually I would set $f(x)$ to be a linear function, then quadratic, then cubic etc. up until the last order of polynomial that we know it will be exact to. I don't know how accurate it has to be, but I'm assuming this particular rule will be exact up to cubics as it resembles Simpson's rule, so since I have six constants to find, the symmetric condition will need to provide 2 more (I estimate).
However, running through my usual method of setting $f(x) = 1$, I would get $2h = w_1 + w_2 + w_3$ as expected. However, since $f$ is constant, I derive the exact same condition. Setting $f(x) = x$ then gives me $0 = w_1x_1 + w_2x_2 + w_2x_2$, and again the extra condition won't help since $\int_{-h}^{h} -x = 0$ aswell. This pattern seems to continue as I use higher order polynomials, so I think that I must be using this symmetric condition wrong. Any help with where to go from here would be very much appreciated.
Comment: (1) as written, your symmetry condition does not make much sense. That equation is always true for any function $f$. And (2) what kind of quadrature rule do you want? You can choose any $x_i$ you want, and any $w_i$ that satisfy $2h=w_1+w_2+w_3$ to get *some* consistent quadrature rule. Though it wouldnt be very good for most choices...
Comment: @Simon this is basically what I thought, it seems like useless information. Usually with these problems we're told that it's exact up to say, cubics, and you can then set `f(x) = 1,x,x^2,x^3` to find up to four constants. The fact there is six unknowns here suggets it should be exact for quintics, however the resulting system of equations will be quite complicated.
Comment: Actually no. The x can be chosen complety arbitrary and by adjusting the w you can always get exact up to quadratic. There are better and worse choices for the x, but there is no way to achieve quintic exactness with three points.
Comment: You're totally right, thank you for the input. I didn't even consider how only three points would limit the accuracy.
Answer: probably what is meant by the symmetry condition is this (though the phrasing is not completely clear):
Exact integrals always have the symmetry $\int f(x) = \int f(-x)$, so it would be nice if your quadrature-rule had this symmetry too. I.e.
$$w_1f(x_1) + w_2f(x_2) + w_3f(x_3) \stackrel{!}{=} w_1f(-x_1) + w_2f(-x_2) + w_3f(-x_3)$$
for all functions $f$ (not only for low-order polynomials). You should convince yourself that the only way to achieve this symmetry is to choose $x_2=0$ and $x_1=-x_3$. This should simplify the rest of your calculations a bit as well.
Comment: I am having some trouble however, if we take $f(x) = x$, then wouldn't the above equation imply that all $x_i = 0$? Since e.g $f(x_1) = f(-x_1)$? I'm not sure how this relation allows you to derive $x_2 = 0$ and $x_1 = -x_3$ specifically.
Comment: In order for the both sides to be equal (for all possible functions $f$), the points $\{x_1,x_2,x_3\}$ have to be the same as $\{-x_1,-x_2,-x_3\}$. This is possible in two different ways: either the $x_i$ is already zero, so the minus sign does not do anything. Or: there are two points which are the negative of one another, i.e. $\{x_1,x_3\}=\{-x_3,-x_1\}$. For this to work you will also need $w_1=w_3$. You have three points in total, and you know that choosing the same $x$ multiple times is not helpful. So it is necessary to choose one of the $x$ as zero, and the other two as a $\pm$ pair.
Comment: This makes a little more sense, but why do only two of points need to be equal to the negative of eachother? I just don't understand why the alternative of all the points being equal to $0$, is only one $x_i = 0$ and the others being a $\pm$ pair. Is there a way to see why this is the case in a more algebraic sense?


The ranges of $T+iI$ and of $T-iI$.

Question: In Rudin's book: Functional analysis. P386.exercises 9.

Let $H^2$ be the space of all holomorphic function $f(z)=\sum_{n=0}^{\infty} c_{n}z^n$ in the open unit disc that satisfy
  $$\Vert f\Vert ^2=\sum_{n=0}^{\infty} \vert c_{n}\vert^2<\infty.$$
  Define $V\in \mathscr{B}(H^2)$ by $(Vf)(z)=zf(z)$. And operator $T$ in $H^2$ given by
  $$ (Tf)(z)=i\frac{1+z}{1-z}f(z).$$

I have proved $V$ is the Cayley transform of the symmetric operator $T$. Actually,
$$(Tf)(z)=i\sum_{n=0}^{\infty}\Big(2\sum_{k=0}^{n-1}c_{k}+c_{n}\Big)z^n.$$
And I know that the $H^2$ is isomorphic to $l^2$ via $f \to \{c_{n}\}$.
But I do not know the reasons for the ranges of $T+iI$ and of $T-iI$; Rudin tells one is $H^2$ and one has codimension 1. Thanks for any advance details on this question.
Answer: You can calculate explicitly:
$$
\frac{1+z}{1-z}+1=\frac2{1-z},\ \ \ \ \frac{1+z}{1-z}-1=\frac{2z}{1-z}.
$$
So $T+iI$ is multiplication by $2i/(1-z)$, which is invertible (multiply by $(1-z)/2i$), while $T-iI$ is multiplication by $2iz/(1-z)$, which is not invertible; its range is $zH^2$, which has codimension $1$.
Comment: Sorry, I am not familiar with it. Why does $T+iI$ invertible result in $R(T+iI)=H^2$?
Comment: Oh! I got it. Thanks a lot.
Comment: Glad I could help.

The ranges of $T+iI$ and of $T-iI$.


Generating pages with multiple views based on url parameter

Question: I wish to generate pages that populate a series of views of different content types based on a parameter in the url.
For example, a user may navigate to:
www.mysite.com/{tag}

The generated page would find all content tagged with the {tag} parameter and present it as a series of views, for example:
Custom page for {TAG}

View 1                 View 2
Item 1 (type A)        Item 1 (type B)
Item 2 (type B)        Item 2 (type B)
etc                    etc

and etc.

I wish to style and theme the resulting page considerably. Ideally I would also make it possible for an end user to style the resulting page.
I am a little unsure what the best 'drupal' way to make such a page is.
a) Is it possible to somehow style and manage the taxonomy page for 'tag' to look how I want?
b) Should I programatically generate the pages in a custom module that searches for content based on a taxonomy term (not even sure how this would be done)
c) Should I generate a series of views then pass parameters to them on each specific page?
d) Is there some other, better way to achieve such a page in Drupal 8?
One final question, which solution would perform best in terms of page loads, or would they all be pretty similar?
Comment: What are `type A` and `type B`?
Comment: They will be custom content types. The could be anything. I want to have 6-7 different content types in their own views. The only thing they will all have in common as they would be the taxonomy term.
Comment: Why is your question about multiple views? That seems to look more like one view where you have as argument the tag and sort the nodes by content type and group them.
Answer: Create 7 different views, one for each content type. Create a block display for each view, and use block layout to put them all on one page.
Use contextual filters for the block view to get an argument from the URL. I believe it's a bit odd to configure:
"in the section 'What to do if the URL is not available' select ' Provide default value' and select 'Raw value from URL from the dropdown box. From the 'Path Component' box select the position in the URL that your contextual filter gets its value."
This is a straightforward Drupal approach, should be performant.
Alternatively, you could use Views aggregation to use only 1 view, divided into 7 different groups, and use CSS wizardry to adjust the layout.
Which approach you prefer depends on whether you want to be able to customise each view, and whether you want to use UI rather than CSS to control layout.


Is this a good case for horizontal integration? Find enclosed area btw 2 equations. Why or why not?

Question: When doing horizontal integration... why do we write the function as a function of y with the x by itself? What is the high level point of that?
So here is my work. Is this right? I am asked to find the area enclosed between these equations:
$$ 4x + y^2 = 12, x = y$$
First thing's first is to graph it and find the points of intersection:

Point of intersection:
$$ \frac{12 - y^2}{4} = y$$
$$ 12 - y^2 = 4y$$
$$y^2 + 4y -12 = 0$$
$$(y - 2)(y+6) = 0$$
$$y = {2,-6}$$
So the points are $(2,2) , (-6, -6)$.
So the integral...why do we write it as a function of y? Can't we write it as a function of x still?:
$$ \int_{-6}^2 - y \, dy$$
$$= \int_{-6}^2 3 \cdot \frac{-1}{4} y^2 \, dy$$
$$= [ 3y - \frac{1}{4} \cdot \frac{y^3}{3} - \frac{y^2}{2} ]_{-6}^2$$
$$ 6 - \frac{2}{3} - 2 - (-18 + 18 -18) = 21 \frac{1}{3}$$
Does this look right? More importantly, why do we use the equation where y is the variable?
Comment: What's the actual problem asking you to do?
Answer: You could write it as a function of whatever you  want; as long as you do the integral correctly, either will give you the area between the two curves.  However, choosing one variable (in this case, $y$) to set up the integral for is sometimes easier than the other.
Here, for instance, writing this as a function $f(y)$ and integrating with respect to $y$ lets us write this area as a single integral $\int_{-6}^2 f(y)\, dy$. Here your $f(y)$ should be $\frac{12 - y^2}{4} - y$.
However, if we tried to integrate $dx$, we would run into two inconveniences. First, setting it up as a function $g(x)$ of $x$, we would have $y = \pm\sqrt{\text{something}}$, and we would have to make a choice of  sign here. Secondly, when trying to write this integral, we have to integrate the top function minus the bottom function right? But these change; from $x = -6$ to $x =  2$, the top function is $y = x$, and the bottom is the $4x + y^2  = 12$ function.  However, at $x = 2$, we switch; the area is now enveloped on top by the positive square root $y = \sqrt{12 - 4x}$, and on the bottom by the negative square root.
Thus,  in trying to do the $dx$ integral, we would a) have to work with more annoying functions, and b)  have to split our integral up  into two integrals. It's easier to integrate $dy$!


google chrome AddressBookUrlForwarder pop up when url link clicked

Question: i have the user click on the icon. If the user is on a desktop they will get redirected to the webpage lets use facebook as an example. If the user clicks the icon when in mobile they will be directed to the facebook app but if they do not have it they will go to the webpage via there browser.
The mobile view is fine but on the desktop when the link is clicked this keeps popping up(in chrome).if i use a href tag it doesnt pop up. From a user experience perspective this is annoying. Is there a way to fix this.?

javascript code im using to direct them to webpage via browser or open app if they have it
<code>function goToURL() {
  setTimeout(function () { window.location = "https://www.facebook.com/page/"; }, 8000);
    window.location = "fb://profile/page";

}
</code>
Answer: So i managed to get rid of the problem. I just took away the
<code> window.location = "fb://profile/page";
</code>
On the same page I have instagram and soundcloud. For these two i just put in the url for the page and on mobile they open in the app instead on the mobile web browser. For facebook however it does not have this feature(idk why?) it opens up safari and goes to the mobile facebook website. A work around i found was to use a deep link such as URLgenius and it worked. If anyone has ran into this issue i hope it helps you out.


Caching includes in PHP for iterated reuse

Question: Is there a way to cache a PHP include effectively for reuse, without APC, et al?
Simple (albeit stupid) example:
// rand.php
return rand(0, 999);

// index.php
$file = 'rand.php';
while($i++ < 1000){
    echo include($file);
}

Again, while ridiculous, this pair of scripts dumps 1000 random numbers. However, for every iteration, PHP has to hit the filesystem (Correct? There is no inherit caching functionality I've missed, is there?)
Basically, how can I prevent the previous scenario from resulting in 1000 hits to the filesystem?
The only consideration I've come to so far is a goofy one, and it may not prove effective at all (haven't tested, wrote it here, error prone, but you get the idea):
// rand.php
return rand(0, 999);

// index.php
$file = 'rand.php';
$cache = array();
while($i++ < 1000){
    if(isset($cache[$file])){
        echo eval('?>' . $cache[$file] . '<?php;');
    }else{
        $cache[$file] = file_get_contents($file);
        echo include($file);
    }
}

A more realistic and less silly example:
When including files for view generation, given a view file is used a number of times in a given request (a widget or something) is there a realistic way to capture and re-evaluate the view script without a filesystem hit?
Comment: Somehow "wrong" seems a subjective, and unhelpful response.
Comment: if your code needs such algorithm - your system designed totally wrong.
Comment: it's a comment, not response. [This book](http://www.amazon.com/Objects-Patterns-Practice-Matt-Zandstra/dp/1590599098) will be helpful.
Comment: @OZ_ I appreciate the suggestion.
Comment: how about `include_once` or `require_once`  ??
Answer: This would only make any sense if the include file was accessed across a network.

There is no inherit caching functionality I've missed, is there?

All operating systems are very highly optimized to reduce the amount of physical I/O and to speed up file operations. On a properly configured system in most cases, the system will rarely revert to disk to fetch PHP code. Sit down with a spreadsheet and have a think about how long it would take to process PHP code if every file had to be fetched from disk - it'd be ridiculous, e.g. suppose your script is in /var/www/htdocs/index.php and includes /usr/local/php/resource.inc.php - that's 8 seek operations to just locate the files - @8ms each, that's 64ms to find the files! Run some timings on your test case - you'll see that its running much, much faster than that.
Comment: Thanks **symcbean**; I assumed as such (*my quote referred to inherit **PHP** caching functionality, for such situations*) One could call this premature optimization, however I'd like to keep the bottlenecks low.
Answer: As with Sabeen Malik's answer you could capture the output of the include with output buffering, then concat all of them together, then save that to a file and include the one file each time.
This one collective include could be kept for an hour by checking the file's mod time and then rewriting and re including the includes only once an hour.
Comment: Thanks **Question Mark**; This is feasible for a higher level cache of rendered output, however I'm more interested in solving the issue when it involves returning values from an included file, not generating output.
Answer: I think better design would be something like this:
// rand.php
function get_rand() {
    return rand(0, 999);
}

// index.php
$file = 'rand.php';
include($file);

while($i++ < 1000){
    echo get_rand();
}

Comment: Thanks **Karolis**; Certainly, however this application takes advantage of `return` when dealing with included files.
Answer: Another option:
while($i++ < 1000) echo rand(0, 999);


Colocar imagem no html que está no google drive

Question: Como colocar o endereço da imagem do google drive no src de uma img?
a pasta está publica (para todos) e o link gerado é este:
https://drive.google.com/file/d/0B_qsYuljopvWNlV5ckRHSDZZalU/view?usp=sharing
Tentei o que tem nessa resposta: Hospedar imagens para um HTML no Google Drive , mas não funcionou.
Comment: tentou usar essa url: `https://lh4.googleusercontent.com/eLMEVklGAYfVE2XqNJwR7O2lpK9mPJMjvJVH8K6ygZJTOVBOJLOmHfbxIJZ8PgRt7MoBtU-iN-t_1ZI=w1366-h638`
Comment: tentei, essa url muda depois de um tempo, ou não fica mais disponivel.
Answer: Descobri um modo: Se colocar o id da imagem nessa url, da certo:
https://docs.google.com/uc?id=idDaImagem
o id da imagem eu peguei do link de comaprtilhamento que ele gera:
https://drive.google.com/file/d/0B_qsYuljopvWNlV5ckRHSDZZalU/view?usp=sharing
resultado final:
https://docs.google.com/uc?id=0B_qsYuljopvWNlV5ckRHSDZZalU
Answer: Bom se imagem se alterna, pode ser algum tipo se segurança do google para proteger arquivos, ou seja se você quiser usar uma imagem do drive no seu site o google disponibiliza iframes, oque não é ideal para imagens. vou upar essa mesma foto no meu drive para exemplificar.
após o upload irei abrir com 'documentos do google'
já no documentos clico em 'arquivos' e em seguida em 'publicar na web', seleciono a opção incorporar e clico em publicar, resultado

Oque não faz nenhum sentido
porém na hora de gerar o iframe me deparei com outra url no mesmo, ao ir até ela você verá a foto em forma de documento, ao clicar somente na foto para abrir em uma nova guia ele gerou uma url extensa, que pode ser imutável mas não sei ao certo...

contudo, a menos que seja regra de negócio, não recomendo usar imagens hospedadas no drive.
Comment: Essa solução funciona, mas é mais trabalhosa que a solução que eu encontrei depois, obrigado pela ajuda.
Comment: Denada haha, oque vale é o caminho mais curto e simples.


How to calculate ideal amount of reps needed for good average in R

Question: Basically, I have some samples I'm processing to get moisture results on and I want to get a good average on the readings based on the ideal amount of repetitions.  Duplicates is not enough and 10 reps would take too long.  So far, I have run a control sample hundreds of times across many days and months, and I calculated off of those results what I think would be the best amount of reps before I start wasting time.
Example moisture results: 10.5, 11.5, 12.2, 10.8, 10.9, 11.8, [hundreds more results from the same sample that all range between 10.5 and 12.5].
The way I did this, which will probably make some statisticians cry, is to take the results and average them with the next 2,3,4,5, up to 10 runs and compare the min, max, and averages of each groups of averages.  So for my 2 rep test, I took the first result and averaged it with the second.  Then I took the second result and averaged it with the third.  At the end, I took the difference between the min and max of the averaged data and it came out to 1.8.  This was "better" than individual samples as the min/max difference was 2.0.  I then did the same test with 3 reps instead of just 2.  So, the first, second, and third results were averaged, then the second, third, and fourth results were averaged, etc.  I did this in Excel all the way up to 10 reps.
Results:
<code>Reps  StDev  Min    Max    Range
1     0.48   10.5   12.5   2.0
2     0.40   10.5   12.3   1.8
3     0.35   10.5   12.2   1.7
*4    0.33   10.6   12.0   1.4
*5    0.31   10.7   12.0   1.3
6     0.30   10.8   12.0   1.3
7     0.29   10.8   12.0   1.2
8     0.29   10.8   11.9   1.1
9     0.28   10.8   11.9   1.1
10    0.28   10.9   12.0   1.1
</code>
Based on time and resources, I decided that 4 or 5 reps is the "sweet spot".
I know this isn't the right way to do it, which is why I'm asking here.  The results I used are just sequential, in the order they were created across many days and months.
So, I decided the sweet spot would be at 4 reps based on how long each rep takes.  This isn't the right way to do it, as it's just taking the results sequentially and averaging them in groups.  So some are run on the same days, some different days, etc.  Is there a way I can run my control sample data through R and it give me a better way to figure this out?
I've never really done any statistics, so I don't even know what this is called to search for a solution.  Everything I tried resulted in search results like "Build the most mass in the shortest amount of time using X amount of reps in the gym" and such.
I'm wanting to do this in R so I can process it through C# and R.NET.  This is a win-win for me.  I'm learning how to use R through R.NET and this would help me find the most accurate results before the cost in time and resources for doing multiple reps starts to outweigh the need for a good, solid result.
tl;dr: have hundreds of process result reps of same sample, how can I use that data in R to see how many reps to use on other samples before "overdoing" it?
Answer: If you have a feel for standard deviation that is acceptable then calculating the standard deviation across the number of "reps" as you have done here is a start.  Another approach would be to calculate the Kuder-Richardson Formula or Cronbach's alpha.  The "psych" package in r has functions and documentation on how to perform either of these (and a handful of other) reliability calculations.


LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected

Question:
LogicException: The controller result claims to be providing relevant
  cache metadata, but leaked metadata was detected. Please ensure you
  are not rendering content too early. Returned object class:
  Drupal\rest\ResourceResponse. in
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext()
  (line 154 of
  /srv/bindings/8c5ccf24ccc9492bb85469725da608ea/code/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php).

I am facing this issue when i try to access REST endpoint through ajax get request.
Important thing, when i was logged-in then every works find but when i am not logged it it through above exception.
Here is my code
namespace Drupal\one_rest_api\Plugin\rest\resource;

use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\Entity\Media;
use Drupal\node\Entity\Node;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\taxonomy\Entity\Term;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Provides article resource endpoint
 *
 * @RestResource(
 *   id = "one_article_resource",
 *   label = @Translation("One Article Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/one/v1/articles"
 *   }
 * )
 */
class ArticleResource extends ResourceBase
{
    /**
     * A current user instance.
     *
     * @var \Drupal\Core\Session\AccountProxyInterface
     */
    protected $currentUser;

    /**
     * Constructs a Drupal\rest\Plugin\ResourceBase object.
     *
     * @param array $configuration
     *   A configuration array containing information about the plugin instance.
     * @param string $plugin_id
     *   The plugin_id for the plugin instance.
     * @param mixed $plugin_definition
     *   The plugin implementation definition.
     * @param array $serializer_formats
     *   The available serialization formats.
     * @param \Psr\Log\LoggerInterface $logger
     *   A logger instance.
     * @param \Drupal\Core\Session\AccountProxyInterface $current_user
     *   A current user instance.
     */
    public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        array $serializer_formats,
        LoggerInterface $logger,
        AccountProxyInterface $current_user) {

        parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

        $this->currentUser = $current_user;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->getParameter('serializer.formats'),
            $container->get('logger.factory')->get('one_rest'),
            $container->get('current_user')
        );
    }
    /**
     * Responds to GET requests.
     *
     * Returns a list of bundles for specified entity.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function get() {
        global $base_url;

        $response_result = [];
        $response_code = 200;
        // You must to implement the logic of your REST Resource here.
        // Use current user after pass authentication to validate access.
        if (!$this->currentUser->hasPermission('access content')) {
            throw new AccessDeniedHttpException();
        }

        $entities = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'article')
            ->condition('langcode','en')
            ->notExists('field_f1')
            ->sort('created', 'DESC')
            ->range(0, 20)
            ->execute();

        if(!empty($entities)){
            foreach ($entities as $node_id) {
                $node = Node::load($node_id);

                if(is_object($node)){
                    $image_url = '';
                    $image_target = $node->get('field_image')->target_id;
                    if(!empty($image_target)){
                        $media = Media::load($image_target);
                        if(is_object($media)){
                            $image = File::load($media->get('field_image')->target_id);
                            $image_url = ImageStyle::load('rest_api')->buildUrl($image->getFileUri());
                        }
                    }

                    $output_tags = [];
                    $tags = $node->get('field_tags')->getValue();
                    if(!empty($tags)){
                        foreach($tags as $key => $tag){
                            $term = Term::load($tag['target_id']);
                            $output_tags[] = $term->get('name')->value;
                        }
                    }

                    $result = [
                        "nid" => $node->id(),
                        "base_url" => $base_url,
                        "title" => $node->getTitle(),
                        "field_image" => $image_url,
                        "field_tags" => $output_tags
                    ];

                    $response_result[] = $result;
                }

            }
        }

        if(!empty($response_result)) {
            $headers = [
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PATCH, DELETE',
                'Access-Control-Allow-Headers' => 'Authorization'
            ];

            $response = new ResourceResponse($response_result, $response_code, $headers);
            return $response;
        }

        throw new HttpException(t("Empty Response"));
    }
}

And Below is my typescript code
load(){

    if(this.data){
      return Promise.resolve(this.data);
    }

    return new Promise(resolve => {
      this.http.get('https://example.com/api/one/v1/articles?_format=json')
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        },err => {
          console.log(err);
        });
    });

  }

I didn't understand what i am missing in drupal code
Comment: Then try to skip the access checks: `->accessCheck(FALSE)`
Comment: See https://drupal.stackexchange.com/questions/225956/cache-controller-with-json-response for how to avoid this for normal urls. You can try something like this for the image style. If you don't get this working, then another option is to wrap the code in your own render context, see https://drupal.stackexchange.com/questions/245715/how-to-get-cache-metadata-from-nested-render-array-when-returning-response
Comment: Sorry not to be able to provide an easy answer, this is really a [DX nightmare](https://www.drupal.org/project/drupal/issues/2638686). You might need to wait until image styles are provided in the image field to get an easier solution https://www.drupal.org/project/drupal/issues/2825812.
Comment: Tried that but that didn't help me
Comment: @4k4 I believe \Drupal::entityQuery('node') creating cache / context or something else which is causing metadata issue.
Comment: @4k4 Any working example of accessCheck(FALSE)
Comment: Like this
 $entities = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'article')
            ->condition('langcode','en')
            ->notExists('field_f1')
            ->sort('created', 'DESC')
            ->range(0, 20)
->accessCheck(FALSE)
            ->execute();
Comment: @4k4 Thanks a lot, its working like a charm now, Really appreciate your help, You Save Me :)
Answer: I have solved it by adding code at the end because class ResourceResponse is using CacheableResponseTrait which is responsible to cache metadata.
In POST, PATCH, DELETE we don't want that because resources are modified.
return new ModifiedResourceResponse($node);

Comment: +1 - Remember to add `use Drupal\rest\ModifiedResourceResponse`.
Answer: Modify your entity query to something like below
$entities = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'article')
            ->condition('langcode','en')
            ->notExists('field_f1')
            ->sort('created', 'DESC')
            ->range(0, 20)
            ->accessCheck(false)
            ->execute();

Comment: Although this may work I don't believe disabling access check is the correct way to do deal with the problem, is it?
Comment: accessCheck(false) resolved my issue, it's because you can have a hook like a node_access who checks entity access and add metadata, with accessCheck(false) you skip this hook.
Answer: I think the answers that are currently listed are the proper methods to follow. However, I think its relevant to note, that I was able to fix this (possibly temporarily) by reinstalling the jsonapi module in drupal using composer. In case it may help someone, this is what I ran from the command line:
composer require 'drupal/jsonapi:^1.24'

Don't forget to change the code to the version you are trying to install. As you can see, this is specifically for version 1.24.
Comment: thank you, works for me.
Answer: For me, wrapping the query in a render context fixed the issues without having to define the the accessCheck(FALSE):
// Wrap Query in render context.
$context = new RenderContext();
$nids = \Drupal::service('renderer')->executeInRenderContext($context, function () {
  // Query some nodes.
  $my_query = \Drupal::entityQuery('node')
    ->condition('type', 'my_type')
    ->condition('status', 1);
  return $my_query->execute();
});

https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8
Comment: I encountered this error while using GraphQL to pull entities for an entity-reference field configured to use views-entity-reference result type.  This response was the best option for me.  Thanks.
Comment: Thanks @scott this worked for me.


How can I compare data comparison with values submitted in a webform?

Question: I am trying to use webforms with the Rules module.
How can I compare data with the values submitted in a webform ?
For example, if the webform has a yes/no radio button, how can check the submitted value is yes?
When adding a new condition, I choose:

Data Comparison
Data selector *
Data (the submitted webform value)

I'm not sure how to access a particular form_key to check its value. I feel like Data should have more options to choose from.
Answer: At a minimum, make sure you have the Webform Rules module enabled. Some details about it (from its project page):

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

You may also want to have a look at feature request "Expose submission data to rules". Here is a summary of it:

Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue.
Time for a work around ...
The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words, checkout the screenprint included in that comment.
... and a demo
Consider this rule (in Rules export format):
{ "rules_validate_a_component_of_a_submitted_webform" : {
    "LABEL" : "Validate a component of a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022 and another field \u0022[data:contact_us_message-title]\u0022 which has value \u0022[data:contact_us_message-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:contact_us_message-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : { "text" : [ "submitted-form-component-value" ], "match" : "mail.ru" } },
            "DO" : [
              { "drupal_message" : {
                  "message" : "Stop and listen! ... One of the form components of the form you just submitted (= \u0022[submitted-form-component-value:value]\u0022), contains some value that is not allowed around here ...",
                  "type" : "error"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After a webform has been submitted
Rules Conditions: User does NOT have role "authenticated" (i.e: an anonymous user submitted the form).
Rules Actions:

Show an informal message on the site (this is just for QA-purposes, omit this action after you're convinced it works).
Add a variable (this is the clue of it all ...), named submitted_form_component_value and with label "Submitted form component value", and with value [data:contact_us_message-value-raw] (the form component we want to validate in subsequent Rules Actions).
Use the Conditional Rules module to perform some text comparison. In this case it checks if it contains mail.ru. If so, then perform another Rules Action like "Show an error message on the site". Obviously, at this point you could make any Rules magic happen ("block IP address" seems appropriate).

Be aware: as per the Rules Event we used here, the Webform has been submitted (and so far I've not found a more appropriate event like "Before submitting a Webform").
Showtime
With the above rule enabled, I submitted a webform. This is the message I got (as per the first Rules Action):

The webform component submitted by Pierre (= First name:) Vriens (= Last name:) contains a field labeled "Subject:" which has value " This is a demo of a validation of a webform component using Rules ... " and another field "Message:" which has value "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ...".

And sure enough, this is the error message that follows it right away (as per the last Rules Action):

Stop and listen! ... One of the form components of the form you just submitted (= "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ..."), contains some value that is not allowed around here ...

PS: In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Haskell list recursion - why does one work and not the other?

Question: Anyone familiar with Haskell will have likely seen this implementation of the Fibonacci sequence.
fibs = 0:1:zipWith (+) fibs (tail fibs)

The way I understand this is as follows:

Haskell's lazy evaluation allows for this infinite recursion with no issues
The way Haskell constructs lists (pairing the first element with the rest of the list) means the zipWith is evaluated to obtain the next element when needed
When fibs is referenced in the zipWith parameters, it takes the list as it currently exists without the new element being evaluated

With that knowledge, why does this loop infinitely rather than generate a list of primes?
main = print $ take 10 primes

dividesNone x ys = not $ any ((==0) . (x `mod`)) ys

primes = 2:[x | x <- [2..], x `dividesNone` primes]

I've tried similar implementations using dropWhile and find but the same thing happens. I've settled on this one as the one I most think "should" work. I'm sure there is some way to make this work the way I want - but even if I knew what that way was, I wouldn't understand why this doesn't. What is the difference between these two examples that causes one to work and one to loop infinitely?
Comment: You do not need to test for the prime numbers that are beyond the square root of the candidate number; this is infinitely too expensive. Try with this change: `dividesNone x ys = not $ any  ((==0) . (x `mod`))  (takeWhile (\y -> y*y <= x) ys)`
Comment: @jpmarinier Thank you for pointing that out, but I'm aware. I was trying to keep it as simple as possible to solve the problem at hand.
Answer: From a denotational perspective, it's because 2:⊥ is a fixed point of the equation that defines primes.
The semantics of Haskell say that the meaning of a recursive definition is the least fixed point of the equation -- we should find the least defined value that satisfies the equation.  Our equation is:
primes = 2:[x | x <- [2..], x `dividesNone` primes]

Notice that 3 `dividesNone` (2:⊥) gives ⊥.  The check against 2 fails, then we ask if 3 divides any of the elements of the list ⊥, a list about which there is no information, so we have no information about that answer.
If we fill in 2:⊥ for primes:
2:⊥ = 2 : [x | x <- [2..], x `dividesNone` 2:⊥]  -- 2 fails the filter
    = 2 : [x | x <- [3..], x `dividesNone` 2:⊥]
    = 2 : [x | x <- [3..], ⊥]
    = 2:⊥

It satisfies the equation.  And the only things less defined than 2:⊥ are  ⊥ and ⊥:⊥, which do not satisfy the equation:
⊥   /= 2:[x | x <- [2..], x `dividesNone` ⊥]   = 2:⊥
⊥:⊥ /= 2:[x | x <- [2..], x `dividesNone` ⊥:⊥] = 2:⊥

So 2:⊥ is the least fixed point.  That is, we will output two and then infinite loop.
In practice I use both the denotational and operational perspectives to reason about my code.  Thinking about laziness operationally can get really complicated really quickly, so it's nice to have another tool in your belt.
Comment: I think I'm a little early in my FP journey to fully grasp this answer, but being exposed to concepts like this is going to be helpful. I look forward to adding this tool to my belt in the near future!
Answer:
When fibs is referenced in the zipWith parameters, it takes the list as it currently exists without the new element being evaluated.

It holds a reference to the list that is not entirely evaluated yet. But if it had to access the third element before that was evaluated, it would get stuck in an infinite loop. It thus initially looks like:
            ╭─────────────────────────────────╮
            │          ╭────────────────────╮ │
            ▽          ▽                    │ │
        ┌───┼───╮  ┌───┼───╮  ┌───────────╮ │ │
fibs ─▷ │ o │ o───▷│ o │ o───▷│  zipWith  │ │ │
        └─│─┴───╯  └─│─┴───╯  ├───┬───┬───┤ │ │
          ▽          ▽        │ o │ o │ o───╯ │
          0          1        └─│─┴─│─┴───╯   │
                                ▽   ╰─────────╯
                               (+)

and the zipWith will each time evaluate an item, and then the references will move to the next node, and that node is always evaluated already, or at least sufficient to not get into an infinite loop, so the next step, it looks like:
                       ╭─────────────────────────────────╮
                       │          ╭────────────────────╮ │
                       ▽          ▽                    │ │
        ┌───┬───╮  ┌───┼───╮  ┌───┼───╮  ┌───────────╮ │ │
fibs ─▷ │ o │ o───▷│ o │ o───▷│ o │ o───▷│  zipWith  │ │ │
        └─│─┴───╯  └─│─┴───╯  └─│─┴───╯  ├───┬───┬───┤ │ │
          ▽          ▽          │        │ o │ o │ o───╯ │
          0          1          ▽        └─│─┴─│─┴───╯   │
          △          △        ┌───────╮    ▽   ╰─────────╯
          │          │        │  (+)  │   (+)
          │          │        ├───┬───┤
          ╰──────────│──────────o │ o │
                     │        └───┴─│─╯
                     ╰──────────────╯

That is also what happens with your primes. The dividesNone will for example look for 3, and thus walk to the end of the thus far evaluated primes list. But since 3 is not dividable by 2, it will enumerate further, and thus walk into an unevaluated node. It will thus start evaluating the third item of the primes list (in order to evaluate the third element of the prime list), but that will again require to generate the third item, and thus gets stuck in an infinite loop.
It thus does not get a "copy" of the list that stops where it still has to evaluate. The list simply points to a node that still needs to be evaluated, triggering the interpreter to evaluate it, and thus gets it stuck into an infinite loop.
Comment: @scatter: yes. From the moment it has to evaluate against something that is at that point unevaluated, then there is a problem.
Comment: @ReinHenrichs: yes, `ascii-art-to-unicode`: https://hackage.haskell.org/package/ascii-art-to-unicode although it requires some (minimal) post-processing.
Comment: So would I be correct in saying the difference is that the fibs list builds itself *as part of* that evaluation, while the list comprehension is stuck because it has to test against the entire list *before* calculating the next element?
Comment: Are you using a tool to create these unicode diagrams?


State the Riemann's condition for the integrability of $f$ with respect to $\alpha$ on $[a,b]$.

Question: Let $f$ and $\alpha$ be two functions on $[a,b]$ with $\alpha$ being increasing on $[a,b]$.State the Riemann's condition for the integrability of $f$ with respect to $\alpha$ on $[a,b]$.
Is the answer simply $\alpha$ being increasing?
Comment: No. $\alpha$ increasing is already given. But is $f$ allowed to be arbitrarily wild?
Comment: @HagenvonEitzen There is no more restriction on f. So is the answer would be like given epsilon>0 there exists a partition P then Upper sum minus Lower sum is smaller than epsilon?
Comment: @HagenvonEitzen Or I think probably it would be the infimum of Upper sum is equal to the supremum of Lower sum
Answer: The thing I know of as "Riemann's criterion" is that $f$ (bounded) is Riemann integrable on $[a, b]$ iff whenever $\epsilon > 0$ we can find a dissection $\mathcal{D}$ of $[a, b]$ with the difference $S(f, \mathcal{D}) - s(f, \mathcal{D})$ of the upper sum and the lower sum of $f$ with respect to that dissection is less than $\epsilon$.
Recall the definition of the upper sum $S(f, \mathcal{D})$ with respect to a dissection $\mathcal{D} := \{a = x_0, x_1, \dots, x_n = b\}$: $$\sum_{i=1}^n (x_i - x_{i-1}) \sup_{x \in [x_{i-1}, x_i]} f(x)$$
Presumably you are to substitute $f(\alpha(x))$ instead.