jquery add class to element inside this element only

Question: This is for a user account. When the user hits the edit button I want an edit box to be displayed inside the element where the button exists.
So I have this markup

    Account Settings

            Profile Status

<?= $this->escape($this->status); ?>

                <button class="edit-btn"></button>

                    edit 1

                Name

 <?= $this->escape($this->name); ?>

                <button class="edit-btn"></button>

                    edit 2

                Username

<?= $this->escape($this->username); ?>

                <button class="edit-btn"></button>

                    edit 3

                Bio

<?= $this->escape($this->bio); ?>

                <button class="edit-btn"></button>

                    edit 4

                Email

<?= $this->escape($this->email); ?>

                <button class="edit-btn"></button>

                    edit 5

                Password

**********

                <button class="edit-btn"></button>

                    edit 6

Then I have jquery
$(document).ready(function()
{
    $('.edit-btn').click(function()
    {
        $('.edit-box').addClass('open');
    });
});

Is there a way to add a class only to the .edit-box that lives in the same .col as the .edit-btn?
Here is a js fiddle https://jsfiddle.net/y6ukq3th/
Answer: Yes you can use .siblings('.edit-box') to add the class to the one who has that as a sibling of the clicked button:
$(document).ready(function() {
     $('.edit-btn').click(function() {
         $(this).siblings('.edit-box').addClass('open');
     });
 });

Demo
Comment: Ah thanks I knew it was something simple like that just couldnt find the selector.
Answer: $(document).ready(function() {

    $('.edit-btn').click(function() {

        // clear all first ( if you want to do )
        // $('.edit-box').removeClass('open');

        // select in parent of target
        $(this).parents('.col:first').find('.edit-box').addClass('open');

        // [or] select between siblings of target
        // $(this).siblings('.edit-box').addClass('open');

        // [or] select next node of target
        // $(this).next().addClass('open');
    });
});

https://jsfiddle.net/mvrv7065/


I can't load inline jQuery

Question: I have a Drupal 9 page, where I am trying to load some inline jQuery code, from CKEditor, but it isn't working and I am not getting any error on the console.
This worked perfectly in Drupal 8.
<code><script>
 window.onload = function() {
  jQuery('.className').fadeOut();
  console.log("HI");
 };
</script>
</code>
Comment: These things are generally not done, nor advised, from WYSIWYGs.
Comment: From a frontend developer view (I do backend as well,) I think that it involves too many steps, to create modules or libraries, just to swap a couple of divs around and add some css. It is very convenient to just go into the CKEditor and splash out some jQuery, that is only meant to do its work, on a specific page or block.
Answer: The right way of doing it, is to add a js file  to the js folder, then declare it in the my-theme.libraries.yml file, either globally or not. Then the trick is to make a hook for the specific node (or node-type, even theme) in the my-theme.theme file.
Comment: Yeah and never put it in a contrib theme. Either create a new custom sub-theme or a custom module from where you attach the JS like it's written in the docs.

I can't load inline jQuery


Root(zero) of a polynomial

