Número triangular

Question: Gostaria de saber, por que quando digito no programa abaixo que verifica se o número digitado é triangular, ou seja, é múltiplo de três números consecutivos, como exemplo o 60 ele imprime dois "NAO" e um "SIM", e quando digito 336 aparecem cinco "NAO" e um "SIM"?
#include <stdio.h>

int main(void)
{
    int numero, i;
    scanf("%d",&numero);

    for(i = 1 ; i*(i+1)*(i+2)<=numero ; i++)
    {
        if(i*(i+1)*(i+2)==numero)
        {
            printf("SIM\n");
        }
        else
        {
            printf("NAO");
        }
    }
    return 0;
}

Answer: Quando i for 1 o programa vai fazer o if
if (1 * 2 * 3 == numero)

e ou imprime "SIM\n" ou imprime "NAO".
Quando o i for 2 o if passa a ser
if (2 * 3 * 4 == numero)

e o programa imprime "SIM\n" ou "NAO".
Ou seja, o programa imprime qualquer coisa sempre que corre o loop. O que tu queres e imprimir apenas uma vez, no fim do loop.
O uso duma variable auxiliar pode-te ajudar:
int variavel_auxiliar = 0;
for(i = 1 ; i*(i+1)*(i+2)<=numero ; i++)
{
    if(i*(i+1)*(i+2)==numero)
    {
        variavel_auxiliar = 1;
    }
}
if (variavel_auxiliar) printf("SIM\n");
else                   printf("NAO\n");

Comment: (+1) ou mesmo `for(i = 1 ; i*(i+1)*(i+2)<numero ; i++){}
if(i*(i+1)*(i+2)==numero) { printf("SIM\n"); }else { printf("NAO"); }`
Comment: por causa disso eu costumo por `/* void */` nos sítios vazios: `for (a, b, c) { /* void */ }`
Comment: (o if está fora do ciclo)
Comment: os *braces* vazios enganaram-me :)
Comment: E a desformatação dos comentários tb nao ajuda nada :)
Answer: Para saber quais são os números triangulares até determinada posição eu fiz um código:
int main(){
    int limitador=0,i;

    printf("Digite ate qual posicao voce quer saber o numero triangular: ");
    scanf("%d",&limitador);
        while(limitador < 0 || limitador > 1290){
        printf("Valor invalido!! Digite um numero entre 0 e 1290: ");
        scanf("%d",&limitador);
        }
    for(i=0; i<limitador; i++)
        printf("%d x %d x %d =%d\n",i,i+1,i+2,i*(i+1)*(i+2));

    system("pause");
    return 0;
}

Observação: O código só vai até a posição 1290 porque na próxima posição o resultado passa da quantidade de um valor inteiro na linguagem C.
Answer: O código em questão não chega a validar se um número é triangular ou não, pois veja, se multiplicarmos 2, 3 e 4 (ou seja, três números consecutivos) o resultado será 24, sendo este um número não triangular(o 6º termo triangular é 21 e o 7º é 28), da mesma forma se quisermos validar 10 como sendo um número triangular não seria possível, pois não existe sequência de três números multiplicados que resultem neste valor.
Todo número é triangular quando resultado da soma de N números consecutivos; exemplo: 1 + 2 = 3 (triangular), para encontrar os próximos termos somasse 3, depois 4, depois 5 e assim sucessivamente.
Um número triangular é dado também pela fórmula: Tn=n*(n +1)/2; utilizaremos ela para fazer o calculo.
#include <stdio.h>

int main(void){
    int numero, i, auxiliar = 0;
    scanf("%d",&numero); //escaneamos o resultado triangular

//aqui percorremos o index "i" ate alcançar o dobro do numero que esta sendo analisado
//pois assim garantimos que eles nunca serao impares durante a analise
    for(i = 1 ; (i*(i+1))<=(numero*2) ; i++){
        if((i*(i+1)/2)==numero){ //validamos se o resultado é de fato triangular
            auxiliar = 1; //caso sim, utilizamos a variavel auxiliar como um boolean
        }
    }
    if(auxiliar)
        printf("SIM, EH TRIANGULAR\n");
    else
        printf("NAO EH TRIANGULAR\n");

    return 0;
}

Comment: O autor da pergunta quer saber o motivo porque o algoritmo dele está emitindo varia vezes as mensagem de confirmação e negação.  Existem maneiras diretas de verificar se um número é triangular sem recorrer a laços de iteração, por exemplo https://ideone.com/r58oyR

Número triangular


PIMCore Call to a member function supportsInheritance() on null

Question: Whenever I click on search button to select object from list as shown in image below.

I get the error Call to a member function supportsInheritance() on null. It was working  but today its started showing this error. Image showing error is below

I already have lists to select by searching and it was working today.
I have created fields inside bricks and using bricks inside classes.
Below is the full details of Error.

Any solution will be appreciated. My pimcore version is 6.6.
Thanks in advance
Comment: Can you click on "Details" and add the full exception to the question please?
Comment: @Blackbam I have included exception Details. Please check
Answer: Either you have changed your class definitions recently or you have added/imported Objects with empty localized fields. Populate the localized fields in your object and find the problematic field, then the Exception will be gone.
Read more:
https://github.com/pimcore/pimcore/issues/2809
https://github.com/pimcore/pimcore/issues/2810
https://github.com/pimcore/pimcore/issues/6658
If you think you found a bug within the Pimcore system itself create a new bug report which is as specific as possible in https://github.com/pimcore/pimcore/.
Comment: I had this issue after adding inheritance to an existing class definition which contained localized fields. Re-saving the data object in the admin UI fixed it for me.


Solve the equation $6(3^{2x})=2^{(x+1)}$

Question: To begin this question, I start by using the properties of logarithms:
$$\ln 6 + 2x \ln 3 = (x+1) \ln 2$$
I then distribute the $x+1$ term across ln 2
$$x \ln 2 + \ln2$$
Rewriting the RHS with this, the equation is now:
$$\ln 6 + 2x \ln 3 = x \ln 2 + \ln 2$$
I don't know if this is possible, but in the $2x$ term in the equation, is it possible to put the two back in the exponent of the three and make the three nine? What I mean:
$$2x \ln 3 = x \ln 9$$
For the right hand side, would $x \ln 2 + \ln 2 = x \ln 4$? I believe that is the case but I want to make sure.
I know that the solution is $\frac{-\ln 3}{2 \ln 3 - \ln 2}$, I just do not understand the process of getting to that answer
Comment: You got to $\ln 6 +2x\ln 3=x\ln 2 +\ln 2$.  From that point:  Isolate the "$x$" terms on one side  to write $2x\ln 3 - x\ln 2 =\ln 2 -\ln 6\implies x(2\ln 3 -\ln 2)=\ln 2-\ln 6\implies x= \frac {\ln 2 - \ln 6}{2\ln 3 - \ln 2}$.  Now, you can simplify a little further if you write $\ln 6 = \ln 2 +\ln 3$
Answer: Another way to approach it for the sake of curiosity:
\begin{align*}
6\cdot3^{2x} = 2^{x+1} & \Longleftrightarrow 3\cdot 9^{x} = 2^{x}\\\\
& \Longleftrightarrow \left(\frac{9}{2}\right)^{x} = \frac{1}{3}\\\\
& \Longleftrightarrow x\ln\left(\frac{9}{2}\right) = -\ln(3)\\\\
& \Longleftrightarrow x = -\frac{\ln(3)}{2\ln(3) - \ln(2)}
\end{align*}
Hopefully this helps!
Comment: I see exactly what you mean thank you very much!!
Comment: @ArtVandelay5692 you are welcome! I am glad I could help.
Answer: The answer to your first question is yes:  $$2x \ln 3 = x \ln 3^2 = x \ln 9.$$  The answer to your second question is no:  $$x \ln 2 + \ln 2 \ne x \ln 4,$$ because if this were true, it would erroneously imply $$2^{x+1} = 4^x.$$
Instead of taking logarithms so early, it is more useful to simplify first, observing that $6 = 2 times 3$:
$$6(3^{2x}) = 2^{x+1}$$
implies $$2 \cdot 3 \cdot 3^{2x} = 2 \cdot 2^x.$$  Note on the right-hand side, I have used the identity $b^{x + y} = b^x b^y$ with the choice $b = 2$ and $y = 1$.
Then we cancel out the $2$ and absorb the factor of $3$ on the left into the exponent, using the reverse of the same exponent rule we just used earlier:
$$3^{2x + 1} = 2^x.$$
Now we can take logs:
$$(2x+1) \ln 3 = x \ln 2.$$
Rearrange:
$$\frac{2x+1}{x} = \frac{\ln 2}{\ln 3}.$$
Then the left side is
$$2 + \frac{1}{x} = \frac{\ln 2}{\ln 3},$$ hence
$$x = \frac{1}{\frac{\ln 2}{\ln 3} - 2}.$$

Alternatively, we could have obtained this solution from an intermediate point in your calculation, but we would need to observe that
$$\ln 6 = \ln (2 \cdot 3) = \ln 2 + \ln 3.$$
Then substituting this into
$$\ln 6 + 2x \ln 3 = x \ln 2 + \ln 2$$
yields
$$\ln 2 + \ln 3 + 2x \ln 3 = x \ln 2 + \ln 2$$ and canceling then gives
$$(2x + 1) \ln 3 = x \ln 2,$$ which brings us back to the earlier solution above.
Comment: Thank you! It helps to think about it the way you described it because I think I was overthinking it.
Answer:
is it possible to put the two back in the exponent of the three and make the three nine? What I mean:$$2x \ln 3 = x \ln 9$$

Yes, this step is correct.

For the right hand side, would $x \ln 2 + \ln 2 = x \ln 4$? I believe that is the case but I want to make sure.

No, this step is wrong, $x\ln 2+\ln2\neq x\ln4$

Rewriting the RHS with this, the equation is now:
$$\ln 6 + 2x \ln 3 = x \ln 2 + \ln 2$$

You can proceed from this step, to solve for $x$. First, move and combine all terms containing $x$
$$\begin{align}(2\ln3-\ln2)x&=\ln2-\ln6\\
\\(2\ln3-\ln2)x&=\ln\left(\frac{2}{6}\right)\\
\\(2\ln3-\ln2)x&=-\ln3\\
\\x&=\frac{-\ln3}{2\ln3-\ln2}\end{align}$$


clearing form fields after submitting via ajax not working

Question: I am trying to clear form fields after submitting via ajax but it does not work. Someone please help check my codes and give me some good suggestions. Below is my code:
jQuery(document).on('click', '.um-message-send:not(.disabled)',function(e){

    e.preventDefault();

    jQuery('.um-message-send:visible').addClass('disabled');

    var message_to = jQuery('.um-message-body:visible').attr('data-message_to');

    var content = jQuery('.um-message-textarea textarea:visible').val();

    jQuery.ajax({

        url: um_scripts.ajaxurl,

        type: 'post',

        dataType: 'json',

        data: { action: 'um_messaging_send', message_to: message_to, content: content },

        success: function(data){

            jQuery('.um-message-textarea textarea:visible').val('');

            jQuery('.um-message-body:visible').find('.um-message-ajax:visible').html( data.messages );

            if ( data.limit_hit ) {

                jQuery('.um-message-footer:visible').html( jQuery('.um-message-footer:visible').attr('data-limit_hit') );

            }

            jQuery('.um-popup-autogrow:visible').mCustomScrollbar('update').mCustomScrollbar("scrollTo", "bottom",{ scrollInertia:0});

        }

    });

    return false;

});

