Unconstrained convex quadratic integer programing

Question: Let $N_i=\{0,1,\dots,\bar{n}_i\}$ and define $N=N_1\times \dots \times N_I$. I have a minimization problem of the form
$$
\min_{n\in N} \sum_i A_i n_i +\sum_i \sum_{j\neq i} B_{ij} (n_i-n_j)^2
$$
where $A_i\geq 0$ and $B_{ij}\geq 0$ for all $i,j$. This problem can be written as a convex quadratic integer program.
What are the standard algorithms to solve these problems numerically? Are they guaranteed to find a global solution? How fast are they?
Comment: Yes, I know that using the word "convex" here is a bit tricky but several people in the literature use convex in this way for integer programs.
Comment: Typically, a mixed integer nonlinear programming problem (MINLP) whose continuous relaxation is convex is referred to as a "Convex MINLP"  This is terminology that's been around for at least 25 years...
Comment: This seems like a misnomer to me.  According to Boyd and Vandenberghe, a Convex Optimization problem is an optimization problem whose domain is a convex set.  But an integer programming problem is one where the solutions must be integers.  The set of integers is not convex.
Comment: Your terminology is fine. You would think it might be possible to exploit the fact that it is unconstrained (that is, beyond the integrality constraints), but I'm not seeing it.
Answer: Typically, you'd use a branch and bound algorithm to solve this problem and obtain a globally optimal solution if the problem isn't unbounded.  This does require worst-case exponential time.
Several commercial LP/QP packages have support for solving these MIQP problems.
Comment: Thanks. I was hoping that simpler algorithms might work given the nice properties of the problem but maybe that's not the case.


functional equation of type $f(x)-f(y) = f\left(\frac{x-y}{1-xy}\right)$