Question: How is the Root of a polynomial defined? I found on Wikipedia's page written: "A root of a polynomial is a zero of the corresponding polynomial function." Or the URL:https://en.m.wikipedia.org/wiki/Zero_of_a_function
Now if I want to find the root of polynomial 9a-2b then that would be it's corresponding function?
Answer: If you are working over a field $F$, then the function will be$$\begin{array}{ccc}F\times F&\longrightarrow&F\\(a,b)&\mapsto&9a-2b.\end{array}$$
Comment: Sorry, but I am unfamiliar with abstract algebra topics, i.e fields, etc. Kindly tell in layman language
Comment: It's the functions that maps the pair $(a,b)$ into $9a-2b$.
Answer: A root of a polynomial is the value (or values) given to its variable (or variables) that results in the polynomial evaluating to zero. For example, the root of a polynomial $x+2=0$ is $x=-2$. Likewise, roots of the polynomial $x^2-1=0$ are $x=\pm 1$. In your case, the polynomial has two variables. But we have only one equation $9a-2b=0$. Therefore, the roots of this polynomial are any pair of numbers $a$ and $9a/2$.
Answer: $9a-2b$ is not a polynomial without any more context. It is a linear formula in two unknowns, so we could indeed see it as a polynomial in the two variables $a,b$, say $p(a,b) = 9a-2b$ (which also defines a function). Over the reals, or the rational numbers, this has many zeroes, e.g. $(1,4\frac{1}{2})$ is a root of the polynomial in $\mathbb{Q}^2$, because if we fill in the values in $p$ we get $0$.
If $b$ were some known number or parameter, then we could also see it as a polynomial in $a$: $q(a) = 9a-2b$, and then it has only one root, if $b$ is in some field: $a = \frac{2b}{9}$, which lies in the same field as $b$ provided $9$ has an inverse (it probably has, as I think you're working over real, complex or rational numbers?). In this case $b$ is not seen as an "unknown" or variable that can be substituted.

Root(zero) of a polynomial


Displaying post from specific category in WordPress

Question: I would like to display 5 post from a specific category on homepage. First one have to be with a Large thumbnail and excerpt and others 4 post with small image and post title.
Like this : https://i.stack.imgur.com/utQ9s.png
Answer: For that you will need to select specific template and edit it.
Free templates are not allowed to be editted by code but on the dashboard you can customize the visiblity of the site.
Are you having the same Template? If not then first select the specific template and you'll get this feature by default.


How to correctly number rows in the indicated column in the table

Question: How to correctly number rows in the indicated column in the table
<?php
    require_once('conect.php');
    $result = $conn->prepare("SELECT * FROM tabelatestowa ORDER BY pkt DESC");
    $result->execute();
    for($i=0; $row = $result->fetch(); $i++);
    $numbers_rows = 1; {
?>

      <?php echo $row['id']; ?>
      <?php echo ++$number_rows;?>
      <?php echo $row['name']; ?>
      <?php echo $row['pkt']; ?>

<?php } ?>

Comment: `$numbers_rows = 1;` should be before `for` loop
Answer: This can be easily accomplished by doing PDOStatement::fetchAll() and looping over it with foreach. This way you don't have to worry about manually setting or incrementing a counter:
<?php
            require_once('conect.php');
            $result = $conn->prepare("SELECT * FROM tabelatestowa ORDER BY pkt DESC");
            $result->execute();
            $results = $result->fetchAll();
            foreach ($results as $index => $row) {
        ?>

                  <?php echo $row['id']; ?>
                  <?php echo ($index + 1);?>
                  <?php echo $row['name']; ?>
                  <?php echo $row['pkt']; ?>

            <?php } ?>

Comment: Thank you very much, just how to make the first row = 1 and not 0. $index = 1 not work
Comment: @Marianna If you're echoing `$index +1` like I have it here, the first row will be 1, not 0.
Answer: Try Removing the ';' at the end of for loop and shifting the $numbers_rows = 1; before the for loop.
Answer: try this,seems issue with for loop format and numbers_rows should before loop
<?php
            require_once('conect.php');
            $result = $conn->prepare("SELECT * FROM tabelatestowa ORDER BY pkt DESC");
            $result->execute();
            $numbers_rows = 1;
            for($i=0; $row = $result->fetch(); $i++)
             {
        ?>

                  <?php echo $row['id']; ?>
                  <?php echo ++$number_rows;?>
                  <?php echo $row['name']; ?>
                  <?php echo $row['pkt']; ?>

            <?php } ?>

Answer: The general point of the other answers is correct about moving the initialisation of the variable outside the loop and correcting where the { goes.
Generally it's written like Alive to Die pointed out with a while() loop...
$numbers_rows = 1;
while($row = $result->fetch()){

The one thing I wanted to add was your echo of the value is using a pre increment (add 1 then use the value), so setting the value to 1 before the loop will mean the first value printed will be 2.
Change the echo to...
echo $number_rows++;

to ensure it starts with 1.


When to Stop Using L'Hôpital's Rule

Question: I don't understand something about L'Hôpital's rule. In this case:
$$
\begin{align}
& {{}\phantom{=}}\lim_{x\to0}\frac{e^x-1-x^2}{x^4+x^3+x^2} \\[8pt]
& =\lim_{x\to0}\frac{(e^x-1-x^2)'}{(x^4+x^3+x^2)'} \\[8pt]
& =\lim_{x\to0}\frac{(e^x-2x)'}{(4x^3+3x^2+2x)'} \\[8pt]
& =\lim_{x\to0}\frac{(e^x-2)'}{(12x^2+6x+2)'} \\[8pt]
& = \lim_{x\to0}\frac{(e^x)'}{(24x+6)'} \\[8pt]
& = \lim_{x\to0}\frac{e^x}{24} \\[8pt]
& = \frac{e^0}{24} \\[8pt]
& = \frac{1}{24}
\end{align}
$$
Why do we have to keep on solving after this step:
$$\displaystyle\lim_{x\to0}\dfrac{(e^x-2)'}{(12x^2+6x+2)'}$$
Can't I just plug in $x=0$ and compute the limit at this step giving me:
$$\dfrac{1-2}{0+0+2}=-\dfrac{1}{2}$$
I'm very confused, because I get different probable answers for the limit, depending on when do I stop to differentiate, as clearly $-\frac1{2}\neq \frac 1{24}$.
Comment: You ought to stop already at $\frac{e^x-2x}{4x^3+3x^2+2x}$, which gets you to $\frac{1}{0}$. The limit doesn't exist.
Comment: it has to be 0/0 or infinity/infinity to use L'hopital per iteration
Comment: You should stop using L'Hôpital's rule if you feel dizziness, if it begins to interfere with your relationships with other mathematicians, or if you find yourself obsessively thinking about how to apply L'Hôpital's rule to objects in your environment, such as your cat.
Comment: You're missing "$\lim\limits_{x\to0}$" in front of your third fraction on the first line.  Without that, the "$=$" just before that is not true.
Comment: Please make your question self-contained. At present it is not since to get crucial information requires going to an offsite (and possibly transient) page.
Comment: @DanielFischer, Do you mean that teacher is wrong saying that answer is 1/2?
Comment: After each derivative calculation, *stop and look.* Perhaps the limit can be read off. Perhaps you can do some manipulation to simplify the two expressions.
Comment: Are you sure you typed the question correctly?  It seems more natural for the numerator to be $e^x - 1 - x$ instead of $e^x - 1 - x^2$.
Answer: Once your answer is no longer in the form 0/0 or $\frac{\infty}{\infty}$ you must stop applying the rule. You only apply the rule to attempt to get rid of the indeterminate forms. If you apply L'Hopital's rule when it is not applicable (i.e., when your function no longer yields an indeterminate value of 0/0 or $\frac{\infty}{\infty}$) you will most likely get the wrong answer.
You should have stopped differentiating the top and bottom once you got to this:
$\dfrac{e^x-2x}{4x^2+3x^2+2x}$. Taking the limit at that gives you $1/0$. The limit is nonexistent.
Also, don't be tempted to say "infinity" when you see a 0 in the denominator and a non-zero number in the top. It may not be the case. For example, the function $\frac{1}{x}$ approaches infinity and negative infinity from both sides of the limit as x approaches 0. Its not necessarily infinite; its best just to leave it as "nonexistent".
Comment: @Val, it depends. If you are adding two infinities, $+\infty$ and $-\infty$, to the reals, which is the usual approach in analysis, then those two are utterly different. If you're only adding one infinity, $\infty$, as is sometimes done in, say, topology, then it is what it is. The qestion is whether you want something that goes *up* forever to have the same limite as something that goes *down* forever.
Comment: @Val Saying a limit infinity is **qualitative** information, in this case of the behaviour of the function near the point. The difference is between saying "*its values go indefinitely far from the origin*", $\lim=\infty$, to saying "*its values go indefinitely far from the origin in the negative direction*", $-\infty$, (or "*in the positive direction*", $+\infty$)". It is less information. In this case may not be important at all. On the other hand, having more information allows you to use the result if you need to do other stuff with it.
Comment: Maybe I should rephrase: the two-sided limit does not exist. We can say that the one sided limit 0+ is infinite, and the other is negative infinite.
Comment: What I meant to say is this: what is your logic in saying that positive infinity equals negative infinity? It doesn't make sense to me.
Comment: Sorry, I have reread the Johnson-Freyd comment, and he says that +inf is identical to -inf indeed, http://mathoverflow.net/questions/10124/the-factorial-of-1-2-3#comment354984_137634 So, I do not take your argument that you cannot write answer =∞ neither the premice that left limit ≠ right limit.
Comment: But what about this case? Why do we assume that we do not want them to be equal and why we cannot call that infinity if it is infinity (whether it is plus or minus)?
Comment: For example, what *dfeuer* was telling you about is related to this: You can say $\lim_{\rightarrow0}-1/x^2=\infty$. But then that information doesn't help you to compute $\lim_{x\rightarrow0}(f(x)-1/x^2)$, even if you are told that $\lim_{x\rightarrow0}f(x)=-\infty$.
Comment: I have this very silly doubt,
I can't find a supporting question but is it legal to simplify limit in between L'Hospital application?
Suppose an intermediate step satisfies the 0/0 condition but its also possible to factor out x from both numerator and denominator and cancel it. My question is the factor and cancel legal?
Answer: After differentiating just once, you get $$\lim_{x \to 0} \dfrac{e^x-2x}{4x^3+3x^2+2x}$$ which "evaluates" to $\dfrac 10$, i.e., the numerator approaches $1$, and the denominator approaches $0$. Hence, L'Hopital no longer applies and we have $$\lim_{x \to 0} \dfrac{e^x-2x}{4x^3+3x^2+2x}\quad\text{does not exist}.$$
L'Hopital's rule applies provided and only while a limit evaluates to an "indeterminate" form: e.g., $\dfrac 00, \;\text{or}\;\dfrac {\pm\infty}{\pm\infty}$.
Comment: Lets make it an even 20 TU's! :-) +1
Comment: What if the numerator is positive infinity and the denominator is negative infinity?
Comment: Isn't 1/0 also indeterminate form?
Comment: No, it is not an indeterminate form, if you mean something like $\lim_{x\to 0} \frac 1{0}$; then we say the limit approaches infinity.
Answer: A quick addition to Ra1nMaster's otherwise excellent answer: you can only apply L'Hopital's rule if you have an indeterminate form and if the limit, after applying L'Hopital's rule, exists.
This second condition is equally important; for instance a classic stumper is
$$\lim_{x\to\infty} \frac{x}{x+\sin x}.$$
Since this limit has the form $\frac{\infty}{\infty}$, one might naively apply L'hopital's rule, getting
$$\lim_{x\to\infty} \frac{1}{1+\cos x}$$
and concluding the original limit does not exist. This is wrong;
$$\lim_{x\to\infty} \frac{x}{x+\sin x} = \lim_{x\to\infty} \frac{1}{1+\frac{\sin x}{x}}=1.$$
Comment: The method used by the top answers seem to be wrong, based on this.
Comment: Inspired me +1 !
Comment: This explains subtle details. +1!
Answer: One must be very careful about using l'Hospital's rule.  It applies only when the numerator and denominator both tend to $0$ or $\infty$ and the denominator is never $0$ in a punctured neighborhood of the point.  A denominator of the form $x\sin \frac1x$ is ineligable for the rule.
But, students should try to avoid the rule anyway.  Here is a parable.  A student is assigned the task of finding
$$
\lim_{x\to 0} \frac{\sin^6 x}{x^6}.
$$
A bad student cancels the $6$ and the $x$ giving $\sin$.
A naive student applies l'Hospital's rule 6 times and eventually gets $\frac{720}{720} = 1$.
A mediocre student applies the rule once, and gets
$$
\lim_{x\to 0} \frac{6\sin^5 x \cos x}{6x^5}.
$$
He cancels the $6$, and removes the $\cos x$ term since it tends to $1$.  He repeats the process 5 more times.
A good student writes the expression as:
$$
\lim_{x\to 0} \left[\frac{\sin x}{x}\right]^6.
$$
He uses continuity of $t^6$ to move the limit inside the brackets and gets $1^6 = 1$.
An engineer says "$\sin x = x$, so the expression is $1$."  And, he'd be right!

Using l'Hospital's rule can also hurt the students understanding of a problem.  Here's a classic example.
The $p$-power mean of two positive numbers, $x$ and $y$ is defined as:
$$
M_p(x,y) = \left[\frac{x^p + y^p}{p}\right]^{\frac1p}.
$$
Can one provide suggestive evidence without using l'Hospital's rule that
$$
\lim_{p\to0^{+}} M_p(x,y) = \sqrt{xy}?
$$
One way to do this is to use the approximation $x^p \approx 1 + p \log x$ for $p$ small, taken from the Taylor expansion of $x^p$ at $p=0$.  Substitute into the power mean formula, and one gets:
$$
\left[1 + \frac p2 (\log x + \log y)\right]^{\frac1p} = \left[1 +  p \log \sqrt{xy}\right]^{\frac1p}.
$$
Let $s = \frac1p$, and this is
$$
\left[1 +  \frac{\log \sqrt{xy}}{s}\right]^s
$$
The limit of that as $s\to{+\infty}$ is
$$
e^{\log\sqrt{xy}} = \sqrt{xy}.
$$
Making this rigorous is not trivial.
Comment: Engineers are always right, for physically plausible values of "right".
Comment: The best math student will say that sin x ~~ x and thus you just get 1. And will point out equivalent infinitesimals https://math.fel.cvut.cz/en/mt/txtb/5/txe3bb5l.htm
Answer: You can't use L'hopital in the third equality sign because you don't have a $"0/0"$ expression.
You get
$$
\lim_{x\to 0}\frac{e^x - 2x}{4x^3 + 3x^2 + 2x}.
$$
Here the numerator approaches $1$ and the denominator approaches $0$, so in all the limit doesn't exist.
Also note that
$$
4x^3 + 3x^2 + 2x
$$
is negative when $x <0$ and it is positive when $x>0$. Therefore one can't say that the limit is $\infty$ or $-\infty$. The limit just doesn't exist.
Answer: From the second equality we find
$$\lim_{x\to0^+}\frac{e^x-2x}{4x^3+3x^2+2x}=\infty$$
thus the other equalities are false.
Comment: It is not infinite because the right and left limit are different. "infinity" implies positive infinity. If the limit's left and right values are different, the limit is nonexistent.
Comment: Its not necessarily infinite; approaching from the right and left yield different values.
Comment: I don't think that the limit is $+\infty$.
Comment: The limit is $+\infty$ at $0^+$ and $-\infty$ at $0^-$.
Comment: @Ra1nMaster How itsn't necessary infinite? It's $\pm \infty$.
Comment: @Ra1nMaster So we agree on the result look to my comment just above  and that's exactly what I meant by writing $\infty$ without sign $\pm$.
Comment: My bad. I misunderstood your argument. The limit is, however, nonexistent. I do not believe that positive infinity can be considered negative infinity; what is the logic behind that.
Comment: @Val there is an argument, "even if" they did not. If the left and right limits are not equal (which positive infinity, as far as I know, is not the same as negative infinity), the limit is nonexistent.
Comment: Ok, but in this case limits are equal, since ∞ = 2∞ = -∞, http://mathoverflow.net/questions/10124/the-factorial-of-1-2-3#comment354984_137634 (Please note how Theo Johnson-Freyd mocks my hesitation whether I should have + or - in the negative factorial). I therefore would not be as cathegorical as you.
Answer: L'Hôpital's rule is ment to applied only when you have to limit of the form 0/0. Once your limit is not in 0/0 form, you are not supposed to apply L'Hôpital's rule.
Answer: In layman's terms:
L'Hôpital's rule should only be applied when we have the limit of the form:
0/0
Read: http://tutorial.math.lamar.edu/Classes/CalcI/LHospitalsRule.aspx
and
http://tutorial.math.lamar.edu/Classes/CalcI/TypesOfInfinity.aspx
Another tip:
If you are using the rule and you find yourself differentiating many times then there is another way to solve these limits. Like simple reduction or change of base.

When to Stop Using L'Hôpital's Rule


Remove Parent Theme Settings From Child Theme

Question: I'm in the middle of creating a custom theme using the Bootstrap theme as it's parent. As you may, or may not be aware, the Bootstrap theme comes with lots of useful theme settings. These are great, but as this custom theme will be used for a client, most of these settings could be dangerous for them to be able to change.
I'd like to remove all of these theme settings, so only the ones I add in my custom theme will appear.
I know these theme settings would still be available to change in the Bootstrap theme, but that's not a problem.
Thanks
Answer: This definitely isn't the nicest solution, but it does work. If you find a better one, do post it here.
function THEMENAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  unset($form['global']);
  unset($form['bootstrap']);
  unset($form['general']);
  unset($form['theme_settings']);
  unset($form['logo']);
  unset($form['favicon']);
  unset($form['components']);
  unset($form['update']);
  unset($form['javascript']);
  unset($form['advanced']);
}

Comment: A note on this approach - if your theme relies upon any settings defined in those form elements, the settings effectively get wiped. So, 2 solutions - either make sure your child theme does not rely upon any of those settings, or set some defaults for these values in your hook.


Recommendations for real analysis

Question: I have completed two courses in real analysis that covered up to chapter 9 in Rudin's Principle of Mathematical Analysis (and one on complex analysis). So if I am interested in continuing on in analysis (real analysis and not complex analysis), what would be a good direction to go from here? What would be a good book to learn from? As my interest is primarily number theory I was wondering if there is a direction in analysis that would be helpful in this aspect.
Comment: Perhaps learn enough ergodic theory to be able to handle its number-theoretic application.
Comment: Complex analysis is certainly useful when dealing with number theory.
Comment: @FernandoMartin As you can see in the question, I've done some complex analysis and I'm looking to foray into real analysis.
Comment: @AndréNicolas That is a very good suggestion. I didn't think of that. Thanks!
Comment: @AndréNicolas I really like your suggestion on ergodic theory best. Do you mind putting your comment as an answer so that I can accept it?
Comment: I think there are a number of good suggestions. The comment did its job drawing your attention to the subject!
Answer: I suggest Folland's Real Analysis: Modern Techniques and Their Applications. It covers all you need to know about measure theory and Lebesgue information, and has chapters on probability, distributions, Fourier analysis, and lots of information about functional analysis.
Other people will recommend "Big Rudin," Royden, and Stein and Shakarchi's series of books, but I find Folland the most clearly written and comprehensive.
Comment: Would the downvoter please say why they don't like this answer?
Answer: If you are interested in number theory, you really should get further into complex analysis. Analytic number theory uses some ideas from complex analysis like the gamma and zeta functions. A good book for this subject, especially the number theory aspect of complex analysis is Stein and Shakarchi's Complex Analysis.
If you want to go further into Real Analysis, you should continue with measure theory and functional analysis. (I can't remember if the first 9 nine chapter of the first Rudin covers measure theory.) A good book for a first introduction to functional analysis and measure theory would be Rudin's Real and Complex Analysis. For more advance book on functional analysis, I would recommend Brezis Functional Analysis, Sobolev Spaces, and Partial Differential Equation$.
Comment: @DylanMoreland Thanks for letting me know.
Comment: @William Thanks for the complex analytic suggestions but I am already familiar with the gamma and zeta functions.

Recommendations for real analysis


Which answer is correct for this product rule based probability problem

Question: The question reads like this:

A bag contains 5 black and 3 red balls. A ball is taken out of the bag and is not returned to it. If this process is repeated three times, then what is the probability of drawing a black ball in the next draw?

Solution 1
I think the three balls can be drawn in 4 ways

All the three balls are black = 5/8 .4/7 .3/6 then the probability of next black ball can be drawn is 2/5.
2 black and 1 red = 5/8 . 4/7 . 3/6 then the probability of next black ball can be drawn is 3/5.
1 black and 2 red = 5/8 . 3/7 . 2/6 then the probability of next black ball can be drawn is 4/5.
All red = 3/8 . 2/7 . 1/6 then the probability of next black ball can be drawn is 1.

And probability of each way is 1/4.
Hence desired probability $=\frac{1}{4}\times\frac{2}{5}+\frac{1}{4}\times\frac{3}{5}+\frac{1}{4}\times\frac{4}{5}+\frac{1}{4}\times1=\frac{7}{10} = 0.7$
Solution 2
Probability of 4th ball being black when

All first first 3 draws are black balls $=\frac{5}{8}\times\frac{4}{7}\times\frac{3}{6}\times\frac{2}{5}=\frac{120}{1680}$
First three draws contain all red balls $=\frac{3}{8}\times\frac{2}{7}\times\frac{1}{6}\times\frac{5}{5}=\frac{30}{1680}$
First three draws contain 2 red and 1 black ball $=\frac{3}{8}\times\frac{2}{7}\times\frac{5}{6}\times\frac{4}{5}\times 3=\frac{360}{1680}$
First three draws contain 1 red and 2 black ball $=\frac{3}{8}\times\frac{5}{7}\times\frac{4}{6}\times\frac{3}{5}\times 3=\frac{540}{1680}$

Summing all above probabilities gives $=\frac{5}{8}=0.625$
I cant decide which one is correct. I feel the second one is just far more precise. Is it?
Comment: The answer is (after a while I think obviously, without calculation) $5/8$.
Comment: The second one is correct. In the first solution you are wrong in assigning to the four cases the same probability.
Comment: good its not just me who feels second approach is correct, however the [book](https://goo.gl/FlL6mv) I am referring solves it 7/10. Unfortunately solution key page is omitted in Google books. (But next question in the book asks probability of red ball in next draw and it solves in similar approach as solution 2.) Also few people online solves this question to 7/10. User @appi1107 on [this](http://goo.gl/rwScCa) page. And also on [this](http://goo.gl/hsC7z6) page. Also [this](http://goo.gl/PTtyix) site, though I feel this site simply copy pastes stuff from other sources. So am still confused.
Comment: Hi please tell why 1st one is incorrect. After thinking more I feel solution 1 is incorrect because it does not take into account the permutations of first three balls drawn that can result in each of the four cases. Is it the reason?
Comment: @Mahesha999  That is so.  The first solution calculates the probability of drawing two black balls then a red ball (in that order), but neglects to consider the possibility of drawing a red ball then two black balls, or of drawing a black ball, a red ball, then a black ball.  And so forth.
Comment: @GrahamKemp , is there a way to correct the first solution ? , I'm trying to figure out how to correct the first solution. Thank you :)
Comment: @PruthviRaj The second solution *is* the corrected way.  It takes account of the *3 arrangements* the first three balls can when one is a different colour, *and* the conditional probability of the fourth ball being black when given the count among the first three.
Comment: I will go with the solution 1 because the it includes the probability of the certain case to occur. We need to keep in mind that each case independent and the 1st solution counts it in. Although the second one is plausible it does not take into account the probability of the case itself which is relevant in this question because of the multiple trials !!!
Answer: You are overcomplicating things.   There are eight balls, and any one of which could be the fourth ball drawn with equal probability.   Five of these balls are black.   The probability that a black ball is drawn on the fourth draw is thus: $$5/8$$

This agrees with your second solution, which correctly considers that there are three ways to arrange two balls of one colour and one of another.

To see this in action, lets examine ways to draw balls from a bag of two black and two red balls, and count those where the third ball is black.  By my method we should expect $2/4$ of the possible arrangements to have a black ball drawn in third place. Let's see...
$$\begin{array}{cc}\bullet\bullet\circ\circ \\\bullet\circ\bullet\circ &\star\\ \bullet\circ\circ\bullet \\ \circ \bullet\bullet\circ & \star \\ \circ\bullet\circ\bullet \\ \circ\circ\bullet\bullet & \star\end{array}$$
Comment: your approach is quite surprising to me. *There are eight balls, and any one of which could be the fourth ball drawn with equal probability.   Five of these balls are black.   The probability that a black ball is drawn on the fourth draw is thus: 5/8*. However some black balls may have already taken out. Then there are not five black balls remained but lesser, in that case the probability will also be less. I could have said that the probability of (first) ball drawn without replacement is black is 5/8, but not the same about the fourth ball drawn. What I am missing?
Comment: @Mahesha999 Consider the case where you continue drawing the balls, one by one, from the bag and placing them in a line.  Sometimes more black balls will be drawn before it, and sometimes less, but of *all* of the (equally-)possible arrangements, five in eight will have a black ball drawn in the fourth place.  This is true for any particular place you choose, whether that place is first, second, third, fourth, all the way to last.
Comment: Is this approach supposed to be basic understanding that everyone should have? I mean I have practiced many problems on probability & my solution approach used to be like the one above, mostly driven by sample problems given in the book. Now seeing your seemingly simple approach, am just guessing what all types of problems are solvable with this approach? Am still disturbed why my [book](http://goo.gl/Q4iOJ9) (which is very popular for Indian business school exam prep) did not taught this & kept preaching more weird approaches. Now guessing what all it might have ill-taught to me.


disjoint union of projective morphisms is projective?

Question: A morphism $f:X \to Y$ of schemes is projective if it factors into a closed immersion
$i:X \to \mathbb{P}_{Y}^n(=\mathbb{P}_{\mathbb{Z}}^n\times_{Spec\mathbb{Z}} Y)$ for some $n$,followed by the projection $\mathbb{P}_{Y}^n \to Y$.
Let $f_{i}:X_{i} \to Y (i=1,2)$ are projective morphism of schemes.
Is it true that $f_{1}\coprod f_{2}:X_{1}\coprod X_{2} \to Y$ is projective?
Answer: Yes. It suffices to show that $\mathbb{P}^m\coprod\mathbb{P}^n$ can be embedded in to some $\mathbb{P}^r$. Take $r\geq m+n+1$ and include the first copy as the coordinate subspace on the first $m+1$ coordinates and then second copy as the coordinate subspace on the last $n+1$ coordinates.
Writing $f_1\coprod f_2$ as $X_1\coprod X_2 \to \mathbb{P}_Y^{n_1}\coprod \mathbb{P}_Y^{n_2} \to \mathbb{P}^{N}_Y \to Y$ we see the desired result.


Is it possible to obtain result set of a sp as a table that I can query?

Question: Is it possitble to get a stored-procedure's result set as a table so that I can query that?
something like:
SELECT PK_Item, Count(PK_Item)
FROM (pMyStoredProcedure) --This sp returns a table that has PK_Item column
GROUP BY PK_ITEM
ORDER BY PK_ITEM DESC
I am not an T-SQL expert but my friend says it is kind of impossible to do this with sprocs.
Is not there any way? But without modifying the stored procedure.
thanks!
Comment: From your sample code, I assume that SP has no parameter, yea?
Answer: If you know the table structure that the sp will return using sql server 2005
you can use
<code>declare @table table(
  columns here...
)

INSERT INTO  @table exec your_sp params

select * from @table
</code>
Comment: What if the sp returns 2 or more tables as a result set?


Why is the octatonic scale described as a equal interval chromatic scale?

Question: I read a dissertation in which the author describes the octatonic scale as 'equal interval chromatic'. I thought that the octatonic was a mixture of semitones and tones?
Moreover the dissertation is in relation to Rachmanioff's association of it with 'intensification, destabilisation and climax'.
Comment: In this case, chromatic may mean that the author doesn't have a logical framework for reasoning about its use. Check Barry Harris on youtube, he seems to have frameworks for diminished scales.
Comment: Why did you accept an answer so quickly? This question just became the Official Internet Truth on the subject of why "the octatonic scale" (as if there was only one) is described as a chromatic scale. But I don't really understand it. The major scale contains whole steps and half steps, so it is a combination of the chromatic scale and whole-tone scales, so should the major scale be described a chromatic scale?
Comment: I accepted it because I made the mistake in the heading question of putting chromatic, whereas in the body of the question I put the full description: equal interval chromatic. Laurence answered the question by saying it was a mixture of the chromatic and whole tone scale which made sense to me. Moreso, yes the major scale does contain whole and half steps it is a asymmetrical scale= it could be Whole, whole, half (start of major scale).. Whereas the octatonic is half, whole or vice versa consistently and is a symmetrical scale
Comment: Apologies for the confusion. I've changed the heading
Answer: I guess you are referring to this PhD thesis: https://deepblue.lib.umich.edu/handle/2027.42/63739. Certainly the phrase "equal interval chromatic" occurs twice in the abstract, and once adjacent to the word "octatonic".
Anyone who can make sense of the word salad in the summary is welcome to post an explanation - e.g.

I show that different harmonic components have different rhetorical
  associations in the works studied; that different components are
  generally associated with different locations in form; and that
  acknowledging the interaction of different kinds of harmonic
  structures in a work contributes significantly to an understanding of
  expressive trajectory and large-scale organization, and—especially—to
  exegesis of climax events.

Maybe reading the complete 305-page document will produce enlightenment. Or maybe not.
Comment: It's not "word salad," which implies nonsensical constructions.  The passage you quote makes grammatical and semantic sense -- it's just a *run-on sentence*.
Comment: Word salad!  It's not a light read
Comment: If talking about music is like dancing about architecture, then this must be dancing about dancing about architecture. The expressive trajectory goes totally ballistic!
Answer: Obviously the scale is not all equal steps. It's a combination of whole and half steps.
You need to look at some other interval relationship between tones beside step by step intervals.
You can generate an octatonic scale by superimposing two diminished seventh chords each of which is composed of equally spaced minor thirds.
Ex. take a B diminished seventh chord and superimpose a C# diminished seventh chord and you get an octatonic scale.
Answer: If the dissertation in question is the one linked to in guest's answer, "equal-interval" is the general term here, referring to structures that divide the octave equally.  This tends to be especially applied to division of the octave into major thirds or minor thirds.  (Equal division into seconds also produces both the standard chromatic scale, as well as the whole-tone scale, which is discussed periodically in the dissertation too.)
However, such divisions don't tend to be very useful by themselves -- they just produce static diminished or augmented chords.  (Or a whole-tone scale by itself, which generally sounds pretty static harmonically.)  Instead, a lot of times these notes (and others) are used to produce progressions around such division points within the octave.
One possible extension of equal division is to superimpose two cycles of equal division next to each other (as Michael Curtis describes).  If one does this for augmented triads, one produces a hexatonic scale.  If one does this with diminished seventh chords, one produces an octatonic scale.  Hexatonic and octatonic scales can be used to produce progressions that move between the major/minor thirds that the "equal division" structures are originally based around.  Hexatonic and octatonic scales also allow one to build simple major or minor triads within them, which isn't possible with a simple equal division of the octave by itself (again, just an augmented or diminished seventh chord).
Thus, hexatonic and octatonic scales can be used with standard major and minor triads (as well as more dissonant chords) to produce progressions that move chromatically across equal intervals (i.e., major or minor thirds).  Hence equal interval chromatic (which is more about the type of progression possible than a description of the pure scale).  This is opposed to normal functional chromaticism, which tends to be organized around fifth and fourth relationships with dominants (and secondary dominants) progressing to tonics and generally isn't organized around progressions of equal intervals.
EDIT: Also, if the dissertation linked is the one OP is discussing, I'm not sure where the term "equal-interval chromatic" is used to describe the octatonic scale.  Rather, octatonic pitch collections are used in the dissertation at times as a basis for finding "equal-interval chromatic structures" (again, mostly based around progressions that involve symmetry by minor third intervals).  If there's a place where OP sees a specific designation of "equal-interval chromatic" referring to the scale itself, it might be easier to interpret the question.
Comment: Well, even though you're dealing with tonal music, the dissertation makes heavy use of notation based on some pitch-class set theory and post-tonal theory.  I don't know what your level of theory knowledge is, but one of the clearest textbooks that covers some of that is Joseph Straus's *Introduction to Post-Tonal Theory*, which is the origin of the notation used in the dissertation to label octatonic pitch collections.  If there's something unclear or that you need more explanation on in my answer, let me know: I'm happy to expand or give more details (or you can ask a separate question).
Comment: Thank you for this detailed answer. I'm trying my best to try and understand it. Do you know of any theory books that cover this level of music theory?
Answer: Here's one writer's description of the octonic scale: 'The octatonic scale alternates between whole and half steps, and is therefore a combination of the principles behind the chromatic scale and the whole-tone scale.'
http://www.musiccrashcourses.com/lessons/scales_more.html
Maybe that's what your guy was getting at?   Give us some more context, it might make more sense.


Implicit type casting in Swift

Question: Playing with the sample code from Swift Language Guide: Extensions I've extedned struct Double like this
extension Double {
    func someFunc() {
        print("someFunc")
    }
}

I was surprised that this statement
2.someFunc()

did not generate compile time error like: Value of type 'Int' has no member 'someFunc'. I've expected value of 2 to be implicitly casted to Int but Swift casted it to Double. Why is that ? How does Swift determine that value of 2 in this case is of type Double ?
Then I've tried calling someFunc() like that
let x = 2
x.someFunc()

Here I get the expected compile time error
Does'n this contradict statement in Swift Programming Language 3.0.1 : Language guide : The basics : Type Safety and Type Inference?

Type inference enables a compiler to deduce the type of a particular
  expression automatically when it compiles your code, simply by
  examining the values you provide.

EDIT
From the responses I've learned that it happens because Double conforms to ExpressibleByIntegerLiteral protocol. However Float struct also does conform to it and some other types as well. Below I have created my struct that also conforms to that protocol. In the end however Double is chosen at compile time. Why? How is the precedence of method from one extension determined over the method from other extension ?
struct someStruct: ExpressibleByIntegerLiteral{
    var i:Int = 0

    init(integerLiteral value: Int64){
        i = Int(value)
    }
}

extension someStruct {
    func someFunc() {print("Somestruct someFunc") }
}

extension Double {
    func someFunc() { print("Double someFunc") }
}

4.someFunc()

//prints: Double someFunc

Comment: That's a good question in the edit.
Answer: Double is one of the types that conforms to the protocol ExpressibleByIntegerLiteral.  Since 2 is an integer leteral, the compiler can check which of the types conforming to the protocol has a someFunc() and since only Double does, there is no abiguity in this context.
Comment: Float struct does also conform to this protocol but it does not compile.
extension Float {
    func someFunc() {
        print("float someFunc")
    }
}

4.someFunc()
Is it all that is needed?

And what if I'd extended two structs with that someFunc() - how do I know wchich one will be choosen at execution time?
Comment: I think it has to do with this: "Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers" https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
Answer: Double conforms to ExpressibleByIntegerLiteral. In your example, the compiler sees that of the all the types that conform to ExpressibleByIntegerLiteral, only Double contains someFunc(), so it knows to create a Double out of 2.
As you noticed in your second example, this behaviour doesn't define implicit casting between types. It only applies to literals.

Implicit type casting in Swift


on_member_join can't print a message

Question: I'm doing a Discord bot with Python 3.8 and I have a problem with my event on_member_join().
@bot.event
async def on_member_join(member):

    embed = discord.Embed(
    title=f"that doesn't function")
    channel = discord.utils.get(member.guild.channels, name='WELCOME_CHANNEL_NAME')

    await member.send('Hello')
    await channel.send(embed=embed)

member.send sends a private message with hello but channel.send  sends this error await channel.send(embed=embed) AttributeError: 'NoneType' object has no attribute 'send'
I really don't know how to do,
Thanks for your help!
Answer: Because you probably don't have a channel named WELCOME_CHANNEL_NAME. That's why channel returns None. You need to type the real welcome channel name instead of WELCOME_CHANNEL_NAME in channel = discord.utils.get(member.guild.channels, name='WELCOME_CHANNEL_NAME').
Comment: xD i'm so stupid, i thought "WELCOME_CHANNEL_NAME" was the "general" channel, thanks !!!! i would never check that :D

on_member_join can't print a message


Receber nome do formulário ou submit PHP

Question: Como posso receber em uma função de outra página o nome do formulário ou so submit enviado através de POST?
<code><form class="form-inline" name="indicador" method="post" action="funcoes/indicadores.php" >

   <button type="submit" class="btn btn-theme" name="indicador">Atualizar</button>

</form>
</code>
O name="" que vou utilizar será dinâmico, e quando receber o POST na página funcoes/indicadores.php quero saber qual o nome do POST ou SUBMIT...
Comment: no seu exemplo o formulário e o botão tem o mesmo `name`, você pode descrever melhor qual o problema? [Edite a pergunta](http://pt.stackoverflow.com/posts/96561/edit) e adicione mais detalhes
Answer: Pegar o nome do formulário não é possível.
Acho mais fácil colocar um campo hidden, com o nome do formulário, ai você pega por esse campo, ou também pegar o name ou value do botão submit.
Answer: Sugiro utilizar um campo hidden, este tipo de campo fica invisível para o usuário, ou seja, não aparecerá na tela.
Exemplo:

Neste caso, você coloca o valor dinâmico no atributo "value" do input.
Ai para pegar esse valor através do POST, basta usar:
$valorDinamico = $_POST['exemplo'];
Espero ter ajudado.
Comment: desculpa, faltou o exemplo do input:
Comment: Correto. Obrigado


Near 100% accuracy during training but <50% during testing/validation on image classifier

Question: I've been trying to train my model for the past few days, but each time no matter what I try, I get the same issue. My accuracy starts low and reaches above 90% within the first epoch, but validation at the end of each epoch comes out as anywhere between 20-50%, and testing the model predictions is accurate with some classes but completely wrong for most. My dataset has 20000 images, 2000 per class, and 100 testing images(can get more if necessary). I would greatly appreciate any input any of you have, as I am quite new to machine learning as a whole and I do not completely understand everything that goes into this.
I've looked at several posts and articles online describing similar issues and their fixes, whether it be defining activations as their own layers rather than parameters, adding in batch normalization layers and changing their momentums, trying several different optimizers and learning rates, different sizes of datasets, using a custom initializer, and even completely changing the structure of my model. Nothing works.
Here is the main part of the network:
model = Sequential()
initializer = keras.initializers.he_normal(seed=None)

model.add(Conv2D(64, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer, input_shape=x_train.shape[1:]))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(128, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(256, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(256, (3, 3), padding='same', use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(2048, use_bias=False, kernel_initializer=initializer))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.4))
model.add(Dense(num_classes, use_bias=False))
model.add(BatchNormalization())
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(lr=0.00005), metrics=['accuracy'])

# train the model
if not testing_mode:
    model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, shuffle=True, validation_data=(x_test, y_test))

scores = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])

Here is the last few batches of an epoch and its validation at the end:
19776/20000 [============================>.] - ETA: 25s - loss: 0.4859 - acc: 0.9707
19840/20000 [============================>.] - ETA: 18s - loss: 0.4855 - acc: 0.9708
19904/20000 [============================>.] - ETA: 11s - loss: 0.4851 - acc: 0.9709
19968/20000 [============================>.] - ETA: 3s - loss: 0.4848 - acc: 0.9710
20000/20000 [==============================] - 2323s 116ms/step - loss: 0.4848 - acc: 0.9710 - val_loss: 1.9185 - val_acc: 0.5000

Edit: I've been told to add more info about my dataset. I am training on this dataset with 10 classes of different hand gestures. Each image is preprocessed to be 128x128 and grayscale, and my 100-image testing set is 10 images taken from every class in the training set. I know it's better to get data that's separate from the training set for testing, but I wasn't sure if deleting images from the training set was a good idea. This is also one of the reasons why I think this issue is strange, because if the model is overfitting onto the training data, then why is the accuracy so low when faced with data it has already seen? Let me know if you need any more information.
Comment: Your model is overfitting! You'll need to describe what you're training on, what you're testing on, the classification values, the distribution of the class values, and whole bunch more to get more meaningful comments.
Answer: It seems that your model is overfitting which means that it's adapting [learning] very closely to the training set.
This can be caused if your training set doesn't include all cases types, try shuffling your data again.
Comment: Do you know of any way to shuffle the data without messing up the labels?
Answer: Most likely your model is overfitting. This means that your model has poor prediction accuracy and cannot generalize beyond the training set. There are several reasons this could occur, so a recommendation cannot be made until we have more information about your model.
Edit 1
My understanding is that a model should not have the test set observations found in the training set. I am not very familiar with the syntax used but I think you can separate the sets using the validation_split parameter in the .fit function. A recommended split would be around 85% training / 15% test
Source: https://keras.io/models/model/
Comment: @mattsap's comment is a good start. If i understand your edit#1 correctly, is your test set included in your training set? i am not following that
Comment: To my understanding that is not good. Test set data should NOT be in your training set.
Comment: The test images are stored in a separate location, but they can all be found somewhere in the training set. So, yes.
Comment: So, should I create a new testing set but remove the images I take from the training set?
Comment: I was going to do this originally, however it seems that parameter takes the split from the end of the training set before it shuffles, and my training set is loaded in order at first. It relies on shuffling. If you know of any way I can shuffle beforehand, I will use the validation split.
Comment: what do you mean when you say in order?, I am not following this concept of order in your data set
Comment: The images for each class in the training set are stored in a folder that encompasses the entire class. When I load these images into an array, it goes folder by folder, such that (for example) the first 2000 values in the array all belong to the same class, and the next 2000 to another class, etc. So, if I did a 10% validation split, it would split one entire class of images from the rest of the dataset.
Comment: is it possible to shuffle the data set before calling .fit() then?
Comment: That's what I'm trying to figure out. I don't know of any ways to do it, and it would have to also be a way that lets me shuffle the labels in the exact same way. I'm going to look at the Keras documentation and look for one.
Comment: any progress on the model?
Answer: As you are training your Convolutional Neural Network(CNN), to get rid of the overfitting problem, you can apply the following approaches -

You can play around with the Dropout with their probability value which acts as a
regularizer for CNN
Add more data by using techniques like Data Augmentation
Use Transfer Learning (Pre-Trained Models)
Comment: Should I be using higher or lower dropout values?
Comment: Good value for dropout in a hidden layer is between 0.5 and 0.8. But I can say, you can play around with values range in between 0.3 to 0.8 and check which gives the better result.


Calculating and comparing lifetime risk

Question: Is the following calculation/approximation appropriate when calculating lifetime risk (?):

The lifetime risk of developing a disease or adverse event secondarily to a therapy or intervention was denoted as Lifetime Risk (adverse event) and calculated by:
Lifetime Risk (adverse event) = RR (intervention) * Lifetime Risk (general population)
where "Lifetime Risk (general population)" is the general lifetime risk of developing the disease or adverse event without being subject to the therapy or intervention, and "RR (intervention)" is the relative risk (RR) from previously published RR data (relating to the development of the questioned disease or adverse event to the intervention).
Or is the following equation better (?):
Lifetime Risk (adverse event) = [RR (intervention) - 1] * Lifetime Risk (general population) ???
Comment: What is your thinking behind your second equation? If, say, RR=1 (same risk in intervention group as among controls, it says that lifetime risk = 0 \times risk in general pop.  Can that be correct???
Answer: It is your first equation.  When you think about what RR (relative risk) means, it is the risk in the treatment group compared to the risk (probability of being affected) for the control group, where we take the control group as representative of the general population (that identification seems to be implicit in your question, even if it in general is doubtful).
As for why your second equation do not make sense, just look at what it says if RR=1!

Calculating and comparing lifetime risk


Assumptions of generalized linear models

Question: On page 232 of "An R companion to applied regression"  Fox and Weisberg note

Only the Gaussian family has constant variance, and in all other GLMs the conditional variance of y at $\bf{x}$ depends on $\mu(x)$

Earlier, they note that the conditional variance of the Poisson is $\mu$ and that of the binomial is $\frac{\mu(1-\mu)}{N}$.
For the Gaussian, this is a familiar and often checked assumption (homoscedasticity). Similarly, I often see the conditional variance of the Poisson discussed as an assumption of Poisson regression, together with remedies for cases when it is violated (e.g. negative binomial, zero inflated, etc). Yet I never see the conditional variance for the binomial discussed as an assumption in logistic regression. A little Googling did not find any mention of it.
What am I missing here?
EDIT subsequent to @whuber 's comment:
As suggested I am looking through Hosmer & Lemeshow. It is interesting and I think it shows why I (and perhaps others) are confused. For example, the word "assumption" is not in the index to the book. In addition, we have this (p. 175)

In logistic regression we have to rely primarily on visual assessment, as the distribution of the diagnostics under the hypothesis that the model fits is known only in certain limited settings

They show quite a few plots, but concentrate on scatterplots of various residuals vs the estimated probability. These plots (even for a good model, do not have the "blobby" pattern characteristic of similar plots in OLS regression, and so are harder to judge. Further, they show nothing akin to quantile plots.
In R, plot.lm offers a nice default set of plots to assess models; I do not know of an equivalent for logistic regression, although it may be in some package. This may be because different plots would be needed for each type of model. SAS does offer some plots in PROC LOGISTIC.
This certainly seems to be an area of potential confusion!
Comment: If you have a copy of Hosmer & Lemeshow, *Applied Logistic Regression,* then check out the chapter on "Assessing the fit of the model": the conditional variance of the Binomial shows up *everywhere* and is explicitly accounted for in almost all the GoF tests.
Comment: I think the binomial assumption is imposed by the real experiment: responses are independent 0/1 so the binomial distribution is the only one which models the real experiment. At the opposite the assumption of Poisson distribution for counts is not realistic.
Comment: Thanks @whuber . I do have that book and will check it out
Comment: ... but the link function is not natural and it determines the conditional variance... so my above comment was not very sensible
Answer:
These plots (even for a good model, do not have the "blobby" pattern characteristic of similar plots in OLS regression, and so are harder to judge. Further, they show nothing akin to quantile plots.

The DHARMa R package solves this problem by simulating from the fitted model to transform the residuals of any GL(M)M into a standardized space. Once this is done, all regular methods for visually and formally assessing residual problems (e.g. qq plots, overdispersion, heteroskedasticity, autocorrelation) can be applied. See the package vignette for worked-through examples.
Regarding the comment of @Otto_K: if homogenous overdispersion is the only problem, it is probably simpler to use an observational-level random effect, which can be implemented with a standard binomial GLMM. However, I think @PeterFlom was concerned also about heteroskedasticity, i.e. a change of the dispersion parameter with some predictor or model predictions. This will not be picked up / corrected by standard overdispersion checks / corrections, but you can see it in DHARMa residual plots. For correcting it, modelling the dispersion as a function of something else in JAGS or STAN is probably the only way at the moment.
Answer: The topic you explain is frequently called overdispersion. In my work I saw a possible solution to such topic:
Using a Bayesian approach, and estimating a Beta-Binomial distribution. This has the great advantage to other distributions (induced by other priors), to have a closed form solution.
References:

Beta-binomial distribution
Peter Hoff Bayes estimators notes (pdf)


Replace the date of a filtering criterion with "Views PHP"?

Question: I created a "like" flag on the nodes.
I created a comment view.
I want my view to show only comments posted since the flag date.
The solution will be to create a filter criteria with the filter "Comment: Publication date" (Is greater than or equal to) and replace the value with the date of the flag.
The problem is that there are no tokens for the filter criteria.
How to do this with "Views PHP" ?
https://www.drupal.org/project/views_php
Answer: Don't.
Views PHP or any other method of stored PHP is a bad idea (What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?). It's also extremely slow, because it usually involves loading all data and then doing all the processing in PHP.
Instead, build a module and define a views filter plugin there, then you can build the query there how you like it. How exactly to do that is IMHO too complex to answer in a single question, you should find plenty of examples and tutorials on how how to create views filter plugins (there are dozens of plugins in core alone), look for something similar to your use case and start from there.
Comment: Here is my question about this problem with a solution without using PHP code in the view  https://drupal.stackexchange.com/questions/255576/in-a-view-how-to-replace-the-date-of-creation-of-the-comment-by-the-date-of-the


Como não perder a session de uma aba para outra?

Question: Estou tentando criar um login no qual após validar que o usuário e senha estão corretos crie na sessionStorage a seguinte variavel:
sessionStorage.setItem('ClienteId', resp.ClienteId);
Fazendo assim com que ao entrar em cada page eu verifico antes se existe o cliente na session, mas ao mudar de aba perco a mesma. Teria como trabalhar sem perdê-la?
Ou alguma forma melhor de realizar o login? Obrigado desde já.
Answer: Para isso você pode usar o localStorage, onde poderá ser compartilhado entre as abas do browser.
Answer: Acho que usando o sessionStorage é uma boa opção, visto que esse não realizará a persistência dos dados, enquanto o localStorage o fará.
Ou seja, se você reiniciar o navegador por exemplo, os dados do sessionStorage serão apagados(não-persistente), enquanto os dados permanecerão no localStorage.
Aí vai da sua necessidade. Acredito no seu caso, por se tratar de um ID de cliente, o interessante é 'sumir' com ele quando você fechar o navegador, então sessionStorage mesmo.
Comment: Utilizei o LocalStorage mesmo realizando um session abandon caso saia da page ou peça para deslogar!


Creating custom document action Alfresco javascript

Question: I'm trying to create a custom document action in Alfresco. But, when i try to run the new "Button" created, nothing happens, the function is not called. I'm trying, in this time, make a button equal to the "Copy to..." only for testing, so, my code is this:

~/alfresco/tomcat/webapps/share/components/documentlibrary/actions.js

<code>(...)
onActionSign : function dlA_onActionSign(record)
  {
     //testar upload de um documento
     this._copyMoveTo("copy", record);
  },
(...)
</code>

~/alfresco/tomcat/webapps/share/WEB-INF/classes/alfresco/share-documentlibrary-config.xml

<code>(...)
<action id="document-sign" type="javascript"  label="actions.document.document-sign">
            <param name="function">onActionSign</param>
            <evaluator>evaluator.doclib.action.editableByCurrentUser</evaluator>
</action>
(...)
</code>
I saw that in the

~/alfresco/tomcat/webapps/share/components/documentlibrary/actions-min.js

my function not appears, i think that is because not works, but how i generate this file? What is my error?
Thanks.
Comment: Start by copy pasting your action.js into action-min.js
Comment: If you want @TahirMalik put like answer and i put correct.
Comment: Great, I've the comment as an answer.
Answer: Like answered in the comment. Alfresco uses the *-min.js versions of JavaScript to lookup the actions.
If you don't have a build script which automatically creates these files, then you can just copy and paste your normal code in these files.
Comment: A little late but you can use the yui-compressor library of alfresco fro doing that: /opt/alfresco/alfresco-4.2.e/java/bin/java -jar /opt/alfresco/alfresco-4.2.e/tomcat/webapps/share/WEB-INF/lib/yuicompressor-2.4.7.jar users-size-quota.js -o users-size-quota-min.js


Views 3, contextual filter on language - allow for multiple languages

Question: So for this site I'm building I need to be able to do the following.

When user views the site in English show all English articles
When the user views the site in Dutch, show all Dutch articles - but also the untranslated English ones
When the user views the site in German, show all German articles - but also the untranslated English ones.

The contextual filter, 'Content translation: Language' only allows to put in one value. That is either a language specified, or all.
But in my case it would be required to be able to set for instance "en+nl" or "en+de". Like one can do with taxonomy 'Has Taxonomy', I would like something like 'Has Language'.
Answer: I solved this task like so:

For "When the filter value is not available",  select option "Provide default value".
then use "PHP Code" as the value for "Type"
the actual PHP code I added is as shown in the screenshot below:
Comment: Adding php on a view ? That is ugly..... It solve the problem but I do not think this is a good idea.
Comment: This may be hackish but this exactly got me what is needed for a slightly different requirement - one view page, with language prefixes: site.com/en and site.com/ja ... When user is on EN, shows all content with EN content; when switched to JA interface, shows only content with JA translation. Thanks!
Answer: One solution would be to use field translation:

Set "Enable language fallback" to active in the entity translation
configuration page.
Set the view to use the current user language
(Advanced>Other>Field Language).

Done.
Comment: can't see a "Enable language fallback" option on that page. need to install Entity translation module before, I think...
Comment: how else would you access the modules configuration page?  I should have pointed that out more clearly though, so thanks for adding that information.
Answer: I guess you need this module:
https://www.drupal.org/project/select_translation

it provides language fallback functionality for nodes translated with
  Content Translation (not Entity translation) inside views listings.
  This is an alternative to the Views "Field Language" option which
  would not work for nodes translated with Content Translation.
Answer: To have a View with a default language fallback if a node translation doesn't exist and then show the default language one, just ensure UNCHECK:
X When needed, add the field language condition to the query


Firebase para uma Lista

Question: Preciso pegar todos os dados do firebase e criar uma lista, para usar em um listadaper que criei.
Essa é a estrutura do Banco no Firebase:

Como podem ver, quero pegar todos os child de Wallpapers(wallpaper1, wallpaper2, etc).
Tenho o seguinte código:
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Wallpapers").child("Wallpaper1");

E no value listener:
 ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<Wallpaper> list = new ArrayList<>();

            String Nome = (String) dataSnapshot.child("Nome").getValue();
            String Descricao = (String) dataSnapshot.child("Descricao").getValue();
            String URL = (String) dataSnapshot.child("URL").getValue();

            Wallpaper wallpaper = new Wallpaper(Nome, URL, Descricao);
            list.add(wallpaper);

            List_Adapter adapter = new List_Adapter(getApplicationContext(), list);
            lista_principal.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
    ref.addListenerForSingleValueEvent(eventListener);
}

Mas como tá meio óbvio, só tá pegando os itens de Wallpaper1;
O que preciso é que pegue todos os itens de Wallpapers e adicione numa Lista dessa classe:
public class Wallpaper {
private String Nome;
private String Url;
private String Descricao;

public Wallpaper(String nome, String url, String descricao) {
    Nome = nome;
    Url = url;
    Descricao = descricao;
}

pra eu poder usar ela no Listview adapter que criei.
Comment: Por que o banco está estruturado desse jeito? Se você tem uma lista de elementos do mesmo tipo, o ideal é usar um vetor. Fica mais fácil tanto para gravar quanto para recuperar.
Answer: Consegui resolver fazendo o seguinte.
Removi o child de Wallpapers
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Wallpapers");

E fiz um foreach em cada Datasnapshot
for (DataSnapshot item : a) {
                String Nome = (String) item.child("Nome").getValue();
                String Descricao = (String) item.child("Descricao").getValue();
                String URL = (String) item.child("URL").getValue();
                Wallpaper wallpaper = new Wallpaper(Nome, URL, Descricao);

                list.add(wallpaper);
            }

Firebase para uma Lista


Probability density and moment generating

Question:
Please show some working when substituting the equation.
Comment: please add the `self-study` tag for textbook questions
Comment: Please don't radically alter your question in a way that makes answers to what you originally asked no longer an answer - the form of the original was fine, but now my answer doesn't look like it responds to your question - people would rightly downvote my answer on that basis. You can add followup questions or clarifications without changing the question quite so much. Your new question is basic mathematics and isn't on topic here; it's *exactly* like changing from $\sum_{i=1}^n x_i$ to $\sum_{j=1}^n x_j$ -- changing the dummy variable doesn't alter anything.
Comment: Sorry, cause I was unable to type out the math equations through the text box.. I change back the question. I am sorry, Thanks anw!
Answer: Actually, @DilipSarwate explained exactly how to do it in your previous question.
\begin{align}
M_Z(t) &= E[e^{sZ}] \\
&=  \int_{-\infty}^\infty e^{tz}\, f_Z(z) dz \\
&=  \int_{-\infty}^\infty e^{tz}\, [pf_X(z)+(1-p)f_Y(z)] dz
\end{align}
and then use basic properties of  expectations / integrals
Comment: Note that the argument in a mixture is going to be the same ($z$ in this case), even though the subscript that denotes the *form* of the density is different. See [here](http://en.wikipedia.org/wiki/Mixture_distribution#Finite_and_countable_mixtures) for example.


jquery: Disable/Enable button not working after reset

Question: I have a form with n multiple choice questions implemented as radio buttons (using jquery-ui). I would like to ensure that all the questions have been answered before allowing the user to submit the form. I am running into two issues while performing this validation:

On initial load, the submit button does not respond to clicks or mouseovers until all questions have a response selected as desired. However, it still appears to be clickable (I would like this to be faded out)

If the reset button is pressed, the submit button is faded out (as desired) but I am unable to re-enable the submit button once the form has been completed.

This is my first time using javascipt/jquery. What is going wrong? How do I achieve the desired functionality across both cases?

Here is the pertinent javascript portion:
$(document).ready(function(){
    $( '.button' ).button ();
    $( '.radio-set' ).buttonset ();
    $( 'input[type="submit"]' ).attr( 'disabled', true );

    var progress = 0;
    var total_fields = $('.response').length

    /* Track Progress function*/
    $('input[type="radio"]').click( function(){
      progress = $('input[type="radio"]:checked').length
      $(".progressbar").progressbar( {value: ( progress / total_fields ) * 100} )
      console.log(progress, total_fields)
      if( progress == total_fields ){
        console.log( "Hello from inside the conditional" )
        $( 'input[type="submit"]' ).removeAttr( 'disabled' );
      }
    });

    $( 'input[type="reset"]' ).click( function(){
      progress = 0
      $( ".progressbar" ).progressbar( {value: 0} )
      $( 'input[type="submit"]' ).attr( 'disabled', true );
    });
});

Example of one of the questions within the form (with bacon filler text):

          M1

            1
            <input type="radio" name="M1" id="M1-1" value="1"  class="feature-input" autocomplete="off" />
            0
            <input type="radio" name="M1" id="M1-0" value="0"  class="feature-input" autocomplete="off" />
            Unknown
            <input type="radio" name="M1" id="M1-Unk" value="Unknown"  class="feature-input" autocomplete="off" />
          </span
          Chicken spare ribs capicola beef brisket hamburger. Kielbasa filet mignon tail ribeye ball tip ground round.

Input and Reset buttons for completeness:
        <input type="reset" class="button" id="reset-button" />
        <input type="submit" class="button" id="submit-button" disabled="disabled" />

Answer: As you turn you button to a jQuery UI Button, you'd better use the jQuery UI methods of the Button plugin to enable/disbale your button, instead of the changing directly the DOMElement attribute disabled.

For the initial state, you initialize your Button and then only change the disabled attribute, so the change is taken into account by the Button plugin.
// either disable first the button then initialize
$( 'input[type="submit"]' ).attr( 'disabled', true );
$( '.button' ).button ();

or
// set the Button's option
$( '.button' ).button ();
$( 'input[type="submit"]' ).button('option', 'disabled', true);

For the second problem, use the Button's option setter to re-enable your button:
$( 'input[type="submit"]' ).button('option', 'disabled', false);

Answer: I solved the issue by waiting for a while before adding the disabled attribute. Example,
var btn = $("button").first();
$(btn).button("loading");
$(btn).button("reset");
setTimeout(function () {
    $(btn).prop("disabled", true);
}, 0);

A same so question here and a gihub issue here.


Standard error of coefficient estimates for model II regression

Question: I'm working with time series data that has error in both the dependent and independent variables, so I'm analyzing each half hour of data with model II linear regression, specifically geometric mean regression (GMR, described here). In GMR, the slope estimate is the square root of the dependent data divided by the square root of the independent data. The intercept can be calculated based on the fact that the line passes through the point (mean(x), mean(y)).
Later in my analysis, I have to filter out half hours based on the standard error of the slope estimate, but I don't know how to calculate the standard error of the GMR slope.
Possible leads:
I've found a function in the lmodel2 R package that calculates the 97.5% confidence intervals for the GMR coefficients. Is there a way to transform that into standard error?
I read somewhere that the Standardized Major Axis method of computing coefficient standard errors can be used for GMR. This webpage presents that equation but doesn't explain the variables and I can't find an explanation in the source they cite. Does anyone know about this equation?
I know about the deming functions in R that calculate SE, but deming regression isn't behaving well with my data so I'd rather not use it.
Answer: I found a good source that answered my question [1]. Standard error of the slope ($s_a$) can be calculated using $s_a = \frac{\sigma_y}{\sigma_x}\sqrt{\frac{1-r^2}{n}}$ where $\frac{\sigma_y}{\sigma_x}$ is the slope estimate, $r^2$ is the square of the correlation coefficient, and $n$ is the number of observations used in the regression.
The standard error of the intercept ($s_b$) can be calculated using $s_b=\sigma_y\sqrt{\frac{1-r^2}{n}(1+\frac{\bar{x}^2}{\sigma_x^2})}$, where $\bar{x}$ is the mean of the independent data.
Sources
1) Miller, R.L., and J.S. Kahn, 1962. Statistical Analysis in the Geological Sciences. Wiley: New York, 205 p
2) A brief history of model II regression usage
3) Steven Holland's lecture notes on model II regression


Flask SqlAlcheny TypeError: 'Fermentables' object is not iterable

Question: No model FermentableTypes:
class FermentableTypes(db.Model):
    __tablename__ = "fermentable_types"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    desc = db.Column(db.String(255))
    def __str__(self):
        return self.name

No model FermentableProducers:
class FermentableProducers(db.Model):
    __tablename__ = "fermentable_producers"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    desc = db.Column(db.String(255))
    def __str__(self):
        return self.name

No model Fermentables:
class Fermentables(db.Model):
    __tablename__ = "fermentables"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    desc = db.Column(db.String(255))
    ppg = db.Column(db.Integer)
    color = db.Column(db.Integer)
    fermentable_types_id = db.Column(db.Integer, db.ForeignKey('fermentable_types.id'))
    fermentable_types = db.relationship('FermentableTypes', backref=db.backref('fermentables', lazy='dynamic'))
    fermentable_producers_id = db.Column(db.Integer, db.ForeignKey('fermentable_producers.id'))
    fermentable_producers = db.relationship('FermentableProducers', backref=db.backref('fermentables', lazy='dynamic'))

Popular o banco de dados:
db.session.add_all((
    FermentableProducers(name='Agrária'),
    FermentableProducers(name='Castle Malting')))
db.session.commit()
db.session.add_all((
    FermentableTypes(name='Malte de cevada'),
    FermentableTypes(name='Malte de trigo'),
    FermentableTypes(name='Mel')))
    db.session.commit()
db.session.add_all((
    Fermentables(
        name='Malte Pilsen',
        desc='Malte Extra Pilsen usada pelas principais cervejarias da Mundo. \
Possui alto poder diastático o que resulta em um tempo de sacarificação menor.',
        ppg='35',
        color='2,8',
        fermentable_producers='Agrária',
        fermentable_types='Malte de cevada')))
    db.session.commit()

Erro:

Traceback (most recent call last):
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 1808, in full_dispatch_request
    self.try_trigger_before_first_request_functions()
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/flask/app.py", line 1855, in try_trigger_before_first_request_functions
    func()
  File "/home/carlos/code/brewblog/__init__.py", line 46, in create_admin_user
    populate_fermentable()
  File "/home/carlos/code/brewblog/utils.py", line 49, in populate_fermentable
    fermentable_types_id='1')
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/carlos/code/env-python3/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1784, in add_all
    for instance in instances:
TypeError: 'Fermentables' object is not iterable

Answer: Se você vai adicionar só um objeto no banco, use db.session.add, o método add_all é para um objeto iterável - no seu caso você deve ter copiado o código de algum lugar que adicionava uma tupla de objetos - eles estariam no menor nível de parênteses, separados por ",".
Em Python, objetos separados por "," são uma tupla - um objeto iterável - ela pode ou não estar entre parenteses - ex.  (2, 5). Mas um único objeto entre parênteses é só o valor de uma expressão - os parêneteses são então descartados - no seu caso tem um nível parenteses sobrando dentro da chamada à add_all:  add_all((Fermentables(...))) - se quiser uma tupla com um único elemento (caso em que o add_all funcionaria), tem que ter uma vírgula dentro do parêneteses - é a forma oficial de se indicar tuplas de um único elemento: add_all((Fermentables(...),)). Mas-  reiterando o que eu disse lá em cima - você não precisa da tupla, nem do par extra de parenteses, nem chamar o add_all para inserir um único objeto no banco.
Comment: Não é somente isso, pois testei das 2 formas que você propos e não funcionou, mas obrigado
Comment: _esse_ erro é por isso - está bem visível no código acima.
Answer: Consegui resolver o problema da seguinte forma
Popular o banco de dados:
malte_cevada = FermentableTypes(name='Malte de cevada')
malte_trigo = FermentableTypes(name='Malte de trigo')
db.session.add_all((malte_cevada, malte_trigo))

agraria = FermentableProducers(name='Agrária')
cargil = FermentableProducers(name='Cargil')
db.session.add_all((agraria, cargil))

db.session.add_all((
    Fermentables(
        name='Malte Pilsen',
        desc='Malte Extra Pilsen usada pelas principais cervejarias da Mundo. Possui alto poder diastático o que resulta em um tempo de sacarificação menor.',
        ppg='35',
        color='2.8',
        fermentable_producers=cargil,
        fermentable_types=malte_cevada),
    Fermentables(
        name='Malte Pilsen',
        desc='Malte Extra Pilsen usada pelas principais cervejarias da Mundo. Possui alto poder diastático o que resulta em um tempo de sacarificação menor.',
        ppg='35',
        color='2.8',
        fermentable_producers=agraria,
        fermentable_types=malte_cevada),
))
db.session.commit()

Dessa forma funciona, apesar de não ficar da forma que eu queria, com cada parte dividida em uma função.
Comment: Perceba que agora você tem uma tupla com dois elementos na chamada ao `add_all` - o que eu escrevi na minha resposta está correto. Talvez você tenha tido algum outro erro ao tentar simplesmente escrever `.add` em vez de `.add_all` - mas  o "object is not iterable"  é por que você não estava passando uma tupla.


Looking to change the header from a color to an image

Question: I am using the NewsCenter theme for my Drupal site, and we have had a new logo/banner designed for our website that I want to implement -- but it's not as simple as just uploading it and replacing the old logo.

This is the header of our site as it stands currently:

This is what I want to get to:

Also, with the final option, I still need to have users be able to click in the banner and get directed 'Home' -- I presume that to do this I would still upload a logo.png, but that it would just be a large transparent rectangle.
Thanks!
Comment: Update your site logo with the new logo on a transparent background. The background image needs to be set with CSS, which is off topic on this site but can be asked on [stackoverflow](http://stackoverflow.com).
Comment: I couldn't include a third image -- but basically the entire banner is a single image. It essentially _is_ the logo.  But your post has inspired me to try something -- to take the main text off the background, treat that as the logo, and use the remaining banner as the background image. That still leaves me with the initial question of "Where do I go to change the charcoal gray background of the header to be the violet sunburst image?"
Comment: `to take the main text off the background, treat that as the logo, and use the remaining banner as the background image` That is what I meant. `Where do I go to change the charcoal gray background of the header to be the violet sunburst image?` That is a theme CSS issue and you need to set the background of your header div using CSS. As I stated earlier, it is off-topic as it not specific to Drupal.
Comment: @howard-price I will do the CSS for you over lunch today bro.  I found your site. I need the Reputation points.
Answer: Add this CSS:
<code><style>
  #header {
    background: url('critic-banner-image.png');
  }
  #logo {
    margin: 0 15px 5px 15px;
  }
</style>
</code>
Add this background image
(use better ones that your client provides)
Replace your old logo with this:

(use better ones that your client provides)
Comment: Hey Howard Prince, I just did all the work for you.  how about an up-vote, or a solved?  ;-)
Comment: Hi! Just got the notice in my email that this message came through. :)  I definitely upvoted it. Marked it as solved, but couldn't get my upvote count to show (as I, too, lack enough reputation points for that to happen).  Thanks! Soon as I get back the graphics that are being reworked, this is exactly what I will do!