Html

    <?php echo $this->emoji(); ?>

    <textarea name="um_message_text" id="um_message_text" data-maxchar="<?php echo $limit; ?>" placeholder="<?php _e('Type your message...','um-messaging'); ?>"></textarea>

    <?php echo $limit; ?>

    <?php _e('Send message','um-messaging'); ?>

Comment: You're trying to clear the textarea correct? Just use:
`$('#um_message_text').empty();`
Comment: where do i put it
Comment: I just tried adding it after the success function and it did not work. Its like nothing inside the success function works. What could be the issue
Comment: I would suggest trying to figure out if your success function is actually working. Try using console.log('...'); or something similar to see if you are getting any output from that function. The code I gave you above will clear that textarea with the given ID. EDIT: Also make sure your ajax function is actually entering success. It could be failing everytime.
Comment: Am not good at javascript please where do i enter the cosole.log and what parameters do i put inside
Comment: I would put it at the very beginning of the success call and you can put any text inside. It will print to your browser's console if it is executed. However, I would recommend you learn more about how ajax and javascript work before diving deep into questions such as this. If this is more complicated of an issue than just syntax and such, you will have a very difficult time solving this problem.
Comment: @Kyle can i contact you to fix this and i get you paid a few bugs please
Comment: I got it working by replacing success with complete
Comment: Interesting. Not sure why success wouldn't work here. I use it all the time for my ajax calls. Seems specific to your server's configuration. Also worth noting this previous question: https://stackoverflow.com/questions/5240876/difference-between-success-and-complete
Answer: The answer was simply to replace success with complete as such...
success: function(data) {
  // [...]

=>
complete: function(data) {
  // [...]


An inequality $(a+b+c)^p-a^p-b^p-c^p \le C \sum\limits_{\mathrm{cyc}} [(a + b)^p - a^p - b^p]$

Question: Does anyone know how to prove the following inequality?

There exists some constant $C=C(p)$ such that
$$(a+b+c)^p-a^p-b^p-c^p\leq C[(a+b)^p-a^p-b^p+(a+c)^p-a^p-c^p+(b+c)^p-b^p-c^p] $$
for any $a,b,c>0$ and $p>1$.
Comment: What is $p$? Real?
Answer: Some estimate:
If $a=b=c=x$ we get $$(3x)^p-3x^p \leq C\Big(3(2x)^p-6x^p\Big)$$
so if divide it by $x^p$ we get $$3^p-3 \leq C\Big(3\cdot 2^p-6\Big)$$
so $$C \geq {3^p-3 \over 3\cdot 2^p-6}$$
So try if $C = \displaystyle{3^p-3 \over 3\cdot 2^p-6}$ works. You can also assume that $a+b+c=1$, when trying to prove it.
Comment: Well, I know this constant, but not sure how to prove it.


Solving $\int_0^{\pi/2} \sin^2\theta \sqrt{1-k^2\sin^2 \theta}d\theta $

Question: I have the following integration to solve.
$$f(k) = \int_0^{\pi/2} \sin^2\theta \sqrt{1-k^2\sin^2 \theta}d\theta,\quad0<k<1$$
assuming $\sin\theta = t$ which results $d\theta = \frac{dt}{\sqrt{1-t^2}}$
and when $\theta = 0, t=0$ and $\theta=\frac{\pi}{2},t=1$
so above equation can be rewritten as,
$$f(k) = \int_0^1{t^2\frac{\sqrt{1-k^2t^2}}{\sqrt{1-t^2}}}dt$$
I'm stuck in solving this further.
Can somebody help me with some clues/solution to solve this further.
Comment: what is $k$? are there any conditions for $k$?
Comment: $f$ does not depend on $\theta$, so it should be $f(k)$
Comment: @Jane Thanks for your comment. condition for $k$ is $0<k<1$.
Comment: @YuriyS. Corrected. Thanks
Comment: You can see the final solution in terms of elliptic integrals [here](http://www.wolframalpha.com/input/?i=integrate+sin(x)%5E2+Sqrt%5B1-k%5E2+sin(x)%5E2%5D+from+x%3D0+to+Pi%2F2)
Comment: Thanks for your reply @YuriyS can you please elaborate. Actually I'm not a mathematics guy. If you can help me to simplify this into elliptical integral form then I can solve it. Thanks.
Comment: I don't actually know how to solve it, but you can use the link I provided to check your own result if you do. I suggest you try integration by parts and/or taking $k^2$ derivative of some known integrals
Comment: Ah thanks. Actually I did not notice the link earlier. I can I think solve it now. Thanks once again.
Comment: There did this integral come from, by the way?
Answer: I will use $I(k)$ for the integral instead of $f(k)$.
$$
I(k)=\int^1_0 t^2 \frac{\sqrt{1-k^2 t^2}}{\sqrt{1-t^2}}dt
$$
First, let's find some particular value, we will need it later.
$$I(1)=\frac{1}{3}
$$
Now the definition for the elliptic integral of the second kind:
$$
E(k)=\int^1_0 \frac{\sqrt{1-k^2 t^2}}{\sqrt{1-t^2}}dt
$$
It's easy to show that:
$$
I(k)=E(k)-\int^1_0 \sqrt{1-t^2} \sqrt{1-k^2 t^2} dt
$$
Taking $k$ derivative:
$$
\frac{dI}{dk}=\frac{dE}{dk}+k \int^1_0 t^2 \frac{\sqrt{1- t^2}}{\sqrt{1-k^2t^2}}dt
$$
Now let's use integration by parts for $I(k)$:
$$
I(k)=-k^2 \int^1_0 t^2 \frac{\sqrt{1- t^2}}{\sqrt{1-k^2t^2}}dt+\int^1_0 \sqrt{1-t^2} \sqrt{1-k^2 t^2} dt
$$
Finally we use all three equations to show:
$$
I(k)=-I(k)+E(k)-k\frac{dI}{dk}+k\frac{dE}{dk}
$$
We get a linear ODE for $I(k)$:
$$
\frac{dI}{dk}=-\frac{2}{k} I(k)+\frac{dE}{dk}+\frac{E(k)}{k}
$$
Using the usual method for such equations (reference here) we get the general solution:
$$
I(k)=\frac{C_1}{k^2}+\frac{1}{k^2} \int k^2 \left(\frac{dE}{dk}+\frac{E(k)}{k} \right) dk
$$
To calculate the integral we use the known formula (can be seen here):
$$
\int k E(k) dk=\frac{1}{3} \left[(1+k^2)E(k)-(1-k^2)K(k) \right]
$$
Integrating by parts:
$$
\int k^2 \left(\frac{dE}{dk}+\frac{E(k)}{k} \right) dk=k^2 E(k)-\int k E(k) dk
$$
Finally, the general solution:
$$
I(k)=\frac{C_1}{k^2}+\frac{-(1-2k^2)E(k)+(1-k^2)K(k)}{3k^2}
$$
Now we use the value $I(1)$ we calculated earlier and the known values $E(1)=1$ and $\lim_{k \rightarrow 1} (1-k^2)K(k)=0$ (see here) to obtain the final solution:

$$I(k)=\frac{(1-k^2)K(k)-(1-2k^2)E(k)}{3k^2}$$

We can also check the result. From the original integral we can see that:
$$I(0)=\frac{\pi}{4}$$
From the solution (and using series expansions for $E$ and $K$) we get:
$$I(0)=\frac{\pi}{6k^2}(1-k^2+k^2/4-1+2k^2+k^2/4)=\frac{\pi}{4}$$
Answer: Possible hints to perfume some kind of calculations.
Leaving apart the extrema of the integra, for the moment.
$$\int\sin^2\theta \sqrt{1 - k^2 \sin^2\theta}\ \text{d}\theta$$
Using the substitution
$$k\sin\theta = \cos\phi ~~~~~~~ \sin\theta = \frac{\cos\phi}{k} ~~~ \to ~~~ \sin^2\theta = \frac{\cos^2\phi}{k^2}$$
$$\phi = \arccos(k\sin\theta)$$
$$\text{d}\phi = \frac{- k\cos\theta}{\sqrt{1 - k^2\sin^2\theta}}\ \text{d}\theta = -\frac{k\sqrt{1 - \sin^2\theta}}{\sqrt{1 - \cos^2\phi}}\ \text{d}\theta = -\frac{k\sqrt{1 - \frac{\cos^2\phi}{k^2}}}{\sin^2\phi}\ \ \text{d}\theta$$
Thence $$\text{d}\theta = -\frac{\sin^2\phi}{\sqrt{k^2 - \cos^2\phi}}\ \text{d}\phi$$ and the integral becomes
$$- \int \frac{\sin^2\phi}{\sqrt{k^2 - \cos^2\phi}}\left(\frac{\cos^2\phi}{k^2}\right)\sin^2\phi \text{d}\phi = -\frac{1}{k^2}\int \frac{\sin^4\phi\cos^2\phi}{\sqrt{k^2 - \sin^2\phi}}\ \text{d}\phi$$
Now we can use the trigonometric reduction formula for the numerator of the integrand:
$$\sin^4\phi\cos^2\phi = \frac{1}{32}(2 - \cos(2\phi) - 2\cos(4\phi) + \cos(6\phi))$$
to get
$$
-\frac{1}{32k^2}\int\ \frac{2 - \cos(2\phi) - 2\cos(4\phi) + \cos(6\phi)}{\sqrt{k^2 - \sin^2\phi}}\ \text{d}\phi
$$
Which might be splitter into four parts, and then.. who knows!
The solution, however, lies into Jacobi Elliptic Functions of the First an Second Kind.
More on Jacobi Elliptic Integrals
https://en.wikipedia.org/wiki/Elliptic_integral
Comment: You made a mistake when calculating $d \phi$, there should be $-k \cos \theta$ in the numerator, which will complicate the integral
Comment: @YuriyS Thant's it!!! Thank you so much, I'm going to delete/edit the answer! I don't think I will be helpful but who knows.. Upvote for you
Comment: Note, that I made a mistake myself, I edited the comment. Check it again to be sure
Comment: @YuriyS Haha funny! Don't worry, I found my error the same, thanks to your hint!
Answer: Following on from @Yuriy-s, I have noticed that the integral:
$$\int k E(k) dk=\frac{1}{3} \left[(1+k^2)E(k)-(1-k^2)K(k) \right]$$
Is incorrect according to wolfram alpha. @Yuriy-s has used this to evaluate the expression, but note that wolfram alpha read this as:
$$\int k E(k^2) dk$$
Making a correction to this gives me this:
$$\int k E(k) dk=\frac{2}{45} \left[3k^2 + k-4)K(k)+(9k^2+k+4)E(k) \right] + C_2$$
where $C_2$ is a constant.
The following @Yuriy-s and subbing in various things:
$$I(k)=\frac{C_1}{k^2}+\frac{1}{k^2} \int k^2 \left(\frac{dE}{dk}+\frac{E(k)}{k} \right) dk$$
$$I(k)=\frac{C_1}{k^2}+E(k) - \frac{2}{45k^2} [(3k^2 +k -4) K(k) +(9k^2 +k +4)E(k)]  + C_2$$
But there is a problem.
putting in the boundary conditions of:
$$I(0)=\frac{\pi}{4}$$
$$E(0)=\frac{\pi}{2}$$
$$K(0)=\frac{\pi}{2}$$
Gives us:
$$\frac{\pi}{4} = \frac{C_1}{0}+\frac{\pi}{2} - \frac{2}{0} [-4\frac{\pi}{2} +4\frac{\pi}{2}] +C_2 $$
$$C_2=\frac{-\pi}{4}$$
$$C_1=0$$
for a final result of:
$$I(k)=E(k) - \frac{2}{45k^2} [(3k^2 +k -4) K(k) +(9k^2 +k +4)E(k)]  - \frac{\pi}{4}$$
Unfortunately this is not the same as wolframs' final answer though:
$$I(k)=\frac{ \sqrt{1-k^2} [K(\frac{k^2}{k^2-1})  + (2k^2-1)E(\frac{k^2}{k^2-1}) ]}{3k^2}$$
Comment: There are two typical conventions for elliptic integrals: Taking them to be functions of $k$, or as functions of $m=k^2$. Mathematica, and therefore Wolfram Alpha, uses the latter; the answer by Yuriy-s, by contrast, uses the former convention. That'd be my guess for why there's a seeming discrepancy.
Comment: @Semiclassical-19 That seems plausible.
But then why does wolfram give different results depending on whether you input the k varaible as any other symbol?
http://www.wolframalpha.com/input/?i=integrate+a+EllipticE%5Ba%5D
http://www.wolframalpha.com/input/?i=integrate+k+EllipticE%5Bk%5D
Answer: No I find a problem with the last formula: with MAPLE the real part is false but the  imaginary part is right.
A true formula is according to WOLFRAM is [(1-k^2)K(k^2)+(2k^2-1)E(k^2)]/3k^2.


Set HTTP body using HTTPService class in the Adobe Air

Question: I need to send a byte array of data as a HTTP body using HTTPService class in the Adobe Air API. Can anyone suggest me the way of doing this?
Answer: Try this
<code>var encodedString : String = Base64.encode( imageByteArray );
var service : HTTPService = new HTTPService();
service.method = "POST";
service.contentType = 'application/x-www-form-urlencoded';
service.url = 'http://www.mydomain.com/upload.php';
var variables : URLVariables = new URLVariables();
variables.imageArray = encodedString;
variables.variable2 = "some text string";
variables.variable3 = "some more text";
service.send( variables );
</code>
Base64 class get from
http://code.google.com/p/jpauclair-blog/source/browse/trunk/Experiment/Base64/src/Base64.as


Mysql carrying out the rate according to the range given

Question: I have a below table in mysql.
CREATE TABLE `mdc_tariff_slabs` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
`type` varchar(50) DEFAULT NULL,
`slab_name` varchar(50) NOT NULL COMMENT 'Name of the Slab',
`slab_start` int(50) NOT NULL COMMENT 'Start of the slab',
`slab_end` int(50) DEFAULT NULL COMMENT 'End of the slab',
`rate` varchar(50) NOT NULL COMMENT 'Rate of slab',
`t_id` int(11) NOT NULL COMMENT 'Tariff ID, Foriegn Key',
 PRIMARY KEY (`id`),
 KEY `T_ID` (`t_id`),
 CONSTRAINT `T_ID` FOREIGN KEY (`t_id`) REFERENCES `mdc_tariff` (`id`) ON DELETE CASCADE
 ) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=latin1;

/*Data for the table `mdc_tariff_slabs` */

insert  into `mdc_tariff_slabs`(`id`,`type`,`slab_name`,`slab_start`,`slab_end`,`rate`,`t_id`) values (1,NULL,'S-1',1,100,'10',1),(2,NULL,'S-2',101,150,'12',1),(3,NULL,'S-3',151,NULL,'14',1),(4,NULL,'S-1',1,50,'5',2),(5,NULL,'S-2',51,100,'7',2),(6,NULL,'S-3',101,NULL,'8',2),(52,'WAPDA','S-1',1,100,'12',12),(53,'WAPDA','S-2',101,150,'14',12),(54,'WAPDA','S-3',151,NULL,'16',12),(58,'Generator','S-1',1,100,'17',12),(59,'Generator','S-2',101,150,'20',12),(60,'Generator','S-3',151,NULL,'22',12);

The same is in my SQL Fiddle
I have slabs range. Within that range of a particular type I want to check the rate. Assuming the value to be checked is 40 and the type is Generator. So if the value is in the slab range 1-100 the rate would be 17 and vice versa.
Expected Output
 type     |value|rate|
======================
 Generator| 40  |17  |
....

How can I achieve this?
Any help would be highly appreciated.
Answer: It looks like slabs can overlap, so you should go for the MAX of slab value to ensure you're handling bad data. This is tricky, because you have rate defined as a varchar. That's why I'm casting it to an int value before summing it. You may still have issues with this. I suggest instead going with an int value for that column.
It also looks like the slab_end can be NULL, representing no end, so a simple BETWEEN condition won't work for your case. I handled it with an OR condition.
Here's how I would do it:
SET @value = 40;
SET @type = 'Generator';

SELECT @type AS type,
    @value AS value,
    MAX(CAST(rate AS UNSIGNED)) AS rate
FROM mdc_tariff_slabs
WHERE type = @type
    AND @value >= slab_start
    AND (@value <= slab_end OR slab_end IS NULL);

Comment: no I don't want to sum it. I just want to get the rate within the range. If `type=Generator` and if the value is between `1-100` the rate would be `17`, if the value is between `101-150` the rate is `20` and if it's above `150` the rate will be `22` and so on
Comment: @FaisalQayyum got it - edited my response to address that


Help on require answer $\int_0^1\frac{2}{[1+x+(-\phi)^{-n}(1-x)]^2}dx=\frac{1}{-{\phi}F_n+F_{n+1}+1}$

Question: $\phi=\frac{1+\sqrt5}{2}$
$F_0=0$, $F_1=1$ ;$F_{n+1}=F_n+F_{n-1}$ ; Fibonacci numbers (0,1,1,2,3,5,...)
Show that,
$$\int_0^1\frac{2}{[1+x+(-\phi)^{-n}(1-x)]^2}dx=\frac{1}{-{\phi}F_n+F_{n+1}+1}$$

Trying to work out...
$$\int_0^1\frac{2}{[1+x+(-\phi)^{-n}(1-x)]^2}dx=\frac{-2}{1-(-\phi)^{-n}}\left[\frac{1}{2}-\frac{1}{1+(-\phi)^{-n}}\right]$$
$$=-\frac{1+(-\phi)^{-n}-2}{1-(-\phi)^{-2n}}$$
This is correct, but it is not getting me to the proposed answer, what do I need to do to get the require answer?
Answer: Use the explicit formula for Fn, as opposed to the recursive formula.
Comment: I know what the closed form is, and I know where to look if I forget those signs. But other people might not know.
Comment: I think answers should be more self-contained. What is the explicit formula?
Comment: @fonini Hmmm... https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
Answer: Observe that
$$\frac{-2}{1-(-\phi)^{-n}}\left[\frac{1}{2}-\frac{1}{1+(-\phi)^{-n}}\right]=\frac{1}{1+(-\phi)^{-n}}$$
$\therefore$ Need to prove by induction that $(-\phi)^{-n}=-{\phi}F_{n}+F_{n+1}$, for nonnegative integer n
Answer: In the linear difference equation $F_{n+1}=F_n+F_{n-1}$, let $F_n=r^n$. Then $r^{n+1}=r^n+r^{n-1}$ or $r^{n-1}(r^2-r-1)=0$. Solution of the characteristic equation is $r=\frac{1\pm\sqrt5}2$, so $r\in\{\phi,-1/\phi\}$. Since this is a linear homogeneous difference equation, superposition works, so $F_n=c_1\phi^n+c_2\left(-\frac1{\phi}\right)^n$. Then
$$F_0=c_1+c_2=0$$
$$F_1=\phi c_1-\frac1{\phi}c_2=1$$
Solving, $c_1=-c_2=1/\sqrt5$, so
$$F_n=\frac1{\sqrt5}\left(\phi^n-\left(-\frac1{\phi}\right)^n\right)$$
Checking, we see that $F_0=0$, $F_1=1$, and
$$\begin{align}F_{n+1}-F_n-F_{n-1}&=\frac1{\sqrt5}\left(\phi^{n+1}-\phi^n-\phi^{n-1}-\left(-\frac1{\phi}\right)^{n+1}+\left(-\frac1{\phi}\right)^n+\left(-\frac1{\phi}\right)^{n-1}\right)\\
&=\frac1{\sqrt5}\left(\phi^{n-1}(\phi^2-\phi-1)-\left(-\frac1{\phi}\right)^{n-1}\left(\left(-\frac1{\phi}\right)^2-\left(-\frac1{\phi}\right)-1\right)\right)\\
&=\frac1{\sqrt5}\left(\phi^{n-1}(0)-\left(-\frac1{\phi}\right)^{n-1}(0)\right)=0\end{align}$$
Then $$\begin{align}F_{n+1}-\phi F_n&=\frac1{\sqrt5}\left(\phi^{n+1}-\left(-\frac1{\phi}\right)^{n+1}-\phi^{n+1}-\left(-\frac1{\phi}\right)^{n-1}\right)\\
&=\frac1{\sqrt5}\left(-\frac1{\phi}\right)^n\left(\frac1{\phi}+\phi\right)=\left(-\frac1{\phi}\right)^n\end{align}$$
And then
$$\begin{align}-\frac{1+(-\phi)^{-n}-2}{1-(-\phi)^{-2n}}&=\frac{1-\left(-\frac1{\phi}\right)^n}{\left(1+\left(-\frac1{\phi}\right)^n\right)\left(1-\left(-\frac1{\phi}\right)^n\right)}\\
&=\frac1{1+\left(-\frac1{\phi}\right)^n}=\frac1{1+F_{n+1}-\phi F_n}\end{align}$$


C# Class constructor default value question

Question: I have the following class:
public class Topic
    {
        public string Topic { get; set; }
        public string Description { get; set; }
        public int Count { get; set; }
    }

I would like to have the Count always set to zero when the class is created with the following:
var abc = new Topic {
  Topic = "test1",
  Description = "description1"
}

I am a bit confused with constructor. Is this possible or do I need to specify Topic, Description and Count when I create abc?
Answer: The default value of an int is 0.
All value types have default values as they can't be null.
See Initializing Value Types on this MSDN page.
Comment: This is good news for me. How about strings and bool. Do they default to "" and false ?
Comment: @Geraldo - No. Strings are reference types, so they default to `null`.
Comment: Is there a way that I could set a string to default to something or do I have to specify each string?
Comment: @Geraldo - You can use a parameterless constructor, but you will still need to set each string in turn. There is not magical way to change such defaults.
Answer: You have a few different options.
1) int defaults to zero so it will be zero if you dont initialize it.
2) you can use a constructor
public Topic(){ Count = 0;}