Question: If $f(x)-f(y) = f\left(\frac{x-y}{1-xy}\right)$ and $f$ has domain equal to $(-1,1)$, then which of the following is the function satisfying the given functional equation?
Options:
(a) $2-\ln\left(\frac{1+x}{1-x}\right)$
(b) $\ln\left(\frac{1-x}{1+x}\right)$
(c) $\frac{2x}{1-x^2}$
(d) $\tan^{-1}\left(\frac{1+x}{1-x}\right)$
From the options given we can easily get $f(x) = \ln\frac{1-x}{1+x}$,
but how can I solve using analytical method?  Help me please.
Comment: Taking $x=0$ shows the function must be odd. Only two options satisfy this condition, and one of them is easily determined to be invalid.
Answer: Taking $y=0$ gives $f(0) = 0$. Using this we can rewrite the functional equation as
$$\frac{f(x)-f(y)}{x-y} = \frac{1}{1-xy}\frac{f\left(\frac{x-y}{1-xy}\right) - f(0)}{\left(\frac{x-y}{1-xy}\right)}$$
Now assuming $f$ is differentiable at $x=0$ we can take the limit $y\to x$ above to obtain the ODE $$f'(x) = \frac{1}{1-x^2}f'(0) = \frac{f'(0)}{2}\left[\frac{1}{1-x} + \frac{1}{1+x}\right]$$
which can be integrated with the initial condition $f(0) = 0$ to get the general solution $f(x) = C\log\left(\frac{1-x}{1+x}\right)$ where $C = -\frac{f'(0)}{2}$ is a free constant.
Comment: It is worth noting that the parity of the function can be determined almost immediately. This leaves only two options available.
Answer: Let's first change $y \mapsto-y$. Now, the functional equation in the question would be $$f(x)-f(-y)=f\left(\frac{x+y}{1+xy}\right)$$
Also by setting $x=0$ it turns out that $f$ is an odd function, i.e., $f(y)=-f(-y)$. Applying this to the previous equation gets $$f(x)+f(y)=f\left(\frac{x+y}{1+xy}\right)\label{eq1}\tag{1}$$
One way to find $f$ is to note the similarity between the expression $\frac{x+y}{1+xy}$ in equation (\ref{eq1}) and the following property of $\tanh$ function $$\tanh(a+b)=\frac{\tanh{a}+\tanh{b}}{1+\tanh{a}\tanh{b}}$$ By setting $x=\tanh{a}$ and $b=\tanh{b}$, the equation becomes $$\tanh(a+b)=\frac{x+y}{1+xy}$$ Therefore equation (\ref{eq1}) can be rewritten as
$$f(\tanh{a})+f(\tanh{b})=f(\tanh{(a+b)})$$
Obviously $f(u)=\tanh^{-1}{u}$ is a solution; since it cancels out all $\tanh(\cdot)$ functions and then the true statement $a+b=a+b$ will emerge. By using the definition of $\tanh u$ and a few manipulation, you can verify that $$\tanh^{-1}{u}=\frac12\log{\frac{1+u}{1-u}}$$
Moreover, due to the linearity, the function $f(u)=k\tanh^{-1}{u}$, where $k$ is a constant, is a solution either. By setting $k=-2$, you'll find (b) as the correct answer.


Be $\Omega \subset \mathbb{C}$ an open and connected set. If $f \in A\mathbb{(\Omega)}$ and $f \neq 0$ show that the set of all zeros is numerable

Question:
Be $\Omega \subset \mathbb{C}$ an open and connected set. If $f \in A\mathbb{(\Omega)}$ and $f \neq 0$ show that the set of all zeros is numerable.

I already demostrated by contradiction that $Z(f)$ is discrete, but I don't know how use it to demostrated that $Z(f)$ is numerable. Any hint please?.
Comment: See https://math.stackexchange.com/questions/3793068/zeroes-of-non-zero-holomorphic-function-form-an-atmost-countable-set or https://math.stackexchange.com/questions/625734/holomorphic-function-has-at-most-countably-zeros
Comment: @MartinR thanks for the links, now i understand what should I have done. But I have a doubt in the answers, what is the consistency in the fact of linking $a_{1} +ia_{2}$ with $Q$, I know that as $\mathbb{Q}$ is countable then $Z(f)$ is countable, but how can you get the linking of it? i think is because $Q$ is dense in $R$ right? if not, what is the theory?.
Answer: Let $f$ be analytic and suppose that $z_0$ is a zero of $f$.
Then $f$ has a power series centered at $z_0$, that is, there exists $r > 0$ such that $f(z) = \sum_{n=0}^\infty a_n(z-z_0)^n$ for all $z$ such that $|z-z_0|<r$.  Now there exist a minimal $N > 0$ such that $a_N \neq 0$ or else $f$ would be identically equal to $0$ by the uniqueness theorem for analytic functions.  Hence, $f(z) = \sum_{n=N}^\infty a_n(z-z_0)^n = (z-z_0)^N\sum_{n=N}^\infty a_n(z-z_0)^{n-N} = (z-z_0)^Ng(z)$.  Now $g(z)$ is continuous and $g(z_0) \neq 0$ so there exists a neighborhood of $z_0$ such that $g(z) \neq 0$ in this neighborhood. Hence each zero is isolated so just pick a rational in each such disk $\implies$ the zeros are countable.


find the limit $\frac{\frac{g(y)-g(0)}{y}-g'(0)}{y}$ as $y \to 0$

Question: I was asked to find the exact form of the limit
$$\frac{\frac{g(y)-g(0)}{y}-g'(0)}{y}$$
as $y\to 0$ without using L'Hospital's rule or the Taylor's theorem.
I tried to solve this using the mean value theorem but I failed. Here's my try:
By the mean value theorem, there exists some c between $y$ and $0$ such that
$$\frac{g(y)-g(0)}{y}=g'(c)$$
so what we're dealing with would become
$$\frac{g'(c)-g'(0)}{y}$$ and I don't know how to proceed.
Comment: I don't think you can do it without L'Hospital's Rule or something equivalent.
Answer: Define $h(y)$ to be $g^\prime(0)$ if $y=0$ and $\frac{g(y)-g(0)}{y}$ otherwise, so $h$ is continuous at $0$ and you seek$$L:=\lim_{y\to0}\frac{h(y)-h(0)}{y}=h^\prime(0).$$For $y\ne0$,$$h^\prime(y)=\frac{yg^\prime(y)-g(y)+g(0)}{y^2}.$$This has $y\to0$ limit$$-L+\lim_{y\to0}\frac{g^\prime(y)-g^\prime(0)}{y}.$$Hence$$L=\lim_{y\to0}\frac{g^\prime(y)-g^\prime(0)}{2y}=\frac12g^{\prime\prime}(0).$$
Comment: Sorry, but how do we know that h is differentiable?
Comment: One can prove that the limit in question is $g''(0)/2$ under the assumption that $g' '(0)$ exists. However such a proof requires the use of L'Hospital's Rule or something equivalent. Your approach assumes that $h' $ is continuous at $0$.


Python: Copy and pasting to specific row and column

Question: I have 2 input files and 1 main file in excel. I want to use python to copy values from the input file and paste into the main file of the corresponding row and column as such:
Input file 1 (COPIED)
Col Row extra1 extra2 value

A    70                6.1
B    87                5.0
G    90                4.4

Input file 2 (COPIED)
Col Row extra1 extra2 value

C    10                0.9
F    17                3.3
G    20                1.1

Main file (PASTED)
Col Row value
A   70   6.1
B   87   5.0
C   10   0.9
F   17   3.3
G   20   1.1
G   90   4.4

The row and col columns are already filled in the first place.
Anyone has any solutions or insights into how to go about doing this? thank you in advance
Answer: Copying columns between two different workbooks using openpyxl could be done as follows:
import openpyxl

wb1 = openpyxl.load_workbook('B.xlsx')
ws1 = wb1.active

wb2 = openpyxl.load_workbook('E.xlsx')
ws2 = wb2.active

for src, dst in zip(ws1['B:B'], ws2['AN:AN']):
    dst.value = src.value

wb2.save('E.xlsx')

For a range of columns, the following would work:
import openpyxl

wb1 = openpyxl.load_workbook('B.xlsx')
ws1 = wb1.active

wb2 = openpyxl.load_workbook('E.xlsx')
ws2 = wb2.active

for src, dst in zip(ws1['A:I'], ws2['AN:AV']):
    for cell_src, cell_dst in zip(src, dst):
        cell_dst.value = cell_src.value

wb2.save('E.xlsx')

Answer: if your main file is empyty
df1=pd.DataFrame({"Col":[1,2,3],"Row":[2,3,4],"value":[6,5,7],"ree":[0,0,0]})

    Col Row value ree
0   1   2   6   0
1   2   3   5   0
2   3   4   7   0

df2=pd.DataFrame({"Col":[9,8,0],"Row":[6,4,22],"value":[26,55,27]})

    Col Row value ree
0   1   2   6   0
1   2   3   5   0
2   3   4   7   0

df1=df1[["Col","Row","value"]]
df2=df2[["Col","Row","value"]]

main=pd.concat((df1,df2))

    Col Row value
0   1   2   6
1   2   3   5
2   3   4   7
0   9   6   26
1   8   4   55
2   0   22  27

so after this you can create a main file or save it in the existing csv
this works if main is empty if its filled then concat as done above.


Spivak's proof of Inverse Function Theorem.

Question: This question concerns the Inverse Function Theorem done in the book.
Spivak states that
$$|D_jf^i(x) - D_jf^i(a)| < 1/2n^2$$ for all $i,j$ and $x \in U$
Here $U$ is a closed rectangle set, $n$ is an integer.
The lemma 2.10 (on the previous page) states that

Let $A \subset \mathbb{R}^n$ be a rectangle and let $f: A \to \mathbb{R}^n$ be continuously differentiable. If there is a number M such that $|D_jf^i(x)| \leq M$ for all $x$ in the interior of $A$, then $$|f(x) - f(y)| \leq n^2 M|x - y|$$

He define $g(x) := f(x) - x$ and states that, for $x_1, x_2 \in U$, we have
$|f(x_1) - x _1 -(f(x_2) - x_2)| \leq \frac{1}{2} |x_1 - x_2|$
and it's ok for me, because
$|D_jg^i(x) - D_jg^i(a)| \leq \frac{1}{2n^2} n^2 |x_1 - x_2| = \frac{1}{2} |x_1 - x_2|$
by the lemma, but we can do this only if $|D_jg^i(x)| \leq M$, my doubt is why is this valid?
Answer: Correct me if I am wrong - the broader context is we have the following results already:

(a) $Df(a)= I$, the identity matrix, by assumption.
(b) $|D_jf^i(x) - D_jf^i(a)| < \frac{1}{2n^2} $ for all $i,j$ and $x \in U$.

So $g=f-I$. From (b) we have almost what you wrote,
$$ |D_jg^i(x)| = |D_jf^i(x) - D_jI^i(x)| = |D_jf^i(x) - D_jf^i(a)| <\frac{1}{2n^2} =M $$
since $D_jI^i(x) = D_jI^i(a) = D_jf^i(a)$ ($I$ is a linear map). We can then apply lemma to deduce,
$$ |g(x_1 ) - g(x_2)  | \le \frac{1}{2n^2} n^2 |x_1 - x_2| = \frac{1}{2} |x_1 - x_2 |.$$


Javascript Switch Statement for Adobe Acrobat Form

Question: I have an Adobe Acrobat form with the fields "Store Address" and "Store Phone". The Store Address field is a dropdown with the address as the option and the store number (e.g. "Store 1") as the export value. The Store Phone field has a custom calculation script on it with the following code:

var store = this.getField("Store Address");

switch(store) {
case 'Store 1':
   event.value = '867-5309';
   break;
case 'Store 2':
   event.value = '555-1234';
   break;
default:
   event.value = '';
   break;
}

Presently, selecting an address from the pulldown menu does nothing. What did I do wrong?
Comment: There's not enough code here to know, where are attaching the event handler?
Answer: In the first line, you're only getting the Field object, not it's value. Use...
var store = this.getField("Store Address").value;


Postfix split domain setup

Question: I need to have a split domain setup on Postfix.  This is possible with Zimbra which uses Postfix as described here:

If delivering to a single secondary mail system, configure a catchall on the domain to         deliver mail to a secondary mail transport if users for the same domain reside on the second system.
<code>  zmpov cd example.com
  zmprov md example.com zimbraMailCatchAllAddress @example.com zimbraMailCatchAllForwardingAddress @example.com zimbraMailTransport smtp:mail.example.com:25
</code>
Mail for Zimbra recipients on the primary system to @example.com will be delivered Zimbra mailboxes. Any address that does not exist on the Zimbra system will be routed to the secondary mail transport. This configuration will likely work with 4.5.x, but it has not been tested.

How can I achieve this in Postfix?
Answer: Zimbra is not an MTA; it uses postfix as its MTA component.
Hence, anything Zimbra can do, postfix can too.
I don't understand your question as it is not related to postfix; restate it so it deals with SMTP terms.
Comment: I want **any** email address that is not on postfix to be delivered to a secondary mail transport, depending on the domain.  Just like the instructions for zimbra above state.
Comment: relay_domains = other.domain1, other.domain2
Comment: My "local" users are actually in ldap (on exchange), so already by default, the email is relayed to them.  I already have a relay_domains file that lists all the domains we manage.
Answer: http://www.postfix.org/VIRTUAL_README.html
I was going to setup Postfix like this as well, migrating from a Qmail server. With 14 domains and having issues with the Qmail setup, it was easier to go with Zimbra.

Postfix split domain setup


Not sure what this line of code means in C

Question: Stumbled across this particular line of code and am having some trouble understanding it:
a = ((((z * y) + 31) & ~31) / 8) * abs(x);

a, z, y, and x all are of type int.
I understand that ~ has the effect of flipping all the 1's and 0's, in this case, doesn't 31 become 0? How does the & come into play in this line? Isn't it used for logical statements rather than equations like this?
Comment: Split the line up in it parts, with temporary variables. Then run through that code in a debugger, stepping line by line. That will make it very easy to see what going on.
Comment: Why do you think only the lowest bits will be flipped, and not the higher, 0-bits too?
Comment: `&` is bitwise "and". `&&` is short-circuit logical "and". See any decent C reference for more information.
Comment: As an interesting point the behavior of the line is such that it produces `(z*y)/32.0` rounded up to the next integer multiplied by `4 * abs(x)` for `z * y >= 0`
Answer: Let's step through the code using a simple example. Let's set x = y = z = 10; for the example. Your single line can be split up into several parts:
temp1 = z * y;
temp2 = temp1 + 31;
temp3 = temp2 & ~31;
temp4 = temp3 / 8;
a = temp4 * abs(x);

Here, temp1-temp4 are also of type int. Using the above code and the example values, temp1 and temp2 are straightforward to calculate:
temp1 = 10 * 10 = 100
temp2 = 100 + 31 = 131

To get temp3, we need to know the binary representation of temp2, which in this case is 10000011. As such, we get:
  10000011
& 11100000
----------
  10000000 = 128 in decimal

So temp3 = 128. From here, temp4 and a are trivial:
temp4 = 128 / 8 = 16
a = 16 * 10 = 160

For future reference, when you are confused what a line of code does, first split it up like I've done above, then use a debugger (like gdb) to step through the code. That will help make the code clear.
Answer: Part of the confusion stems from the fact that you've incorrectly evaluated ~31 in your head.
For the simple case of 8-bit numbers 31 is actually 00011111 and therefore ~31 = 11100000 Not 00000000. To answer your question about the & operator, it's a bitwise AND operator, just as ~ is a bitwise NOT operator; therefore, ((z * y) + 31) & ~31 performs the bitwise AND operation on the result of (z * y) + 31 and ~31


Related to the dual space of $c$

Question: In the analysis class, the instructor defined the following map between $\ell^1$ and $c^*$:
$$T:\ell^1\to c^*,\quad g\mapsto\phi_g$$
where $\phi_g$ is defined as
$$\phi_g:c\to\mathbb{C},\quad \phi_g(f)=g(1)\lim_{n\to\infty}f(n)+\sum_{n=1}^\infty g(n+1)f(n)$$
By showing that $T$ is an isometric isomorphism, we can conclude that $c^*=\ell^1$.
The proof of isometry can be seen here in the body of question. However, I am not quite sure about the onto part. My instructor proved the same way as in the answer of the linked question: for each $\phi\in c^*$, define
$$g(n)=\begin{cases}\phi(\mathbf{1}),&n=1\\
\phi(e_{n-1}),&n>1\end{cases}$$
where $\mathbf{1}$ is the sequence with all terms equal to 1, and $e_n$'s are the canonical coordinates. We can show that $g\in\ell^1$. Then my instructor said it is obvious that $\phi=\phi_g$. However, this does not seem quite convincing to me. I did the following: we have
$$\phi(f)=\sum_{n=1}^\infty f(n)\phi(e_n)=\sum_{n=1}^\infty f(n)g(n+1).$$
which is missing a term $g(1)\lim_{n\to\infty}f(n)$.
Where are my mistakes and what is the right way to show this?
Answer: The mistake is that you wrote
$$\phi(f) = \sum_{n=1}^\infty f(n)\phi(e_n).$$
That would hold if we had
$$f = \sum_{n=1}^\infty f(n)\cdot e_n\tag{$\ast$}$$
in the space $c$, but the series on the right hand side of $(\ast)$ converges only if $\lim\limits_{n\to\infty} f(n) = 0$. For we have
$$\left\lVert f - \sum_{n=1}^N f(n)\cdot e_n\right\rVert = \sup_{n > N} \lvert f(n)\rvert \geqslant \left\lvert \lim_{n\to\infty} f(n)\right\rvert.$$
The system $\{ e_n : n\in \mathbb{N}\setminus \{0\}\}$ is a Schauder basis of the closed subspace $c_0$ of null-sequences, not of $c$.
The correct representation of $f\in c$ is
$$f = \lambda\cdot \mathbf{1} + \sum_{n=1}^\infty \bigl(f(n)-\lambda\bigr) \cdot e_n,\tag{1}$$
where $\lambda = \lim\limits_{n\to\infty} f(n)$.
Using the representation $(1)$, we obtain
$$\phi(f) = \lambda\phi(\mathbf{1}) + \sum_{n=1}^\infty \bigl(f(n)-\lambda\bigr)\phi(e_n) = \lambda\cdot \left(g(1) - \sum_{n=2}^\infty g(n)\right) + \sum_{n=1}^\infty f(n)\cdot g(n+1),$$
which however in general is different from $\phi_g$. One must choose a slightly different $g$ to get $\phi_g = \phi$.
Comment: Yes, we can find such a sequence. Let's call it $h$, since we've already used $g$. We want $\phi = \phi_h$, so we need $$h(1)\cdot \lim_{n\to\infty} f(n) + \sum_{n=1}^\infty f(n) h(n+1) = \biggl(g(1) - \sum_{n=2}^\infty g(n)\biggr)\cdot \lim_{n\to\infty} f(n) + \sum_{n=1}^\infty f(n)g(n+1)$$ for all $f\in c$. Taking $f = e_k$, we see that $h(k+1) = g(k+1) = \phi(e_k)$ for all $k$, so the only difference is in the first coordinate. Instead of $g(1) = \phi(\mathbf{1})$, we need $h(1) = \phi(\mathbf{1}) - \sum_{k=1}^\infty \phi(e_k)$.
Comment: Thank you for your answer, this make sense. But there is one more question, can we find such a $g$ with $\phi=\phi_g$; and is $T$ indeed an isomorphism?

Related to the dual space of $c$


Is this a valid proof of this predicate statement?

Question: $\forall x [P(x) \rightarrow Q(x)] \Rightarrow [\forall x P(x) \rightarrow \forall x Q(x)]$
If the LHS is true, then Q(x) must be true for all values of x. Since Q(x) is true for any value, then Q(y) is always true. Thus the RHS is also always true.
Comment: Why must $Q(x)$ be true for all $x$? Notive that "false implies false" is true.
Comment: If you mean to say $Q(x)$ is true for all $x$ because $\forall x P(x)$ you should say this, and explain exactly why. For instance for any $x$, we have $P(x) \rightarrow Q(x)$ and since $P(x)$ for every $x$ this means we have $Q(x)$ for every $x$.
Comment: hmm, but i don't think it's a tautology because Q() is true for any value of y and P() and Q() can have different values in the RHS; whereas P() and Q() must always have the same value in the LHS. Right?
Answer: It is not a correct proof.  Say that $P(x)$ is the statement "$x$ is a ruby" and $Q(x)$ is the statement "$x$ is red".
Your claim is:

If the LHS is true, then $Q(x)$ must be true for all values of $x$.

The LHS,  $\forall x[P(x)\to Q(x)]$ is quite true, since for any $x$, if $x$ is a ruby then it is red.  But contrary to your claim, $Q(x)$ is not true for all values of $x$, since not every $x$ is red—crows are not red, and neither is snow.
(However, the RHS is still true; it says that if every $x$ were a ruby, then every $x$ would be red, and this is correct, if the LHS is. But your argument is wrong.)
Answer: MJD has given the right response. But what an extraordinary thing to say:

If the LHS is true, then Q(x) must be true for all values of x

The LHS renders "Take anything $x$ you like, if (yes, IF) $Px$, then $Qx$". The 'if' is crucial. That you missed this suggests you badly need to get back to basics and have another look at a good exposition of the way we render statements of generality using quantifiers-and-variables in logic. I've mentioned it before here, but an excellent freely available resource is Paul Teller's A Modern Formal Logic Primer -- check out the first four chapters of Vol. II and you will never make a bad mistake like this again, promise! (Or of course get my Introduction to Formal Logic out of the library ...!)


Beginners issue in polynomial curve fitting [Part 1]

Question: I have just started understanding modeling techniques based on regression models and was going through MATLAB curve fitting toolbox and the SO. I have fundamental doubts and unable to proceed further. I have a single vector set with k=100 data points which I want to fit into an AR model,MA model,ARMA model successively to see which is better suited.Starting with an AR(p) model of the form y(k+1)=a*y(k)+ b*y(k-1)The command
coeff = polyfit(x,y,d)

will fit a polynomial of degree say d=1 with p number of coefficients indicating the order of the model (AR(p)). But I just have 1 set of data which is the recording of the angular moment.So,what will go as the first parameter (x) of the function signature i.e what will be x,y?Then, what if the linear models are not good enough so I may have to select the nonlinear models.Can somebody please guide with code snippets what are the steps in fitting,checking for overfitting,residual calculation etc.
Answer: x is likely to be k (index of y). And the whole code:
c =polyfit(1:length(y), y, d).
Matlab has a curve fitting toolbox. You could use it to check different nonlinear fitting in GUI to get some intuition.
If you want steps there's a great Coursera Machine Learning course. The beginning of this course is related to linear regression and I recommend you to spend some hours at least on that beginning.
Comment: Could you kindly give some examples here with nonlinear fitting so that I have somehting too begin with.Also,thank you for the course link but it begins very late around April :(
Comment: The videos and pdf should be avaliable now. Click `preview` on the site.
Comment: As for nonlinear fitting examples, check `nlinfit` in documentation. I'd play with `curve fitting tool` first


Showing the proportionality? (Calculus)

Question: "A radioactive substance decays according to the formula $W= 20e^{-kt}$ grams where $t$ is the time in hours."
$a)$ Find $k$ given that after $50$ hours the weight is $10$ grams.
$b-d$ I do not need help with
$e)$ Show that $\frac{dW}{dt}$ is proportional to the weight of substance remaining.
For $a)$ I got $k= 0.0139$ (to be exact it was $1/50\cdot\ln2$, but I rounded it to $4$ significant figures)
I am not exactly sure what I am supposed to find in $e)$. When I derive the formula, it is equal to $(1/50\cdot\ln2) \cdot 20e^{-(1/50\cdot\ln2)t} $. What do they want me to find/show? I got the derived equation, is that all I am supposed to show?
Comment: Proportional means that the ratio is constant. Differentiate. What do you notice?
Comment: That the value in front is indeed a constant. Thank you ^^
Answer: You want to find $\frac{dW}{dt}$ and show that it is a constant times $W$.
Taking the derivative of $W=20e^{-kt}$ using the chain rule we get
$$\frac{dW}{dt}=20e^{-kt}\cdot(-k)=-kW$$
We know that $-k$ is a constant, so we are done.

Showing the proportionality? (Calculus)


7 - Add classes to individual fields of paragraph bundle

Question: Hi in paragraphs module for drupal 7, how can we assign classes/html tags to individual field items of paragraph bundle?
There is Classy Paragraph module that lets us to add classes to the paragraph wrapper/section. How to achieve the same for individual fields of paragraphs?
Answer: Most people add another field, such as a select list with predefined options, and turn that into a class using a preprocess, or merge in the paragraph twig template.  If don't have a predefined list, and you allow user input, you will need to sanitize the input.
How I do it in the twig template is like this:
<code>{# Renders Width field. #}
{# Sets class name from values in database. #}
{% if content.bp_width|render %}
  {% set layout_width = content.bp_width['#items'].getString() %}
  {% set layout_width_classes = [
'paragraph--width--tiny' == layout_width ? 'paragraph--width--tiny',
'paragraph--width--narrow' == layout_width ? 'paragraph--width--narrow',
'paragraph--width--medium' == layout_width ? 'paragraph--width--medium',
'paragraph--width--wide' == layout_width ? 'paragraph--width--wide',
'paragraph--width--full' == layout_width ? 'paragraph--width--full',
  ]
  %}
{% endif %}

{# The template default set classes. #}
{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}

{# Merges Width field with classes. #}
{% set width_field = content.bp_width|render %}
{% if width_field %}
  {% set classes = classes|merge(layout_width_classes) %}
{% endif %}

{# Prints div with classes, and content without Width field. #}
<div{{ attributes.addClass(classes) }}>
  <div class="paragraph__column">
    {{ content|without('bp_width') }}
  </div>
</div>
</code>
How do the Bootstrap styles get added?  Here is an excerpt from the LESS file:
<code>.paragraph {
  .make-row();
  margin-left: 0;
  margin-right: 0;
}

.paragraph > .paragraph__column {
  .make-sm-column(12);
  .make-md-column(12);
  .make-lg-column(12);
  padding-bottom: @jumbotron-padding;
}
</code>
Which compiles into the following CSS:
<code>.paragraph {
  margin-left: -15px;
  margin-right: -15px;
  margin-left: 0;
  margin-right: 0;
}
.paragraph > .paragraph__column {
  position: relative;
  min-height: 1px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 30px;
}
</code>
You can overwrite that in your theme if needed.
Comment: Sounds like it is coming from the bootstrap layouts module.
Comment: How to get rid of the "row" class that gets added to the paragraph wrapping div? @jim
Comment: Added to the answer above.
Comment: Hmm thanks. However if we use bootstrap layouts module in D8. There is a actual "row" class being appended to paragraph wrapper. Was trying to figure out where it is coming from and how to get rid of it. Any clues?
Comment: Correct. More here https://www.drupal.org/node/2877051
Comment: This answer is relevant for Drupal 8, not Drupal 7 (as specified in the original question).


Find optimal configuration ranges for manufacturing process

Question: Let's assume I have some industrial manufacturing process with one costs and a produced output as well as a number of variables to configure the process.
Based on my historic data I would like to find out what is the optimal range of var1, var2, var3 to produce my output with low costs (costs/unit). So I would like to find out e.g. var1 should be between 0.1-0.2, var2 0.8-1.0 and var3 0.2-0.3 for cheap production and which variables are most important for the optimization.
<code>costs/unit      var1    var2    var3
20              0.5     0.1     0.12
19              0.4     0.2     0.13
15              0.4     0.1     0.16
10              0.1     0.9     0.23
23              0.5     0.3     0.24
</code>
The table above is just an example, in reality there are 50 variables and much more rows, but I just wanted to ask if you have some ideas which approach is the best for that requirement? Is it possible to use clustering therefore?
Thanks!
Answer: You face with a regression problem. You can train a regression tree on your data, where the cost/unit is the label. The learned tree reflects the required knowledge. Each path starting from the root ending in one leaf shows a rule that reflect which variables have impact on the cost and how they influence the cost.
Comment: Okay thanks, but then how would I get the recommended ranges for my variables to produce with low costs?
Comment: Then you should select those leaves that their cost values are low. The paths associated with these leaves give the appropriate ranges for different variables. Your final rule is obtained by making the OR of these rules.


Different BIC value from strucchange plot and reconstructed model

Question: I'm analysing a time series with the aim of assessing the presence of significant break points, using R package strucchange (v. 1.5-1).
The number of break points considered for interpretation should be based on the BIC.
bi <- data.frame( one=c(-291.646215, -352.906441, -203.847738, -265.890719, -239.569567, -115.730344,  -26.390263, -132.666324, -304.392077, -203.838021,-40.730929, -111.718441,
-134.439897, -256.708336, -100.273491,  -94.650407, -224.786040, -255.487975, -248.194932, -147.786471, -378.227251, -203.866693, -186.334344, -176.35081,7
-195.005512,  -96.399400, -151.217169, -215.296981, -132.246881, -410.438924, -305.406041, -438.224547, -334.886909, -304.906075, -249.427925, -277.21129,5
-391.637535, -506.200948, -410.195394, -249.840484, -353.658063, -294.074160, -306.975331, -196.784605, -224.970929,  -77.684773, -113.751598, -334.41126,6
-250.120219, -186.494178, -256.462787, -152.020462, -138.775345,  -84.182954,  -28.133517,  -53.180936, -241.289883,  -69.507575,  -16.108901,  -10.659180,
 -7.893134))

bits<-ts(bi$one,frequency=1)
bp<-breakpoints(bits~1,h=.15)

plot(bp,main="")

The resulting plot shows a BIC around ~739 for the 3-breakpoints model (black line, left scale).

However, when I then use breakfactor to reconstruct the model (for further plotting) :
bp3 <- breakpoints(bits~1,h=.15,breaks = 3)
fm3 <- lm(bits ~ breakfactor(bp3, breaks = 3))

BIC(fm3)

The resulting BIC is smaller (727).
Which value should I consider ? Why is there a difference ?
More precisely, I'd like to compare with the BIC from other models obtained previously with lm and nls.
Answer: The difference is in how the degrees of freedom (df) are calculated. This is most easily seen from extracting the logLik() which includes the df. Additionally, the nobs() can be consulted to check whether the number of observations is indeed the same (which is the case here).
logLik(fm3)
## 'log Lik.' -352.8972 (df=5)
nobs(fm3)
## [1] 61

The 5 parameters are intercepts in the 4 segments plus 1 constant variance. From these two pieces of information BIC() puts together the information criterion:
BIC(fm3)
## [1] 726.3488
-2 * (-352.8972) + log(61) * 5
## [1] 726.3488

The estimated breakpoints bp3 or, equivalently, bp (because this is associated with the minimum-BIC solution) count the df differently and hence lead to a different BIC:
logLik(bp3)
## 'log Lik.' -352.8972 (df=8)
nobs(bp3)
## [1] 61
BIC(bp3)
## [1] 738.6814
-2 * (-352.8972) + log(61) * 8
## [1] 738.6814

The df are 8 and not 5 because bp and bp3 account for the fact that in addition to the 5 parameters above 3 breakpoints were estimated. In contrast, fm3 assumes that the segment specification is given exogenously.
Additionally, you could consider the variances to differ across the four segments. However, given that least-squares estimation is used (as opposed to full maximum likelihood estimation) we had decided to keep the standard homoscedastic view by default. See Zeileis, Shah, Patnaik (2010, Computational Statistics & Data Analysis, 54(6), 1696-1706. doi:10.1016/j.csda.2009.12.005) for an approach that considers the variance a full model parameter.
Comment: The answer of @Achim Zeileis helped me a lot in a current problem, but I still wonder how to deal with the d.f. in case we compare two breakpoint models in a likelihood ratio test, e.g. `anova(fm3, fm0)`?
Comment: If you run `anova()` this assumes that the breakpoints were given exogenously and didn't need to be estimated. This then leads to a standard F test. However, when you want to account for estimation of the breakpoints (as appropriate here) you can use the same test statistic but it is no longer F-distributed. In `strucchange` we only implement the maximally-selected likelihood ratio test for 0 vs. (at least) 1 breakpoint, see `?Fstats`. In the literature you also find test for 0 vs. k or k vs. k+1 breaks. See the Bai & Perron (2003, Journal of Applied Econometrics) paper for more details.


Are 7th chords made up from 4 notes?

Question: I'm new to guitar, and I have been learning basic chords over the months. I know that C Major is made up from C E and G
When learning C7, there's an extra finger and that makes up 4 notes, so, C E G and Bb?
I saw in some website, that it's made up from "Bb". What does that mean? Is it made up from one note only? I couldn't find that anywhere when searching in the notes diagram.
Is it something that you have to learn scales first to understand?
Comment: Good explanation, but G is the fifth isn't it, not the fourth?
Comment: From one newbie to another, I didn't understand chords until I started learning scales. I would play a C chord but have no musical understanding of why I was positioning my fingers over specific frets.
When I learnt the C major scale, I understood how a C chord (triad) is formed using the scale and why my fingers are positioned on those frets.
C Major is made up of C E G because C is the first note of the C Major scale, E is the third and G is the fourth. Add the seventh (B) and you get C Major 7.
The scale is a palette of notes (colours) and the chord is the painting.
Comment: @upsidedowncreature yes, G is the 5th in C.
Comment: *"Is it something that you have to learn scales first to understand?"*  **No way!**  Don't even think about it.  Get so you can play and sing 10 simple songs.  Then get so your strumming hand has the same amazing feel of Paul Stanley!  Only then worry about BS like notes.  All that matters is you have the right feel for strumming and get the right sound.
Answer: Yes, seventh chords are made up using 4 notes. 1,3,5 and 7. That's why they are named 'seventh' chords. But that's going to be too simple! There are quite a few different 7th chords, and the one you're asking about is the dominant seventh.It's actually a chord that belongs to key F, rather than key C. The B♭ note that's added to the basic triad doesn't really belong to key C - which doesn't have B♭ in its scale.
You say it uses an extra finger - that's true here, but if you looked at A7, you can actually take a finger away, and play it with only two fingers, so don't think a 7th chord always needs an extra finger! However, from an open C chord, adding B♭ on 3rd string, 3rd fret produces C7.
A quick list of 7th chords - dominant; major; minor; m7♭5; dim7; mM7; aug7 covers most - each and every one featuring 4 notes. On guitar in particular, you can actually get away with playing only 3 notes - root(1), 3 and 7. Sometimes this is needed in order to finger it comfortably.
Comment: Ha! You've been on too many guitar sites!! That note has two names - A#; **and** Bb. Except that an awful lt (and a lot of awful) guitar sites seem to deny the existence of flat notes - only favouring sharps. In my quoted key of F, there is no A#, only a Bb.
Comment: @user65342, a great deal of the confusion about scales becomes clearer when you learn about key signatures. _In the key a C_ Bb makes more sense than A# in common situations, while _in the key of B minor_ A# makes more sense than Bb. That kind of understanding is predicated on understanding keys and key signatures. It will also help grapple with modes and some exotic scales too.
Comment: I'd make a start at understanding it better by avoiding a lot of the 'guitar expert' sites, which seem to carry and spread a lot of misinformation! Scales are a great place to start - also, there is a lot of *accurate* information available on this very site. One of the best I've found so far! Guitar teachers are often the fount of knowledge too...
Comment: Isn't 3rd string, 3rd fret an A#? How is pressing it down when playing a C major makes it a C7? Isn't like,  C E G A#? How does it become Bb?
Comment: Oh, wow. Most of the diagrams I've seen only show A#. How can I understand this stuff better? Do I start learning scales and where do I really begin?
Comment: @LaurencePayne - somehow, I consider C7 to belong more to C Mixolydian than C major as far as Blues is concerned. Devil's advocate...
Comment: One thing I don't get is, if the 3rd string, 3rd fret has 2 notes, A# and Bb, how can you tell the difference / use one than the other when playing chords?
Comment: Oh. That just made it easier to understand. Thanks!!. When starting to learn scales, what do I begin with? All I know is that scales are a group of notes that sound good together, not sure if that's true or not. There are different scales such as: Minor Pentatonic, Major Pentatonic, Minor scales, etc. Not sure where to begin. If there are some reliable sites that teach scales (or maybe here), that'd be fantastic.
Comment: Wow, scales are really confusing, no? Most people say that it's simple, but I have no idea where to start learning them.
Comment: I get it!!, so the Root note(R) is what the scale is, so If I put my finger on the 6th string 5th fret, that becomes an A minor scale, correct? And now, I just have to memorize the pattern and how to play it I assume?
Comment: @user65342 I would recommend finding learning materials that don't misspell chords.  It may be simpler in the beginning to explain that a C7 chord has an A sharp in it, but I suspect that it will cause confusion down the road.  If you learn from the beginning that the note is B flat, you won't have to re-learn it later.  But I am not a guitarist, much less a guitar pedagogue, so I could be wrong.  (I began learning theory through piano lessons, as one might guess from my earlier comment.)
Comment: C7 very much 'belongs' to C major in at least one form of music that a novice guitarist is very likely to encounter, the 12-bar blues.
Comment: To all intents and purposes,in 12tet, A# and Bb have the same sound. Same pitch. It's just that, technically, when writing (or talking about) C7, the note is always Bb, never A#. (unless it's in a clueless guitar site!) Bb is the m7, whereas A# is aug.6, and has no place in the harmony discussed here.
Comment: @user65342 "12tet," in case you aren't aware, means "twelve-tone equal temperament," and I think it must be much easier to understand with reference to a keyboard. I was discussing this recently with an organist friend of mine. We were both baffled at the prospect of trying to explain to a string player why some natural pitches (e.g., A and B) are separated by a whole step, with something in between, while others (e.g., B and C) are not. On a keyboard, the thing in between is a black note, which can be either the sharpened note below or the flattened note above.
Comment: @user65342 similarly, on a guitar, wherever you stop a string to play an A (or on the open A string), you get a B by stopping the string two frets higher -- two half steps.  The fret in between can be either B flat or A sharp.  The correct spelling of that pitch depends on the key and the harmonic context: every scale should contain each of the seven letters from A to G, which principle is broken if you spell that note as A sharp when playing an F scale.  Since C7 is a chord from the key of F, that note should be B flat.
Answer: A dominate 7th chord (often written as x7 where x is the root) will contain the Root (1st degree), 3rd, 5th, and flat 7th.
Therefor a C7 will be C, E, G and Bb.
At times a player can choose to leave out a note, usually the 5th or the root but in those case it is common that the other players will be playing them or that they are implied. The 3rd and 7th are a little more important because if you don't play them it is harder to tell if it is a major or minor 3rd or a major or minor 7th.
As far as what you found on the internet that it will be "made up from Bb"...I am not sure what that means but don't believe everything you read on the internet.
EDITING TO EXPAND ON THIS:
If you look at the major scale and build chords off it every key will have the same quality of chords built off the same scale degrees.
For example the chord build off the tonic (root) of the key will have a Major triad or a Major 7th chord built off it.
For the key of C the I chord (one chord) is C E G  or C E G B and for the key of G it is G B D (G B D F#). If you looked at the distance between those notes (i.e. the intervals they are the same for each, because all major scales will have the same intervals between notes.
You can do this from other scale degrees too. If you start at the second scale degree you get a Minor triad or a Minor 7th chord.
In C the second scale degree is D, so the Diatonic chords (the chord that belong to the key of c for that scale degree) are D F A and D F A C. Notice that the F is natural, because that is the note that is diatonic to the key of C and the F is natural as well for the same reason.
If we want to build a major triad or a major 7th from D you would need to use the notes that are diatonic to D as we have already seen that a chord built off the root of the key is a Major triad or a Major 7th: D F# A or D F# A C#.
So, where does this Dominate 7th come from? glad you asked. It comes from the 5th degree. Look at the 5th degree in C. It is G. If we build a chord from G using the notes from our C scale we have G B D, a major triad. So, a G major triad is diatonic to C. It is also Diatonic to G (as we saw above) but serves a different function as it is built on a different scale degree. If we turn this into a dominant 7th chord we get G B D and F. Note that it is not F# which would be diatonic to G but F natural which is diatonic to C.
So, the 5th scale degree is a diatonic 7th chord. Now, back to your question...How can we build a C7? Well, what key does C function as the 5th degree of? F Major! So, if we take the key F we have F G A B♭ C D E and F. If we take those notes and build a chord starting on C we get C E G and  B♭!
If you want to build out all the chords in a major key we would have:
Triads:

Major : I
minor : ii
minor : iii
Major : IV
Major : V
minor : vi
diminished : Vii°

and 7ths:

Major 7th : I Maj7
minor 7th : ii min7
minor 7th : iii min7
Major 7th : IV Maj7
Dominant 7th : V7
minor 7th : vi min7
minor7thFlat5 : Viimin7♭5

One thing to note is the way the chords are named:

Major7th chord is a major triad with a Major 7th (interval about the root of the chord).
minor7th chord is a minor triad with a minor 7th.
7th (Dominant 7th) is a major triad with a minor 7th.
Minor7th flat5  is a Diminish triad (root, minor 3rd,  diminished 5th) with a minor 7th.

(Notice that in the above definitions the triad qualities mentioned match the triads that are diatonic to the key, which makes sense if you think about it)
There are other 7th qualities that are not diatonic to a major key, such as MinorMajor7th, but lets not get ahead of ourselves.
Just because a chord is not diatonic to the key doesn't mean you can't use it, and actually non-diatonic chords (or borrowed chords, or secondary chords) are used all the time in all styles of music.
Comment: this is the most correct answer. A 7th chord does not *have* to have 4 notes.
Answer:
...Are 7th chords made up from 4 notes?

The simple answer is yes. C E G Bb is a dominant seventh chord and it has 4 tones.
In practice it is common to not play all chord tones - you can call those implied or incomplete chords - and sometimes the root of a chord is not actually play - implied or rootless chords.
A little more sophisticated answer is that chords are made from tones above a root. Those tones added above the root form intervals. So we can talk about chords as a collection of intervals above a root.
A seventh chord is minimally defined by a tone added a seventh above a root.
You could play only C Bb for a incomplete dominant seventh chord, or E Bb for an implied, rootless dominant seventh chord. The other chords used in the music will make more or less clear how such incomplete or implied chord are perceived.

...I saw in some website, that it's [C7] made up from "Bb"

Probably the intended meaning was something like: just a Bb alone above a root of C will provide an incomplete C7 chord. In that sense the C7 is "made up from" the addition of the "Bb." It seems like a poorly worded description.
Comment: I suspect that the actual intention was that adding B flat to a C-major chord gives you a C7 chord.  The point about chord tones often being omitted is a good one.
Comment: Sure, that's possible. Either way "made up from Bb" is a poor explanation.
Comment: That's certainly true!
Answer: The chord you are describing is referred to as a dominant seventh, which flattens the seventh note of the scale. By doing this the chord becomes very useful for resolving back to the tonic of the scale because of the tension caused by the flatted seventh scale degree when it is combined with the other harmonies in the chord. Compare that to the major seventh chord (also a four note chord) where the seventh degree of the scale is not flattened.
The digital age brings easy access to a whole boat load of information about almost anything you may have a question about, but more often than not that information is incomplete and taken out of context. This usually leaves us with more questions than we had before we started asking. As long as you have questions, you'll need to keep searching for the correct answers. Personally, I don't expect to ever arrive at that point, but good luck searching.
Comment: In reality it doesn't flatten the 7th note of the scale. It uses notes from a different scale. It is the *dominant seventh* of F, as the OP's question stands, so flattening the 7th of that would give an Eb - not the question.
Comment: @Tim I'm a little confused by "from a different scale."  The dominant seventh chord in its canonical form doesn't flatten any notes; it uses the notes 5-7-9-11 (or 5-7-2-4) of the diatonic scale.  That's where its name comes from, because the 5th scale degree is the dominant, and the chord is built on the fifth scale degree.  So C7 has a B flat in it because C7 is a chord from the key of F, where the diatonic fourth degree is B flat.  Is that what you're getting at with your comment?
Comment: @Tim-I stand corrected and at the same time better understand the difference between a dominant seventh and a major seventh. My instructor presented it very differently so many years ago. Many thanks for the enlightenment :-)
Comment: @phoog - if you read the first two or three sentences of this answer, you'll see that it refers to 'the scale', and resolving back to the tonic, after flattening the 7th note to do so. That's not correct - the 'flattened 7th' actually belongs to a *different* key/scale.Yes, hence my comment.
Answer: "I saw in some website, that it's made up from "B♭". Let's get that out of the way for a start!  Yes, a B♭ does come into it, but that statement, as it stands, is nonsense. Carry on...
Yes, a major chord has three notes.  If we consider the lowest note to be the root of a major scale (yes, if you want to understand theory you'll need to know about scales) it's the 1st, 3rd and 5th notes of the scale.  C major chord is the 1st, 3rd and 5th notes of a C major scale - that's C, E and G.
So a 'seventh' chord should be the 1st, 3rd, 5th and 7th notes of the scale, right?  C, E, G and B?    Sorry, no!  That's a 'major 7th' chord, written   C(maj7).  'C seventh', written C7, is C, E, G, B♭.  The basic C chord plus the flattened seventh.
You want some 'why'?  Because this type of chord first appeared as a 'dominant 7th'.  An addition to the dominant chord, the one built on the 5th note of a scale. That's the 5th, 7th, 2nd and 4th (it wraps round) notes of the scale. And this chord type is often called a 'dominant 7th'.  The 'dominant 7th' in the key of C is G7 - G, B, D and F.  Whereas C7 - that's C, E, G, B♭ - is the 'dominant 7th' of F major.
Now, you have the opportunity to avoid falling into a very common misconception.
Indeed, C7 can  be a gateway from the key of C major to F major. Something 'borrowed' from F major, that takes us into F major.  But it can also be firmly 'in C major'.   One example, which I'm sure every novice guitarist will have already encountered, is the 12-bar Blues.  One of these in the key of C will use three chords, C7, F7 and G7. Your melodies will doubtless include lots of flattened 3rds and 5ths (E♭ and G♭).  And all ABSOLUTELY IN C MAJOR. Notes that aren't in the scale are OK, and don't necessarily imply a change of key.
Get this idea clear at the start, and you'll avoid a lot of brain-ache when you encounter other 'not in the scale' chords!
Answer: 7th chords are made of 4 notes, which is a sort of an extension of a typical triad making a chord. min7, M7, maj7,  or 7 (a dominant chord which a C7 is an example of) are constructed with 4 notes.
Answer: A "proper" C7 chord is C-E-G-B♭.  However, it is educational to look at what accordions, which have whole chords on a button do.  While some older German accordions do the "correct" C-E-G-B♭, this is more a quirk of history than anything else: most accordions use only three notes in order to have all chords have similar "weight" and air usage.  On accordions with 4 chord rows, C7 is usually represented by C-E-B♭, leaving off the fifth.  If you really, really want the fifth, you can press the normal Cmajor key in addition and it will add the G.
On accordions with 3 chord rows, the "diminished chords" row is missing.  However, C7 is represented as E-G-B♭ then and can also serve as Gdim (again with the fifth, namely D♭, missing).  Many chord accompaniment schemes alternate between a bass note and a chord, and if the chord does not repeat its root, that is surprisingly inconspicuous.
So functionally, not much more than the seventh (to establish the seventh character) and the third (to establish the major character) are really making a significant difference in character when absent.
The "weight" argument also applies reasonably well to piano accompaniments where an abundance of simultaneous bass notes tends to create a muddy sound character.  Depending on the pitch there, it might be expedient to leave off the third (or only play it in a higher octave) since it has a higher "mud factor" than the fifth.
Guitars tend to suffer less from that affliction, so one usually is fine with sounding the regular major chord on all feasible strings and modify one of the higher strings to sound the seventh.
Answer: Well, basically it's correct that the C Major chord is made up of the tones C, E and G. On a usual guitar, when you strum the "normal" C chord (not the barré one) and omit the low E string, the following tones sound: C E G C E. So that's five distinct tones ringing, but actually only 3 really different ones, yet in different octaves.
Your're right, the C7 chord requires the tone Bb to create a "minor seventh" chord (that's what the "7" means); the "minor seventh" tone is always 1 full tone below the octave above a base tone, so for the C tone, the "minor seventh" tone is the Bb above it.
When trying to play that on a guitar, the best choice is to put a finger on 3rd fret of the G string, so tone Bb rings. When you now strum, omitting the low E string, the following tones sound: C E Bb C E. As you see, there's no G in it. The G is the fifth (interval) tone above the C, and as others already commented, not so very important for the character of a chord (it makes it only more "bold" or "fat").
On a guitar, you always depend on how you can best put your fingers onto the neck.
Seventh chord and keys
Of course you won't usually see a C7 chord in a song which is in C major key, because there's no Bb "defined"; you will see it more likely in a song in key F major.
Dominant seventh chord
Some mentioned the "dominant seventh chord": the "dominant" is the 5th step of the scale; for C major, it is G. For F it is C, for G it is D. Together with the "sub-dominant", which is the fifth below the base tone, it forms the cadence: this is the sequence base chord (or tonic) - sub-dominant chord - dominant chord - base chord (tonic). For C major, it are the chords C - F - G - C, for F major, they are F - Bb - C - F. Play them and you'll notice that many songs use that scheme.
Now when you play C - F at the end, this sounds like a "real end", that's why this is called the "authentic end". If you play C7 - F, it sounds still more like that, but you still go from the dominant to the tonic. This is why the C7 chord is called the "dominant seventh chord" in that context.
(C7 - F sounds a little more beautiful than C - F, because it contains that tone Bb goes to tone A (the third tone of the F chord). This half tone step sounds lovley.)
Whereas a seventh chord virtually always "wants" to be "resolved" to the chord a fifth below, this needs not always be so. E.g. you may well use the chord sequence C7 - F7 - G7 - C7 to accopmany a song. Sounds cool.
The "above Bb" issue: inversions
Now to your last question, about starting the C7 from Bb. As i said, C7 consists of the tones C, E, G and Bb. Now, actually that's just the set of tones that may be used in the C7 chord. Now there's the concept of "chord inversion".
I explain it for the C chord first: it has tones C - E - G. In German we call that the "quint (=fifth) position", because the fifth tone above the C is "on top" of the chord.
First inversion: put the C one octave up --> tones E - G - C, "octave position".
Now the bass tone is the E, giving the so called "sixth chord". It's used as transition chord, the usual chord sequence is: C - C/E - F. The /E means "E in the bass, not the C".
Second inversion: put the E one octave up --> tones G - C - E, "third position".
Now the bass tone is G, giving the so called "quart-sixth chord". It's also used as a transition chord, the usual chord sequence is: C - C/G - G.  The /G means (again) "G in the bass, not the C".
Doing inversion once more, i.e. putting the G one octave higher, we are back at the original sequence C - E - G (only one octave higher, but that's not of importance for that subject).
Inversions for C7
Now we can also do inversion with the C7 chord:
Base: C - E - G - B7
1st:  E - G - B7 - C ("quint-sext-chord")
2nd:  G - B7 - C - E ("third-quart-chord") (rather seldom used)
3rd:  B7 - C - E - G ("second chord")
(the strange names in brackets stem from the "basso continuo" theory - do not worry about it, you would only need it for classic music: e.g. a chembalo accompaniment then very often only noted the bass tones and some numbers or symbols written above it, telling which chord to play above the given bass tone - everything else was free to the player's art)
Now i guess the 3rd inversion above is the one you are talking about when saying "above Bb". It's also used very often as transition chord; the usual sequence is: C - C/Bb - F(/A), to note here that the bass goes down a scale. You might want to add Fm/Ab - C/G - G to the sequence - very familiar i suppose (but hard to play on the guitar alone. In a band you would divide it up between guitar and bass).
But how to play that on a guitar? As i said above, you need to look how to arrange the fingers on the neck... For C/Bb, there's the following option:
do a barré on 1st fret, and do 2nd fret on D string and 3rd fret on G string. When strumming, omit both E strings. Now the tones Bb - E - Bb - C ring, making up a C/Bb. Although it's a little limited, and the Bb is doubled, it does the job. On a piano it were far easier - you just would go down 1 tone with the left hand.
Scales and intervals
There's no real need to learn scales or intervals before learning to play an instrument. But if you want to understand all the theory behind notes and scores, it's the very foundation! But i know a lot of (good!) musicians who can't even read notes and scores...  Music lives from what you put into it as a performer, not from the theory :-D
Answer: You can make all possible 7th chords that are consistent with harmonizing the diatonic scale by taking 4 consecutive 3rds of the major scale.  The notes of the major scale are referenced by their degree (an index 1, 2, 3, 4, 5, 6, 7, 8 for Do, Re, Mi, Fa, Sol, La, Ti, Do).  The tricky thing is that when we build chords we always use the major scale degrees as a reference with the chord root on 1.  For example a minor chord is (1, b3, 5).  The 3rd is flat because in the major scale the 3rd degree is a major 3rd.  Flattening it makes it minor. So, a G Maj and G min chord are both built from the degrees of the G major scale.  A variety of chords naturally occur in any key by starting on different notes of the key.  For the triads we get the following pattern.
Maj occurs on 1, 4, and 5
min occurs on 2, 3, 6
dim occurs on 7
In the key of G maj you have G, C, and D major triads, and A, B, and E minor triads all in the same key.  The formula for C maj is still (1, 3, 5) using the C major scale but in the Key of G it can be described as (4, 6, 8).  It's like using absolute frames versus relative frames of reference in science and engineering.  You can build a variety of 7th chords by adding another interval of a 3rd (more correctly the next note in the sequence of "every other note") to any of the triads (including Augmented, not provided).
You get the following basic 7th chords.
Major 7 = (1, 3, 5, 7)
minor 7 = (1, b3, 7, b7)
Dominant 7 = (1, 3, 5, b7)
Minor 7 b5 = (1, b3, b5, b7)
Full Diminished = (1, b3, b5, bb7)
You also have altered versions of these by moving one or more of the notes.
min Maj 7 = (1, b3, 5, 7)
Dom 7 +5 = (1, 3, #5, b7)
etc.
The standard notation is that a "7" chord is a dominant seventh chord, hence the Bb.

Are 7th chords made up from 4 notes?


Holding off displaying figure window in Matlab

Question: The following piece of code is from the great book "An Introduction to Programming and Numerical Methods in MATLAB" by S.R. Otto and J.P. Denier
x = 0:pi/20:pi;
n = length(x);
r = 1:n/7:n;
y = x.ˆ2+3;
plot(x,y,'b',x(r),y(r),'r*')
...
Code continues from here specifying x axis and y axis labels and so on. When I start to write the code in command window, as soon as I put the last round bracket for plot command, Matlab returns figure window with the plot, without me having a chance to insert x and y axis labels and so on. How do I get the plot with everything complete?
Comment: Once the figure has been created, you can add axis labels and stuff with commands like `xlabel`, etc.
Comment: I was wondering if I can get a plot once and with final appearance, however after the generation of the figure, adding title and label stuff is fine, thanks.
Answer: Matlab's documentation for the plot function contains the following code example:
figure
plot(x,y,'Color',[0,0.7,0.9])

title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')

I believe this is the standard way to do it in Matlab --- axis labels, title, etc. are added with additional commands after calling the plot function.


Would an accidental in a mordant still be effective for the whole measure?

Question: This is from Bach's Chromatic Fantasie and Fugue:

This would obviously be played D, C#, D. Let's say that there was a C on the same octave later in that measure. Would the C be sharp?
Comment: Highly related, but not a duplicate: [Do accidentals earlier in the measure affect a trill?](https://music.stackexchange.com/q/35930/21766)
Answer: The convention for ornaments is that a sharp or flat will affect only the ornament, and not other notes within the measure.  So in your example, any note written in the C space will be played as a C natural - but if there is a second mordent in the same measure, the C in that mordent will also be sharped without needing an additional accidental.
This rule applies only to accidentals over or under the ornament symbol.  An ornament that is written within the staff (e.g. a grace note with a sharp) WILL alter any following notes on the same line/space within the measure.
Comment: I'll look through my notation manuals when I get a chance.  But there are some references on the web that back me up, like https://www.liveabout.com/turns-piano-ornaments-2701410
Answer: Note (sic) that the sharp sign is not there in reference to the D note, instead it's above it (rather than before it), thus referencing the mordant itself. The target note after the fiddly bit will be a D natural. That sharp defines which actual notes will be played during the mordant. It certainly won't affect anything else in that bar at all, in particular the actual D note itself, and certainly not any subsequent C notes.
Comment: Mr. Grammar Pedant would like to inform you that you've incorrectly used "(sic)" because it is correct to initiate a sentence with "Note that...." .  :-)
Comment: @CarlWitthoft - I was, in fact, referring to an answer that was in my mind, sorry I didn't include you in it (init?). More of a pun really. Really. Already wearing that pointy hat, standing in the proverbial corner, deciding what the 'D' stands for today...


Causal Inference for experiment

Question: I'm working through a textbook (Regression and Other Stories) and have come across a particular problem that I am having difficulty convincing myself I understand.
I am specifically interested in part (b), but I include (a) as context.
It is as follows
'Before-after comparisons: The folder Sesame contains data from an experiment in which a randomly selected group of children was encouraged to watch the television program Sesame Street and the randomly selected control group was not.
(a) The goal of the experiment was to estimate the effect on child cognitive development of watching more Sesame Street. In the experiment, encouragement but not actual watching was randomized. Briefly explain why you think this was done. Think of practical as well as statistical reasons.
(b) Suppose that the investigators instead had decided to test the effectiveness of the program simply by examining how test scores changed from before the intervention to after. What assumption would be required for this to be an appropriate causal inference? Use data on just the control group from this study to examine how realistic this assumption would have been.'
I think this question is hinting at the problem of attaining an unbiased estimate for ATE from a difference in means from pre-post scores with systematic differences in pre-treatment variables between the treated and control groups, leading to differences in the outcome that is dependent on these differences rather than the effect of treatment - either through sampling bias. For example, more intelligent children are encouraged to watch the TV program because their parents are aware of its supposed effects, or through heterogeneous treatment effects such as socioeconomic factors.
The question suggests looking at control group data - which I have done, but I am not entirely sure what I am looking for in the data to test the above assumptions given the question suggests only looking at control data.
Answer: The validity of the post-pre estimator in the intervention group depends on there being no change in the control group. If there was change in the control group, then any changes you see in the treatment group could be due either to the treatment or to whatever caused changes in the control group. For example, if cognitive performance naturally increases in this period of a child's life, even in the absence of watching Sesame Street, then even if the intervention had no effect, you would expect to see increases in scores in the intervention group. Only by also observing the control group and noting the test score changes in the absence of the intervention can one ascribe causality to the intervention for score changes in the intervention group.
So, what you should do is to look in the control group for changes in scores between post and pre. If there are no changes, this suggests that just using the differences in the intervention group is sufficient to establish causality. If there are changes, then just using the intervention is not sufficient to establish causality; the competing explanation that the observed changes are due simply to the same forces that change scores in the control group remains, and you cannot say the intervention was effective. Subtracting the post-pre changes in the control group from the change in the intervention group would give you a causal effect; this is also known as the method of difference-in-differences.
In an experiment, this is not the best way to adjust for pre-intervention scores, but it does not invalidate the inference. If the experiment was randomized, comparing the post-difference means (assuming perfect compliance) is sufficient to estimate the causal effect. Adjusting for pre-treatment scores using regression/ANCOVA is even better. Things, of course, are a bit more complicated in the face of non-compliance.
Comment: very informative, thank you!

Causal Inference for experiment


Convergence $ \sum \frac{\sin \sqrt{n}}{n^{3/2}}, \quad \sum \frac{\sin n}{\sqrt{n}}, \quad\sum \frac{\sin \sqrt{n}}{n^{3/4}} $

Question: I need to examine the convergence of the following infinite series:
$$ \sum_{n=1}^\infty \frac{\sin \sqrt{n}}{n^{3/2}},  \,\,\,\, \sum_{n=1}^\infty \frac{\sin n}{\sqrt{n}}, \,\,\,\,\sum_{n=1}^\infty \frac{\sin \sqrt{n}}{n^{3/4}} $$
I was able to show that the first two converge. For (1) I used  $|\frac{\sin n}{n^{3/2}}| \leq \frac{1}{n^{3/2}}$ and the comparison  with a convergent p-series  to prove it converges.
For (2) I used the Dirichlet test knowing that $\sum_{n=1}^m \sin n$ is bounded for all $m$ to show it converges.
With the third series, the comparison $|\frac{\sin \sqrt{n}}{n^{3/4}}| \leq \frac{1}{n^{3/4}}$ does not help and I'm pretty sure $\sum_{n=1}^m \sin \sqrt{n}$  is not bounded.
I am unsure how to make progress with this third series.
Comment: How do you know the partial sums of $\sin n$ are bounded?
Comment: @MatthewTowers that was rhetorical for the OP to consider, but thanks nonetheless for your good intent :)
Comment: Well, you got the first two down.
Comment: @AdamHughes https://math.stackexchange.com/questions/17966/how-can-we-sum-up-sin-and-cos-series-when-the-angles-are-in-arithmetic-pro
Answer: The third series is convergent.  While not monotonic, a type of integral test applies.
We can show in general that a series $\sum_{k=1}^\infty f(k)$ and integral $\int_1^\infty f(x) \, dx$ converge and diverge together if $f'$ is absolutely integrable over $[1,\infty).$
The convergence of the series
$$\sum_{k=1}^\infty \frac{\sin \sqrt{k}}{k^{3/4}},$$
follows from the convergence of the improper integral
$$\int_1^\infty \frac{\sin \sqrt{x}}{x^{3/4}} \, dx = \int_{1}^{\infty}\frac{2u\sin u}{u^{3/2}} \, du = 2 \int_{1}^{\infty}\frac{\sin u}{\sqrt{u}} \, du,$$
where the RHS integral converges by the Dirichlet test.
Integrating by parts, we see
$$\int_{k-1}^k (x - \lfloor x\rfloor)f'(x) \, dx= \int_{k-1}^k (x - k +1)f'(x) \, dx \\ = \left.(x - k +1)f(x)\right|_{k-1}^k - \int_{k-1}^k f(x) \, dx \\ = f(k) - \int_{k-1}^k f(x) \, dx.$$
Hence,
$$|C_k| := \left|f(k) - \int_{k-1}^kf(x) \, dx\right| \leqslant \int_{k-1}^k\left| (x - \lfloor x \rfloor )f'(x)\right| \, dx \leqslant \int_{k-1}^k|f'(x)| \, dx$$
and we have absolute convergence
$$\sum_{k=2}^\infty|C_k| \leqslant \int_1^\infty |f'(x)| \, dx < \infty.$$
This implies convergence of
$$\sum_{k=2}^\infty C_k = \sum_{k=2}^\infty f(k) - \int_1^\infty f(x) \, dx,$$
whence the series and integral must converge or diverge together.
In this case with $f(x) = \sin \sqrt{x}/x^{3/4}$ we have
$$\int_1^\infty |f'(x)| \, dx  = \int_1^\infty \left|\frac{\cos \sqrt{x}}{2x^{5/4}} - \frac{3 \sin \sqrt{x}}{4 x^{7/4}} \right| \, dx < \infty$$
Comment: Oh nice, I did not know the integral test extends like so.
Comment: I saw.  :D  Nice.
Comment: @RRL May I ask, why/how your absolute convergence implies the convergence of $\sum_{k=2}^\infty f(k) - \int_1^\infty f(x) \, dx$? I have made a [post](https://math.stackexchange.com/questions/3000246/similar-to-the-integral-test) about it, and I still am working on how it is justified ...
Comment: @UnknownW: OK I provided an answer to your other post with an explanation.
Comment: @RRL I hope that you are doing well.  (+1) for this nice development.  I had not seen this before.


string indices must be integers

Question: tenho um Json que me retorna esse dados:
"errorCode": 0,
    "result": [
        {
            "username": "Captain Samafa",
            "callsign": "24K",
            "latitude": 39.7100376616406,
            "longitude": 59.01369415537506,
            "altitude": 33900.229864846835,
            "speed": 476.06915753461686,
            "verticalSpeed": 4.759671688079834,
            "track": 197.1294708251953,
            "lastReport": "2020-10-06 16:42:52Z",
            "flightId": "1854b0ee-ba71-473c-86b2-ac1935792dee",
            "userId": "27786ee9-8bcf-4a5b-9055-ebc0a5edaf39",
            "aircraftId": "230ec095-5e36-4637-ba2f-68831b31e891",
            "liveryId": "d09a1283-b2ff-4cd2-92f4-1d54c2a46c1b",
            "heading": 201.18605,
            "virtualOrganization": null
        },
        {
            "username": "IFATCLee3440",
            "callsign": "Madras 12",
            "latitude": -52.60996492913441,
            "longitude": -54.92538650405199,
            "altitude": 29345.708025272826,
            "speed": 422.9940309420305,
            "verticalSpeed": -1455.298828125,
            "track": 289.4452819824219,
            "lastReport": "2020-10-06 16:42:52Z",
            "flightId": "6d7feaf2-5705-4b3e-8003-0f984259e769",
            "userId": "0c326e97-ee4c-4246-9588-11b87f1bed9f",
            "aircraftId": "e59fa7b4-b708-4480-aebd-26659a4f312b",
            "liveryId": "9508c65e-2992-4759-b382-3c0e75c24923",
            "heading": 290.7723,
            "virtualOrganization": null
        },
        {
            "username": "ajfl",
            "callsign": "Southern Air 120",
            "latitude": 49.95203285892042,
            "longitude": 7.273932297661211,
            "altitude": 1663.5415957890098,
            "speed": 0.00031879721291165077,
            "verticalSpeed": 0.032275911420583725,
            "track": 88.79496765136719,
            "lastReport": "2020-10-06 16:42:52Z",
            "flightId": "60e0cec7-9e98-4a3b-8d88-cb2fbd073cb6",
            "userId": "f9f8adbd-682f-47f3-9e52-4ac0a1c1d195",
            "aircraftId": "6925c030-a868-49cc-adc8-7025537c51ca",
            "liveryId": "0ffc1641-3ab9-4b16-a701-033ab41ed08d",
            "heading": 122.89578,
            "virtualOrganization": null
        },
        {
            "username": "arjun",
            "callsign": "Airbus 010 Heavy",
            "latitude": -1.4518363199159487,
            "longitude": 29.408336730183667,
            "altitude": 11000.026394873705,
            "speed": 358.0320414644207,
            "verticalSpeed": 23.87726402282715,
            "track": 89.05824279785156,
            "lastReport": "2020-10-06 16:42:52Z",
            "flightId": "f152d38f-63cb-4077-8337-f58ebd1fe618",
            "userId": "496c096c-4e59-44b2-9c94-acb74c668ff5",
            "aircraftId": "230ec095-5e36-4637-ba2f-68831b31e891",
            "liveryId": "f334063e-5103-4b3b-bd15-b1b2fdb220fd",
            "heading": 90.01053,
            "virtualOrganization": null
        },
        {
            "username": "GER-ALLIANCE MuKa7",
            "callsign": "MK-7",
            "latitude": 64.4744059592217,
            "longitude": 13.611431742529339,
            "altitude": 34999.82801008071,
            "speed": 489.1741898339633,
            "verticalSpeed": -3.9575376510620117,
            "track": 195.6558837890625,
            "lastReport": "2020-10-06 16:42:52Z",
            "flightId": "35847c52-12c2-4af2-adbe-ec4d3483f1d8",
            "userId": "69884110-69dd-498f-a25a-ec88a384a9c8",
            "aircraftId": "bec63a00-a483-4427-a076-0f76dba0ee97",
            "liveryId": "a20ebf14-830a-4f05-b173-2dcd30c5a586",
            "heading": 194.24469,
            "virtualOrganization": null
        }

Estou tentando filtrar por indice "virtualOrganization"
flight = get_json('https://api.infiniteflight.com/public/v2/flights/7e5dcd44-1fb5-49cc-bc2c-a9aab1f6a856?apikey=[key]')

for x in flight:
  if "IFATC" in x["virtualOrganization"]:
    print(x['username'])

Só que está me retornado erro que não estou conseguindo resolver:
TypeError: string indices must be integers
Answer: Imagino que flight seja esse JSON apresentado, então me parece que você esta fazendo o for no nível do errado.
O x o vai ser o "errorCode" e "result", para você confirmar basta deixar seu for assim:
for x in flight:
    print( x )
    #if "IFATC" in x["virtualOrganization"]:
    #    print(x['username'])

Veja funcionando no ideone
Por esse motivo esta ocorrendo esse erro:
TypeError: string indices must be integers

x é uma string e você esta procurando uma key, o erro informa que em strings os índices tem que ser inteiros. Ex:
x = "errorCode"

# o indice 5
print( x[5] ) # C

# a partir do indice 5
print( x[5:] ) # Code

# até o indice 5
print( x[:5]) # error

# toda a string ao contrario
print( x[::-1]) # edoCrorre

Veja funcionando no ideone
Me parece que você quer percorrer o flight["result"], como o código abaixo:
for x in flight["result"]:
    print( x )
    #if "IFATC" in x["virtualOrganization"]:
    #    print(x['username'])

Veja funcionando no ideone

string indices must be integers


Let $f:[-3,1] \to \mathbb{R}$. Show that there is $c \in [-3,1]$ such that $|f'(c)|\geq \frac{5}{2}$

Question: Let $f:[-3,1] \to \mathbb{R}$ a differentiable function such that $f([-3,1])=[-5,5]$. Show that there is $c \in [-3,1]$ such that $|f'(c)|\geq \frac{5}{2}$
I tried to use Mean Value Theorem, but since I don't have $f(-3)$ nor $f(1)$ then how can I proceed? I can see that if it were $f(-3)=-5$ and $f(1)=5$ then I would find some $c$ where $|f'(c)|=\frac{5}{2}$ by MVT.
Comment: You are soooooo close. Think about what you just said.
Answer: There must be some $x_1\in [-3, 1]$ such that $f(x_1) = -5$. Similarily, there must be some $x_2\in [-3, 1]$ such that $f(x_2) = 5$. Now use the mean value theorem on those two values, together with some inequalities, like $|x_2-x_1|\leq 4$.
Answer: From your notation I presume that range of $f(x)$  for $x\in [-3,1]$ is $[-5,5]$.
Thus we must have some $a,b$ (consider $a\lt b$, the result is unaltered) so that $[a,b] \subset [-3,1]$ and that $f(a) = -5$ and $f(b) = 5$ and since $[a,b]$ is subset of $[-3,1]$ we have that $|b-a| \le |1-(-3)| = 4$.
So apply Lagrange MVT on $[a,b]$ for $f(x)$ on $[a,b]$, that we must have $c$ so that
$$|f'(c)| = \left|\frac{f(b)-f(a)}{b-a}\right| = \frac{10}{|b-a|} \ge \frac{10}{4} = \frac{5}{2}$$
Note that we can have $a>b$ without altering the result.
Comment: Your second paragraph is false. It could be $f(a)= 5,f(b)=-5.$ Also we don't know $|b-a| < 4.$
Comment: She I meant to say $f(a)=5$ and $f(B)=-5$. And then we have two cases $a\gt b$ or $a\lt b$. The result is same. Also as already said, since $[a,b]$ is subset of $[-3,1]$ so $|b-a|\le 4$
Answer:
I can see that if it were $f(-3)=-5$ and $f(1)=5$ then I would find some $c$ where $|f'(c)|=\frac{5}{2}$ by MVT.

Hint: and if it doesn't happen in the endpoints, then it has to happen somewhere in the interval (which isn't as long!); meaning there exist $a,b \in [-3,1]$ such that $f(a)=-5$ and $f(b)=5$. Now assume $a<b$ and apply the MVT on $[a,b]$, the other case is similar.
Can you take it from there?
Comment: @Sobolev if the image is $[-5,5]$, then $f$ takes these extreme values somewhere...
Answer: Let $a,b$ in $[-3,1]$ such that $f(a)=-5$ and $f(b)=5$ and assume  that $a$ or $b$ are not endpoints of the interval $[-3,1]$ (otherwise you already shown what happens). Then there is $c$ between $a$ and $b$ such that
$$|f'(c)|=\frac{|f(b)-f(a)|}{|b-a|}=\frac{10}{|b-a|}> \frac{10}{4}=\frac{5}{2}.$$
Moroever, since $a$ or $b$ are in $(-3,1)$ it follows that $f'$ attains the value $0$ and, by Darboux theorem, $|f'|$ assume any value in the interval $[0,5/2]\subset[0,|f'(c)|]$.
Answer: Since $f([−3,1])=[−5,5].$ there exists $x,y\in [-3,1]$ such that $|f(x)=5$ and $f(y) =-5$

We have, $x\neq y$ assume $x<y$ then  $|x-y|\le 1-(-3)=4$ and   by MVT there exists $c\in(x,y)$  such that

$$f'(c)= \frac{f(x)-f(y)}{x-y} =\frac{5-(-5)}{x-y} =\frac{10}{x-y}$$
That is $$|f'(c)|= \frac{10}{|x-y|}\ge\frac{10}{|1+3|} =\frac52$$
Comment: I don't know why you added comment and then posted very similar answer to those already present.


Integrate $\int_0^{2 \pi} \frac{2}{\cos^{6}(x) + \sin^{6}(x)} dx$

Question: Integrate $$\int_0^{2 \pi} \frac{2}{\cos^{6}(x) + \sin^{6}(x)} dx$$
I have tried to do Tangent substitution, but there is huge power.
What method is better to use here?
Comment: You might start with $$1=(\cos^2x+\sin^2x)^3=\cos^6x+\sin^6x+3\sin^2x\cos^2x.$$ Then...
Comment: Just to clarify, by $cosx^6$ you mean $(\cos x)^6$ right?
Answer: $$
\begin{aligned}
\int_0^{2 \pi} \frac{2}{\cos^6 x + \sin^6 x} dx
&=8\int_0^{\frac{\pi}{2}} \frac{1}{\cos^6 x + \sin^6 x} dx\\
&=8\int_0^{\frac{\pi}{2}} \frac{1}{(\cos^2 x  + \sin^2 x)(\cos^4 x-\cos^2 x\sin^2 x+\sin^4 x)} dx\\
&=8\int_0^{\frac{\pi}{2}} \frac{1}{\cos^4 x-\cos^2 x\sin^2 x+\sin^4 x} dx\\
&=8\int_0^{\frac{\pi}{2}} \frac{1}{\cos^4 x}\frac{1}{1-\tan^2x+\tan^4 x} dx\\
&=8\int_0^{\frac{\pi}{2}} \frac{dx}{\cos^2 x}\frac{1}{\cos^2 x}\frac{1}{1-\tan^2x+\tan^4 x}\\
&=8\int_0^{\frac{\pi}{2}} d(\tan x)\left(1+\tan^2 x\right)\frac{1}{1-\tan^2x +\tan^4 x}\\
&=8\int_0^{+\infty} \frac{(1+t^2)}{1-t^2+t^4} dt\\
&=8\int_0^{+\infty} \left(\frac{1}{t^2}+1\right)\frac{1}{\frac{1}{t^2}-1+t^2} dt\\
&=8\int_0^{+\infty} \frac{d\left(t-\frac{1}{t}\right)}{\left(t-\frac{1}{t}\right)^2+1}\\
&=8\int_{-\infty}^{+\infty} \frac{ds}{s^2+1}\\
&=8\operatorname{arctan} s|_{-\infty}^{+\infty}\\
&=8\pi
\end{aligned}
$$
Comment: The third term is a repetition of the second, and there are two $dx$ in the 7th term. Otherwise, it's perfect! +1
Comment: @Nicolas fixed.
Answer: I suspect the OP did not intend for this, but let's go with the residue theorem.  Even if we make no simplification to the denominator, things end up pretty simple.  Note that, when $z=e^{i x}$,
$$\cos^6{x}+\sin^6{x} = \left (\frac{z+z^{-1}}{2} \right )^6 - \left (\frac{z-z^{-1}}{2} \right )^6 = \frac1{16} \left (3 z^4+10+3 z^{-4} \right )$$
As usual, sub $z=e^{i x}$ in the integral; then the integral is equal to
$$-i 16 \oint_{|z|=1} \frac{dz}{z} \frac2{3 z^4+10+3 z^{-4}} = -i 32 \oint_{|z|=1} dz \frac{z^3}{3 z^8+10 z^4+3}$$
The poles of the denominator occur inside the unit circle where $z_k^4=-1/3$.  By the residue theorem, the integral is equal to $i 2 \pi$ times the sum of the residues at these poles inside the unit circle, or
$$64 \pi \sum_{k=1}^4 \frac{z_k^3}{24 z_k^7+40 z_k^3} = 8 \pi \sum_{k=1}^4 \frac1{3 z_k^4+5} = 8 \pi (4) \left (\frac14 \right ) $$
Thus,

$$\int_0^{2 \pi} dx \frac{2}{\cos^6{x}+\sin^6{x}} = 8 \pi$$
Comment: Always a fan of the residues method.
Answer: HINT:
$$\cos^6x+\sin^6x=(\cos^2x)^3+(\sin^2x)^3=(\cos^2x+\sin^2x)^3-3\cos^2x\sin^2x(\cos^2x+\sin^2x)$$
$$=\dfrac{4-3\sin^22x}4=\dfrac{4(1+\cot^22x)-3}{4\csc^22x}$$
Set $\cot2x=u$
Comment: Haha I hope one day I will be able to find solutions to problems as beautifully and quickly as you do!


Magento EE and Go questions

Question: Magento (the company, part of eBay, etc) states provides support for EE and Go customers. From my experience as an ex-partener and from my customers experience, Magento support is not really keen on supporting you.
As an example: we worked alot with one of our customers to grow his business and went from Magento CE to Professional Edition and then upgraded to Enterprise.
Now, as a developer, if you try to do this process on a vanilla Magento, you will see that you encounter many issues with the upgrade scripts that are not working.
Content Staging and Merging doesn't work (database consistency issues) and Magento's official response was: your database doesn't look like it should after the upgrade process. Well, yes, but what are all those upgrade and install scrips for? Aren't those part of Magento? (end of large parenthesis)
Back to the main issue, Magento EE and Go questions:

I believe the customer/developer that asks a question should first open a case for Magento Support
We might end up encouraging Magento to keep the current support policy (because "it works") as developers are eager to show their Magento skills and help other developers/customers

What are your opinions?
Answer: I don't see the problem.
Most of us Magento partners are very familiar with the "support process" with Magento's core team - and I can well imagine those not in the know to be pursing better/faster answers from a 3rd party.
EE is a licensed product - but that shouldn't detract from the fact there are questions surrounding it - after all, Microsoft Windows is a licensed product and questions about that are not forbidden on other SE sites?

I believe the customer/developer that asks a question should first open a case for Magento Support

If this becomes policy. The first answer or comment on a question will be "Have you asked Magento yet" - which would cause useless clutter. Whether we work on the proviso the question has already been submitted to Magento, or not, it is irrelevant to a SE member electing to answer the question.

We might end up encouraging Magento to keep the current support policy (because "it works") as developers are eager to show their Magento skills and help other developers/customers

Magento aren't going to be dictated to by the community; the addition of a dedicated Magento SE site isn't going to change that.
Answer: We should discourage people from posting questions that can only apply to EE; however, the fact that someone with a question came across it on EE shouldn't require him to prove that it also applies to CE if it's not already obvious. In essence I think it's fine for people to post questions about EE as long as they:

Don't violate the ToS (for example, by posting proprietary code).
Are widely-enough defined as to be of use by CE users.

A good example of such a question might be something like How do I write an extension that can be used on both CE and EE? that contains examples of the extension code and references a troublesome overriding template that is difficult to handle generically for both EE and CE.

Magento EE and Go questions


Problemas com arquivos javascripts inseridos na Masterpage

Question: Não consigo utiliziar uma função javascript contida em um arquivo que está inserido em uma MasterPage. Onde posso estou errando?
Segue tag  da MasterPage

    <title></title>
    <link href="Content/css/bootstrap.css" rel="stylesheet" type="text/css"/>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

Answer: Acredito que o problema esteja na hierarquia dos seus arquivos, por exemplo:
--- Aplicacao/
    ---- Scripts/
    ---- Content/
    ---- MinhaPasta/
         ---- MinhaPaginaQueNaoFunciona.aspx
    ---- Site.Master

O que acontece é que quando você entra na MinhaPasta pra você acessar os arquivos da pasta Scripts não funciona o src="Scripts/jquery-2.1.4.min.js" porque ele interpreta como src="MinhaPasta/Scripts/jquery-2.1.4.min.js"
Pra resolver esse problema de diretórios você pode utilizar o .ResolveUrl, dessa forma:
<link href='<%= ResolveUrl("~/Content/css/bootstrap.css") %>' rel="stylesheet" type="text/css"/>

Comment: Perfeito! Só perdi o css. Mas eu voltei o antigo.


How many possible guesses?

Question:
A game show offers a contestant three prizes A, B and C, each of which is worth a whole number of dollars from $ 1$ to $ 9999$ inclusive. The contestant wins the prizes by correctly guessing the price of each prize in the order A, B, C. As a hint, the digits of the three prices are given. On a particular day, the digits given were $1, 1, 1, 1, 3, 3, 3$. Find the total number of possible guesses for all three prizes consistent with the hint.

This is a confusing problem, I think casework is required.
If Case 1:
$$A-4; B-2, 1; C-1, 2$$
So if $A$ has a 4digit value then $B$ has a $2$ or $1$ and $C$ has a $1$ or $2$.
$$1, 1, 1, 1, 3, 3, 3$$
But that would take way too long. I tried stars and bars.
But that gave me too low of an answer, so I am not sure where to turn next.
edit: I tried the casework didn't go too well.
I lined it up to:
$$\binom{7}{4} [\binom{3}{2} + \binom{3}{1}] 2 + \binom{7}{3}[\binom{4}{3} + \binom{4}{2} + \binom{4}{1}][3] + ... + \binom{7}{1}[...][5]$$
It have an overlarge answer.
What to do here?
HINTS ONLY PLEASE!
Answer: Not sure if hint, more like an advice: Thinking about it with numbers might make it more confusing than it really is. For example:

Your contestant is given 4 red balls and 3 green balls. He must organize them in 3 ordered stacks A,B,C. No less than 1 ball per group, and no more than 4. How many ways are there to distribute them?

You can easily pretend the given problem is this because with those numbers you'll never find a situation where a 4 digit number goes over your limit.
Comment: Nice idea, I'll try to do this now.
Comment: This has an awful smell of [Lah numbers](https://en.wikipedia.org/wiki/Lah_number)...
Answer: Hint: There are ${7 \choose 3}$ ways to order the digits, basically by choosing where the 3's go. Then you want to split the ordered digits into 3 contiguous groups (think stars and bars) such that each group has length at least 1, and you rule out the case where 2 groups have only length 1 (say, by brute force counting) because then you would have a group with 5 digits which isn't allowed.
Comment: I did this, but I got: $$120\binom{7}{3}$$ Which is ten times the actual answer?
Answer: Hint: First count the distinct orderings of the digits (e.g. 1331131). For each such ordering, count the number of ways to insert two commas (e.g. 1,331,131) at least one space but no more than 4 spaces apart.
Comment: Why doesn't order matter in this problem? $13$ isnt the same guess as $31$ right. Using $\binom{7}{3}$ this is the number of ways to order the numbers so that the order does NOT matter?
Comment: It's the number of orderings of the digits where all the 1's are indistinguishable and all the 3's are indistinguishable. If you had more than two different digits you'd use a multinomial coefficient (a MISSISSIPPI problem).
Comment: so,

$1331131$ is a different configuration from $1311331$? or the same?
Comment: Different! You will get different sequences of prices as well when you put in the commas.
Comment: This allows $11,11,333$ which presumably isn't legal. It also distinguishes between $113,311,3$ and $311,113,3$, and so on.
Comment: @vonbrand These are both legal. The prices don't need to be distinct, and order matters: you have to assign the right price to the right object.

How many possible guesses?


How do I create a commit without a parent in Git?

Question: I have a small project I was working on without any kind of version control software, and I ended up with three different versions of the same script, where each one does something slightly different from the others. I initialized a git repo with one of the versions, and I'd really like to commit each of the other two without parents. That way, I can merge the differences as though each of the three versions of the script were the tips of different branches.
I'm not even sure whether this is necessarily a sane or reasonable way to go about solving this problem... Any advice on how to do things this way, or advice on a better way to handle this situation would be much appreciated.
Comment: Why don't you create two branches and add the two other versions to them and then work on the branches?
Comment: This is called a *root commit*.
Comment: See: [how to insert a commit as the first, shifting all the others?](http://stackoverflow.com/questions/645450/git-how-to-insert-a-commit-as-the-first-shifting-all-the-others)
Answer: From my comment:

Why don't you create two branches and add the two other versions to them and then work on the branches?

Which I think would agree with ctcherry's answer as well.

But if you really do want to create a completely different "branch" that is unrelated to master, then you can do it with git checkout --orphan. The manual for git checkout describes to work of the option --orphan:

Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

You might use it like this:
git checkout --orphan version2
git rm -rf .
<add version2 script>
git add your files
git commit -m 'Initial commit for version 2'

If your Git is older than 1.7.2 (when git checkout --orphan was introduced), then you can use the alternate command sequence from "Creating New Empty Branches" in the Git Community Book:

Ocasionally, you may want to keep branches in your repository that do not share an ancestor with your normal code. Some examples of this might be generated documentation or something along those lines. If you want to create a new branch head that does not use your current codebase as a parent, you can create an empty branch like this:
git symbolic-ref HEAD refs/heads/newbranch
rm .git/index
git clean -fdx
<do work>
git add your files
git commit -m 'Initial commit'

Comment: +1 for explaining why the OP might want to rethink their strategy, but then answering the question anyway, instead of saying "Your approach is wrong" and leaving it at that.
Comment: +1 for mentioning `git checkout --orphan` - even if my git 1.7.1 does not support this yet. But it looks like [Ubuntu 11.04 will contain git 1.7.4](http://packages.ubuntu.com/natty/git), so I only have to wait for more two weeks.
Comment: After performing `git checkout`, you can also use `git reset --hard` to remove the staged files.
Answer: You can create a branch for each version of the script, and commit them to those individual branches. Then merge them one at a time back into master. That should have the effect you are looking for.
Answer: Why not start with an 'Empty' repo (e.g. a single readme of your problem statement above). Then you can branch the three times and add the different script versions into each of the branches, and commit them separately.
You can then branch/edit/commit/merge and try out all you options in a well managed way.


Subclass __init__ is not called if superclass __new__ is defined

Question: See the following ipython session:
$ ipython --no-banner

In [1]: class foo(object):
   ...:     def __new__(self, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return self
   ...:
   ...: class bar(foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [2]: b = bar()
in superclass __new__

In [3]: b.val
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-c55d38c9d4d9> in <module>()
----> 1 b.val

AttributeError: type object 'bar' has no attribute 'val'

What is going on here? Why does defining __new__ in foo prevent the __init__ from running in bar?
Comment: https://docs.python.org/3/reference/datamodel.html#object.__new__ "If `__new__()` does not return an instance of *cls*, then the new instance's `__init__()` method will not be invoked."
Comment: Just a conceptual misconception: `__new__` doesn't take a `self`, because `self` doesnt exist at this point. `self` is what's going to be returned by `__new__`, which will then be passed on to `__init__` for initialization
Comment: `__new__` is special-cased to be a class method without having to decorate it as such. The first argument (conventionally) should be `cls`, because `foo.__new__` gets `foo` as its first argument, not an instance of `foo`.
Answer: You are returning an invalid value from __new__.  Quoting the documentation:

If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked ... If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.

Note that the first argument to __new__ is a class, not an object. __new__'s job is to allocate the object, often by calling super().__new__.
Try this:
class foo(object):
    def __new__(cls, *args, **kwargs):
        print 'in superclass __new__'
        return super(foo, cls).__new__(cls, *args, **kwargs)

class bar(foo):
    def __init__(self, *args, **kwargs):
        print 'in subclass __init__'
        self.val = 42

b = bar()
print b

Answer: From the datamodel documentation:

If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.

So, try again like this:
class foo(object):
    def __new__(cls, *args, **kwargs):
        print 'in superclass __new__'
        return super(foo, cls).__new__(cls, *args, **kwargs)

class bar(foo):
    def __init__(self, *args, **kwargs):
        print 'in subclass __init__'
        self.val = 42

Answer: Your __new__ function signature implies you don't quite understand what is going on. The first argument to __new__ will be the class, calling it self which is conventionally used for the instance should be a warning: __new__ is a constructor, the instance doesn't exist yet. So what happens is you are returning an object that isn't the same type as the class, (it is the class in fact, so it is of type type) thus, __init__ is skipped! You want something like this:
In [4]: class Foo(object):
   ...:     def __new__(cls, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return super(Foo, cls).__new__(cls, *args, **kwargs)
   ...:
   ...: class Bar(Foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [5]: b = Bar()
in superclass __new__
in subclass __init__


grouping nodes with collapsible fieldset

Question: I use entityreference to link nodes to other nodes and field_group to display collapsible fieldsets with fields.
Assume I have node#1 which has a field related_nodes containing node#2, node#3 and node#4.
The display of this node looks like this:
node title

node body

related:
- node#2
- node#3
- node#4

I can use hook_node_view to remove nodes from the related_nodes field on the fly using something like:
unset($node->content['field_info_case_law_references']['#items'][?]);

I want to remove all those nodes (e.g based on their title) and place them in groups, each in a collapsible fieldset within that related: field. so it ends up looking something like this:
node title

node body

related:
+ starting with A (collapsible fieldset)
  - node#2
+ starting with B (collapsible fieldset)
  - node#3
  - node#4

The default collapsible behaviour, html and styling of that I can configure from admin/structure/types/manage/*/display is good enough.
Where should I look at?
Answer: OK I found it.
In the HOOK_node_view I can do:
if ($node->type=='CONTENT_TYPE') {

  // clone from a fieldset nearby
  $node->content['#fieldgroups']['group_FOO']=clone $node->content['#fieldgroups']['group_ORIG'];

  // modify fieldset
  $node->content['#fieldgroups']['group_FOO']->label="xxxxxxxxxxxxxxxxxxxxxxxx";
  $node->content['#fieldgroups']['group_FOO']->weight=-1;
  $node->content['#fieldgroups']['group_FOO']->identifier=...
  $node->content['#fieldgroups']['group_FOO']->group_name=...

  // clone from a field nearby
  $node->content['field_FOO'] = $node->content['field_ORIG'];

  // modify field
  unset($node->content['field_FOO']['#items'][0]);
  unset($node->content['field_FOO']['#items'][1]);
  unset($node->content['field_FOO']['#items'][2]);

  // position fieldset and field
  $node->content['#group_children']['group_FOO'] = 'group_ORIG';
  $node->content['#group_children']['field_FOO'] = 'group_FOO';

}


Como fazer dump automático no MySQL?

Question: Tenho um sistema simples pra gerenciamento de uma loja que por enquanto, na fase de testes, está rodando com servidor local.
Queria saber uma forma de fazer o dump da base de dados do MySQL automaticamente no mesmo horário todos os dias (por exemplo: final de tarde) utilizando PHP ou outra sugestão.
Comment: Veja se isso pode te ajudar https://sourceforge.net/projects/automysqlbackup/ ou isto https://www.noupe.com/development/10-ways-to-automatically-manually-backup-mysql-database.html
Answer: Olá.
Primeiramente, vai depender do ambiente em que a base de dados esteja.
Se for em um Windows, você pode programar um .bat e agendar sua execução no Agendador de Tarefas. Assim você pode determinar quais os horários que ele será executado. E caso seja em um Linux, a saída é criar um script e agendar a sua execução no crontab. Tanto o Agendador do Windows, quanto o Crontab do Linux, basicamente possuem a mesma funcionalidade. Se sua intenção é utilizar uma linguagem, python é muito interessante e pode te atender muito bem. Mas isso fica a seu critério :)
Lembrando que para ambos os sistemas, o MySQL dispõe de ferramentas para realizar o dump.
Agora deixando de lado a questão do script e do S.O., um fato importante é que você deve pensar muito bem em como irá desenvolver esse código. Um exemplo bem bacana é você programar dois ou três dumps diários, com horários "estratégicos", por exemplo, um no início do dia, outro ao meio dia e o último no fim do dia. Além disso, é importante manter essas cópias por um determinado tempo. Ex: (i) guardar a última cópia do mês de todos os meses, (ii) a última cópia da semana e (iii) as cópias de todos os dias da semana, apagando-as apenas na troca da semana.
Para finalizar, vejo que apesar das cópias, algo muito importante é manter essas cópias replicadas em outro meio, seja um HD externo, uma máquina da rede ou um servidor FTP. Outro fato, é programar uma rotina para validar se as cópias estão íntegras, além é claro, de verificar se elas estão sendo executadas, ou se o arquivo está sendo criado (no linux pode acontecer alguns problemas com permissão de pastas).
Este é um assunto que pode render muito, pouco ou nenhum trabalho, tudo depende da sua preocupação com a segurança dos dados do seu cliente! Comece com algo pequeno, mas procure sempre dar atenção a esse assunto. O Backup só é lembrado quando precisamos dele.

Como fazer dump automático no MySQL?