.NET Regex taking long time to find the match

Question: Why this innocent looking regex is killing my requests?
([\d\w-]+.){6}hi

Is this candidate for catastrophic backtracking?
Running this on .NET framework 4.5.2, C#
Comment: Yes, [it might](https://regex101.com/r/juz7Ap/1), what should your `.` match? If a literal dot, escape it.
Comment: Thanks @WiktorStribiżew, got the issue with the regex. should have escaped the dot.
Answer: To match a literal dot, you must escape it.  If you do not, a quantified group ([\d\w-]+.){6} will lead to a catastrophic backtracking with longer inputs. Change to ([\w-]+\.){6}hi.
Note that [\d\w-]+ matches 1 or more (unknown number) letters, digits, _ or -. A . matches any char. When you apply a quantifier, the regex engine tries all possible ways to match a string before it fails. It is usually not a problem with a string where a match is found, it usually happens with strings where the match cannot be found since all possible ways are tried then (until the engine reports a crash).
Besides, the \d pattern matches digits, and \w matches digits, too, so there is no point using both inside a character class.
Comment: I was not aware that `\w` matches digits too. +1 for this.


Lambda Expression for Query to select different values based on condition

Question: I am working with lambda expression in c#. I am trying to select a value based on type and then the resultant is summed.
var  length = (from al in tmp
                from n in al
                 where n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2"
                 select n.trippath.length).sum();

this works fine  but my issue is i need to set vales for other types to a defalute value 0 before it is summed, similar to
   List<double> ActualLength = new List<double>();

   if( n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2")
       ActualLength.Add(n.trippath.length)
   else
       ActualLength.Add(0);

   return ActualLength.sum();

Comment: Why do you need to set it to 0? If the where filters them, they are excluded from the select and not included in the sum. This would have the same effect as setting it to 0.
Comment: Please tag your question with the language or tool it's about. Nobody that knows C# and is looking at the C# tag would know this question existed.
Comment: Pieter is right. The additional point is that `Enumerable.Empty().Sum()` or similar is `0`. These 2 points make the additional filter redundant.
Answer: If I understand correctly, you want something like this:
var projection =
    tmp.SelectMany(x => x)
       .Select(x => {
           if(x.TripPath.DataType == "type1" || x.TripPath.DataType == "type2") {
               return new { Item = x, Length = x.TripPath.Length };
           }
           else {
               return new { Item = x, Length = 0 };
           }
       });

Then you can say
int length = projection.Sum(x => x.Length);

That is how you can accomplish what it seems like you are trying to do (project each item matching a predicate to its length and otherwise project it to zero).
However, your usage looks like you aren't even using the projections. In which case, you can get away with
return tmp.SelectMany(x => x)
          .Where(x =>
              x.TripPath.DataType == "type1" ||
              x.TripPath.DataType == "type2"
          )
          .Sum(x => x.TripPath.Length);

Items that don't match the predicate don't hit the sequence that is summed over and therefore they don't contribute anything to the sum.
Answer: You can use ternary condition like that:
List<double> ActualLength = new List<double>();
var TotalActualLength =  ActualLength.sum(n=> n.TripPath.DataType =="type1" || n.tripPath.DataType == "Type2" ? n.trippath.length : 0);

Answer: Take a look at the OfType extension method.  You can then project into an anonymous type to assign a default value and .Sum off this.


Calculation of the center of a circle given two points and one tangential angle?

Question: Suppose a circle in a 2 dimensional plane, given two points on the circle, i.e. $(x, y)^T, (x', y')^T$ and the angle between the tangle line at $(x, y)^T$ and horizontal axis is $\theta$. We have the coordinates of the center of the circle as follows
$\begin{pmatrix}x_c \\ y_c\end{pmatrix} = \begin{pmatrix}\frac{x + x'}{2} + \frac{1}{2}\frac{(x-x')\cos(\theta)+(y-y')\sin(\theta)}{(y-y')\cos(\theta)-(x-x')\sin(\theta)}(y - y') \\ \frac{y + y'}{2} + \frac{1}{2}\frac{(x-x')\cos(\theta)+(y-y')\sin(\theta)}{(y-y')\cos(\theta)-(x-x')\sin(\theta)}(x' - x)\end{pmatrix}$
How to derive this formula ? The only hint that "this results from the center of circle lies on a ray that lie on the half-way point between $(x, y)^T$ and $(x', y')^T$ and is orthogonal to the line between these coordinates. "
Answer: ![https://i.stack.imgur.com/A7oHL.jpg][1]
[1]:
From the diagram, $$\frac ap=\tan(\theta-\alpha)=\frac{\sin\theta\cos\alpha-\cos\theta\sin\alpha}{\cos\theta\cos\alpha+\sin\theta\sin\alpha}$$
Furthermore, $$a\cos\alpha=\frac 12(x-x')$$ and $$a\sin\alpha=\frac 12(y-y')$$
Hence $$p=a\frac{(x-x')\cos\theta+(y-y')\sin\theta}{(x-x')\sin\theta-(y-y')\cos\theta}$$
Now $$\overrightarrow {MC}=\left(\begin{matrix}-p\sin\alpha\\p\cos\alpha\end{matrix}\right)$$
And $$ \overrightarrow {OM}=\left(\begin{matrix}\frac 12(x+x')\\\frac 12(y+y')\end{matrix}\right)$$
From which the result follows immediately.
Answer: Are you sure this formula is correct? it should have symmetry in $x$ and $y$, so the first term in the $y_c$ term should involve $y$ values.
Testing $(x,y)=(2,0)$ and $(x',y')=(0,0)$ doesn't give the right answer....
Comment: Sorry, I had a typo there. The formula is revised.
Answer: I can get this formula but only if the bracket at the end of the expression for the $x_c$ coordinate is $(y'-y)$ rather than the way you have given it. is your formula correct?
Comment: Yes, the formula is correct. Do you use the parametric form of the line to express it ?
Comment: Hmm I will have to check my working. I just used trigonometry. If I het a chance I will post a solution soon.


mod rewrite +d error

Question: I'm using this .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_URI} .(html|php)$ [OR]
RewriteCond -d
RewriteRule (.*) /index.php?s=$1 [L,QSA]

And if i try to access a site afflected by the rule i get an 500 Server Error.
My logs say:

[Fri Dec 17 13:40:43 2010] [alert] [client 127.0.0.1] C:/xampp/htdocs/.htaccess: RewriteCond: bad argument line '-d'

If i access something like that:

http://localhost/icon/help.png

There is no problem
Can someone help me please?
Comment: RewriteCond needs two parameters
Answer: The RewriteCond needs to look like this:
RewriteCond %{REQUEST_FILENAME} !-d

Comment: Now i get:
[Fri Dec 17 13:46:41 2010] [error] [client 127.0.0.1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
Comment: @Philipp that is because you've built an infinite loop: index.php gets redirected too. If you want to rewrite URLs for files that don't exist, use `-f` instead of `-d`
Comment: @Philipp `-d` = is existing directory `-f` = is existing file `-s` = is existing symbolic link
Comment: well if i use -f i get
[Fri Dec 17 13:52:04 2010] [alert] [client 127.0.0.1] C:/xampp/htdocs/.htaccess: RewriteCond: bad argument line '-f' :x  i want to forward files with .html and .php and folders eg www.example.com/folder => www.example.com/index.php?s=folder
Comment: @Philipp show the entire line you are using. You are using `REQUEST_FILENAME`, right?
Comment: oh sorry, did that syntax error again^^ i get
[Fri Dec 17 13:56:03 2010] [error] [client 127.0.0.1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace. again with -f
Comment: @Philipp ahh quatsch. You need to use `!-f` of course to negate the condition. My fault, didn't notice that
Comment: @Philipp try prepending `!`, see my comment above
Comment: get that error again ): [Fri Dec 17 14:00:02 2010] [error] [client 127.0.0.1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
i updated my pastebin file!
Comment: @Philip index.php exists? Can you remove the `[OR]`? I don't think it's needed
Comment: yap its here. i removed [OR] now its okay :D THANK YOU but what does [OR] mean? : x
Comment: No problem. Well, OR means OR :) It applied the condition when the extension was php / html OR when the requested file didn't exist. Which had to cause an endless loop for index.php
Comment: now the .htaccess doesnt affect directorys :x http://localhost/index doesn't foreward
Comment: @Philipp yeah, that's what the rule says - it applies only to php and html files. If you want it to apply to *all* file types, remove the first condition and add a line containing `!-d`
Comment: but it only should foreward .php, .html and folders :D i dont want the images to be affected.
Comment: @Philipp then you'll need to expand the file type regex to match URLs with no dots in them. I'm not regex literate enough to write that out without experimenting, but you can ask a new question, should be easy enough to answer
Comment: @Pekka `-l` is a symlink, `-s` is the same as `-f` where the file is not 0 bytes.

mod rewrite +d error


What's wrong with my for loop?

Question: I am making a game using lite-C (exactly same syntax as C). and I cannot make this loop work.
It gives me an error at this line at compilation.

for(int i = 0; i < (cantenemigu * 3); i += 3)

I have an array with the information of where to create the enemies.
the array contains the x,y,z coordinates.
cantenemigu is the amount of enemies that there are in the array.
With this loop I would get the information of each enemy and create it.
[EDIT]
The answers didn't work. I added the ; acsidently while writing the post.
Maybe the problem is somewhere else;
Here is the hole part.
int cantenemigu = 3;
var posenemigu[] = {-900, 550, -10, -1100, 1600, -10, 70, 1680, 20};
void load_enemigunan()
{
 for(int i = 0; i < (cantenemigu * 3); i += 3)
 {
  ent_create("targetr.mdl",vector(posenemigu[i],
             posenemigu[i + 1],
             posenemigu[i + 2]),NULL);
 }
}

This is the code if I don't add the

I solved it.
this worked.
int i
for(i = 0; i < 3*cantenemigu; i += 3)
{
    ent_create("targetr.mdl",vector(posenemigu[i],
                                                posenemigu[i + 1],
                                                posenemigu[i + 2]),NULL);
}

In C# it doesn't have be declared before. I assumed it was also so in C. (or maybe it's a bug in the compiler).
Comment: May I ask what the error message was?
Comment: What exactly is the error? Mind pasting it here?
Comment: @ChaosPandion The compiler gave a syntax error. Sorry I forgot to write it?
Comment: the  is he code isn't in. Some times I use html to format the queastions
Comment: Could you edit the post to 1) make the code match exactly what's in your program (you say the semi-colons are accidental but they're still there, and there's a  for some reason), 2) include the compiler's error message?
Comment: @Aaron de Windt: RE: EDIT: You still have that semicolon there. Are you sure that's not the problem? Don't use html to format your code.
Comment: @Aaron: can you at least edit your question so the source matches what you're trying to compile? And then write a less shitty title?
Comment: wrap your code in a [code] block please...unless...your source code was all on one line??
Comment: it is in a code block. I don't know what is happening with the code.
Comment: It could be a typedef.  It's really impossible to say exactly what the problem is without more information.
Comment: @Mark. It can hold numbers with decimals. The coordinates must be a var
Comment: It only sais syntax error at that line. nothing more.
Comment: can you show us the declaration for `ent_create`?
Comment: ent_create(STRING* filename, VECTOR* position, function);
Comment: And the declaration of vector?
Comment: Which line does the syntax error appear on? What's the return type of vector()?
Answer: for (int i = 0; i < (cantenemigu * 3); i += 3)
There should not be any ; after i += 3.
Answer: Get rid of the 3rd ;.
for(int i = 0; i < (cantenemigu * 3); i += 3)

Answer: Try changing your code to this: (note what I've done is move the declaration of i outside the for loop.
int cantenemigu = 3;
var posenemigu[] = {-900, 550, -10, -1100, 1600, -10, 70, 1680, 20};
void load_enemigunan(){
    int i;
    for(i = 0; i < (cantenemigu * 3); i += 3){
         ent_create("targetr.mdl",vector(posenemigu[i],
             posenemigu[i + 1],
             posenemigu[i + 2]),NULL);
     }
}

Comment: You posted it just 5 min to late. This solved the problem. Is it a compiler bug?
Comment: @Aaron, no, this isn't a compiler bug, it's standard C syntax (not C99 syntax which would allow what you originally wrote). FWIW, if this solved the problem the etiquette here is to accept the answer.
Comment: yes I know. sorry. I don't talk english. sorry if it sounded bad. thanks for the answer. Wath I wanted to say is that I just solved it the same way.
Comment: C99 is standard C. It's just that many implementations don't conform to modern standards.
Comment: @R what I meant was it was C90, as opposed to C99...what gcc, for instance will call just plain "C".
Answer: It looks like you are missing a closing parenthesis for your call to vector.
ent_create(
    "targetr.mdl",
    vector(
        posenemigu[i],
        posenemigu[i + 1],
        posenemigu[i + 2],
        NULL
);

Comment: @Aaron - Please post the exact error the compiler is giving you.
Answer: for(int i = 0; i < (cantenemigu * 3); i += 3;)

What is the error? That last semicolon shouldn't be there.
What is the body of the loop?
What type of variable is cantenemigu? Can it be coerced to int?
Comment: I really hope `cantenemigu` is a domain specific term because it looks like gibberish to me.
Comment: @ChaosPandion I speak papiamentu. It stands for cantidad di enemigu (amount of enemies).

What's wrong with my for loop?


Javascript || não exibir um bloco dependendo do valor de um array

Question: Boa tarde amigos!
Deixe-me explicar melhor o meu caso. No código que coloco em anexo, temos 6 inputs. A ideia é que o bloco
NEXT 60 ESPORTE
 não pode ser exibido se o valor de uma dessas 6 inputs for maior que 65. Vejam o código abaixo:

const noSport = ()=> {
                let sportPlan = document.querySelectorAll('.nome-plano');
                if(sportPlan = "NEXT 60 ESPORTE") {
                    sportPlan.style.display = "none";
                }
            }

            document.addEventListener("DOMContentLoaded", ()=> {
                let paxAge = document.querySelectorAll(".idade-viajantes");
                for (i=0;i<paxAge.length;i++){
                    let paxAgeValue = paxAge[i].value;
                    let paxAgeNumber = parseInt(paxAgeValue);
                    if(paxAgeNumber[i]>65) {
                        noSport();
                    }
                }
            });
Preencha abaixo a idade dos viajantes na data da viagem
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="66">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">

NEXT 15

R$52

NEXT 60 ESPORTE

R$52

Eu fiz um laço passando por cada uma das inputs e transformando seus valores de string para inteiros.
Minha ideia é que se um dos campos for um numero inteiro maior que 65 nós executamos a função noSport() que deve mudar o style do elemento para display: none;.
Porém não roda, e o console do browser não está me dando erro... Tentei também executar a função noSport como anonima mesmo aberto dentro do desvio condicional, mas não rodou também.
Em que estou pecando? deveria fazer um outro laço para verificar os valores individuais do array se são maior que 65? a forma como eu estou montando a função noSport está errada? Uma biblioteca como jQuery me ajudaria neste caso?
Se alguém puder me dar um força agradeço!
Answer: Note que no seu código, o if está sendo feito como se paxAgeNumber fosse um array (utilizando o [i] para acessar um elemento), quando na verdade, na linha de cima, a variável é iniciada com um valor inteiro.
Portanto, o código deverá ser o seguinte:
if(paxAgeNumber>65) {
    noSport();
}

Answer: Possíveis erros:
DOMContentLoaded pode não estar sendo disparado pois o DOM já foi carregado quando o JavaScript rodar.
Solução: verifique se a página já está carregada, e se não, adicione o event listener:
if (document.readyState === 'complete') start();
else document.addEventListener('DOMContentLoaded', start);

paxAgeNumber é uma valor, não um array, não faz sentido acessar a posição i para compara-lo, penas compare o próprio paxAgeNumber:
if(paxAgeNumber[i] > 65) {
    noSport();
}

sportPlan é um array, no if você o trata como uma única variável. Não apenas isso, mas você atribui o valor 'NEXT 60 ESPORTE' para esse array ao invés de fazer uma comparação.
Minha sugestão:

function noSport () {
  let sportPlan = document.getElementById('next60esportes');
  sportPlan.style.display = 'none';
}

function start() {
  let paxAges = document.getElementsByClassName('idade-viajantes');

  for (let paxAge of paxAges) {
    let paxAgeValue = paxAge.value;
    let paxAgeNumber = parseInt(paxAgeValue);

    if (paxAgeNumber > 65) {
      noSport();
      break;
    }

  }
}

if (document.readyState === 'complete') start();
else document.addEventListener('DOMContentLoaded', start);
Preencha abaixo a idade dos viajantes na data da viagem
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="66">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">
            <input name="idade" maxlength="2" class="idade-viajantes only-number" type="text" value="">

NEXT 15

R$52

NEXT 60 ESPORTE

R$52


Integral of the usual mollifier function: finding its necessary constant

Question: Context: I'm going through some notes on $L^p$ and Sobolev spaces, and - in a portion on approximating $L^p$ via $C^\infty$ - I came across the notion of a mollifier function. The standard example seems to be the function $\eta \in C^\infty(\Bbb R^n)$ given by
$$\eta(x) = \begin{cases}
\displaystyle c_n \exp \left( \frac{1}{|x|^2 - 1} \right) & |x| < 1 \\
0 & \text{otherwise}
\end{cases}$$
where $c_n \in \Bbb R_{>0}$ is a constant (presumably dependent on the dimension of $\Bbb R^n$) which ensures normalization, i.e.
$$\int_{\Bbb R^n} \eta = 1$$
Now, in some past MSE posts (e.g. here, here), people have asked my question of concern already: "what is this normalization constant precisely?" However, their primary concern seems to have been simply with "how do I verify that, indeed, $\int_{\Bbb R^n} \eta = 1$?" -- which is quite simply the definition of the constant, and is not what I'm concerned with.

The Question: My concern is simply one of curiosity: is there some nice closed form for the mollification constants for $\eta$ as given above? Not in the sense of "I need this for some application of the theory" -- indeed, I have no real reason to suspect one even exists, and I recognize no one really uses the actual value anyways -- but rather I'm just examining this as an interesting integral problem.
Clearly, we can write these in terms of the unit $n$-dimensional ball,
$$c_n = \frac{1}{\displaystyle \int_{B(0;1)} \exp \left( \frac{1}{|x|^2 - 1} \right) \, \mathrm{d}x}$$
but from there I'm stuck. Of course, $c_1$ is slightly easier to manage in that, through evenness,
$$c_1 = \frac{1}{2\displaystyle \int_{0}^1 \exp \left( \frac{1}{x^2 - 1} \right) \, \mathrm{d}x}$$
but that doesn't get us any further.
A couple of approximations, for what it's worth:

$c_1 \approx 2.25228$
$c_2 \approx 2.14357$

Really struggle with getting Wolfram to do much else for me, to be honest. Multidimensional integrals and series are not my forte.
Any thoughts would be appreciated!
Comment: For general $n$ you can always reduce to an integral on $(0,1)$ using radial symmetry - at least this way wolfram should be able to approximate specific values numerically.
Comment: I'm finding that $c_3\approx 2.267, c_4 \approx 2.611, c_5\approx 3.2305, c_6\approx 4.262$. Julia ran out of memory on my computer to calculate $c_7$.
Answer: With $|\cdot|_p$ the $\ell^p$-norm on $\mathbb{R}^n$, and "good enough" $f:\mathbb{R}_+\to\mathbb{R}$, we have $$\int_{\mathbb{R}^n}f(|x|_p)\,dx=K_{n,p}\int_0^\infty nr^{n-1}f(r)\,dr,\quad K_{n,p}:=\frac{\big[2\Gamma(1+1/p)\big]^n}{\Gamma(1+n/p)}$$ (see e.g. this answer of mine). Now we may consider, more generally, $$\frac1{c_{n,p,q}}:=\int_{\substack{x\in\mathbb{R}^n\\|x|_p<1}}\exp\frac1{|x|_p^q-1}\,dx=K_{n,p}I_{n,q}\qquad(p,q>0)$$ (so that $c_n=c_{n,2,2}$) where, after $r=(1-t^{-1})^{1/q}$ and integration by parts, $$I_{n,q}:=\int_0^1 nr^{n-1}\exp\frac1{r^q-1}\,dr=\int_1^\infty(1-t^{-1})^{n/q}e^{-t}\,dt.$$ Thus, using Tricomi's confluent hypergeometric function $U$, $$I_{n,q}=e^{-1}\Gamma(1+n/q)U(1+n/q,2,1).$$

The case $[p={}]q=2$ (as in the question) results in expressions using the exponential integral $E_1(z)=\int_z^\infty\frac{e^{-t}}{t}\,dt$ (if $n$ is even) or the modified Bessel functions $K_0(z),K_1(z)$ (if $n$ is odd).
Specifically, the result is as follows. Let \begin{align*}X_0&=(1,0),&X_1&=(1,1),&X_{n+1}&=\frac{2n+1}{n}X_n-X_{n-1}\\Y_0&=(1,-1),&Y_1&=(1,1),&Y_{n+1}&=\frac{4n}{2n-1}Y_n-Y_{n-1}\end{align*} so that $X_n=(A_n,B_n)$ and $Y_n=(C_n,D_n)$; then $$I_{2n,2}=A_n e^{-1}-B_n E_1(1),\quad I_{2n-1,2}=\frac{C_n K_1(1/2)-D_n K_0(1/2)}{2e^{1/2}}.$$
Note that oeis.org has $(n-1)!A_n=\texttt{A321942}$ and $(n-1)!B_n=\texttt{A000262}$ listed.
Comment: Simply impressive!
Comment: @metamorphy In his book *Topological Vector Spaces, Distributions and Kernels* (1967), Francois Treves defines $\eta$ as above and then presents the function $\eta_\epsilon(x)=\epsilon^{-n}\hspace{0.08cm}\eta(\frac{x}{\epsilon}), \epsilon>0, n\in\mathbb{N}$. He prompts the reader to observe that $\eta_\epsilon(0)=\epsilon^{-n}$. This suggests to me that $c_{n,2,2}=e^{-1}$, but I've found that rather hard to "observe". I've found it hard to work through your answer above for $p=q=2$, but it doesn't seem that simple. I would appreciate your thoughts on this.
Comment: Sorry, that should be "This suggests to me that $c_{n,2,2}=e$".
Comment: @MarkoStojovic: Not following. The answer gives the value of $c_{n,2,2}$ (and it is **not** $e$). Particularly $$c_{2,2,2}=\frac1{\pi\big(e^{-1}-E_1(1)\big)}.$$
Comment: I understand - we've all got limited time. That still helps.


Bass - Is it broken!

Question: I've just bought a second hand Squier bass. When it arrived I immediately restringed it and that was when I noticed that the action was extremely high - Almost half an inch!
I adjusted the saddles to see if that'd make any difference. It did but not enough. I then decided to adjust the truss rod. This also didn't make a difference and I'm not sure if the truss rod is broken? It felt very forced turning clockwise however when I moved it back moved with no force whatsoever, as if it was just spinning.
I've played guitar for years and I've never had any issues like this but honestly I have no idea what I'm doing! The action of the strings is highest towards the middle of the neck?
At first I thought the bass was supposed to have a really high action but after checking with friends who play bass this is not the case.
Comment: You admit you don't know what you're doing. We can't make you a guitar or bass tech just by writing some words on the Internet. You'll probably have to take the bass to a tech to get it set up properly. From what you've written it seems unlikely that a little online advice will help you set it up yourself. It's just not that simple a process.
Comment: If you bought this instrument from a dealer you should see about returning it as defective. An instrument shouldn't be sold with an extremely bowed neck and excessively high action.
Comment: Does the neck look very curved?   (This is best answered with photos).  The truss rod only changes action as a side effect, its purpose is to adjust relief, i.e. how curved the neck is.
Comment: Just out of curiosity: what was the action like before you restrung it? You didn't even play it once before restringing?
Answer: There's high and then there's HIGH, and by this sounds like the bad kind.
If you fret at the first and last fret, there should be slight room between the frets and strings at around the 10th to 12th fret. If there's a lot of room, then the neck is too bowed. When you tighten the truss rod, it should straighten out, but this is make a quarter turn, stop of there's too much resistance, and let it sit for some time before you turn again. If you can't turn it, or turning it makes no difference, see your local repair shop.
Once the neck is straight, if the action is still high, then you adjust the saddles. You then need to do intonation and pickup height, but that's gonna need to happen anyway.
There's a chance that you will still be unable to get the action low enough, and here you would shim the neck, which will adjust the neck angle to where it's good. A thin piece of wood, maybe the size of a business card, would be enough to get the neck angle back to good. I did this with my Tele years ago and got that action way down.
Without seeing and handling the guitar, I don't think I can fully diagnose your problem, but this is about all you can do without making sawdust from your bass.
Good luck.
Answer: Questions -
Why did you re-string it?
Did you notice the action was awful before?
Did you use the same gauge strings?
Is it tuned properly (I've known people tune up an octave, and no, the strings didn't break).
Have you tried adjusting the trussrod with the strings slackened off?
Have you contacted the seller again?
Have you shown it to someone who knows what they're doing?
Have you sighted along the neck with slack and tuned strings?
Comment: All excellent questions.  @ashjm - if you answer these questions in comments, we can provide much better help.
Answer:
measure "relief," which is the curvature of the neck.  From the Fender shop manual:

The factory specification for appropriate neck
relief for Fender® bass guitars is between . 012" and . 014", measured
between the bottom of the string and the top of the fret, at the 7th
fret. 4-string bass, depress the "E" string at the last fret with one
hand.

You can get feeler gauges at any auto parts shop or hardware
store to measure this. While the manual doesn't say this, it's
generally best to put a capo at the first fret when measuring, in case
nut height is wrong.

Make a SMALL adjustment of the truss nut.  This nut should NOT be loose; if it is, tighten it until you get firm resistance, turn one half-turn more, and then measure relief again.  If it's already firm, turn a half-turn and measure again.  Repeat until either this feels too tight (like you're going to break something) or you can measure the change in relief.  Important: after each adjustment, let the bass sit for a day!  If it gets so tight it feels like you're going to break something, then back it off a whole turn or two, and take the bass to a shop.

Once you're in the ballpark, only adjust the truss rod by about 1/4 turn at a time, and give it a day to react.  Measure and adjust again.

Once you have the relief in the right general area, check the action and try adjusting the saddles.  If this works, great; you're done.  If not, continue.

Check the nut height.  This is pretty obvious: use the feeler gauge at the first fret.  Google for what this should be on a Fender bass.  As a general rule, though, it should be close to the difference between first and second fret, and so on.  At most, about twice as much.

If everything else is reasonable but you're still out of range of saddle adjustment, then the neck needs to be reset.  The good news is that Fender basses have bolt-on necks, so this is possible.  I would get a luthier to do it, but if you're at all handy with woodwork you might be able to do it yourself, by adding a shim.  (It's also possible to re-file the neck, but I'd avoid that without expert advice, since you can't undo a mistake.)  Use the hardest wood you can find for a shim.  It'll need to be very thin with a very small angle so you'd need access to a good shop to make one, but perhaps you can find something that works.  For the most part, this won't damage anything so you can experiment without too much worry.  But I'd take it to a luthier.

Bass - Is it broken!


The sum of Fibonacci numbers $F_{4k}$

Question: Consider the sum,
$$\sum_{k=0}^n F_{4k}$$
I would like to find this sum,
$F_n$ being the $n$-th Fibonacci number.
Answer: My Solution:
Since:
$$
F_{n}=\frac{1}{\sqrt{5}}\left(\frac{1+\sqrt{5}}{2}\right)^{n}-\frac{1}{\sqrt{5}}\left(\frac{1-\sqrt{5}}{2}\right)^{n},
$$
(Please refer to Fibonacci number - Wikipedia)
we have:
$$
F_{4k}=\frac{1}{\sqrt{5}}\left(\frac{1+\sqrt{5}}{2}\right)^{4k}-\frac{1}{\sqrt{5}}\left(\frac{1-\sqrt{5}}{2}\right)^{4k}.
$$
Let $a=\left(\frac{1+\sqrt{5}}{2}\right)^{4}$ and $b=\left(\frac{1-\sqrt{5}}{2}\right)^{4}$, then:
$$
F_{4k}=\frac{1}{\sqrt{5}}(a^k-b^k),
$$
and
$$
\begin{align}
\sum_{k=0}^n{F_{4k}}=&\sum_{k=0}^n{\frac{1}{\sqrt{5}}\left( a^k-b^k \right)}\\
=&\frac{1}{\sqrt{5}}\left[ \left( \sum_{k=0}^n{a^k} \right) -\left( \sum_{k=0}^n{b^k} \right) \right]\\
=&\frac{1}{\sqrt{5}}\left( \frac{1-a^{n+1}}{1-a}-\frac{1-b^{n+1}}{1-b} \right).
\end{align}
$$
P.S.
I wanted to subtitute $a$ and $b$ with their original value, and simplify the formula, but I found the form may be complicated and not simpler than the original result.
(Please refer to My Attempt based on WolframAlpha.)
Comment: There _may_ still be a simplification out there. Consider, for instance, that $\sum_{k = 0}^n F_k$ may be calculated exactly the same way (using $a$ and $b$ without fourth powers), and getting the exact same result, but it is also equal to $F_{n+2}-1$. And $\sum_{k = 0}^n F_{2k}$ has a similarly simple closed form. It would be fun if $\sum_{k = 0}^n F_{4k}$ could also have a nicer form. But if it turns out that it doesn't simplify, _proving_ that it doesn't simplify seems daunting.
Comment: I figured out the F(k) one by the fact that F(k)=F((k+1)+1)-F(k+1)
I figured out the F(2k) one by the fact that F(2k) = F(2(k+1)-1)-F(2k-1)
I figured out the F(3k) one by the fact that F(3k) = (F(3(k+1)-1)/2) - (F(3k-1)/2)
I sadly don't know how to find such a telescoping sum for F(4k)
Answer: Hint
Prove than
$$a_n=\sum_{k=0}^n F_{4k}=F_{2n}\,F_{2n+2}$$ Induction, may be ?
Answer: $$\sum_{k=0}^nF_{4n}=\frac{F_{4n+4}-F_{4n}-3}5$$
It follows by induction because $F_n+F_{n+8}=7F_{n+4}$
Comment: Also I want to say that I figured out how to do a general sum with f of 2a times k, so thanks for this answer again. F(n-2k)+F(n+2k)= L(2k)F(n)
Comment: I also figured out a formula for 2a+1
Comment: You don't even need induction technically.
Anyway this is the best answer. Thanks

The sum of Fibonacci numbers $F_{4k}$


PHP XML Strategy: Parsing DOM to fill "Bean"

Question: I have a question concerning a good strategy on how to fill a data "bean" with data inside an xml file.
The bean might look like this:
class Person
{
 var $id;
 var $forename = "";
 var $surname = "";
 var $bio = new Biography();
}

class Biography
{
    var $url = "";
    var $id;
}

the xml subtree containing the info might look like this:
<root>

  <person>
   <name pre="forename">
              Foo
   </name>
   <name pre="surname">
    Bar
   </name>
   <id>
    1254
   </id>
   <biography>
    <url>
     http://www.someurl.com
    </url>
    <id>
     5488
    </id>
   </biography>

  </person>
</root>

At the moment, I have one approach using DOMDocument. A method
iterates over the entries and fills the bean by "remembering"
the last node. I think thats not a good approach.
What I have in mind is something like preconstructing some xpath
expression(s) and then iterate over the subtrees/nodeLists. Return
an array containing the beans as defined above eventually.
However, it seems not to be possible reusing a subtree /DOMNode
as DOMXPath constructor parameter.
Has anyone of you encountered such a problem?
Comment: Are you familiar with SimpleXML? http://php.net/simplexml
Answer: Did you mean using an XML file as a sort of template ?
You can use some factory to build the empty person or biography node and then feed it, or validate using DTD's
You can search using xpath on selected DOM nodes, see php DOMXpath manual
Answer: no. The XML contains real data. I need to transform it into a php array (unfortunenatly it must be PHP :/ don't ask why ...).
---> You can use some factory to build the empty person or biography node and then feed it, or validate using DTD's
The "bean" is not the problem ... Constructing the list of beans is harder than i thought.. maybe the main problem is related to the solution, since I want to keep it as general as possible ..
here is some java code I just wrote, maybe you get an idea..
public List<PersonBean> extract(String xml) throws Exception {
    InputSource is =new InputSource(new StringReader(xml));
    XPathFactory xfactory = XPathFactory.newInstance();
    XPath xpath = xfactory.newXPath();
    NodeList nodeList = (NodeList)xpath.evaluate("/root/person", is, XPathConstants.NODESET);
    int length = nodeList.getLength();
    int pos = -1;
    Traverser tra = new Traverser();
    Attribute nameAttr = new Attribute();
    nameAttr.setName("attr");
    while(++pos < length) {
        PersonBean bean = new PersonBean();
        Node person = nodeList.item(pos);
        Node fore = tra.getElementByNodeName(person, "id");
        nameAttr.setValue("forename");
        Node pre = tra.getElementByNodeNameWithAttribute(person,"name",nameAttr);
        nameAttr.setValue("surname");
        Node sur = tra.getElementByNodeNameWithAttribute(person, "name", nameAttr);
        bean.setForeName(pre.getTextContent());
        bean.setSurName(sur.getTextContent());
        bean.setId(fore.getTextContent());
        Node bio = tra.getElementByNodeName(person, "biography");
        Node bid = tra.getElementByNodeName(bio, "id");
        Node url = tra.getElementByNodeName(bio, "url");
        BiographyBean bioBean = new BiographyBean();
        bioBean.setId(bid.getTextContent());
        bioBean.setUrl(url.getTextContent());
        bean.setBio(bioBean);
        persons.add(bean);
    }
    return persons;
}

Traverser is just a simple iterative xml traverser ..
Attribute another Bean for Value and Name.
This solution works fine, given the case there is a "person"-node.. However, the code could grow drastically for all other elements that need to be parsed..
I don't expect ready made solutions, just a small hint in the right direction.. :)
Cheers,
Mike
Comment: Maybe there is some mapping framework out there. something like JAXB, that can "serialize" php objects to xml and vice verse.


Formatar data ao realizar Update no registro - PostgreSQL

Question: Estou salvando no meu banco de dados a data em que determinado registro for alterado, porém o formato que o mesmo é salvo é (YYYY-MM-DD), o comando SQL usado até então é o seguinte:
update public.transportadora set status = 'Ativo', user_update = 'Teste', data_alteracao = current_date where codigo = 3

e o registro fica assim:

Minha necessidade é que a data fique na sequencia DD-MM-YYYY, ou seja, 27/03/2017
Comment: Você precisa se adaptar a reconhecer o banco como uma camada transparente feita para armazenar e manipular dados. Ele vai retornar um tipo de dados, a exibição desse tipo não é necessariamente obrigação dele. Você pode exibir como desejar
Answer: A nível de banco de dados, se você selecionou esse campo como sendo um campo date ou timestamp você não formata a data, quem faz isso é o proprio banco, o que você pode fazer é pegar esse dado e formatar programaticamente, por exemplo em java pode usar o SimpleDateFormat em php se não me engano tem a função date(); Diz aí qual linguagem está usando que alguém dará uma resposta mais precisa.
Comment: Minha dúvida é se no próprio comando de Update eu poderia formatar o modo como a data é salva no banco não em si no `select` mas pelo que você já falou isso não é possível
Comment: No caso de BUSCAR os dados vc pode usar funções do SGBD para fazer isso por exemplo a date do MySQL, mas para salvar eh o SGBD que decide como salvar.
Comment: Sim, percebi pelo que você havia comentado
Answer: Ao exibir utilize: to_char(seu_campo_data, 'DD-MM-YYYY')
Comment: Eu não tenho dificuldade para formatar para exibir, a resposta do @VictorHarturdeCarvalho mostrou isso
Comment: Você está confundindo formato de armazenamento com formato de exibição. Você não modifica o formato de armazenamento de um campo date no PostgreSQL, mas pode alterar o formato de exibição para a maneira que julgar conveniente.


Terminating FFMPEG from Python using Linux

Question: So I have a project that listens for button inputs in Python, and records video from a camera and an external microphone once a certain button is pressed, now when I want to stop recording, I press another button and stop recording on my camera and the microphone, and then I call ffmpeg using the subprocess module:
mergeFiles = subprocess.Popen("sudo ffmpeg -i /home/pi/Video/video.mov -i /home/pi/Audio/test.wav -acodec copy -vcodec copy -map 0:v -map 1:a -shortest /media/pi/USB/Output/output.mkv", shell=True)

to merge the audio and video files I just created.
Now once I call ffmpeg, it doesn't stop until I send the process a signal interrupt from the keyboard... is there a way to either have the process stop as soon as it's done merging, or to automatically terminate/kill ffmpeg after a certain amount of time?
I have read up on other posts like this and none of the solutions work for me. I can't kill the process using the PID because every time I look up ffmpeg's PID, it is a different ID, and calling something like
    mergeFiles.kill()
doesn't work for me.
Comment: mergeFiles.kill() doesn't work because of the supproccess command was called by the root user. Try changing the permission of ffmpeg to allow regular users or run your entire script using the sudo user
Comment: I tried this and it still doesn't stop
Comment: which one did you try ?
Comment: Sorry, I tried not calling ffmpeg as root, by simply omitting "sudo", and using mergeFiles.kill() still didn't kill the process.
Answer: I think the reason it is doing this is because the ffmpeg command starts a second process and you don't have the Pid of the second process (just a guess I am not an expert).
My Solution was to call pkill ffmpeg as a subprocess when I want to terminate ffmpeg. (https://en.wikipedia.org/wiki/Pkill).


Print Link field in View template

Question: I have a 'Link' field that is entered in plain text by user. I am trying to display the raw value of this field in my views template. I did dsm($fields); in the views template.
For the field, the raw data shows as a node id, not the url the user entered. The content attribute shows the url but it is wrapped in html. This is also the case when using ->content or ->raw in my views template.
I need to only print the plain url text the user entered in the template. How can I do this?
Here are the results for content and raw value:
Comment: if you're using the Link module, you can choose how the link is displayed, including plain text
Comment: Even before you solve your problem, please understand that outputting raw content that is put in by users is never a good idea. You are setting yourself up for CSRF and XSS security breaches. If you are doing this in a template file, you really need to make sure that the raw content is handled by Drupal's built-in filtering functions.
Comment: Having said that, what is the view displaying content or fields? If you are displaying fields, then there should be a way to get the raw value in the field-level configuration of the view.
Comment: The view is displaying fields. I got the raw data from using dsm($fields). The raw data doesn't show the Link url entered by the user, it shows the node id where the Link was entered. Is this suppose to be the case or is something broken?

Is there another way to display the plain text entered by the user without any HTML, other than using raw value?
Answer: if you're using the Link module, you can choose how the link is displayed, including plain text

The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.
Comment: Thanks, I've tried using the Link module but I was running into similar issues in the views template. Could you tell me how I would re-print the Link url and title in a template file? (not in the Views UI)
Answer: I figured out what needed to be used in the Views template:
$row->field_field_news_link[0]['rendered']['#markup']

This gets the text entered by the user. No need to change to Link field or get the raw value.

Print Link field in View template


If $\nabla f(x,y,z) $ is always parallel to $xi+yj+zk$, them $f$ must be equal values at the points $(0,0,a)$ and $(0,0,-a)$.

Question: If $\nabla f(x,y,z) $ is always parallel to $xi+yj+zk$, them $f$ must be equal values at the points $(0,0,a)$ and $(0,0,-a)$.
I am having difficulty in the problem. Please help.
Comment: What does the inverse delta sign mean again?
Answer: Suppose that we are given $\nabla f=C\vec r$, where $\vec r$ is the position vector and $C$ is a constant of proportionality.
Then, by integration, we find that $f$ is given by
$$f(x,y,z)=\frac12 C(x^2+y^2+z^2)+C'$$
where $C'$ is an integration constant.
Evaluating $f$ at $(0,0,a)$ and $(0,0,-a)$ reveals that
$$f(0,0,a)=\frac12Ca^2+C'$$
and
$$\begin{align}
f(0,0,-a)&=\frac12 C(-a)^2+C'\\\\
&=\frac12 Ca^2+C'\\\\
&=f(0,0,a)
\end{align}$$
as was to be shown!

EDIT:
If $C$ is a function of $x$, $y$, and $z$, then the result fails to hold in general.  For example, suppose $\nabla f =z\vec r$.  Then, we have
$$\begin{align}
f(0,0,a)-f(0,0,-a)&=\int_{-a}^a \nabla f(0,0,z)\cdot \hat z\,dz\\\\
&=\int_{-a}^a z^2\,dz\\\\
&=\frac23a^3\\\\
&\ne 0
\end{align}$$
However, if $C(x,y,z)$ is an even function of $z$, then we have
$$\begin{align}
f(0,0,a)-f(0,0,-a)&=\int_{-a}^a \nabla f(0,0,z)\cdot \hat z\,dz\\\\
&=\int_{-a}^a zC(0,0,z)\,dz\\\\
&=0
\end{align}$$
and we obtain the proposed result.
Comment: @John If C is not a constant, then the result does not hold in general.  If $C$ is a function of $x$ and $y$ only, then the result still holds.  If $C(x,y,z)$ is an even function of $z$, then the result also holds.
Comment: What if the constant of proportionality C is actually not constant, e.g. C(x, y, z)?
Answer: Here $C$ might not be a constant.
example- take $f(x,y,z)=e^{x^2+y^2+z^2}$


real world examples of causality without correlation

Question: There are several hypothetical instances of causality despite the lack of correlation between two variables, some of them have been mentioned in this forum - Does no correlation imply no causality?
Would anyone be able to share examples of real-world published cases in which there was clear causality without (linear) correlation?
Comment: Heteroscedastic residuals often provide examples where there is a non-linear causal relationship but linear regression has removed any correlation between the residuals  and values of the causal variable
Comment: 0. Welcome to CV.SE. 1. Nice question (+1). 2. The other thing to consider is physical laws where we might have no linear correlation  *and* no causal relation but still observe a very strong relation between the variables included! :)
Comment: Thank you. I appreciate your answer.
Comment: These cases are common in self-regulating processes in biology - see [my answer](https://stats.stackexchange.com/a/388743/57345) to a [related question](https://stats.stackexchange.com/q/26300/57345).
Answer: Yes, of course, we can have examples of real-world cases where we have a causal relationship without a strong correlation; an obvious place to check is causal time-series models. Assume for example we have the structure:

It is easy for to say that $Y_t\perp \!\!\!\perp X_{t-1}|Y_{t-1}$ based on $d$-separation, i.e. we have conditional independence between $X_{t-1}$ and $Y_t$ given $Y_{t-1}$. Here, only the value of $X_t$ would be assistive to predict $Y_t$ and thus Granger causality (or some other "basic correlation" method) would not detect the influence of $X$ on $Y$ because the past of $X$ influences $Y_t$ only via the past of $Y$. As a result, the causal relation of $X$ on $Y$ is completely missed based on correlation measurements; I "borrowed" this example from Ch. 10 in "Elements of Causal Inference" (2017) by Peters et al., check it out for more formal treatment. Now for a published result: "A study of problems encountered in Granger causality analysis from a neuroscience perspective" (2017) by Stokes and Purdon is a quick one; they use a VAR model instead of a simple ARX as above but the logic is the same - a vector auto-regressive (VAR) model generalising a single-variable autoregressive (AR) model by allowing for multivariate time series. In general, search the terms "Granger Causality" and "Common-cause fallacy" alongside each other and a few references pop up; "A review of the Granger-causality fallacy" (2015) by Maziarz is a good place to start too.
Comment: Agreed, I meant to focus on the AR class of models generally, thank you, amended.
Comment: Thank for your thorough answer (+1). Are you aware of a more down-to-Earth example? I read somewhere else that the tobacco industry messed up the data on the causal relation between smoking and cancer with the intent to show they are not correlated. However, if true, this is a case of scientific fraud. I wonder if there is some other example like this that does not involve data fraud.
Comment: I am glad I could help. I haven't come across something like that for the smoking industry, sorry. I think their main line of defence was the absence of RCTs as the correlation was always there; what killed their argument was the use of instrumental variables related to genetic markers (which is something different to "no correlation, but with causation").


Ratio of successive errors does not converge to $2^{-p}$.

Question:
Assume a multistep method with order $p$. Then for the global error we
  have: $$ \| y_{n+1} - y(x_{n+1}) \| = O(h^p) \leq K h^p $$ Given the
  above, if we divide the step $h$ by $2$, then $$
\frac{e_{new}}{e_{old}} \approx 2^{-p} $$ where $e$ denotes the global
  error.

Having this in mind, I'm trying to test it, using bdf3 method, with the problem:
$$
\begin{cases}
y' = 2\sqrt{y-1} \\
y(0) = 5
\end{cases}
$$
for $t \in [0,2]$, with analytical solution: $y(t) = 1 + (t+2)^2$.
However, the sequence of $-\log_2(\frac{e_{new}}{e_{old}})$ doesn't converge to $3$ as expected, instead its value after some iterations seems to be around $-1$, which doesn't make sense to me.
Here's the Matlab script:
clf

% Initialize problem
y0 = 5;
t0 = 0;
tfinal = 2;
errors = [];
error_ratios = [];

for k = 2:10
    h = 2^(-k);

    [tout, yout] = bdf3('f3', t0, tfinal,h,y0);

    if k == 2
        err = max(abs(yout-f3true(tout)));
        errors = [errors err];
    else
        err_prev = err;
        err = max(abs(yout-f3true(tout)));
        err_ratio = -log2(err/err_prev);
        errors = [errors, err];
        error_ratios = [error_ratios, err_ratio];
    end
end
format short g;

disp(errors);
disp(error_ratios);

Output:
1.6941e-05   7.0892e-07   2.6055e-08   8.8711e-10   2.8844e-11   5.8442e-13   7.7804e-13   1.2896e-12   2.9665e-12

       4.5787        4.766       4.8763       4.9427       5.6251     -0.41284     -0.72904      -1.201

Comment: Your code goes not conform with the description or the results. The fraction of positive numbers is seldom negative, so you did apply the logarithm somewhere.
Comment: @LutzLehmann yes. The fraction should have a $-\log_2$ in front of it. I will edit it.
Comment: I guess that the last ratios have no numerical signifiance.
Comment: @YvesDaoust But wouldn't it be more sensible for the negative logarithm of the ratios to be near $3$ at least for some ratios which are numerically significant?
Comment: As this is example 3, do examples 1 and 2 show the correct behavior?
Answer: As a third order method, the error has a component of $h^3$ due to the truncation errors and a component $\mu/h$ due to accumulation of rounding errors in the $T/h$ steps. The latter takes over and dominates the total error somewhere around $h=\sqrt[4]\mu\sim 2^{-13}$. This $\mu h^{-1}$ gives the exponent of $-1$ that you see in the last order estimates. That it starts that early indicates that the method error is extremely small for this example.
In my own implementation of BDF using single RK4 steps in the initialization and an order 3 predictor in a naive PEC scheme, I get errors and estimated orders as
1.58e-05  6.7402e-07  2.5267e-08   8.723e-10  2.8788e-11  7.3896e-13  1.5987e-14           0        0
       4.551      4.7374      4.8563      4.9213      5.2838      5.5305      20.608          -0

This confirms your results, the differences are due to differences in the implementation. (It seems impossible to reproduce the effect of the floating point accumulation in this step size range.)
The interpretation is that the example is too polynomial. The error coefficients of multi-step methods are mostly the higher derivatives of the solution, but these are zero for this equation with quadratic polynomials as solutions.
So what you are essentially seeing in the order estimates is the propagation of the 5th order local error of the first two RK4 steps used for the initialization of the method. That is, the method error behaves now like $h^5$, so that the cross-over with the floating point error $\mu h^{-1}$ is at about $h=\sqrt[6]\mu\sim 2^{-8.5}$, which is about what your data series shows.

Try a different example, $y'(t)=-10(\sin(y(t))-\sin(\cos(t)))-\sin(t)$ with exact solution $y=\cos(t)$. Then the working range starts at about $h=2^{-7}$, for larger step sizes the leading error term is not dominant enough to determine the order. I get for $h=2^{-k-6}$, $k=1,2,...,9$, the errors and estimated orders
2.0842e-08   2.417e-09  2.9028e-10  3.5547e-11  4.3969e-12  5.4867e-13  7.0499e-14  1.8208e-14  1.2323e-14
        3.1082      3.0576      3.0297      3.0152      3.0025      2.9603      1.9531     0.56314

This exhibits the order 3 in the working range of step sizes and a break down in order due to floating point noise accumulation as expected at around $h=2^{-13}$, in the positions $k=7,8,9$.
This change of the origin of the error can also nicely be seen in plots of the error profiles, where the difference to the exact solution is divided by $h^3$ to get a common scale.

The first 6 plots are almost identical, showing the dominance of the leading error term, while the last 3 show the increasing influence of the pseudo-random floating-point error accumulation.


Odds ratio, Meta-analysis

Question: I have the following for the data for the meta-analysis:
OR , standard errors, logged OR , variance of logged OR
I have generated a forest plots first using "OR" with "variance of logged OR" using jamovi software, the results were as expected and significant. then I realized that it may be wrong to do that and then I plotted again but using
"OR" with "standard error" , what I have noticed that results were about the same and that the confidence intervals were slightly wider when I used the "variance of logged OR" .
so that I wonder if its correct to generate forest plot using "variance of logged OR" with "OR" ?
Regards.
Answer: You generally do all your calculations with the log-odds ratios and the standard errors of the log-odds ratios, because these behave a lot better than the untransformed odds ratios (for very large studies the difference may occasionally be small). You back transform back to the odds ratio scale after doing your calculations.
What a particular software package does when given some values may depend on whether it understands what they are, if so it may actually have done appropriate transformations of odds ratios, but you would have to consult the documentation to find out.

Odds ratio, Meta-analysis


How to save modified UIImage with original meta data?

Question: In my iOS app, I have to make some modification on a UIImage, for example adding a watermark on it. After that, I want to save the image with original meta data, but if I tried to using writeImageDataToSavedPhotosAlbum:metadata:completionBlock:, I got nothing in the produced image.
Since I have to modify the image, so I have to pass the NSData for metadata: part using the following method: UIImageJPEGRepresentation(UIImage *, float).
And right before saving the image, the meta data is like:
Meta: {
    ApertureValue = "2.526068811667587";
    BrightnessValue = "-1.807443054797895";
    ExposureMode = 0;
    ExposureProgram = 2;
    ExposureTime = "0.05882352941176471";
    FNumber = "2.4";
    Flash = 16;
    FocalLenIn35mmFilm = 33;
    FocalLength = "4.12";
    ISOSpeedRatings =     (
        800
    );
    LensMake = Apple;
    LensModel = "iPhone 5c back camera 4.12mm f/2.4";
        LensSpecification =     (
        "4.12",
        "4.12",
        "2.4",
        "2.4"
    );
    MeteringMode = 3;
    PixelXDimension = 3264;
    PixelYDimension = 2448;
    SceneType = 1;
    SensingMethod = 2;
    ShutterSpeedValue = "4.058917734171294";
    WhiteBalance = 0;
    "{GPS}" =     {
        Altitude = "147.9932";
        DOP = "76.42908";
        Latitude = "45.7398";
        LatitudeRef = N;
        Longitude = "126.6266";
        LongitudeRef = E;
        TimeStamp = "2013:12:23 08:45:30";
    };

So, what is wrong here?
Comment: Do you get any exceptions? any console log output? Does the actual code that writes the image get executed?
Comment: No, there's no exception at all..
Answer: Try this,
UIImage *newImage = self.yourOriginalImage;

UIImage *anotherImage = @"waterMark.png";
CGImageRef imageRef = anotherImage.CGImage;

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(imageRef),
                                        CGImageGetHeight(imageRef),
                                        CGImageGetBitsPerComponent(imageRef),
                                        CGImageGetBitsPerPixel(imageRef),
                                        CGImageGetBytesPerRow(imageRef),
                                        CGImageGetDataProvider(imageRef), NULL, false);

CGImageRef maskedImage = CGImageCreateWithMask([newImage CGImage], mask);
self.imageView.image = [UIImage imageWithCGImage: maskedImage];

Comment: Well, I didn't quite get it.. This code seems to display the image on a imageView, but what I need is save the image into a image file.
Answer: Assuming you have a UIImage called myEditedImage and the metadata in an NSDictionary (or an NSMutableDictionary...) called "metadata":
ALAssetsLibrary *library;
ALAssetsLibraryWriteImageCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {};
float compressionLevel = 0.75; // Or whatever you want
NSData *dataIn = UIImageJPEGRepresentation(myEditedImage, compressionLevel);
[library writeImageDataToSavedPhotosAlbum: dataIn
     metadata: metadata
     completionBlock:completionBlock];


Join no Eloquent - Join no Eloquent?

Question: Estou aprendendo Laravel agora, e por curiosidade me deparei com o seguinte problema, realizar um join entre duas tabelas, no meu caso, "categorias" e "subcategorias", no qual quando irei listar as subcategorias.
Ele buscar o nome da categoria ao qual ela esta relacionada e exibi-lo, sei que seria mais fácil usando o DB::, mas por questão de curiosidade e aprendizado gostaria de saber como fazer isso no Eloquent?
Tabela Categorias
id_categoria - PK
nome_categoria

Tabela Subcategorias
id_subcategoria - PK
nome_subcategoria
idcategoria_subcategoria - armazena o id da categoria

Comment: Deu certo Carlos?
Comment: Dá uma lida nisso também: https://pt.stackoverflow.com/help/accepted-answer e também https://pt.stackoverflow.com/help para criar e aceitar respostas!
Comment: Opa Virgilio, ainda não, ele não exibe os dados, agora fiquei com uma duvida, oq eu coloco no $p?? Pq vão ser várias categorias, se eu especificar uma, ele não exibiria somente aquela?
Comment: consegui eibir, mas ele só exibe da categoria especificada.
Comment: O que você queria, porque, então a sua pergunta está mau formulada? Qualquer coisa coloque na sua pergunta a idéia dom `DB::` que você disse que seria mais fácil! como seria? ai eu posso traduzir para Eloquent!
Answer: Primeiro precisa configurar seus models eloquent:
Categorias
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Categorias extends Model
{

    protected $table = 'categorias';
    protected $primaryKey = 'id_categoria';
    protected $fillable = ['nome_categoria'];
    public  $timestamps = false;

    public function subcategorias()
    {
        return $this->hasMany(SubCategorias::class,
                              'idcategoria_subcategoria', 'id_categoria');
    }
}

SubCategorias
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategorias extends Model
{

    protected $table = 'subcategorias';
    protected $primaryKey = 'id_subcategoria';
    protected $fillable = ['nome_subcategoria', 'idcategoria_subcategoria'];
    public  $timestamps = false;

    public function categoria()
    {
        return $this->belongsTo(Categorias::class,
                               'idcategoria_subcategoria', 'id_categoria');
    }
}

Verifique se os nomes das tabelas são esses mesmos (categorias e subcategorias) que foram colocados nas configurações protected $table se não altere para o nome corresponde.
Para fazer as pesquisa utilize whereHas da seguinte forma:
$p = 'texto de busca';
$subCategorias = SubCategorias::whereHas('categoria', function ($query) use ($p) {
    $query->where('nome_categoria', 'like', $p);
})->get();

Referencias:

Eloquent: Relationships
Eloquent: Querying Relations
Comment: consegui eibir, mas ele só exibe da categoria especificada no $p

Join no Eloquent - Join no Eloquent?


Cisco ASA 5505 config for VPN traversal

Question: I've recently installed an ASA 5505 to connect several sites via site-to-site VPN which is working just fine.  I also required remote access VPN for users which has also been configured using L2TP/IPSec.  However, I'm having trouble with the configuration to allow the remote access users to access systems on any of the site-VPN connected networks.  Here's the general layout in a hub/spoke configuration:
10.100.20.0/24 - central office (hub)
10.100.50.0/24 - remote office 1
10.100.60.0/24 - remote office 2
10.100.70.0/24 - remote office 3
10.200.0.0/24 - remote access pool
The central office can communicate with any remote office and all remote offices can communicate with the central office.  The remote access users can communicate only with the central office which is their VPN (L2TP) endpoint.
I'm curious what NAT and/or routing configuration do I need to consider to allow the remote access user to access any of the connected remote offices?
Many thanks in advance!
Chris
HERE IS THE CONFIG (with necessary obfuscation):
<code>ASA Version 8.2(1)
!
hostname ciscoasa
enable password ***** encrypted
passwd ***** encrypted
names
name 18.104.22.168 opendns1
name 22.214.171.124 opendns2
!
interface Vlan1
 nameif inside
 security-level 100
 ip address 10.100.20.254 255.255.255.0
!
interface Vlan2
 nameif outside
 security-level 0
 ip address 188.8.131.52 255.255.255.252
!
interface Ethernet0/0
 switchport access vlan 2
!
interface Ethernet0/1
!
interface Ethernet0/2
!
interface Ethernet0/3
!
interface Ethernet0/4
!
interface Ethernet0/5
!
interface Ethernet0/6
!
interface Ethernet0/7
!
ftp mode passive
clock timezone EST -5
clock summer-time EDT recurring
dns domain-lookup inside
dns domain-lookup outside
dns server-group DefaultDNS
 name-server opendns2
 name-server opendns1
same-security-traffic permit intra-interface
object-group protocol TCPUDP
 protocol-object udp
 protocol-object tcp
object-group network opendns-servers
 network-object host opendns2
 network-object host opendns1
access-list outside_1_cryptomap extended permit ip 10.100.20.0 255.255.255.0 10.100.50.0 255.255.255.0
access-list outside_2_cryptomap extended permit ip 10.100.20.0 255.255.255.0 10.100.60.0 255.255.255.0
access-list outside_3_cryptomap extended permit ip 10.100.20.0 255.255.255.0 10.100.70.0 255.255.255.0
access-list inside_nat0_outbound extended permit ip 10.100.20.0 255.255.255.0 10.100.50.0 255.255.255.0
access-list inside_nat0_outbound extended permit ip 10.100.20.0 255.255.255.0 10.100.60.0 255.255.255.0
access-list inside_nat0_outbound extended permit ip 10.100.20.0 255.255.255.0 10.100.70.0 255.255.255.0
access-list inside_nat0_outbound extended permit ip 10.100.20.0 255.255.255.0 10.200.0.0 255.255.255.0
access-list inside_access_in extended permit object-group TCPUDP any object-group opendns-servers eq domain
access-list inside_access_in extended permit object-group TCPUDP host 10.100.20.1 any eq domain
access-list inside_access_in extended deny object-group TCPUDP any any eq domain
access-list inside_access_in extended permit ip any any
access-list outside_access_in extended deny ip any any
access-list outside_nat0_outbound extended permit ip 10.200.0.0 255.255.255.0 10.100.20.0 255.255.255.0
access-list DefaultRAGroup_splitTunnelAcl standard permit 10.100.20.0 255.255.255.0
pager lines 24
logging enable
logging asdm-buffer-size 300
logging asdm informational
mtu inside 1500
mtu outside 1500
ip local pool RA-pool 10.200.0.1-10.200.0.50 mask 255.255.255.0
ip local pool test-pool 10.100.20.200-10.100.20.209 mask 255.255.255.0
icmp unreachable rate-limit 1 burst-size 1
icmp permit any inside
icmp deny any echo outside
no asdm history enable
arp timeout 14400
nat-control
global (outside) 1 interface
nat (inside) 0 access-list inside_nat0_outbound
nat (inside) 1 0.0.0.0 0.0.0.0 dns
nat (outside) 0 access-list outside_nat0_outbound outside
access-group inside_access_in in interface inside
access-group outside_access_in in interface outside
route outside 0.0.0.0 0.0.0.0 184.108.40.206 1
timeout xlate 3:00:00
timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02
timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00
timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00
timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute
timeout tcp-proxy-reassembly 0:01:00
dynamic-access-policy-record DfltAccessPolicy
aaa authentication ssh console LOCAL
http server enable
http 10.100.20.0 255.255.255.0 inside
http 0.0.0.0 0.0.0.0 outside
no snmp-server location
no snmp-server contact
snmp-server enable traps snmp authentication linkup linkdown coldstart
crypto ipsec transform-set ESP-AES-256-MD5 esp-aes-256 esp-md5-hmac
crypto ipsec transform-set ESP-DES-SHA esp-des esp-sha-hmac
crypto ipsec transform-set ESP-DES-MD5 esp-des esp-md5-hmac
crypto ipsec transform-set ESP-AES-192-MD5 esp-aes-192 esp-md5-hmac
crypto ipsec transform-set ESP-3DES-MD5 esp-3des esp-md5-hmac
crypto ipsec transform-set ESP-AES-256-SHA esp-aes-256 esp-sha-hmac
crypto ipsec transform-set ESP-AES-128-SHA esp-aes esp-sha-hmac
crypto ipsec transform-set ESP-AES-192-SHA esp-aes-192 esp-sha-hmac
crypto ipsec transform-set ESP-AES-128-MD5 esp-aes esp-md5-hmac
crypto ipsec transform-set ESP-3DES-SHA esp-3des esp-sha-hmac
crypto ipsec transform-set TRANS_ESP_3DES_SHA esp-3des esp-sha-hmac
crypto ipsec transform-set TRANS_ESP_3DES_SHA mode transport
crypto ipsec security-association lifetime seconds 28800
crypto ipsec security-association lifetime kilobytes 4608000
crypto dynamic-map SYSTEM_DEFAULT_CRYPTO_MAP 65535 set transform-set TRANS_ESP_3DES_SHA ESP-AES-128-SHA ESP-AES-128-MD5 ESP-AES-192-SHA ESP-AES-192-MD5 ESP-AES-256-SHA ESP-AES-256-MD5 ESP-3DES-SHA ESP-3DES-MD5 ESP-DES-SHA ESP-DES-MD5
crypto map outside_map 1 match address outside_1_cryptomap
crypto map outside_map 1 set pfs
crypto map outside_map 1 set peer 220.127.116.11
crypto map outside_map 1 set transform-set ESP-3DES-SHA
crypto map outside_map 2 match address outside_2_cryptomap
crypto map outside_map 2 set pfs
crypto map outside_map 2 set peer 22.214.171.124
crypto map outside_map 2 set transform-set ESP-3DES-SHA
crypto map outside_map 3 match address outside_3_cryptomap
crypto map outside_map 3 set pfs
crypto map outside_map 3 set peer 220.127.116.11
crypto map outside_map 3 set transform-set ESP-3DES-SHA
crypto map outside_map 65535 ipsec-isakmp dynamic SYSTEM_DEFAULT_CRYPTO_MAP
crypto map outside_map interface outside
crypto isakmp enable outside
crypto isakmp policy 5
 authentication pre-share
 encryption 3des
 hash sha
 group 2
 lifetime 86400
crypto isakmp policy 10
 authentication pre-share
 encryption des
 hash sha
 group 2
 lifetime 86400
crypto isakmp policy 30
 authentication crack
 encryption 3des
 hash sha
 group 2
 lifetime 86400
telnet timeout 5
ssh 0.0.0.0 0.0.0.0 inside
ssh 0.0.0.0 0.0.0.0 outside
ssh timeout 15
ssh version 2
console timeout 0
dhcpd auto_config outside
!

threat-detection basic-threat
threat-detection statistics port
threat-detection statistics protocol
threat-detection statistics access-list
no threat-detection statistics tcp-intercept
webvpn
 enable inside
 enable outside
 svc image disk0:/anyconnect-win-2.4.1012-k9.pkg 1
group-policy DefaultRAGroup internal
group-policy DefaultRAGroup attributes
 dns-server value 18.104.22.168 220.127.116.11
 vpn-tunnel-protocol IPSec l2tp-ipsec
 ip-comp disable
 pfs disable
 split-tunnel-policy tunnelspecified
 split-tunnel-network-list value DefaultRAGroup_splitTunnelAcl
group-policy DfltGrpPolicy attributes
 vpn-tunnel-protocol IPSec l2tp-ipsec svc webvpn
 split-tunnel-policy tunnelspecified
 split-tunnel-network-list value DefaultRAGroup_splitTunnelAcl
 webvpn
  svc ask enable
username user1 password ***** nt-encrypted privilege 15
username user1 attributes
 vpn-group-policy DefaultRAGroup
username user2 password ***** nt-encrypted
username user2 attributes
 vpn-group-policy DefaultRAGroup
 service-type remote-access
username user3 password ***** encrypted
username user3 attributes
 vpn-group-policy DefaultRAGroup
 service-type remote-access
tunnel-group DefaultRAGroup general-attributes
 address-pool RA-pool
 default-group-policy DefaultRAGroup
 strip-realm
 strip-group
tunnel-group DefaultRAGroup ipsec-attributes
 pre-shared-key *
 isakmp keepalive disable
tunnel-group DefaultRAGroup ppp-attributes
 authentication ms-chap-v2
tunnel-group DefaultWEBVPNGroup general-attributes
 address-pool RA-pool
 dhcp-server 10.100.20.254
tunnel-group 184.108.40.206 type ipsec-l2l
tunnel-group 184.108.40.206 ipsec-attributes
 pre-shared-key *
tunnel-group 18.104.22.168 type ipsec-l2l
tunnel-group 220.127.116.11 ipsec-attributes
 pre-shared-key *
tunnel-group 184.108.40.206 type ipsec-l2l
tunnel-group 126.96.36.199 ipsec-attributes
 pre-shared-key *
!
!
prompt hostname context
Cryptochecksum:e78f2c61bd1c3b5dea31af3782a04b51
: end
</code>
Comment: Sounds like the addresses in the vpnclientpool either don't have a route to the remote site, or are being blocked by an ACL.  Hard to say which without seeing your config.  Posting it would help.
Comment: my thinking exactly, but where?  I added the config above.
Answer: This:
<code> access-list DefaultRAGroup_splitTunnelAcl standard permit 10.100.20.0 255.255.255.0
</code>
combined with this:
<code> split-tunnel-network-list value DefaultRAGroup_splitTunnelAcl
</code>
is allowing only traffic on 10.100.20.0 onto the splitTunnel. So a VPN client tries to connect to one of your other private IPs, and actually gets routed outside the tunnel, to the Internet.  Not what you want.
Add your other private IPs to the tunnel with:
<code> access-list DefaultRAGroup_splitTunnelAcl standard permit X.X.X.X Y.Y.Y.Y
</code>
for all of your other private IPs.
Comment: ok, I added the changes, but it still doesn't work.  Interestingly, using the "test-pool" DHCP range which overlaps the internal network allows me to get to all the other sites, but not the site I'm VPN'ed to (10.100.20.0/24).
Comment: Try adding the private IPs to the outside_nat0_outbound ACL.
Comment: Nope, I'm afraid that doesn't seem to help either.  Is there a way I can trace this to see where the fault may be?
Comment: also, do I need to clear any connections to realize these changes, just in case I'm falsely assuming it's not working based on ping alone.
Comment: Yes, after updating the splitTunnel you'll need to drop & reconnect the VPN client.
Comment: Unfortunately it still doesn't work.  I've even compared my config to the example given at http://www.cisco.com/en/US/products/hw/vpndevc/ps2030/products_configuration_example09186a008046f307.shtml
Comment: Try firing up the ADSM GUI interface, and using the packet tracer.  It ain't perfect, but it might catch an error in an access-list.
Comment: I use that often, however my results are inconclusive.  Many times the packet tracer shows the packet allowed, however, from my perspective it just doesn't work.  I do most of the work in ADSM which results in rather messy CLI code unfortunately.  I'm still open to any other ideas, though.  I'm considering installing OpenVPN internally for remote user access and leave the ASA for site-to-site only if I can't get this to work soon.
Comment: FWIW, OpenVPN was the working solution I ended up using.  The ASA still handles all site-to-site VPNs and Client VPNs connect to the OpenVPN access server on the internal network via port forwarding.  Once on the internal network, standard NAT/routing handles the inter-site traffic.
Answer: same-security-traffic permit intra-interface
to hairpin in the central site, then back out the same interface to reach the spoke sites

Cisco ASA 5505 config for VPN traversal


custom checkbox with hidden input

Question: I am making a custom checkbox so I can have both my own UI design, and still have the input[type="checkbox"] in the page for purpose of toggling css classes with it and being able to submit a form and it being taken into the form.
I am aware that if the input has display: none; it will not be passed into the form, so I will hide it since I actually don't use it visualy.
Question: what should I take into account when hidding it?
I'm thinking about giving it position: absolute; and then a negative margin so it will not show up. With the label tag I can still trigger it. But should I use opacity or visibility instead?
Comment: Don't know who voted down or why. I voted up since I find this question interesting and relevant to me as well.
Comment: Someone posted a interesting answer but deleted it... And now I got a `-1` with no comment on why, or suggestion helping me improve the question if it needs so. Lets see what the future holds... I'm happy to receive feedback.
Comment: I'm the one who deleted the answer, and the un-deleted it with a better edit.
Answer: As you can see, using opacity:0;, users will still be able to click it. click near the actual label on the snippet below:

.chk { opacity:0; }
.chk + label {
    background-color:red;
    height: 22px;
    width: 22px;
    display:inline-block;
    padding: 0 0 0 0px;
    cursor:pointer;
}
.chk:checked + label { background-color:blue; }
<input type='checkbox' id='mychk' class='chk' />

Now, using a negative margin will make the label disappear too:

.chk { margin:-100px; }
.chk + label {
    background-color:red;
    height: 22px;
    width: 22px;
    display:inline-block;
    padding: 0 0 0 0px;
    cursor:pointer;
}
.chk:checked + label { background-color:blue; }
<input type='checkbox' id='mychk' class='chk' />

Finally: visibility:hidden does the trick:

.chk { visibility:hidden; }
.chk + label {
    background-color:red;
    height: 22px;
    width: 22px;
    display:inline-block;
    padding: 0 0 0 0px;
    cursor:pointer;
}
.chk:checked + label { background-color:blue; }
<input type='checkbox' id='mychk' class='chk' />

Conclusion:
use visibility:hidden to hide the <input>. This will make it invisible still with inline display in your page, without effecting the label using it.
Answer: Use this code

input[type="checkbox"] {
  height: 16px;
  opacity: 0;
  position: absolute;
  width: 16px;
}
 input[type="checkbox"] + label::before {
  border: 1px solid #ccc;
  border-radius: 4px;
  content: "";
  height: 16px;
  left: 8px;
  position: absolute;
  top: 10px;
  width: 16px;
}
 input[type="checkbox"]:checked + label:before {
  border: 1px solid #434452;
  background:#434452;
}
label {
  color: #434452;
  font-size: 18px;
  font-weight: normal;
  line-height: 100%;
  padding-left: 22px;
  cursor:pointer
}
<input type='checkbox' id='chk' class='chk' />check

custom checkbox with hidden input


Metric to quantify how randomly dispersed the points are around the horizontal axis in a residual plot

Question: Residual plots can be used to assess whether a linear regression model is appropriate for the data {1-2}: if the points in a residual plot are randomly dispersed around the horizontal axis, a linear regression model is appropriate for the data; otherwise, a non-linear model is more appropriate. Is there any standard metric to quantify how randomly dispersed the points are around the horizontal axis in a residual plot?

Examples of residual plots:
The first plot shows a random pattern, indicating a good fit for a linear model:

The patterns  in the following plot  are non-random (U-shaped), suggesting a better fit for a non-linear model.

References:

{1} http://stattrek.com/statistics/dictionary.aspx?definition=Residual%20plot
{2} http://blog.minitab.com/blog/adventures-in-statistics/why-you-need-to-check-your-residual-plots-for-regression-analysis
Comment: Possible translation of question: "what are some goodness-of-fit tests for linear regression models?"
Comment: @whuber  Do goodness-of-fit tests measure how randomly dispersed the points are around the horizontal axis in a residual plot? E.g., the coefficient of determination doesn't do so I believe.
Comment: That proves the coefficient of determination is not a goodness-of-fit statistic!  Yes, GoF statistics--practically by definition--test for various kinds of deviations between the residual behavior and ideal residual behavior.  There exist many GoF tests and you can readily construct even more for special purposes: simply posit a more complex alternative model and test it for significance.  *E.g.*, add quadratic terms in the regressors as a crude way of testing nonlinearity.
Answer: The whole reason for plotting residuals is so as to use your eye rather than to rely on a numerical metric. There many different ways in which residuals can fail to be random. Metrics can only be written for particular different types of failure, whereas your eye and your marvelous pattern recognizing brain can respond to anything unexpected.
If you are fitting a simple linear regression and your only aim is to check whether a nonlinear relationship would be better, then you can try a non-parametric curve. In R, the code might go like this:
<code>    fit.linear <- lm(y~x)
    library(splines)
    NS <- ns(x,df=3)
    fit.nonlinear <- lm(y~NS)
    anova(fit.linear, fit.nonlinear)
</code>
The above code fits a cubic regression spline with (in effect) 3 parameters and then uses an anova to test whether the nonlinear curve is a significant improvement over the linear. The ns function constructs a matrix of natural basis vectors for the regression spline.
Alternatively you could fit a polynomial trend, but splines tend to be more flexible and stable.
Here's an example run. The metric here is the p-value, which is 6.5e-9.
<code>    > x <- 1:40
    > y <- rnorm(40)+((x-20)/10)^2
    > plot(x,y)
    > fit.linear <- lm(y~x)
    > library(splines) # import ns() function
    > NS <- ns(x,df=3)
    > fit.nonlinear <- lm(y~NS)
    > anova(fit.linear, fit.nonlinear)
    Analysis of Variance Table

    Model 1: y ~ x
    Model 2: y ~ NS
      Res.Df    RSS Df Sum of Sq      F    Pr(>F)
    1     38 90.309
    2     36 31.698  2    58.611 33.283 6.537e-09 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    > lines(x,fitted(fit.linear))
    > lines(x,fitted(fit.nonlinear),col="red")
</code>
Comment: Thanks, true, we are good at it, but human time is more expensive than CPU time :)


Exploding a string with different separators, Eg ( )

Question: Is there a way to explode a string with different separators/delimiters, for example this string
code code code (1) code code@ (2) code code code (3) code (4)

The 2 is the number I want to get as the result, is there an easy way to do this with php?
Comment: Please be more specific as to what you are using as delimiters. So you want to explode all of that just to get the number 2?
Answer: If you're trying to get the data inside of the parentheses, the following code will match that for you:
preg_match_all('/\((\d+)\)/', $str, $matches);

var_dump($matches[1][1]); // string(1) "2"

If you're trying to split the string using the delimiter of (<some-number>), the code below will work for you:
$arr = preg_split('/\(\d+\)/', $str);

var_dump($arr[2]); // string(16) " code code code "


i need redis high availability statistics

Question: does anyone have any real life statistics on how long they can keep a Redis instance up and running for? I know I can get Redis Sentinel to give me fail over functionality but what is should be my expectation?
A single Redis instance 24x7?
A failure over setup with Redis Sentinel 24x7x365?
Answer: We have about 250 redis instances running. Some are running for 816 days. I havn't seen a single instance crash so far (we have limited the commands a bit).
We are not using Redis Sentinel, but we wrote our own daemon doing the configuration management (realtime configuration changes, etc.), starting/stopping instances, etc. This daemon also starts a slave instance on a second server, but so far: the slave was not needed ;)


Merge multiple block views to a single jump menu

Question: I want to implement a jump menu with a list of three different vocabulary terms grouped by each vocabulary name. If I make only a single view all the terms are shown correctly but I would like to be grouped by their vocabulary names. I thought that I could have this result if I could merge three different views with a view for each vocabulary.
Is this possible?
Answer: Well... It was very simple. I just used a single block view with all the vocabularies and I just used "Group by" the field vocabulary name. This outputs the option values within optgroups for each vocabulary.


Question about tempo markings on timpani part

Question: I'm playing a timpani part in 4/4 at 132 BPM. 4 measures into the excerpt, there is a "dotted quarter note equals quarter note" marking. In this new section (still in 4/4), there are still eighth notes, offset sixteenth notes, and rolls. I've gotten several different answers on how to play this. Do I restrict three eighth notes to each quarter note at the same tempo? Do I divide the 132 tempo by three?
Comment: Hi, welcome! I think a picture of this part of the score would help you to get good answers!
Comment: Is it a well known piece?  If so you can just tell us what it is.
Comment: @Jonah If you've got a graphics program maybe you could use that to halve the size of the picture, or reduce its colours. Either of those will reduce its file size. Then save it and try again.
Comment: Of course! I'll do my best to figure out how to add a picture.
Comment: I am unable to add an image because every time I take a picture and try to add it, it says the file size is too big.
Answer: If what I have printed below is what you're describing (I'm just a little dubious that it is - please check) it's a 'metric modulation' indicating that the time previously taken by a dotted quarter is to be taken by a quarter  i.e. two 8ths in the time previously taken by three.  A reduction to 2/3 of the previous tempo.  132 BPM down to 88 BPM.
(For completeness, I should mention that there is an older convention of this meaning quite the opposite - not Old-tempo=New-tempo but New-tempo=Old-tempo. For various reasons I don't think we need to consider that possibility here.)

Today's composers are rather (over)-fond of this sort of notation for arbitrary tempo changes.  It makes more sense in the case below, where the dotted quarter beat in 12/8 continues as the quarter beat in 4/4.

You'll also see a 'metric modulation' misused to indicate Swing.  Mainly, I think, by educators who are frightened of the fluid concept of 'Swing' and want to quantise it.  Swing is not (necessarily) triplets.  If you want swing, write 'Swing'.  Both notation programs and live musicians understand what is wanted.
Comment: One point on your last image, not all rhythms called "swing" are the same. At least the 8th=triplets notation is unambiguous about which kind of swing is desired.
Comment: Unfortunately it's used indiscriminately.  Not just to describe triplet swing.
Comment: Yes. Because of that older convention I like to see *arrows*: "One of those that side equals one of those THAT side!"
Answer: As Laurence Payne explains, the tempo is modulating from quarter = 132 to quarter = 88. There is also the question of how to make the change.
The "brute force" method is to practice with a metronome set at each speed until you've developed an internalized feel for the pacing of each.
The "mathematical" method is to use subdivisions of the beat. The notation dotted quarter = quarter gives a hint. The common subdivision between the two is the eighth note. If you count as shown in the example below, you'll make the exact tempo transition indicated.
<code>X:1
T:Metric Modulation Example
K:none
M:4/4
L:1/8
V:V1 staff=perc stafflines=1
[Q:1/4=132]B2 B2 B2 B2 | BB BB BB BB | BB BBB BBB | BBB BBB BBB BBB |[Q:1/4=88] B2 B2 B2 B2 |
w: 1 2 3 4 | 1 & 2 & 3 & 4 & | 1 & 2 & 3 & 4 & | 1 & a 2 & a 3 & a 4 & a | 1 2 3 4
</code>
Note that the eighth-note pulse-rate never changes, but you change the emphasis to reorganize them into triplets. That is, where you previously subdivided the beat into two equal pulses, you now use three of those same pulses to comprise a single beat.
Comment: That's all very well as an exercise.  But not much help in practice unless that's what the music DOES!
Comment: @LaurencePayne If and when the OP posts the actual music, I will update.


editor interface with views

Question: I had a site where the developer set up an screen that you went to directly upon logging in. it was a custom view, within a template that displayed all the content. The view was a block and displayed only to editors.  I set this all up but the blocks are not displaying. Am I missing a step here
this is all i have in my page.tpl.php file

    <?php print $content; ?>

Answer: In your page.tpl.php there's nothing regarding regions ? You're certainly missing some code like:
<?php if ($page['sidebar_first']): ?>

    <?php print render($page['sidebar_first']); ?>

<?php endif; ?>

See page.tpl.php documentation.

editor interface with views


Unable to register a COM object for usage in a scheduled task

Question: I'm trying to create a set of C# classes that I can schedule to run at a future time. The intention is to programmatically schedule these via other parts of my code.
This is the current class I'm trying to call via COM.
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Win32.TaskScheduler;

namespace SchedulableTasks
{
    [Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A")]
    public class TaskRegistry : ITaskHandler
    {
        private ITaskHandler _taskHandler;
        public void Start(object pHandlerServices, string data)
        {
            var arguments = data.Split('|');
            var taskTypeName = arguments.FirstOrDefault();
            var taskArguments = arguments.Skip(1).FirstOrDefault();
            var taskType = Type.GetType(taskTypeName);
            _taskHandler = (ITaskHandler) Activator.CreateInstance(taskType);
            _taskHandler.Start(pHandlerServices, taskArguments);
        }

        public void Stop(out int pRetCode)
        {
            var retCode = 1;
            _taskHandler?.Stop(out retCode);
            pRetCode = retCode;
        }

        public void Pause()
        {
            _taskHandler.Pause();
        }

        public void Resume()
        {
            _taskHandler.Resume();
        }
    }
}

Here's how I'm attempting to schedule the task
using System;
using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json;
using Action = Microsoft.Win32.TaskScheduler.Action;

namespace MyProject.Service
{
    public static class SchedulingService
    {
        public enum ScheduledTask
        {
            BillingQuery
        }
        private static readonly Guid RegistryGUI = new Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A");
        public static void ScheduleAction(string name, string description, Trigger trigger, Action action)
        {
            using (var taskService = new TaskService())
            {
                var task = taskService.NewTask();
                task.RegistrationInfo.Description = description;
                task.Triggers.Add(trigger);
                task.Actions.Add(action);
                taskService.RootFolder.RegisterTaskDefinition(name, task);
            }
        }

        public static Action CreateCSharpAction(ScheduledTask task, object data)
        {
            var taskData = $"{task.ToString()}|{JsonConvert.SerializeObject(data)}";
            return new ComHandlerAction(RegistryGUI, taskData);
        }
    }
}

Microsoft.Win32.TaskScheduler is version 2.7.2 of this library
I can create the scheduled task no problem, but when I attempt to run it, I get a Class not registered (0x80040154).
In my .csproj I'm registering the assembly as a COM object.
For the PlatformTarget attribute, I've tried all of AnyCPU, x86, and x64 with the corresponding regasm.exe.
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <RegisterForComInterop>true</RegisterForComInterop>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

I'm using the following post-build event to register the .dll.
powershell C:\Windows\Microsoft.Net\Framework64\v4*\RegAsm.exe /codebase '$(ProjectDir)$(OutDir)SchedulableTasks.dll'

As near as I can tell, it's properly registered.

Procmon.exe seems to report the same. The thing I'm worried about is the "NAME NOT FOUND" for \TreatAs, \InprocHandler and \InprocServer32\InprocServer32
Comment: It is required, that is what got your TaskRegistry.Start() method to run.  It works, got the job done, now it needs to actually execute the task.  But it doesn't, it kicks the can and tries to call ITaskHandler::Start() yet again.  Nobody around to take care of that one.  Note that the TaskRegistry class name is wrong, it should be TaskHandler.  It needs to handle the task.
Comment: I don't understand what the TaskRegistration class tries to do.  It should execute the task, not try to kick the can down the road.  Maybe it is an intentional extra indirection, but then the diagnostic is that whatever "BillingQuery" might be is not properly registered.  Albeit that this ought not raise this exception since it was already created by Activator.CreateInstance().  Hmm.  Just execute the task.
Comment: @HansPassant The idea was to allow me to register only one class, but have it dispatch to different classes based on the caller. So, I might have one class that calls part of our API, or another one that spins up a server, or sends an email, etc.
Comment: Okay, by why use ITaskHandler for that??  Why would "BillingQuery" even implement it?  You already have the benefit of .NET Reflection and you got as far as creating the object for it.  Just use it as-is without demanding that it [ComVisible(true)] and requiring that the task scheduler knows about it.  Which it surely doesn't, thus the exception.  Just declare a C# interface, give it a Start(string data) method.  Implementing Pause and Resume is optional and surely not easy to do in practice.  Consider a CancellationToken for Stop.
Comment: The `ITaskHandler` is unfortunately required by the TaskScheduler library. I agree that it seems like an odd requirement.
Answer: I think I see your problem:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

Try targeting x86. Please see this answer for an in depth description: How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?
Edit:
I couldn't repro it, I added a few things:

The Attribute [ComVisible(true)]
A Parameterless Constructor
Signed the Assembly
Had to run the powershell command once manually.
Comment: Nope, even with the `AnyCPU` changed to `x86` I still get the same error. I'd also prefer to register it as an x64 DLL, since the rest of my code is 64 bit.
Comment: How do I repro this? You've missed the definition of `TaskService`. Do I just create a Class Library (Full.Net) with `TaskRegistry` and then reference it and instantiate it???
Comment: `TaskService` comes from [this library](https://github.com/dahall/taskscheduler). Yup, I have the 2 files in their own projects. I have individual task definitions that the `TaskRegistry` references, but anything that inherits from `ITaskHandler` will work. I don't care if it crashes as soon as `TaskRegistry.Start` gets called. Both projects are compiled against 4.6.2.
Comment: I have referenced David Halls library and am targeting 4.6.1, *did you downvote me?* Kindly provide a [mcve]?
Comment: I'm still having some issues with the class not being registered. I'll try to come up with a more in-depth MCVE tomorrow. Nope, wasn't me.


Does Mozart use music theory, and if so, what type of music theory?

Question: I have heard various people argue that we are taking rules in music theory too seriously these days, often taking them as strict rules (such as the use of V-I cadences to end pieces), while earlier composers are more "free spirited".
What formal techniques did Mozart use in his days? Or did he rely much on formalized techniques in composition?
Comment: He doesn't any more - been dead for a long time! Dare say finished decomposing, too...
Comment: What kind of strange feeling! You'd better inform yourself in wikipedia etc. instead of having feelings. I bet Mozarts' head was more filled with music theory and musical basics at 4 years than the ordinary average of a 16 years old high school student of today.
Comment: I think you're headed in the right direction. IMO, the part about people taking theory too seriously is what sets up opinion-based answers. If it were me, I'd remove that part entirely and make this a pure history question. But consider opening a second question along the lines of asking for examples where composers specifically used or discarded accepted theory.
Comment: There's an excellent question embedded in here about the history of theory and what Mozart would or would not have read or studied. However, as written, it lends itself to opinion-based answers. Please consider rewriting.
Comment: @Aaron good point. I just rewrote the question.
Comment: @Aaron since this question is rewritten to be less opinion based, can it be reopened?
Comment: I do agree there is a history question in here that is very good, however the entire body of the question seems to fall into the pitfall of the assumption seen in this question: https://music.stackexchange.com/questions/61479/can-music-theory-sabotage-creativity. Music theory and "free spirited" composition are orthogonal.  One does not take away from the other.
Answer: Mozart has been musically educated by his father Leopold and was influenced by Johann Christian Bach and Joseph Haydn.
He was trained in studying counterpoint, harmony, chord theory.
It is likely that Mozart studied Fux's work first under the influence of his father ...
http://www.opus28.co.uk/Fux_Gradus.pdf
Fux: Gradus ad Parnassum.
Also see: Haydn - Mozart connection and J.Chr. Bach - Mozart Connection.
The two composers knew each other, defended each other, and learned from each other in ways that shaped their musical output for much of their lives — despite a vast difference in age and temperament.
Perhaps it was the very differences between these two men of genius that drew them to each other. Whatever it was, they drew support and inspiration from one another in ways that profoundly affected their work.  If they had not met, neither would have been as productive, and their output far different.
In this hour, the story behind the deep friendship between Joseph Haydn and Wolfgang Amadeus Mozart, and the great music it inspired.
http://www.capradio.org/classical/connections/2014/03/08/connections-030814/
Mozart's Counterpoint: Its Growth and Significance
https://www.jstor.org/stable/727803
https://www.nytimes.com/1988/08/14/arts/music-what-haydn-taught-mozart.html
Mozart's lifelong admiration for Bach began during the family's first trip to London,
1764-65, when Mozart was only eight years old. This trip marked the beginning of an
extraordinary relationship, documented in letters written by Wolfgang, Leopold and
Nannerl. Mozart met Bach at the height of the latter's fame, when he was completely at
home in the active musical and social life of the metropolis. While in London, Mozart
enjoyed a close relationship with Bach, and apparently composed under his tutelage the Composer.
https://www.biu.ac.il/HU/mu/min-ad/06-2/8_Bach-Mozart89-104.pdf
Answer: The basics of modern western music theory probably originated with Pythagoras about 2,500 years ago. By Mozart's time music theory was already very well developed. How do you think he actually wrote down his music? He used the notation of music theory. It would probably be easier (and much quicker) to identify the music theory that Mozart didn't utilize.
The suggestion that composers like Mozart were "free spirited" and had little to do with music theory shows a lack of knowledge and understanding of both music theory and Mozart's music.
Comment: Ancient Greek music theory had very little to do with Common Practice Tonality. Common Practice theory is generally considered to have begun with Rameau's *Traite de l'Harmony" in 1722.
Comment: @ this would imply that all Baroque-music before Rameaus' *traité* was not common praxis?
Comment: @AlbrechtHügli by definition, "common practice" refers to the harmonic system that arose in the 18th century.  So yes, Baroque music before Rameau did not employ the "common practice."  If you look at early Baroque music, there are certainly elements of it, but yet it is different.  Its harmonies often resemble those of the late Renaissance more strongly than those of the late Baroque.
Comment: @Aaron you're mistaken. Rameau's influence echoed in Mozart's time either, but there were other earlier influences. Tonality isn't a word defined in this era.
Comment: @RodrigoB.Furman It's true that tonality was in the process of being developed earlier and later, but it was Rameau's treatise that codified, in particular, the idea of chords being stacks of thirds and that inversions could be interpreted as variations on a root chord.
Comment: @Aaron, harmony these days was though differently. Even in Mozart's days, for example, you may find scores with minor keys notated in dorian key signature, as dorian mode was the reference for minor. There was a close link between harmony, melody, form and schema - and the stacking of thirds, well theorized by Rameau, was indeed comprehended, but still the harmony was secondary to melodic movement of individual voices or schemata patterns. I suggest you read both books by Robert Gjerdingen: Music in Galant Style and Child Composers in Old Conservatories.
Comment: @RodrigoB.Furman Thanks for the reference. Just know, I agree with you that during Mozart's time there was a continuing evolution from older practices and conceptions of musical form and such. I'm not arguing that composers based their work on Rameau. I'm saying that *theorists* based their work on Rameau -- that Rameau provided the necessary foundation for the theory now typically used to describe common practice-era music. And the larger point was simply that Pythagorean theory had little to do with Mozart.
Comment: @Aaron Fétis was the first theorist after Rameau to write about this, in 1840's, more than 100 years after Rameau's Traité publishing. Before 1850's, every music treatise was counterpoint-centred or "de natura sonoris", in metaphysical meaning. And, also, harmony is one of the tools necessary to describe common pratice period (1650-1900), along form and counterpoint. But CPP's also a concept now being debunked, as some of the "common practices" by many composers aren't so common after all (not fully explained by traditional harmony), as showed brilliantly by neoriemannian analists.