3) You can use a backing field instead of auto-property and initialize that to zero
 private int _count = 0;
 public int Count {
    get  {return _count}
    set {_count = value; }
 }

Answer: Count will default to 0 on initialisation, since it is a value type and can't be null.
Answer: This following idiom is not only a constructor:
var abc = new Topic {
  Topic = "test1",
  Description = "description1"
}

It's a constructor and an object initializer.
What really happens is that new Topic() is called first, hence initializing all values to their defaults (property Topic is null, Description is null and Count is 0). After that, the value "test1" is assigned to Topic, and the value "description1" is assigned to Description.
All value types have a default value different than null (since they can't be null), and reference types default to null.
Answer: EDIT
As I learned from the comments to this answer, it is perfectly valid to leave out the () in the initializer call.
The correct syntax would be My preferred syntax still is:
var abc = new Topic() {
  Topic = "test1",
  Description = "description1"
}

(note the ()).
This would initialize Count to 0, as 0 is the default value for int. In case you want to always specify Topic and Description, add an explicit constructor:
public Topic(string topic, string description)
{
    Topic = topic;
    Description = description;
    // You may also set Count explicitly here, but if you want "0" you don't need to
}

Comment: Huh?? The OP didn't put an empty argument list in his "constructor call" - I pointed him to this and, as I can not make source code bold, noted my change so that it is easier for him to see. That gives me a -1?
Comment: @Thorsten Dittmar: Whether you have `()` or not in the syntax, it makes no difference whatsoever. Check the IL.
Comment: That was indeed new to me. While it is not required, one might still consider it good style. In that case, "The correct syntax" should be changed to "My preferred syntax". Still, I'm glad to see that a minor thing like that - which is not directly related to answering the question and could easily have been explained by writing a more "elaborate comment" - leads to an immediate downvote. That's how things should work.
Comment: I think the thing that led to the downvote was your incorrectness, which seems reasonable to me.  Note that I haven't voted on your answer.  And I've never heard of anyone saying that omitting the optional parens is not good style.
Comment: Well, I can't omit them for "normal methods", so to be consistent with th ... never mind...
Answer: public class Program
{
    public static void Main()
    {
    // Declare a StudentName by using the constructor that has two parameters.
    StudentName student1 = new StudentName("Craig", "Playstead");

    // Make the same declaration by using a collection initializer and sending
    // arguments for the first and last names. The default constructor is
    // invoked in processing this declaration, not the constructor that has
    // two parameters.
    StudentName student2 = new StudentName
    {
        FirstName = "Craig",
        LastName = "Playstead",
    };

    // Declare a StudentName by using a collection initializer and sending
    // an argument for only the ID property. No corresponding constructor is
    // necessary. Only the default constructor is used to process object
    // initializers.
    StudentName student3 = new StudentName
    {
        ID = 183
    };

    // Declare a StudentName by using a collection initializer and sending
    // arguments for all three properties. No corresponding constructor is
    // defined in the class.
    StudentName student4 = new StudentName
    {
        FirstName = "Craig",
        LastName = "Playstead",
        ID = 116
    };

    System.Console.WriteLine(student1.ToString());
    System.Console.WriteLine(student2.ToString());
    System.Console.WriteLine(student3.ToString());
    System.Console.WriteLine(student4.ToString());
}

// Output:
// Craig  0
// Craig  0
//   183
// Craig  116

}
public class StudentName
{
// The default constructor has no parameters. The default constructor
// is invoked in the processing of object initializers.
// You can test this by changing the access modifier from public to
// private. The declarations in Main that use object initializers will
// fail.
public StudentName() { }

// The following constructor has parameters for two of the three
// properties.
public StudentName(string first, string last)
{
    FirstName = first;
    LastName = last;
}

// Properties.
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }

public override string ToString()
{
    return FirstName + "  " + ID;
}

}