Training a model where true value is only known in batches

Question: I would like a model to learn a function $f(x) = y$ based on some data, but suppose that I only know the true value in small batches. More precisely, each training sample consists of $x_1,\ldots,x_n$ for some $n$ (which can vary) and I only know the value of $y_1+\cdots+y_n$.
My goal would be to have a function $f$ which minimizes
$$|\sum_{i=1}^n (f(x_i) - y_i)|$$
for a random batch $(x_i,y_i)$. Can I train such a model using xgboost (or some other model)?
Comment: If you only know $y=\sum y_i$ in the batch, why do you have separate samples? Why not concat all features to one $x$ and use one target value, $y$ and train as usual?
Comment: @gunes Since $n$ is varying for different batches, the number of features would be different for each combined sample. Also I want to stress the fact that $y_i$ is a function of $x_i$ but setting $f(x_1,\ldots,x_n)=y$ would make for a much more complicated function.
Answer: TLDR: You could this with a standard ML method (like xgboost) assuming fixed batch size but it is likely to be extremely data inefficient. One could code up a Tensorflow model relatively easily that actually does this efficiently and allows for varying batch sizes.
Stepping back from this problem, we can think of what our data looks like. We could think of batches of rows of data where we don't know the label of each row, or we could think of each batch as a single row of data and we do have a label that is the sum of the labels we care about. Thinking of each batch as a single row, our features now look like
$X_i = (x_{i,1}, x_{i, 2}, ..., x_{i, n})$
and we have observed label
$Y_i = \sum_{i=n} y_i$
How do we solve this?
Standard ML model: This requires fixed batch sizes.
With this framework, we can now learn a simple mapping $g(X)$ from $\mathbb{R}^n \rightarrow \mathbb{R}$. Feed your batches/rows into your model and learn the mapping. Once you learn that mapping, you can extract $f$ by evaluating $g(X)$ along a grid of values where $x_{i,1} = x_{i, 2} = ... = x_{i,n}$ and then divide your predictions along this grid by n, since the true $g(X) = f(x_{i,1}) + ... + f(x_{i,n})$.
Tensorflow custom model approach: This does not require fixed batched sizes.
Theoretically, with enough data, properly flexible ML model and fixed batch sizes, the method above should converge to the correct answer. However, it's not leveraging as much model structure as it can, and this likely to make it very inefficient, especially for large batches! In particular, it's not using the facts that