LDAPS Microsoft Active Directory Multiple Certificates RFC6125

Question: We have an Microsoft Active Directory Domain with a large pool of domain controllers (DC) that are are setup with LDAP. These are all setup with LDAPS and uses Certificate Services via a template to setup a certificate with the domain name (i.e. test.corp) in the Subject Alternate Name (SAN) for the LDAPS server to serve.
Since these are DC's, DNS is setup in a pool for each these systems to respond to requests to test.corp in a round robin fashion.
Each of these DC's have multiple templates and multiple certificates in the Local Computer\Personal Certificate Store.
Upon testing, using a nodejs module, ldapjs when making a LDAPS request using the domain name, test.corp we notice that a handful of servers fail with the following message:

Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match
certificate's altnames: Host: test.corp. is not in the cert's
altnames: othername:, DNS:.test.corp

As we investigated we found that these handful of LDAPS servers are serving the incorrect certificate. We determined this by using the following command

openssl s_client -connect .test.corp:636

If you take the certificate section of the output and put it in a file and use a tool such as the Certificate manager or certutil to read the file, you can see the certificate is not the correct one. (It does not have the domain "test.corp" SAN). We also verified this by comparing the Serial Numbers
As we investigated, since we have DC's that have multiple certificates in the Local Computer\Personal Certificate store, we came across the following article:

https://social.technet.microsoft.com/wiki/contents/articles/2980.ldap-over-ssl-ldaps-certificate.aspx

It suggests putting the certificate from the local computer\Personal certificate store to the Active Directory Domain Service\Personal store. We followed the steps outlined but we found the same results.
Upon further investigation, it was suggested to use a tool called ldp or adsiedit. We then proceeded to use these tools and spoofed the local machine's host file we were doing the test from, to point the domain (test.corp) to the ip's of one of the DC's that are giving us trouble. After a restart to clear any cache we tested the "ldp" and "adsiedit" tools to connect to test.corp. These systems did not report any errors.
We found this odd, we then ran the openssl command to see what certificate it was serving from this same system and we found it was still serving the incorrect certificate.
Upon further research, it appears that the "ldp" upon selecting the SSL checkbox and "adsiedit" tools were not compliant with RFC6125, specifically B.3

https://www.rfc-editor.org/rfc/rfc6125#appendix-B.3