All features are treated exactly the same, i.e. we don't need to learn $n$ different functions for each item of the batch

We know that we will be summing the independent inputs of each row.

These two facts greatly reduce the space of functions we need to consider and thus leveraging this properly is likely to make for a much more data-efficient approach.
I'm not aware of any published models that current take advantage of such structure, but it would be pretty easy to code one up in tensorflow if we again use the converting batches to rows method. All you would need to is code up something like this psuedocode (note: this definitely won't work but I think convey's the idea):
def call(self, inputs):
  """Predict Y = sum(y) from one batch"""
  n_cols = inputs.shape[1]
  # Note: n_cols may vary for different batches!
  Y_hat = 0
  for i in range(n_cols):
    # Need to define functional form of learned_f
    # during model initialization
    Y_hat += self.learned_f(inputs[:,i])
  return(Y_hat)

You do need to pick what your learned_f will be: this could be a simple feed forward network or better yet a bs_spline (assuming $x_{i,j}$ is univariate).
Now we are fully leveraging the known model structure and this should be much more data efficient than the standard ML model approach. Also, there's no need for the batch size to be fixed: we simply sum over each input regardless.  Final bonus: you can directly query learned_f instead of needing to transform $\hat g(X)$ to $\hat f(x)$.
EDIT: I've added an example of doing this with Tensorflow with a cubic polynomial as the learned function.
Comment: @BenReiniger: right the tensorflow solution has no problem with varying batch sizes. Changing the answer to emphasize this.
Comment: OP specified that the batches are _not_ of the same size: "which can vary" parenthetical note in the question, and again in the comment https://stats.stackexchange.com/questions/643886/training-a-model-where-true-value-is-only-known-in-batches#comment1203617_643886
Comment: This might work if there are many batches where $x_{i,1} = x_{i, 2} = ... = x_{i,n}$, but then we might as well use the sum of $y_i$ as target for a simpler model.
Comment: @picky_porpoise: why do you think $x_{i,1}$ needs to be equal to $x_{i,2}$? For the standard ML model approach (which I don't really endorse), for simplicity we feed them back into the model with all features equal so that it's easiest to extract the learned $f$, but there's absolutely no reason they need to be the same during training for either approach.
Comment: If you think of each batch as a row, this just becomes a regression problem with extra known structure to take advantage of. And we certainly don't need $x_{i,1} = x_{i,2}$ for identifiability of regression problems.
Comment: @CliffAB I misread the loss given by OP. I now see that it can be written in terms of $\sum y_i$, so your approach of targeting the sum works.


Drupal 7 - Node specific template not working

Question: I have done some research and everything I see to create a node specific template says to name the template file, for example, page--node--676.tpl.php
However when I clear the cache and load the file it still shows the old template. What could I be missing?
Comment: In what folder did you put page--node--676.tpl.php?
Comment: sites/all/themes/mytheme/templates
Answer: If you haven't already done so, I'd recommend enabling theme debugging feature of Drupal 7.
In the settings.php file, or preferably in settings.local.php file if you have one, add the following line, and clear the cache once more.
<code>$conf['theme_debug'] = TRUE;
</code>

When debugging is enabled:
  - The markup of each template is surrounded by HTML comments that contain
    theming information, such as template file name suggestions.
  - Note that this debugging markup will cause automated tests that directly
    check rendered HTML to fail.
For more information about debugging theme templates, see
  https://www.drupal.org/node/223440#theme-debug.
Not recommended in production environments.

This should give you the available template name suggestions in the generated HTML.
Comment: debugging returned the suggested
page--node--676.tpl.php
sites/all/themes/mytheme/templates
and that is is loading page.tpl.php
Comment: Are you saying when you view `/node/676` your theme still uses `sites/all/themes/mytheme/templates/page.tpl.php` instead? Or `page.tpl.php` from another theme? Do you use a base theme?
Comment: Yes, when I view /node/676 the theme is still using sites/all/themes/mytheme/template/page.tpl.php instead of page--node--676.tpl.php
the only other template source I can see is modules/system/html.tpl.php
Comment: That's odd. Even if you have a preprocess function in your theme overwriting suggested template names, debugging would show those in results too. Any chance the file name has invisible characters in it? Try copying the suggested name and renaming your template file with that.
Comment: Not sure what I did, but it started working. Thanks for the help.


ROC accuracy measure error when no positive values

Question: I have an unbalanced dataset that I am working to either up or down sample to balance out. But in the meantime I've run into an interesting error when calculating the AUC in R using pROC::auc when no positive predictions are made.
The test prediction resulted in zero positive cases. It predicted all 0's in my binary response. Does it make intuitive sense that the function throws an error for the AUC in this case? Or should it be zero or some other result. I know that balanced accuracy and other confusion matrix measures will still produce some number even when there are no positive predictions.
table(trainy)
trainy
    0     1
10716  1181

table(testy)
testy
    0     1
10646  1250

cvfit <- glmnet(y=trainy, x=trainx, alpha=1, family="binomial")
  cv.glmmod <- cv.glmnet(x=trainx, y=train[,.b], alpha=1, nfolds=10)

  p <- predict(cvfit, newx = testx, type = "class", s = cv.glmmod$lambda.min)
  pred_class <- as.numeric(p)

all(pred_class == 0)
[1] TRUE
auc(pred_class, testy)
Error in roc.default(response, predictor, auc = TRUE, ...) :
  No case observation.

Answer: AUC doesn't take into account binary predictions. It takes into account the continuous score your model outputs. You should look if there are positive cases, not predictions, in your resampled test data.
If there are only samples from one class, AUC won't be computed.
Comment: I have 1000+ positive cases in the test data.
Answer: ROC curves assume that the predictions are continuous values (such as predicted probabilities). You're using predictions of the form $\hat{y}=1$ or $\hat{y}=0$, which is nonsensical for ROC analysis because ROC analysis is about assessing the trade-off between true positives and false positives at different thresholds for an alarm.
This question is a very good introduction to the topic.


What does this bold letter preceeded ny a roman numeral indicate?

Question: I'm trying to read this etude by Coste and frequently I find a bold B followed by a roman numeral in the score. What exactly does this indicate? Thanks. Here is the score: http://www.classclef.com/pdf/Opus%2038%20No%201%20by%20Napoleon%20Coste.pdf .
Answer: I don't think this is necessarily the best notation for it, but the B just stands for "barre" and the Roman numeral is a fret number. BV means that you should barre the fifth fret to perform the bracketed chunk of music. Later, 1/2B is used to indicate a partial barre where only the top few strings are barred at the indicated fret while the lower strings are left open.


Processing file uploads before object is saved

Question: I've got a model like this:
class Talk(BaseModel):
  title        = models.CharField(max_length=200)
  mp3          = models.FileField(upload_to = u'talks/', max_length=200)
  seconds      = models.IntegerField(blank = True, null = True)

I want to validate before saving that the uploaded file is an MP3, like this:
def is_mp3(path_to_file):
  from mutagen.mp3 import MP3
  audio = MP3(path_to_file)
  return not audio.info.sketchy

Once I'm sure I've got an MP3, I want to save the length of the talk in the seconds attribute, like this:
audio = MP3(path_to_file)
self.seconds = audio.info.length

The problem is, before saving, the uploaded file doesn't have a path (see this ticket, closed as wontfix), so I can't process the MP3.
I'd like to raise a nice validation error so that ModelForms can display a helpful error ("You idiot, you didn't upload an MP3" or something).
Any idea how I can go about accessing the file before it's saved?
p.s. If anyone knows a better way of validating files are MP3s I'm all ears - I also want to be able to mess around with ID3 data (set the artist, album, title and probably album art, so I need it to be processable by mutagen).
Answer: You can access the file data in request.FILES while in your view.
I think that best way is to bind uploaded files to a form, override the forms clean method, get the UploadedFile object from cleaned_data, validate it anyway you like, then override the  save method and populate your models instance with information about the file and then save it.
Comment: +1 and accepted! This seems to be the way to go - seems kind of a shame that there's not an elegant way to do this using new-fangled model validation.
Comment: Maybe you could but it is quite new and i am not yet familiar enough with it.
Comment: Could you write an example?
Answer: a cleaner way to get the file before be saved is like this:
from django.core.exceptions import ValidationError

#this go in your class Model
def clean(self):
    try:
        f = self.mp3.file #the file in Memory
    except ValueError:
        raise ValidationError("A File is needed")
    f.__class__ #this prints <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
    processfile(f)

and if we need a path, ther answer is in this other question
Answer: You could follow the technique used by ImageField where it validates the file header and then seeks back to the start of the file.
class ImageField(FileField):
    # ...
    def to_python(self, data):
        f = super(ImageField, self).to_python(data)
        # ...
        # We need to get a file object for Pillow. We might have a path or we might
        # have to read the data into memory.
        if hasattr(data, 'temporary_file_path'):
            file = data.temporary_file_path()
        else:
            if hasattr(data, 'read'):
                file = BytesIO(data.read())
            else:
                file = BytesIO(data['content'])

        try:
            # ...
        except Exception:
            # Pillow doesn't recognize it as an image.
            six.reraise(ValidationError, ValidationError(
                self.error_messages['invalid_image'],
                code='invalid_image',
            ), sys.exc_info()[2])
        if hasattr(f, 'seek') and callable(f.seek):
            f.seek(0)
        return f