, which basically states the identity of the certificate must match the identity of the request otherwise the handshake would fail. This identity verification is done by using the certificate common name (CN) or the SAN.
Based on this appears the tools "ldp" and "adsiedit" are not conforming to the RFC6125 standard.
All this to say, we need to first fix the handful of domain controllers that are serving the correct certificate. We are open to suggestions since we have been working on this problem for the past few months. Second, is there a way to get the MS tools in question to work to the RFC6125 standard?
This has been moved to:
https://serverfault.com/questions/939515/ldaps-microsoft-active-directory-multiple-certificates-rfc6125
Comment: Stack Overflow is for programming questions. You may get better answers at [Server Fault](https://serverfault.com/help/on-topic), which is for questions about managing IT systems.
Comment: I will move this post to server fault.
Comment: This question has been moved to - https://serverfault.com/questions/939515/ldaps-microsoft-active-directory-multiple-certificates-rfc6125
Answer: LDP will supposedly validate the SSL against the client store if you toggle the ssl checkbox on the connection screen.
That said, I'm not surprised that neither it nor ADSI edit enforce that part of the standard given they are often used to configure or repair broken configurations. Out of the box and without Certificate Services they use self signed certs on LDAPS. I would wager 80% of DCs never get a proper certificate for LDAP. If they enforced it most wouldn't be able to connect. A better design decision would have been to toggle off the validation.
I use a similar openssl command to verify my own systems. I think it's superior to LDP even if LDP were to validate the certificate. To save you some effort, I would suggest using this variant of the openssl command:
<code>echo | openssl s_client -connect .test.corp:636 2>/dev/null | openssl x509 -noout -dates -issuer -subject -text
</code>
That should save you having to output to a file and having to read it with other tools.
I've found LDAPS on AD to be a huge pain for the exact reasons you describe. It just seems to pick up the first valid cert it can find. If you've already added it to the AD DS personal store, I'm not sure where else to suggest you go other than removing some of tother certs from the DCs computer store.
Comment: Yes, I do select the SSL checkbox but it still does not validate the identity of the SSL certificate based on the RFC6125 standard but thanks for the suggestion, I updated the post to include this information
Answer: RFC6125 specifically states that it does not supersede existing RFCs.  LDAP cert handling is defined in RFC4513.  Outside of that, RFC6125 has significant flaws.  See also https://bugzilla.redhat.com/show_bug.cgi?id=1740070#c26


Calling an internal Cesium function from outside the script

Question: I am coding a cesium app and I would like to call an internal cesium function that clears all primitives:
function clearAll() {
    primitives.removeAll();
}

when i do a button press. I know about cesium's built in toolbar buttons but I would like to use an html button I already have in place to call this function on click. It's located in:

Any help would be appreciated!
Comment: No. If it's internal (and not exported) it will stay internal (private) until you change the library code.
Comment: Do you know how I would make the function public so I can access it?
Comment: Where do you want to access it? Where did you put your code if not in that `require` callback?
Comment: @Bergi I want to use a button in my html body like this Clear to call the function because I want to be able to alter my script without having to reload the whole script.
Comment: No. Just don't do this. Don't use inline event handlers. Please.
Comment: @Bergi Any reason why this is bad practice?
Comment: You could have done that search yourself, couldn't you? http://stackoverflow.com/q/5871640/1048572 http://stackoverflow.com/q/15792498/1048572
Answer: Take a look at the top of our Billboards example.  When Cesium.Viewer is constructed, it provides access to viewer.scene.primitives which includes the .removeAll() function, which is public.
var viewer = new Cesium.Viewer('cesiumContainer');
var scene = viewer.scene;
var primitives = scene.primitives;

function reset() {
    primitives.removeAll();
}

As @Bergi mentions in the comments, typically you don't wire this up with onclick because you need access to scoped variables like the viewer instance.  Instead, give your button an id attribute, and use addEventListener (or jQuery) to listen for the button click within that scope.
document.getElementById('myButtonId').addEventListener('click', function() {
    primitives.removeAll();
}, false);


What is the vocal technique for Adrien's (Northlane) Low Scream?

Question: I have been told by people that Adrien from Northlane's low screams are growls, but I am not convinced. I have linked below a video with the particular scream I would like to know the name of, and how to accomplish a similar sound.

at time 3:34
Answer: I suspect you're talking about the hallowed Death Growl.  And here's a chap demonstrating how to achieve the technique.
Finally, here's a top 10 from YouTube (NSFW), just to confirm we're talking about the same technique.
Cheers.
Comment: Thanks Morris! However I am finding mixed results. My vocal trainer originally would've agreed with you, but now is convinced it is a low fry scream
Comment: I wouldn't fret over the semantics. As there are multiple terms and phrases to explain the technique you're after, I think you'll just have to investigate further to find the right sound/method/approach for you. [Vocal Fry on Wikipedia](https://en.wikipedia.org/wiki/Vocal_fry_register#In_singing)


Univariate regression analysis - unexpected sign

Question: I am performing an univariate regression analysis by basically regressing a default rate on macro economic variables such as
$DR = \alpha + \beta GDP$
I noticed that sometimes the sign of the betas does not correspond to the economic intuition but when I add some other macro variables (unemplyoment, interest rate), then this variable has a economically intuitive sign.
I was wondering if considering such variable can be problematic ? What is the literature saying about this.
Moreover, concerning the p-value, could be also consider variables that are not significant in the univariate analysis?
Comment: Relevant [answer](https://stats.stackexchange.com/a/74163/7071).
Answer: Once you add one more regressors, your coefficient $\beta$ will always change if the new variable is correlated with the dependent variable and the other independent variable.
So in your case, the change in sign most likely depend on the omission of very important variables like those you mentioned (unemplyoment, interest rate). This is called the omitted variable bias, and if you imagine that the true model depends for example on both GDP and unemployement:
$$  DR = \alpha + \tilde{\beta} GDP + \gamma Unemp + e $$
then your initial $\beta$ will be:
$$ \newcommand{\Var}{\operatorname{Var}}
\newcommand{\Cov}{\operatorname{Cov}}
\beta = \tilde{\beta} + \gamma \frac{\Cov(GDP,Unemp)}{Var(Unemp)}. $$
For what concerns the inclusion  of new varibles in the regression, you should not decide solely on the basis of the p-value of the univariate regression, because as you can see from the previous equation, they can be nevertheless important.


In Windows cmd, how to replace the " special character with a line break?

Question: Just to be thorough, I'll state here my whole project and what I'm aiming at.
I intend to adapt a shell script to work in Windows cmd, as this is intended for people who are not going to have some sophisticate language available.
for g in $(curl -Ls https://api.chess.com/pub/player/hikaru/games/archives | jq -rc ".archives[]") ; do curl -Ls "$g" | jq -rc ".games[].pgn" ; done >> games.pgn

For some reason, Chess.com's API doesn't have a very important feature that Lichess' does, to export all games of a single player, so what I can do manually is to use https://api.chess.com/pub/player/hikaru/games/archives to export all available monthly archives and then hit the API for each one of them. (hikaru inside this will be a set variable, it's the nickname of the desired player to export).
The result for this command is something like
{"archives":["https://api.chess.com/pub/player/hikaru/games/2015/11","https://api.chess.com/pub/player/hikaru/games/2015/12","https://api.chess.com/pub/player/hikaru/games/2016/02","https://api.chess.com/pub/player/hikaru/games/2016/03","https://api.chess.com/pub/player/hikaru/games/2016/04","https://api.chess.com/pub/player/hikaru/games/2016/05"]}

to which I only have to append /pgn to get the desired result.
Obviously, cmd doesn't have jq available, so this involves "parsing" the string inside a batch file.
I figured if I just could replace every occurrence of " with a linebreak and echo the results, I could then use find (or findstr) to easily get a list of lines that only would need to be prefaced with curl  and appended with /pgn to get my final result.
The big question is: how do I replace " with a linebreak in cmd? I found a few answers, but none of them seems to work with a special character, part of the problem is that I also didn't understand these answers enough to try and adapt them.
A second way of perhaps achieving the same result would be replacing [, ] and , with line breaks, but then I would also have to worry with deleting the final " to append /pgn, so if I'm able to do the former, it would be cleaner.
Comment: What you should do, is use something which is designed to parse that type of data, instead of trying to use batch files, which were designed to run a series of simple commands. Windows has PowerShell, which is infinitely more capable, and has built in functionality for JSON
Answer: Stephan's answer gave me the directions I needed to research more and build my own solution. This is not the final script to my project, but it does solve every problem presented in my original question:
@echo off
setLocal enabledelayedexpansion
for /f "delims=" %%a in (input.txt) do (
    for %%b in (%%a) do (
    set string=%%b
    set "string=!string:[=,!"
    set "string=!string:]=,!"
    echo !string!>>replaced.txt
    )
)
for /f "delims=" %%c in (replaced.txt) do (
    for %%d in (%%c) do (
    echo %%~d>>echo.txt
    )
)
for /f %%e in (echo.txt) do echo curl %%~e/pgn|find ".">>list.txt

I basically run 3 sets of loops, the first one loads my input (this could not be done via set because there's a size limit, using a nested loop works around that) and replaces [ and ] for commas.
The second loop sorts again the output. This is done basically to trim unwanted characters from the first and last line.
The last loop generates a list of curl commands that will later be executed into a PGN file (which is a chess file).

This ends the scope of the question, but since my project wasn't that complex, I'll present it's final version, which improves on Compo's answer, in case someone else stumbles upon this question:
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::             Chess.com and Lichess API Scraper               ::
::                  Author: fabiorzfreitas                     ::
:: Extract all games from a player from Chess.com and Lichess  ::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: This tool uses Chess.com and Lichess APIs to extract all games from a given player. ::

@echo off
setLocal enabledelayedexpansion

echo.
echo.
echo.
echo All input must be lowcase!
echo.
echo You can skip the input bellow by pressing Enter
echo.
echo.
echo.
set /p lichess="Input Lichess nickname and press Enter: "
set /p chess="Input Chess.com nickname and press Enter: "
echo.

:Lichess
if not defined lichess goto :Chess

curl https://lichess.org/api/games/user/%lichess% >> Games.pgn

:Chess
if not defined chess goto :End

(for /f "usebackq tokens=2 delims=[]" %%g in (`curl https://api.chess.com/pub/player/%chess%/games/archives`) do (
    for %%h In (%%g) do curl "%%~h/pgn" >> Games.pgn
    )
)

:End
exit

Answer: in batch/cmd, a for loop is used to process a list (separated by default delimiters like space, tab, comma). So just replace [ and ] with a space or comma, and you have a nice list to split. Finally, use find to filter the output to the relevant parts and you're done:
@Echo off
setlocal

set "string={"archives":["https://api.chess.com/pub/player/hikaru/games/2015/11","https://api.chess.com/pub/player/hikaru/games/2015/12","https://api.chess.com/pub/player/hikaru/games/2016/02","https://api.chess.com/pub/player/hikaru/games/2016/03","https://api.chess.com/pub/player/hikaru/games/2016/04","https://api.chess.com/pub/player/hikaru/games/2016/05"]}"

set "string=%string:[= %"
set "string=%string:]= %"
for %%a in (%string%) do echo %%~a|find "/"

Output:
https://api.chess.com/pub/player/hikaru/games/2015/11
https://api.chess.com/pub/player/hikaru/games/2015/12
https://api.chess.com/pub/player/hikaru/games/2016/02
https://api.chess.com/pub/player/hikaru/games/2016/03
https://api.chess.com/pub/player/hikaru/games/2016/04
https://api.chess.com/pub/player/hikaru/games/2016/05

(in case you wonder: the tilde in echo %%~a removes surrounding quotes)
Comment: I just worked with the string you gave. If you want to process a file, surround the code snippet with a `for /f` loop (like you did in your answer). But be aware - that also only works if *each line* is within the max size limit you mentioned.
Comment: This is very close to what I need, except sometimes my input will be bigger than the max size for a set variable. I think I need to do the same, but using `for /f`. I'm trying with `for /f "tokens=* delims=,[]" %%a in (a.txt) do echo %%a`, but this just prints the whole line once. Where am I wrong?
Answer: Based upon your own answer, it seems as if you could remove at least one of those steps by using the brackets [ and ], as delimiters.
You could also nest a for loop within another instead of having individual ones and writing to files.
Here it is as a single line batch-file:
@(For /F "UseBackQ Tokens=2 Delims=[]" %%G In ("input.txt") Do @For %%H In (%%G) Do @Echo curl.exe "%%~H/pgn") 1>"list.txt"

To do it directly in cmd:
(For /F "UseBackQ Tokens=2 Delims=[]" %G In ("input.txt") Do @For %H In (%G) Do @Echo curl.exe "%~H/pgn") 1>"list.txt"

Comment: This seems it would work, except the pgn chess format uses brackets, so I think more passes are needed in order the delims are not applied after the curl command gives it's output. Nevertheless, this is a very good answer and I will study it over the next few days to improve what I already have!
Comment: I did test and it did output the results I informed you, but perhaps my phrasing was wrong. I mean it theoretically seemed to work, but not in practice. The issue presented was beyond the scope of this question, that's why I didn't go into further details. Also, please keep in mind your answer came after I posted mine, indicating the problem was solved. The only reason I didn't accept it yet was for the minimum time to wait before accepting my own answer. I also intended to edit it with knowledge gained from your answer, but as I said, it wound be beyond the scope, so I'll end it now.
Comment: The task was provided in your question, you gave an example and told us what you wanted, i.e. `{"STRING":["URI","URI","URI","URI","URI","URI"]}`, intended results were each of the URI's suffixed with `/pgn` on separate lines. That is what my answer does. You haven't made clear to me what exactly is failing with my code, either in your question, or the above comments, but if there are characters in them which are not normal in a URI, and you haven't told us what those are, I'm struggling to work out how you answer can work when mine cannot. Please provide me with the missing information I need!
Comment: Sure, this is what happens: the final task I intended to do was to run multiple curl commands that look like `https://api.chess.com/pub/player/hikaru/games/2015/11/pgn` (I have barely mentioned it when I wrote about "appending `/pgn` to my output). This command outputs a specific kind of string, a [PGN](https://en.wikipedia.org/wiki/Portable_Game_Notation#Example), which can only be useful by redirecting the output to `file.pgn`. It turns out that pgns have lots of brackets, as you can see in the provided example, therefore I'll need to study carefully when `delims=[]` is active or not.
Comment: Playing games? Perhaps you dislike the fact that I only presented you the exact same courtesy you showed me from the start. I never asked for someone to do the whole job for me, I had an issue with my code and I was trying to learn how to fix it. But here are the instructions to show how your code doesn't work and mine does (I'll even update my answer with a newer version to make it easier): run `curl https://api.chess.com/pub/player/fabiorzfreitas/games/archives>input.txt`, feed it to your code. Run my script, input nothing for lichess nickname, input `fabiorzfreitas` when asked, compare both
Comment: @Fabio, I've removed my last comment, because you seem to have thought it rude, and that was unintended. I've adjusted my code above to just output the results to list.txt, in exactly the same way as your initial answer does. If you take my code and you initial answer, and run them against the same input.txt file, my list.txt will contain a sequence of the same lines as yours, only with correctly used extension for cURL, and with the URI's doublequoted for safety. Mine will not leave an echo.txt or a replaced.txt, it is faster, and more robust. I didn't do the job for you, I fixed your answer.
Comment: Thanks, good thing we are on the same page again. I'll accept your answer, as it's better than mine, although I intend to update mine after I fully incorporate your code into my project, which means including the execution of the curl commands that generate `input.txt` and contained in `list.txt`
Comment: BTW, you need to fix you "single line batch file" part, it has double code, which does not match the code below.


Unity Gear Vr Object Interaction

Question: I want to select an object in the scene with the Gear VR controller when the the laser has hit an object and the user presses the back side button of the controller. I have done the raycasting and the laser for the controller and it's working fine but I can not find a way to make the selection work. The code is as follows and I also have commented the part which I have written and what it's supposed to be doing.
using System;
using UnityEngine;

namespace VRStandardAssets.Utils
{
    // In order to interact with objects in the scene
    // this class casts a ray into the scene and if it finds
    // a VRInteractiveItem it exposes it for other classes to use.
    // This script should be generally be placed on the camera.
    public class VREyeRaycaster : MonoBehaviour
    {
        public event Action<RaycastHit> OnRaycasthit;                   // This event is called every frame that the user's gaze is over a collider.

        [SerializeField]
        private LineRenderer m_LineRenderer = null; // For supporting Laser Pointer
        public bool ShowLineRenderer = true;                         // Laser pointer visibility
        [SerializeField]
        private Transform m_TrackingSpace = null;   // Tracking space (for line renderer)

        [SerializeField]
        private Transform m_Camera;
        [SerializeField]
        private LayerMask m_ExclusionLayers;           // Layers to exclude from the raycast.
        [SerializeField]
        private Reticle m_Reticle;                     // The reticle, if applicable.
        [SerializeField]
        private VRInput m_VrInput;                     // Used to call input based events on the current VRInteractiveItem.
        [SerializeField]
        private bool m_ShowDebugRay;                   // Optionally show the debug ray.
        [SerializeField]
        private float m_DebugRayLength = 5f;           // Debug ray length.
        [SerializeField]
        private float m_DebugRayDuration = 1f;         // How long the Debug ray will remain visible.
        [SerializeField]
        private float m_RayLength = 500f;              // How far into the scene the ray is cast.

        private VRInteractiveItem m_CurrentInteractible;                //The current interactive item
        private VRInteractiveItem m_LastInteractible;                   //The last interactive item
        private String m_IIName;
        private string[] objArrayName1 = {"Clock","Train", "Chair", "Pant", "Bed", "BlueHat" };
        private string[] objArrayName2 = { "BookOld", "Lambo", "NotebookGRN", "Airplane", "Cup1", "Teddy" };
        private int phase = 0;
        private short i = 0;
        private OVRInput.Controller controller;

        // Utility for other classes to get the current interactive item
        public VRInteractiveItem CurrentInteractible
        {
            get { return m_CurrentInteractible; }
        }

        private void OnEnable()
        {
            m_VrInput.OnClick += HandleClick;
            m_VrInput.OnDoubleClick += HandleDoubleClick;
            m_VrInput.OnUp += HandleUp;
            m_VrInput.OnDown += HandleDown;
        }

        private void OnDisable()
        {
            m_VrInput.OnClick -= HandleClick;
            m_VrInput.OnDoubleClick -= HandleDoubleClick;
            m_VrInput.OnUp -= HandleUp;
            m_VrInput.OnDown -= HandleDown;
        }

        private void Update()
        {
            EyeRaycast();
        }

        private void EyeRaycast()
        {
            // Show the debug ray if required
            if (m_ShowDebugRay)
            {
                Debug.DrawRay(m_Camera.position, m_Camera.forward * m_DebugRayLength, Color.blue, m_DebugRayDuration);
            }

            // Create a ray that points forwards from the camera.
            Ray ray = new Ray(m_Camera.position, m_Camera.forward);
            RaycastHit hit;

            Vector3 worldStartPoint = Vector3.zero;
            Vector3 worldEndPoint = Vector3.zero;
            if (m_LineRenderer != null)
            {
                m_LineRenderer.enabled = ControllerIsConnected && ShowLineRenderer;
            }

            if (ControllerIsConnected && m_TrackingSpace != null)
            {
                Matrix4x4 localToWorld = m_TrackingSpace.localToWorldMatrix;
                Quaternion orientation = OVRInput.GetLocalControllerRotation(Controller);

                Vector3 localStartPoint = OVRInput.GetLocalControllerPosition(Controller);
                Vector3 localEndPoint = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

                worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
                worldEndPoint = localToWorld.MultiplyPoint(localEndPoint);

                // Create new ray
                ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
            }

            // Do the raycast forweards to see if we hit an interactive item
            if (Physics.Raycast(ray, out hit, m_RayLength, ~m_ExclusionLayers))
            {
                VRInteractiveItem interactible = hit.collider.GetComponent<VRInteractiveItem>(); //attempt to get the VRInteractiveItem on the hit object
                if (interactible)
                {
                    worldEndPoint = hit.point;
                }
                    m_CurrentInteractible = interactible;

                //****************************************************     I started coding here   (If the user selects an interactive object the we have to check if it's in phase A or B of the game     *****************************************************************
                if (OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger))  //If the user pressed the back side button of the controller
                {

                    m_IIName = m_CurrentInteractible.name;
                    if (phase == 0)
                    {
                        while (m_IIName != objArrayName1[i] && i < 6) // Looking through the object name array to see if we have found an interactive object belonging in Phase A
                        {
                            i++;
                        }
                        if (i < 6) // The object belongs in Phase A
                        { //If we have found an interractive item belonging in Phase A then we have to trigger it
                            Debug.Log("Found an inter item of phase A");
                            m_CurrentInteractible.transform.Rotate(Vector3.right * 10);
                        }
                        else // Did not belong in Phase A
                        {
                            i = 0;
                        }

                    }
                    else
                    {
                        while (m_IIName != objArrayName2[i] && i < 6) // Looking through the object name array to see if we have found an interactive object belonging in Phase B
                        {
                            i++;
                        }
                        if (i < 6) // The object belongs in Phase B
                        { //If we have found an interractive item belonging in Phase B then we have to trigger it
                            Debug.Log("Found an inter item of phase B");
                        }
                        else
                        {
                            i = 0; // Did not belong in Phase B
                        }

                    }
                }

                    //**************************************************************************     I stoped coding here              ********************************************************************

                // If we hit an interactive item and it's not the same as the last interactive item, then call Over
                if (interactible && interactible != m_LastInteractible)
                    interactible.Over();

                // Deactive the last interactive item
                if (interactible != m_LastInteractible)
                    DeactiveLastInteractible();

                m_LastInteractible = interactible;

                // Something was hit, set at the hit position.
                if (m_Reticle)
                    m_Reticle.SetPosition(hit);

                if (OnRaycasthit != null)
                    OnRaycasthit(hit);
            }
            else
            {
                // Nothing was hit, deactive the last interactive item.
                DeactiveLastInteractible();
                m_CurrentInteractible = null;

                // Position the reticle at default distance.
                if (m_Reticle)
                    m_Reticle.SetPosition(ray.origin, ray.direction);
            }

            if (ControllerIsConnected && m_LineRenderer != null)
            {
                m_LineRenderer.SetPosition(0, worldStartPoint);
                m_LineRenderer.SetPosition(1, worldEndPoint);
            }
        }

        public bool ControllerIsConnected
        {
            get
            {
                OVRInput.Controller controller = OVRInput.GetConnectedControllers() & (OVRInput.Controller.LTrackedRemote | OVRInput.Controller.RTrackedRemote);
                return controller == OVRInput.Controller.LTrackedRemote || controller == OVRInput.Controller.RTrackedRemote;
            }
        }
        public OVRInput.Controller Controller
        {
            get
            {
                OVRInput.Controller controller = OVRInput.GetConnectedControllers();
                if ((controller & OVRInput.Controller.LTrackedRemote) == OVRInput.Controller.LTrackedRemote)
                {
                    return OVRInput.Controller.LTrackedRemote;
                }
                else if ((controller & OVRInput.Controller.RTrackedRemote) == OVRInput.Controller.RTrackedRemote)
                {
                    return OVRInput.Controller.RTrackedRemote;
                }
                return OVRInput.GetActiveController();
            }
        }

        private void DeactiveLastInteractible()
        {
            if (m_LastInteractible == null)
                return;

            m_LastInteractible.Out();
            m_LastInteractible = null;
        }

        private void HandleUp()
        {
            if (m_CurrentInteractible != null)
                m_CurrentInteractible.Up();
        }

        private void HandleDown()
        {
            if (m_CurrentInteractible != null)
                m_CurrentInteractible.Down();
        }

        private void HandleClick()
        {
            if (m_CurrentInteractible != null)
                m_CurrentInteractible.Click();
        }

        private void HandleDoubleClick()
        {
            if (m_CurrentInteractible != null)
                m_CurrentInteractible.DoubleClick();

        }
    }
}

Answer: You're VRInteractiveItem is subscribed to the actions OnOver, OnClick, etc. Being OnCancel the action suscribed to the back button on GearVr.
So I recommend you to code another class like (let's suppouse that the object to which the laser gives it is a CubeObject) who have a refference to that Interactive Object, and attach this class to the object:
namespace VRStandardAssets.Menu
{

    public class CubeObject : MonoBehaviour
    {
        [SerializeField] private VRInteractiveItem m_InteractiveItem;       // The interactive item script reference from the same gameobject.
        [SerializeField] private bool isLookingAtIt = false;            //flag to know if player is onOver the object

        private void OnEnable ()
        {
            m_InteractiveItem.OnOver += HandleOver;
            m_InteractiveItem.OnOut += HandleOut;
            m_InteractiveItem.OnCancel += HandleCancel;
        }
        private void OnDisable ()
        {
            m_InteractiveItem.OnOver -= HandleOver;
            m_InteractiveItem.OnOut -= HandleOut;
            m_InteractiveItem.OnCancel -= HandleCancel;
        }

         private void HandleCancel()
        {
            //Do stuff when I click on the object
            doBackButtonStuff();
        }

        private void doBackButtonStuff(){
            if(isLookingAtIt){
                print("user has clicked back button while raycast hit it");
            }
        }

        private void HandleOver()
        {
            //Do things when the object is onOver
            isLookingAtIt = true;
        }
         private void HandleOut()
        {
            //Do things when the object is onOut
            isLookingAtIt = false;
        }
    }
}

Unity Gear Vr Object Interaction


iOS Valid signing identity not found

Question: I see this questions comes up a lot, but no answers for me.  I have revoked the previous Development and Distribution Certificates and generated new ones.  I have downloaded both certificates and installed them by double-clicking.  In my Keychain Access I can see my certificates and they have a green circle with a check mark saying "This certificate is valid".
Then I created my new Development and Distribution Provisioning Profiles and downloaded them.  They have a green button showing they are Active.  I drag the downloaded Provisioning Profiles over to my Xcode icon.  I open Xcode Organizer and click on LIBRARY --> Provisioning Profiles.  They are there with today's date on them but the status is "Valid signing identity not found"
What's the missing step here?
Answer: I got some help from someone who understands the Keychain Access tool.  The problem was that I had multiple certifications and XCode was getting confused.
Thanks everybody.
Answer: Don't forget to set Code Signing Identity under Build Settings !

You have to set all to the same code signing .
And you have to do it in your Project, and Targets too !

Hope this helps!
Answer: If you're still using XCode 4.X you could try Organizer->Library(top left)->Refresh(bottom right) and see if that solves the problem for you.
Hope this helps!

iOS Valid signing identity not found


isFollowingCamelCaseConventionInCPlusPlus more_import_than_readability?

Question: I'm moving back from Python to C++ for my next project.
I know why I shouldn't and I know why I should. Never mind that debate.
C++ conventionForVariablesIsCamelCaseAndI'mHavingTroubleAcceptingIt as, at_least_for_my_eyes_it's_less_readable_than_the_lower_case_underscored_convention.
Did any of you encounter an article or information claiming programmers should adopt lower_case_underscored convention and abandon the camelCase, even in C++ projects? Or perhaps research that shows that one is indeed scientifically more readable than the other?
Comment: This has been discussed a few times before on Programmers: http://programmers.stackexchange.com/q/27264/15464
Comment: C++ doesn't have a convention for naming variables.  I never use camelCase in C++.  You seem to be confusing one arbitrary set of style recommendations for a general standard.
Comment: @Glenn - you're right, my bad
Answer: If coding in a team, consistency is probably more important than personal preference; team members should not have to context switch between reading Joe's code and reading Jane's code.  Equally if coding academic assignments, course style like team style should be adhered to (for right or wrong), simply because the person awarding the marks will be used to reading that, and you need to extract the best possible mark for your work!
I would suggest otherwise that one convention has little advantage over another.  CamelCase does provide a certain efficiency of symbol length.
Answer: If it's a private project, use whatever naming convention you feel comfortable with and helps you be productive. Just bear in mind that it is generally a good idea to be in keeping with the overall "style" oft he language / usual practise since any samples / examples etc. will usually use that style, making integration etc. easier and less "jarring".
If it's a public project it's probably better to use the conventions since that's easier for other people to work with.
If it's corporate, do whatever your corporate guidelines mandate. If there aren't any, then I'd do the same as for a public project.
One thing I'd personally say about CamelCase, is not to get completely hung up on it, and apply common sense for the sake of readability. For example, I've often seen abbreviations in camel case names written as part upper / part lower, which I think really hurts readability. In cases like this I'd always go for the more readable option. So, for example I'd always write:
private string targetURL;

rather than
private string targetUrl;

But, this is just personal preference.
Answer: There is no agreed upon convention for C++ naming among C++ programmers, however  lower case with underscores is used in both the C++ standard library and in boost.

As for the coding standards document you linked...
A link to a random company's coding standards that use "Common practice in the C++ development community" as a justification for their standards, yet provide no citation for that statement smells like a false appeal to authority in order to justify the preferences of whoever wrote the document.
Answer: CamelCase vs underscores: Scientific showdown describes a single scientific study which found:

Considering all four hypotheses together, it becomes evident that the camel case style leads to better all around performance once a subject is trained on this style. Training is required to quickly recognize such an identifier.

But then the page disagrees that their conclusions are valid.  :)
It also has two polls of visitors to the site, both of which are 50/50 in favor of each style.
Comment: Don't forget to read the follow-up study which I link to in a comment: http://www.computer.org/portal/web/csdl/doi/10.1109/ICPC.2010.41 ;p It attempts to solve some of the problems with the original study which I blogged about.


Expected value of sin of brownian motion

Question: I am having trouble finding $E[X_t]$, where $X_t = \sin(B_t)$ and $B_t$ is a Brownian motion. I have learned a little about Ito integrals but I don't think I really understand how to use them.
Here is my approach at the moment:
$$E[X_t] =E[\sin(B_t)] =\left(\frac{1}{\sqrt {2\pi t} } \int_{-\infty}^\infty e^\frac{-(x)^2}{2t} \sin(x) dx\right)\bigg\rvert_{x=B_t}$$
Is this the right approach? Any help would be appreciated, thank you!
Comment: Here $t$ is a fixed number.  Then this is not an Ito integral, it is an ordinary expectation.
Comment: First figure out the distribution of $B_t$ (for any fixed time $t$). Note that the distribution is symmetric about $0$ and $\sin$ is an odd function.
Comment: The integral you wrote is some bizzarre mess: $dB_t$ refers to stochastic integration. Change $B_t$ to $x$ throughout.
Comment: personally I would use the complex exponential expression for the sine, the expectation will follow directly from the characteristic function of a gaussian r.v.
Answer: If you've seen Ito's formula, then you can show that
$$
\sin(B_t) =\sin(B_0)-{1\over 2}\int_0^t\sin(B_s)\,ds+M_t,
$$
where $(M_t)$ is a martingale with $M_0=0$. Define $g(t):=E[\sin(B_t)]$; taking expectations in the above, assuming that $B_0=x$ (constant):
$$
g(t)=g(x)-{1\over 2}\int_0^t g(s)\,ds,\qquad t\ge 0.
$$
Differentiate this to obtain an ODE for $g$ that you can easily solve.
Comment: May I ask why we could move the expectation inside the integral? Is it always true that $$E \left [\int_0^t f(B_s) ds \right] = \int_0^t E \left[f(B_s) \right] ds$$?
Comment: This is okay by Fubini's theorem, because $\sin$ is a bounded function.


A question about continuous actions of topological groups.

Question: Let $G$ act continuously on $X$. If $K$ is a compact subspace of $G$ and $B$ a closed subspace of $X$, is $KB:=\{k.b|k\in K,b\in B\}$ a closed subspace of $X$?
I know this to be true when $X$ is the same as $G$ with the action being the group operation. I think the proof using nets in this case could be adapted to the general case, but I am not completely sure.
Comment: What are $G$ and $X$?
Comment: G is a topological group and $X$ is a topological space. The action is a continuous map.
Answer: Indeed the usual proof idea as used for subsets of topological groups also
applies here:
Suppose that $k_i \cdot b_i$ (for some $i \in I$, a directed set) is a net in $KB$ converging to $x \in X$.
Then $(k_i)_i$ is a net in $K$ so by compactness we have a convergent subnet $(k'_j)_{j \in J}$ (with $J$ also a directed set, and a corresponding connecting map $f: J \to I$) of $(k_i)_i$ (so that $f[J]$ is cofinal in $I$ and $k'_j = k_{f(j)}$ for all $j$ etc.)) converging to $k \in K$.
By continuity of the inverse operation, we have that $((k')^{-1}_j)_j \to k^{-1}$ as well.
The same connecting map $f$ allows us to define the corresponding subnet $(b'_j)_j$ of $(b_i)_i$ as well by setting $b'_j = b_{f(j)}$ as usual.
It follows by the group action axioms that for all $j$: $$(k'_j)^{-1} \cdot (k'_j \cdot b'_j) = ((k'_j)^{-1} \ast_G k'_j)\cdot b'_j = 1_G \cdot b'_j = b'_j$$
and the left hand side converges to $k^{-1} \cdot x$ (as subnets of convergent nets converge to the same limit and the action is continuous). As the $b'_j$ are all from the closed set $B$, $k^{-1} \cdot x \in B$ as well. Hence $x = k \cdot (k^{-1} \cdot x) \in KB$ as well and the latter set is closed.
Comment: Thank you very much!


Show that the equation has non integer solution $x^2-3y = 5$

Question:
Show that the equation has non integer solution $x^2 - 3y = 5$

According to the solutions of the exercise, for that equation to have integer solutions then $$x^2\equiv5\pmod 3$$ must be true, otherwise it has non integer solutions.
Why is this true? Where does the (mod 3) come from? Why not (mod of something else)?
Comment: The mod 3 deals with the $3y$ part, leaving you only with the $x$, which is very convenient.
Comment: @Daniel Which does not because $x^2-4y=5$ has integer solutions, e.g. $x=y=5$. Thus no $(\mbox{mod }N)$ trick works here. So I woudln't call it a technique. More like observation, in some situations it works, in others it does not.
Comment: @Daniel so if the equation was x² - 4y = 5 i would get $$x^2\equiv5\pmod 4$$
Comment: Right, and then you'd need to see if this yields a contradiction or not
Comment: @freakish That's right. Moreover, it may be the case in which there are no solutions at all but taking modulo doesn't yield any contradiction. For instance $x^2  + 2 y^2 = -1$, if you take modulo 2 then it would be $x^2 = -1 \mod 2$, which is not a contradiction of course
Answer: $y=(x^2-5)/3$
For $y$ to be an integer, the numerator should be divisible by 3.
Now,
Every perfect square leaves a reminder of 0 or 1 when divided by 3.
So, $x^2-5$ will leave reminder 1 or 2 but never zero.
Thus no integer solutions are possible.
Answer: We rearrange the equation to get $x^2 = 3y + 5$, which says that we're looking for an $x$ that, when squared, is three times some integer $y$ plus 5. And "is equal to three times some integer plus 5" is the same as "is congruent to 5, mod 3". Hence, $x$ is a solution to the equation if and only if $x^2 \equiv 5\ (\mbox{mod } 3)$.
Answer: Given $x^2-3y =5$, we need $x^2-5 = 3y$. Then constraining $x$ and $y$ to integers gives us that $x^2-5$ is divisible by $3$, and thus $x^2\equiv 5\equiv 2 \bmod 3$, which doesn't have integer solutions since $x\nmid 3 \implies x=3k\pm 1\implies x^2 = 9k^2 \pm 6k +1 \equiv 1 \bmod 3$
Answer: More accuracy, the issue equation has the consequence
$$x^2\equiv 2\pmod3.\quad(1)$$
On the other hand, unknown $x$ must belong to one of residue classes $\{0,1,2\}$ modulo $3$. So
$$x^2\bmod3\in\{0,1\},$$
and that contradicts with $(1).$


How to run multiple color bloom animations that run at the same time?

Question: I've been trying out the new Windows.UI.Composition APIs lately and when using the color bloom animation, I've been trying to run four of them simultaneously from each side of the screen. I've been able to make all four of them run at a click of a button but the last transition I've started always takes over the display in the end for example:
This is what happens:

But what should happen is that all the colors should fill the screen at the same time. How would I be able to do that?
This is the code I used to start the animations:
private void surroundBloomButton_Click(object sender, RoutedEventArgs e)
    {

        //all of these headers are actually textblocks I've placed on the sides of the grid.
        var header = topFlower;

        var headerPosition = topFlower.TransformToVisual(UICanvas).TransformPoint(new Windows.Foundation.Point(0d, 0d));

        var header2 = rightFlower;

        var header2Position = rightFlower.TransformToVisual(UICanvas).TransformPoint(new Windows.Foundation.Point(0d, 0d));

        var header3 = bottomFlower;

        var header3Position = bottomFlower.TransformToVisual(UICanvas).TransformPoint(new Windows.Foundation.Point(0d, 0d));

        var header4 = leftFlower;

        var header4Position = leftFlower.TransformToVisual(UICanvas).TransformPoint(new Windows.Foundation.Point(0d, 0d));

        //Uses values of the textBlock size

        var initialBounds = new Windows.Foundation.Rect()
        {
            Width = header.RenderSize.Width,
            Height = header.RenderSize.Height,
            X = headerPosition.X,
            Y = headerPosition.Y
        };

        var finalBounds = Window.Current.Bounds; // maps to the bounds of the current window
        //The code is super easy to understand if you set a break point here and
        //check to see what happens step by step ;)
        surroundButtonTransition.Start((Windows.UI.Color.FromArgb(255, 255, 0, 0)),  // the color for the circlular bloom
                             initialBounds,                                  // the initial size and position
                                   finalBounds);                             // the area to fill over the animation duration

        // Add item to queue of transitions

        initialBounds = new Rect()
        {
            Width = header2.RenderSize.Width,
            Height = header2.RenderSize.Height,
            X = header2Position.X,
            Y = header2Position.Y
        };

        surroundButtonTransition.Start((Windows.UI.Color.FromArgb(255, 255, 150, 0)),  // the color for the circlular bloom
                           initialBounds,                                  // the initial size and position
                                 finalBounds);                             // the area to fill over the animation duration

        initialBounds = new Rect()
        {
            Width = header3.RenderSize.Width,
            Height = header3.RenderSize.Height,
            X = header3Position.X,
            Y = header3Position.Y
        };

        surroundButtonTransition.Start((Windows.UI.Color.FromArgb(255, 0, 255, 0)),  // the color for the circlular bloom
                           initialBounds,                                  // the initial size and position
                                 finalBounds);                             // the area to fill over the animation duration

        initialBounds = new Rect()
        {
            Width = header4.RenderSize.Width,
            Height = header4.RenderSize.Height,
            X = header4Position.X,
            Y = header4Position.Y
        };

        surroundButtonTransition.Start((Windows.UI.Color.FromArgb(255, 0, 0, 255)),  // the color for the circlular bloom
                           initialBounds,                                  // the initial size and position
                                 finalBounds);                             // the area to fill over the animation duration
    }

   private void SurroundButtonTransition_ColorBloomTransitionCompleted(object sender, EventArgs e)
    {
        //Changes colour of background to "White Smoke " when
        //the animations have finished.
        UICanvas.Background = new SolidColorBrush(Windows.UI.Colors.WhiteSmoke);
    }

Answer: As you said, you are trying out the new Windows.UI.Composition APIs lately and when using the color bloom animation.
Since you had not post your code about the surroundButtonTransition that I use the ColorBloomTransitionHelper from the GitHub. It uses the  ContainerVisual.Children.InsertAtTop method to insert a new visual at the top of the visual collection.
Also there is no method to add new visual at the same zindex as other visual in ContainerVisual.Children. Please check the method in VisualCollection class.
If you want all the colors should fill the screen at the same time, you should be able to change the alpha value of your color.
For example:
surroundButtonTransition.Start((Windows.UI.Color.FromArgb(100, 255, 0, 0)), initialBounds, finalBounds);
surroundButtonTransition.Start((Windows.UI.Color.FromArgb(100, 255, 150, 0)), initialBounds, finalBounds);
surroundButtonTransition.Start((Windows.UI.Color.FromArgb(100, 0, 255, 0)), initialBounds, finalBounds);
surroundButtonTransition.Start((Windows.UI.Color.FromArgb(100, 0, 0, 255)), initialBounds, finalBounds);


If $f(x)=\frac{2}{\sqrt{3}}\int_{0}^{\sqrt{3}}f\left(\frac{\lambda^2x}{3}\right)d\lambda,x>0$ and $f(1)=\sqrt3$ and if $f(\alpha)=6$ . find $\alpha$

Question: Let $f(x)$ be a differentiable function satisfying $$f(x)=\frac{2}{\sqrt{3}}\int_{0}^{\sqrt{3}}f\left(\frac{\lambda^2x}{3}\right)d\lambda,x>0$$
and $f(1)=\sqrt3$ .
If $y=f(x)$ passes through the point $(\alpha,6)$ then determine the value of $\alpha$ .
My Attempt
Since $f(1)=\sqrt3$ we have $\int_{0}^{\sqrt3}f(\frac{\lambda^2}{3})d\lambda=\frac{3}{2}$ and since $f(\alpha)=6$ we have $\int_{0}^{\sqrt3}f(\frac{\lambda^2\alpha}{3})d\lambda=3\sqrt3$.
Also it is given that $f(x)$ is differentiable so $f'(x)=\frac{2}{3\sqrt3}\int_{0}^\sqrt3f'(\frac{\lambda^2x}{3})\lambda^2d\lambda$.
After this I am not able to proceed.
Comment: I was editing an answer while someone is quicker, the rough idea is to use change of variable to get something like $\sqrt{x}f(x) = \int_0^x f(u)/ \sqrt{u} du$, then use fundamental theorem of calculus.
Comment: Can you elaborate a bit more
Answer: Note that
$$f(x)=\frac{2}{\sqrt{3}}\int_{0}^{\sqrt{3}}f\left(\frac{\lambda^2x}{3}\right)d\lambda\overset{\frac{\lambda^2x}{3}\to \lambda}=\frac{1}{\sqrt{x}}\int_{0}^{x}f(\lambda)\frac{1}{\sqrt{\lambda}}d\lambda$$
and hence
$$ (\sqrt xf(x))'=f(x)\frac{1}{\sqrt{x}}=\frac{\sqrt{x}f(x)}{x}. $$
So
$$ \frac{(\sqrt xf(x))'}{\sqrt{x}f(x)}=\frac1x$$
or
$$\ln(\sqrt{x}f(x))=\ln x+C$$
or
$$ \sqrt{x}f(x)=Cx $$
or $f(x)=C\sqrt x$. By $f(1)=\sqrt3$, one has $C=\sqrt3$ and hence
$$ f(x)=\sqrt{3x}. $$
Comment: What Wolfram does mean when face  to the equation
$$f(x)=\frac{2}{\sqrt{3}}\int_{0}^{\sqrt{3}}f\left(\frac{\lambda^2x}{3}\right)d\lambda$$ gives as **solution of the recurrence equation**
$$f(x)=\displaystyle {c_12^{\frac{1-\log(x)}{\log(t/3)}}}$$ where $c_1$ is an arbitrary parameter?
Comment: Sometimes Wolfram doesn't give correct answers.


How to reuse object between Drupal Behaviors?

Question: We have a JS file (basic-page.js) that has the following Drupal Behavior. In this, we created what we believe is considered a Drupal object (need help with correct term) that contains a function that can be called. In the latest request, we need the ability to reuse the same code from the Drupal Behavior in another Drupal Behavior.
How could we reuse the code? Currently the article.js is not able to use the code from basic-page.js, no errors or warnings are given.
basic-page.js (where Drupal object resides)
(function($) {
  'use strict';
  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

  Drupal.behaviors.customName = {
    attach: function(context, setting).once('customName').each(function() {
      /* behavior runs here */
      var func1 = Drupal.customObj;
      var results = func1.function1($('body'));
      //process results
    });
  };
})(jQuery);

article.js (where we want to reuse Drupal.customObj.function1)
(function($) {
  'use strict';

  Drupal.behaviors.articleResults = {
    attach: function(context, setting).once('articleResults').each(function() {
      /* behavior runs here */
      var customObj = Drupal.customObj;
      var results = customObj.function1($('body'));
      //process results
    });
  };
})(jQuery);

Comment: Neither of those are valid JS so you should definitely be seeing errors in the console (`attach: function(context, setting).once('articleResults').each(function() {` specifically). Are you sure those files are in the page?
Comment: @Clive i have updated the weights but no luck. What do you mean by valid JS? How should those be written? My understanding is the when using once() you want to pass in the behavior that you would like to run once? remove 'articleResults' and leaving it as once() has the same behavior
Answer: I'll focus on the inclusion first, then describe what Clive was referring to, while mentioning that your JS is not valid:
For your use case you should add a common library to your module/theme that extends the Drupal object. (You don't even have to extend the Drupal object, but can create an own one, if you prefer.)
Then use dependencies to make sure the object is available in your basic page JS, as well as in your article JS.
Example
In your *.libraries.yml
mymodule/common:
  js:
    js/mymodule-common.js: {}
  dependencies:
    - core/drupal
    - core/jquery

mymodule/page:
  js:
    js/mymodule-page.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

mymodule/article:
  js:
    js/mymodule-article.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

You can then split your JS to the three separate files containing your code. The dependencies section makes sure the scripts your library depends on are loaded before.
Now to the scripts itself:
mymodule-common.js
(function($) {
  'use strict';

  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

})(jQuery);

mymodule-page.js
(function($) {
  'use strict';

  Drupal.behaviors.customName = {
    attach: function(context, setting) {
      $('body').once('customName').each(function() {
        var func1 = Drupal.customObj;
        var results = func1.function1($('body'));
        //process results
      });
    }
  };

})(jQuery);

And similar in your mymodule-article.js.
And here the promised feedback to the comment of Clive: Compare the attach property in the last example. It expects a callable that will be executed every time a page/ajax load finished. Within its body you can then do your magic.
References:
https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
Comment: The thing that i was missing was the dependency on the article library. After updating it fixed the issues


Angular - show cumulative array building in template

Question: How do I show an array building in an Angular template as it builds in values?
const timer = interval(1000);
const array = [1,2,4,6,9,10,8,9,6,5]
let newArray = []
this.count$ = timer.pipe(
    map(i => newArray.push(array[i])),
  );

{{ count$ | async }}

Only shows the last emitted value. I want to see [1], then [1,2] then [1,2,4] etc...
Answer: Try using zip and scan:
this.count$ = zip(timer, array).pipe(
  map(([i, value]) => value),
  scan((acc, cur) => [...acc, cur], [])
);

zip will ensure that the timer only emits as many times as there are values in the array.
map will then get rid of the value from timer and just take the value from array.
scan will then accumulate the values into an array as they are emitted.
Comment: I'm getting a typescript error: Type 'number' is not assignable to type 'never'.
Comment: Do you have more details? Stackblitz? Which part is the error coming from?
Comment: Thanks, I got it working for me by typing the brackets at the end, so [] as number[]. I leave a stackblitz here https://stackblitz.com/edit/angular-ivy-ge5xzu?file=src/app/app.component.ts