Find the range of the function $f(x)=\sqrt {\log (\sin^{-1}x +\frac 23 \cos ^{-1} x)}$

Question: For the inner function
$$\sin^{-1} s +\frac 23 (\frac{\pi}{2}-\sin^{-1} x)$$
$$\frac 13 (\pi +\sin^{-1}x)$$
$$\frac{-\sin^{-1} x}{3}$$
Since it is inside a log function which is inside a square root
$$-\frac{\sin^{-1} x}{3} \ge 1$$
$$\sin^{-1}x \le -3$$ which is looks wrong, and is in fact wrong, because the answer is $[0,\sqrt{\log (\frac{\pi}{2})}]$
Where am I going wrong?
Comment: $π+\sin^{-1}x\ne -\sin^{-1}x$. LHS $\in [π/2, 3π/2]$ and RHS $\in [-π/2, π/2]$.
Answer: You're wrong in saying that $$\pi+\sin^{-1} x =-\sin^{-1}x $$ We have, $$-\frac{\pi}{2} \le \sin^{-1} x \le \frac{\pi}{2} \\ \frac{\pi}{6} \le \frac 13 (\pi +\sin^{-1} x ) \le \frac{\pi}{2} $$Since $\log(x)$ is increasing,  $${\log\frac{\pi}{6}} \le f^2(x) \le \log\frac{\pi}{2} $$ Now we need to take the square root. For this to be defined we must have the argument inside  $\log$ to be $\ge 1$, and so the range comes out to be $$0\le f(x)\le \sqrt{\log\frac{\pi}{2}} $$
Answer: Since $$\arcsin{x}+\arccos{x}=\frac{\pi}{2}$$ and $$0\leq\arccos{x}\leq\pi,$$ we obtain:
$$\frac{\pi}{6}=\frac{\pi}{2}-\frac{\pi}{3}\leq\arcsin{x}+\frac{2}{3}\arccos{x}=\frac{\pi}{2}-\frac{1}{3}\arccos{x}\leq\frac{\pi}{2}-\frac{1}{3}\cdot0=\frac{\pi}{2}.$$
But by the domain should be $$\arcsin{x}+\frac{2}{3}\arccos{x}\geq1$$ and since $\ln$  increases, we obtain the answer: $$\left[0,\sqrt{\ln\frac{\pi}{2}}\right].$$


Como transformar elementos que virão depois de um argumento de função em string

Question: Esto fazendo uma integração da API do Discord com a do Gmail
Como posso fazer para o que vier depois do argumento "content" seja impresso?
https://i.stack.imgur.com/qaSxC.png
<code> @client.command()
 async def enviar_email(ctx, subject, to, content):

 #Create of E-mail
 msg = EmailMessage()
 msg['Subject'] = subject #Subject of E-mail
 msg['To'] = to #To whom will you send
 msg['From'] = EMAIL_ADDRESS #The email address you will use. You already changed it at the beginning of the code, don't mess with anything here.
 content = content
 msg.set_content(content) #Content of E-mail

 with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
     smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
     smtp.send_message(msg)
     await ctx.send(f'{ctx.author.mention}, entreguei seu e-mail. \n \n Destinatário: {to} \n Assunto: {subject} \n Conteúdo: {content}')
     print(content)
</code>
Comment: Por favor, seria muito interessante você descrever a finalidade do projeto ate onde quer chegar , o que vc tentou realizar ( quais códigos usou ) de forma mais detalhada. Infelizmente não tem como ajudar com a sua atual postagem.
Comment: Eu quero enviar emails pelo chat do discord. Se você ver na imagem do post, somente a primeira palavra do conteúdo do email é enviada. Como faço para imprimir o que vier depois do argumento "content" na função enviar_email?
Comment: atualiza a sua postagem com a descrição rsss e inclui a imagem como anexo nao texto por favor
Comment: *...Como posso fazer para o que vier depois do argumento "content" seja impresso?..* não faz sentido. Vi que no histórico de edições que a pergunta esteve em língua inglesa. Caso ainda não tem domínio da língua portuguesa, como poderemos o ajudar?
Answer: Então, pelo que entendi, você quer que o seu bot no discord mostre o conteúdo da mensagem por inteiro que seria "Testando o teste", porém, ao pedir que o bot mande a resposta, você recebe apenas "Testando"
Pra resolver isso é bem simples, basta "compactar" o conteúdo da mensagem e para fazermos essa "compactação" usamos o * antes do "content". Seu código ficaria mais ou menos assim:
<code>@client.command()
async def enviar_email(ctx, subject, to, *, content):
    #Create of E-mail
    msg = EmailMessage()
    msg['Subject'] = subject #Subject of E-mail
    msg['To'] = to #To whom will you send
    msg['From'] = EMAIL_ADDRESS #The email address you will use. You already changed it at the beginning of the code, don't mess with anything here.
    content = content
    msg.set_content(content) #Content of E-mail

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        smtp.send_message(msg)
        await ctx.send(f'{ctx.author.mention}, entreguei seu e-mail. \n \n Destinatário: {to} \n Assunto: {subject} \n Conteúdo: {content}')
        print(content)
</code>


ES6 e addEventListener(). Por que esse método não aceita referência de uma função anônima?

Question: Por que o 'click' não é invocado?
$elemento.addEventListener('click', click, true);
var click = () => { ... };

Answer: Você deve declarar a variável com sua função antes de tentar usar ela...

document.addEventListener('DOMContentLoaded', function() {
  var click = () => {
    alert("Clicou");
  };
  document.getElementById("test").addEventListener("click", click, true);
}, false);
<input type="button" value="test" id="test">
Comment: Entendi. Porém eu achava que ao declarar a variável que armazena a função anônima com var, ela seria de escopo global sendo acessado de qualquer parte de código mesmo sendo declarada antes do uso. Obrigado


Implicit intent failed to send to my other Activity

Question: I have 2 activities: Create/Receive.
Create class:
public void onSendMessage(View view){
    EditText msgText = (EditText)findViewById(R.id.messageText);
    String msg = msgText.getText().toString();
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_TEXT, msg);
    intent.setType("text/plain");

    if (intent.resolveActivity(getPackageManager()) != null){
        startActivity(intent);
    }
}

Receive class:
public static final String EXTRA_TEXT = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receive_message);

    Intent intent = getIntent();
    String msgText = intent.getStringExtra(EXTRA_TEXT);
    TextView msgView = (TextView)findViewById(R.id.receiveText);
    msgView.setText(msgText);
}

The manifest:
    <activity android:name=".ReceiveMessage">
        <intent-filter>
            <action android:name="android.intent.action.SEND"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>
    </activity>

Debugging into it reveals that the msg gets created in first activity, but somehow I got null when it gets to the Receive activity.
Any tips what went wrong?
Edit:
Okay, just to be more clearer on what I hope to achieve. I want my Activity to be able to send the text both to the Messaging app AND my second Activity.
Sending this:
// This works for sending to Messaging app, but my second Activity can't read this
intent.putExtra(Intent.EXTRA_TEXT, msg);

// This works for sending to my second Activity, but the Messaging app can't read this
intent.putExtra("EXTRA_TEXT", msg);

Please advise.
Answer: Use the Same keyName while passing data through Intent and at the time of Receiving..
Define Constant Variable somewhere or create one class for constants and then use it as common keyName.
InSender FirstActivity
intent.putExtra("keyName", msg);
startActivity(intent);

InReceiver SecondActivity
String data= getIntent().getStringExtra("keyName");

Comment: Can you be more specific? Because writing it as:

    intent.putExtra("EXTRA_TEXT", msg);
    String data= getIntent().getStringExtra("EXTRA_TEXT");

works for sending the message to my ReceiveActivity. But now when I try to send the message to the Messaging (Android SMS app), it breaks.

I'm pretty sure this has something to do with syntax, but I couldn't figure out how/why...
Answer: I think your problem comes from this line
public static final String EXTRA_TEXT = "message";`

in your Receive class.
The Intent class already defines an EXTRA_TEXT constant here.
Comment: Hey, thanks. Now that you said that, I just realized I was being dumb :) A year out of OOP really slows my brain down. Thanks!


Can anyone explain me this feature simply?

Question: I have the following code,
float a = 0.7;
if(0.7 > a)
    printf("Hi\n");
else
    printf("Hello\n");   //Line1

and
float a = 0.98;
if(0.98 > a)
    printf("Hi\n");
else
    printf("Hello\n");   //Line2

here line1 outputs Hi but Line2 outputs Hello. I assume there would be a certain criteria about double constant and float, i.e any one of them would become larger on evaluation. But this two codes clarify me that situation can be come when double constant get larger and some other times float get larger. Is there any rounding off issue behind this? If it is, please explain me. I am badly in need of this clear..
thanks advance
Comment: There are several questions regarding floating point round off. Please look at these, because this is the cause of your issues.
Comment: `0.7` and `0.98` are values of type `double`. When you compare a value of type `double` with a value of type `float`, the value of type `float` is converted to type `double`. **The initial conversion of `0.7` or `0.98` to float loses precision**, once making the number larger and the other time making it smaller. Try this: `float a = 0.7f; if (a < 0.7f) /* ... */;`
Comment: Many, many duplicates, e.g. [Floating point comparison `a != 0.7`](http://stackoverflow.com/questions/6883306/floating-point-comparison-a-0-7) and [problems in floating point comparison](http://stackoverflow.com/questions/3962724/problems-in-floating-point-comparison).
Answer: What you have is called representation error.
To see what is going on you might find it easier to first consider the decimal representations of 1/3, 1/2 and 2/3 stored with different precision (3 decimal places or 6 decimal places):
a = 0.333
b = 0.333333
a  b

Increasing the precision can make the number slightly larger, slightly smaller, or have the same value.
The same logic applies to binary floating point numbers.
Answer: float a = 0.7;

Now a is the closest single-precision floating point value to 0.7. For the comparison 0.7 > a that is promoted to double, since the type of the constant 0.7 is double, and its value is the closest double-precision floating point value to 0.7. These two values are different, since 0.7 isn't exactly representable, so one value is larger than the other.
The same applies to 0.98. Sometimes, the closest single-precision value is larger than the decimal fraction and the closest double-precision number smaller, sometimes the other way round.
Comment: is there any easy way to understand which way round off can go??
Comment: Yes and No. Yes: it can go both ways. No: you need to know enough bits in the binary representation to see which way it goes, apart from a few trivial cases (0.5 etc.), that's not easily seen from the decimal representation. You can reduce the number of surprises by sticking to `double` for all variables, but even then, the implementation is allowed to use an internal representation with higher precision.
Answer: This is part of What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Answer: This is simply one of the issues with floating point precision.
While there are an infinite number of floating point numbers, there are not an infinite number of floating point representations due to the bit-constraints. So there will be rounding errors  when using floats in this manner.
There is no criteria for where it decides to round up or down, that would probably be language -implementation or compiler dependent.
See here: http://en.wikipedia.org/wiki/Floating_point, and http://en.wikipedia.org/wiki/IEEE_754 for more details.


Set Theory: proofs for subsets and complements

Question: Let $A$ and $B$ be subsets of a universe $U$ (so $A \subseteq U$ and $B \subseteq U$)
a. Prove that $A^{c} \cap B^{c} \subseteq (A \cap B)^{c}$
b. Define specific sets $A, B, U$ such that the containment is $strict$, where $A^{c} \cap B^{c} \subset (A \cap B)^{c}$
c. Define specific sets $A, B, U$ such that $A^{c} \cap B^{c} = (A \cap B )^{c}$
Comment: @MatthewConroy Thanks Matthew, I really appreciate it. I surely will think twice before posting questions in the future and will provide more context as in what I already know :)
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, many find the use of imperative ("Prove", etc.) to be rude when asking for help; please consider rewriting your post.
Comment: @user124884 You can also edit your own posts to improve the question if you want.
Answer: (a)
Let $x \in A^c \cap B^c \iff x\in A^c$ and $x \in B^c \iff x \notin A$ and $x \notin B \iff x \in (A \cap B)^c$
(b) Let $U = \{ 1, 2, 3\}$, $A = \{1,2 \}$, and $B = \{2 \}$.
So we have $A^c \cap B^c = \{3 \} \cap \{ 1 ,3\} = \{ 3\} \subset (A \cap B)^c = (\{1,2 \} \cap \{ 2\})^c = \{2\}^c = \{1, 3 \}$
(c) Take everything to be the same set, or better yet empty. If you don't like that and want to see numbers, we can try $U = \{1, 2 \}$ and $A = \{1 \}$ and $B = A $.
Comment: Thank you so much, and I apologize starting a "question" with the word PROVE. Please forgive the lack of context of this question :)


A question about Latent Dirichlet Allocation model

Question: when I used LDA model in my project, the result topic terms vary with the random seed. how to solve this problem ? thanks
Comment: I think your problem has already been discussed in that question : http://stats.stackexchange.com/questions/63026/topic-stability-in-topic-models
Comment: Why is that a problem?
Comment: I have seen the link, but the method didn't work
Answer: It is meant to vary as LDA and other topic models are stochastic methods. You can not expect exact same result in multiple runs.


Hypothesis testing variable monotonicity

Question: In my job, I often use variables to build models that traditional business sense would suggest are monotonic in their relationship with the target variable of interest. For example, in business lending, we would always suppose that the older the business, the lower the probability of default is.
In reality, we often see that there are areas where the assumption of monotonicity is broken. My question is, is there a test we can perform which tests whether or not our assumption is valid?
Comment: In linear models, this is sort of the default assumption.  Are you specifically asking about cases where the effect of the covariate is non-linear, such as in GAMs?
Answer: Let's call $X$ and $Y$ two random variables, and say you want to test if $X$ and $Y$ are monotically dependent.
One basic way of doing so can be to use Kendall's tau correlation coefficient. It has the advantage of being non parametric : it does not suppose any particular distribution on $X$ or $Y$, nor suppose any specific link between the two variables. If $X$ increases with $Y$, you should get $\tau > 0$ and if $X$ decreases with $Y$, you'd get $\tau < 0$.
If your dataset is big enough, you can make a (one or two sided) test for $\mathcal{H}_0 : \tau = 0 $  by using the asymptotic distribution of $\tau$ which is $\mathcal{N}(0, {\frac {2(2n+5)}{9n(n-1)}})$ under null hypothesis $\mathcal{H}_0$.
One could also use other non parametric correlation coefficient like Spearman's $\rho$, but this discussion seems to show that Kendall's $\tau$ is better for what you're interested in.


Specializing general CRT formula when residues are constant

Question: Both $p, q$ are prime
$x \equiv y \pmod p$
$x \equiv y \pmod q$
Using Chinese remainder theorem,
$M = p*q$
$x = a1*b1*M/p + a2*b2*M/q$
$x = a1*b1*q + a2*b2*p$
$a1 = y$
$a2 = y$
$b1$ is solution of $(M/p)*x \equiv 1 \pmod p$
i.e. soln of $qx \equiv 1 \pmod p$
Likewise
$b2$ is solution of $px \equiv 1 \pmod q$
$q$ & $q$ are prime - so they are co-prime to each other.
So
$b1 \equiv (1/q) \pmod p$  ----> (1)
$b2 \equiv (1/p) \pmod q$  ----> (2)
So
$x \equiv y*b1*q + a2*b2*q$  ---> (3)
From (1), (2) & (3) is it possible to arrive at
$x \equiv y \pmod{p*q}$
I know it's possible to prove the above in a much more easy way, but I was wondering if it's possible to prove this using CRT?
Comment: This is hard to follow.  If $x\equiv y \pmod p$ and $x\equiv y \pmod q$, for $p\neq q$ distinct primes, then $x\equiv y \pmod {pq}$.  Is that what you were asking?
Comment: @lulu - yes, but I am trying to arrive at it using CRT - if that's possible at all. I know it can be proven much more trivially but I was just wondering if it's possible to prove it using CRT
Comment: But, where is the difficulty?  Since $x\equiv y \pmod p$, we have $x=y+np$ for some $n$.  We know want to solve $x=y+np\equiv y \pmod q$  But that's the same as $np\equiv 0\pmod q$ which is the same as $n\equiv 0 \pmod q$.
Comment: @lulu - as I said, I know that proof. But I was wondering if there is a way to reach that same final point through CRT instead of the simpler proof
Comment: I have no idea what that means.  The Chinese Remainder Theorem is an existence theorem.  The simple algebra described in your post is the associated constructive version.
Comment: @lulu Most versions of CRT assert both existence *and uniqueness*.
Answer: Yes, rotely applying the common CRT formula yields the unique solution
$$ x\,\equiv\, y\,\overbrace{(p(p^{-1}\bmod q) + q(q^{-1}\bmod p))}^{\textstyle u} \pmod{pq}$$
Note $\,u\equiv 1\,$ both mod $\,p$ & $q.\,$ This has obvious solution $\,\color{#c00}{u\equiv 1}\pmod{pq}$ which is unique $\!\bmod pq\,$  by CRT. $ $ Thus $\,x\equiv y\color{#c00}u\equiv y\cdot \color{#c00}1\equiv y\pmod{\!pq},\,$ as claimed.
So rotely applying the CRT formula does indeed solve this constant case of CRT, but it's wasteful. The formula yields the existence of a solution, but that is trivial here since there is an obvious solution $\,x\equiv y\pmod{\!pq}.\,$ So here we need only uniqueness, i.e. proof that this obvious solution is the only solution $\!\bmod pq,\,$  for which see the various proofs  of CCRT = Constant-case CRT.


NativeScript Image with path won't load but url works fine

Question: My NativeScript Image is not showing when I use a a path to a file. My code currently looks like this:
<StackLayout>
    <Image src="~/assets/logo"></Image>
    <Image src="https://play.nativescript.org/dist/assets/img/NativeScript_logo.png"></Image>
</StackLayout>

The lower Image using a url is showing up but the one above isn't.
I also tried these:
    <Image src="/assets/logo.png"></Image>
    <Image src="../assets/logo.png"></Image>
    <Image src="../../assets/logo.png"></Image>

And other options but nothing works.
I have a folder assets inside my app folder and inside I have a logo.png picture, which is the picture from the url above.
Also I don't get any console message, that it can't find my file.
Any Ideas?
Comment: Can you give a try for `~/app/assets/logo.png`?
Comment: try `` or ``. Notice that the path is `./`
Comment: relative path depends on the path your app is running under, is it `/app`? `/dist`? find out and use it
Comment: @Manoj thanks it works with `~/app/assets`. Even though in the docs they just use `~/assets`.
Comment: @JacopoSciampi My component is not in the same folder as the assets. Its in `app/pages/mypage`, while assets is in `app/assets`. So `../../` should work as far as I know but it isn't `./` isn't working either.
Answer: Supposing your structure looks like this:

app/
  assets/
    logo.png
  components/
    ...
  app.component.ts
  ...

I'd recommend trying:
<Image src="~/assets/logo.png"></Image>
~/ means you're looking in home directory of your project.
Check if app is actually your home directory. It might be src above app. Then you'd need to go for ~/app/asset/...
Comment: Yes my structure looks like this. I tried that and it still not working. Thanks for the help tho!
Comment: I see in your comments, that you had to go with ```~/app/assets```. It seemts that your home directory is ```src```, not ```app```.
Glad that you've found your solution.
Answer: it should contain extension name
 <Image src="~/assets/logo.png"></Image>


A diagonal matrix can be expressed as a difference of two squares ($A=B^2 − C^2$ where $BC = CB = 0$)

Question: I got one interesting question from matrix theory. I tried but I am not finding any clue to solve this question.  I need help and suggestions. Thanks in advance.
Let $A$ be a real $n\times n$ matrix. We say that $A$ is a difference of two squares if there exist real $n\times n$ matrices $B$ and $C$ with $BC = CB = 0$ and $A = B^2 − C^2$.
Now If $A$ is a diagonal matrix, then I have to show that that it is a difference of two squares.
Answer: Perhaps this may help you .
Let $a$ be a real number. if $a\geq 0$ we can write $a = b^2 - c^2$ with $c = 0$ and if $a < 0$, we can write $a = b^2 − c^2$ with $b = 0$. Thus, in general, $a = b^2 − c^2$ with $b$ and $c$ real and $bc = 0$. Now if $A = \operatorname{diag}(a_1, a_2, . . . , a_n)$ is a real diagonal matrix, write each $a_i = b_i^{2}− c_i^2$ as above, with $b_i c_i = 0$, and define $B = \operatorname{diag}(b_1, b_2, . . . , b_n)$ and $C = \operatorname{diag}(c_1, c_2, . . . , c_n)$. Then, by the way diagonal matrices multiply, we conclude that $A = B^2−C^2$ and also that
$BC = CB = 0$.
Answer: Write your matrix $A$ as $A^+ + A^{-}$, where $A^+$ is a diagonal matrix consisting of entries on the diagonal of $A$ that are non-negative and $A^-$ is a diagonal matrix consisting of entries on the diagonal of $A$ that are negative. Now let $B = \sqrt{A^+}$ and $C = \sqrt{- A^-}$ and you are done.
Answer: More generally, what are the matrices $A\in M_n(\mathbb{R})$ that can be written $A=B^2-C^2$ where $B,C\in M_n(\mathbb{R}),BC=CB=0$ ?
Clearly, the result is true when $A$ is diagonalizable over $\mathbb{C}$ and $spectrum(A)\subset \mathbb{R}$.
The result is false for any nilpotent Jordan block of dimension $\geq 2$.
$\textbf{Proposition 1}$. The result is true when $spectrum(A)\subset \mathbb{R}^*$.
$\textbf{Proof}$. The problem reduces to the case where $A=I_n+J$ where $J_n$ is the nilpotent Jordan block of dimension $n$.
It suffices to take $C=0$ and $B=I+1/2J-1/8J^2+\cdots$.
$\textbf{Proposition 2}$. The result is true for any $A\in GL_n(\mathbb{R})$.
$\textbf{Proof}$. We may assume that
$A=diag(U,V)$ where $U$ is invertible without any $<0$ eigenvalues and $spectrum(V)\subset (-\infty,0[$.
The result is true for $U$ because  any invertible matrix that has no $<0$ eigenvalues admits always at least one real square root.
When does a real matrix have a real square root?
According to Proposition 1, the result is also true for $V$ and we are done. $\square$


Python Poloniex API returns error 422

Question: I have method, that should returns balance from Poloniex via their API. Code below.
<code> def getBalance(self):
        polo_data = {"command": "returnBalances", "nonce": int(time.time() * 1000)}
        post_data = urllib.parse.urlencode(polo_data).encode()
        sig =  hmac.new(str.encode(self.SETTINGS.PRIVATE_KEY), post_data, hashlib.sha512).hexdigest()

        headers = {
            "Key": self.SETTINGS.PUBLIC_KEY,
            "Sign": sig}
        req = urllib.request.Request(self.SETTINGS.BASE_URI + self.SETTINGS.TRADE_DIR,
                                           data=post_data, headers=headers)
        try:
            res = urllib.request.urlopen(req)
            result =  json.loads(res.read().decode('utf-8'))
            print(result)
        except urllib.error.HTTPError as e:
            print(f'Headers: {e.headers}')
            print(f'Status: {e.status}')
            print(f'MSG: {e.msg}')
            print(f'reason: {e.reason}')
            print(f'url: {e.url}')
            print(f'Name: {e.name}')
</code>
When I run this code I return message HTTPError 422 I thinking problem would be with post_data. I tried do the same with requests and I got error with message: "Error: Invalid command" But I can't understand where exactly. From other side the same code for buy/sell order's commands working like a charm.
I using Python 3.6.1
Any suggestions?
Answer: I found decision for my question. Problem was in nonce. Correct code is:
<code>int(time.time() * 10000)
</code>
not a 1000, but 10000

Python Poloniex API returns error 422


Piano chord fingering and/or pedal use

Question: Although my beginner status doesn't make me eligible to play this particular sheet (part of which I presented here), I found it interesting to analyze the notes written. My question is related to notes circled.
More precisely, how the circled notes should be played. The first two Db notes should last even during second chord of circled notes. So during that chord, the player should have all five RH fingers employed with span of 10 notes.

I tried to imagine the possibility of using pedals (although there is no sign for pedals here), but I haven't found an acceptable answer yet.
Comment: What is the key signature there?
Comment: https://musescore.com/user/27683639/scores/8267288
Answer: The pedal would be used for this.
Although some pianists can reach the B (or Bb?) to Db span, playing all five notes at once would be very difficult because of the distance from the G (which would be played with finger 4) to Db (played with finger 5). I can just barely play it, and I have a fairly wide hand span.
There are some additional possibilities, like holding only only the top Db (which would work for a wide enough hand span), or re-playing the lower Db along with the chord on beat two. For general solutions to this type of problem, see What is the best way to play a chord larger than your hand?.
Comment: Can you elaborate - which pedal, what moment ... should achieve the goal.
Comment: @Zoran I'm referring to the damper pedal (also called the sustain pedal), which is the pedal furthest to the right. In general, when we talk about "the pedal", this is the one we're talking about. For the music in question, you would put the pedal down with the first chord, hold it through the second, and release it as you play the third (I'm speaking in terms of the right-hand part).
Comment: @Zoran  For more on pedal technique, search for the tags [\[keyboard-pedals\] and \[technique\]](https://music.stackexchange.com/questions/tagged/keyboard-pedals+technique). There are also some brief, relevant comments in [Exact timing of piano pedal re-engagement](https://music.stackexchange.com/q/110616/70803).
Comment: If I release the sustain pedal at the end of third chord does it mean that second chord will last longer (all the way during third chord) as pedal is already pressed at that moment?
Comment: @Zoran The pedal should be released at the beginning of the third chord, not the end, for exactly the reason you've said. The third chord is a new harmony, so you don't want the second chord holding through it.
Comment: I understand - suggestion is to shorten two Db notes not to last only over second and not over the third accord. I shell try, just for that "critical" part since it is too complex for me, because of triplets at left hand.

Piano chord fingering and/or pedal use


CRM2011 check if notes on custom form contains data via JavaScript

Question: Hi peeps on stackoverflow,
Product: CRM2011, should be latest roll-up
I'm currently trying to get the following to Work:
- A custom CRM form has been made. This form contain the 'Notes' tab. I would like to dynamically 'expand' this IF and only IF the 'Notes' tab contains notes data. I'm trying to do this through JavaScript loaded into 'Form Libraries'. I can easily 'expand' the notes field but I'm having serious trouble determining if the 'Notes' tab contains notes data.
I can understand that accessing the 'notes' data through the DOM is not a good idea so I've tried through XRM. Looked through https://msdn.microsoft.com/en-us/library/gg334351(v=crm.5).aspx to see my options. But I can't seem to get to one where I can access 'notes' and base the expansion of the notes field on if there is data or not in 'notes'.
Is this possible? I'm looking forward to hear from you and thank you very much.
Answer: Notes are their own entity type, entity logical name is Annotation, that is why you won't find the notes data within Xrm.Page.  I'm making some assumptions here, but if you've set up this custom entity to follow standard conventions, any notes on that record will be separate Annotation records with a reference to the custom entity record. using the sdk.jquery.js script provided with the SDK you can do a query on Annotation records that reference the record you are currently on.  That would be a supported way to determine if the record has notes.  Using the OrganizationData.svc endpoint you would have an OData query that looks something like this
AnnotationSet?$filter=ObjectId/Id eq guid'34d19133-c0ec-e311-b39c-6c3be5bd2b14'

The guid value there would be the guid of the record you are currently on, which if you haven't already acquired within your script, you can get it pretty easily with something like this
window.parent.Xrm.Page.data.entity.getId().substring(1, 37)

or without the window.parent prefixing it
Comment: Hi AK3800 thank you very much for your answer. Highly appreciated. Unfortunately I cannot verify the suggestion as I'm not allowed to spend more hours on the challenge. Your findings though match what I have been able to conclude and I therefore think that this would indeed solve it.


Atualizar automaticamente dados obtidos de api json - Volley

Question: Olá galera estou com o seguinte problema tenho uma aplicação que usa volley pra obter determinado dado json através de api até ai tudo bem ela funciona corretamente mas o problema é o cache do volley que não reseta até a aplicação ser fechada completamente, exemplo enquanto o cel não for desligado ou a propria aplicação ser fechada pelo gerenciador de tarefas os dados da json não vão atualizar de que maneira posso fazer para que em exemplo a cada 30 minutos seja atualizado os dados obtidos.
Meu Code:
<code>JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            JSONObject obj = response.getJSONObject(0);
                            String valor = obj.getString("valor");
                            String data = obj.getString("data");

                            results.setText("Vale R$: " + valor );
                            datav.setText("Última atualização: " + data);

                        }  catch (JSONException e) {
                            e.printStackTrace();
                        }}},
                new Response.ErrorListener() {
                    @Override
                    // Handles errors that occur due to Volley
                    public void onErrorResponse(VolleyError error) {
                        results.setText("Erro ao obter dados");
                        Log.e("Volley", "Error");
                    }
                }
        );
        requestQueue.add(arrayreq);
</code>
Answer: Tu pode usar a biblioteca do AlarmManager
 e setar a cada X tempo efetuar a requisição novamente.
Porém a implementação deste Alarme para chamar uma função você deverá criar um service. É meio complexo a implementação, mas existem bons conteúdos ai na própria API Android.
Tive algo parecido porém era executado também quando o App deveria estar finalizado. Espero ter ajudado
Ou senão no modo mais bruto, você cria uma thread executando a cada tempo X dentro de um loop infinito.
Answer: Você pode utilizar o AlarmManager para executar a cada x minutos como já dito, ou utilizar o framework da google SyncAdapter, onde você também seta de quanto em quanto tempo irá executar o código.


How can I evaluate the limit of this function using series?

Question: Limit as x approaches 0 of $lim_{x\rightarrow 0}\frac{1-cosx}{1+x-e^x}$. I substituted in the Taylor series of $cosx$ and $e^x$ into the function, but it's still in $\frac{0}{0}$ form, and I don't know what to do from there.
Comment: Did you cancel $x^2$ from the numerator and the denominator?
Comment: Can you please show your work? It's unclear to which power you expanded the function into a Taylor's series?
Answer: You did not go deeper enough in your Taylor series you need to go up to the term in $x^2$ to solve this limit.
$\cos(x)=1-\frac{x^2}{2}+o(x^3)$ and $e^x=1+x+\frac{x^2}{2}+o(x^3)$.
So $lim_{x\rightarrow 0}\frac{1-cosx}{1+x-e^x}=lim_{x\rightarrow 0}\frac{1-1+\frac{x^2}{2}+o(x^3)}{1+x-1-x-\frac{x^2}{2}+o(x^3)}=lim_{x\rightarrow 0}\frac{\frac{x^2}{2}+o(x^3)}{-\frac{x^2}{2}+o(x^3)}=-1$


Preview taxes for Recurly

Question: I'm using the Recurly v3 JavaScript API to fetch pricing info for a subscription plan: https://docs.recurly.com/js/
Specifically, I'm using the Pricing API .attach (https://docs.recurly.com/js/#pricing) to resolve the price and tax information.
Here's the problem:  using the Recurly test gateway, I get estimated taxes of 0.00 for a plan using the Recurly v3 JS API.  However, when I actually purchase the plan, and then if I check in the Recurly management portal, I can see my 'estimated taxes' as 17 cents.  So, seeing the taxes in the Recurly management website confirms that I've configured things correctly... in other words my plan has 'collect taxes' checked, and the billing address that I'm testing with matches a state that I have configured my Recurly account to collect taxes for.
Regardless of all that, the  Recurly JS API does not report the correct taxes (0.00 instead of 0.17)!
Any suggestions or insights?
Answer: It may be that you haven't got the digital value in your form.  It's a hidden field that is populated by the system to tell rjs that this is a taxable item and to use the configuration to calculate the taxes in the pricing.api
https://github.com/recurly/recurly-js-examples/blob/master/public/advanced-tax/index.html#L59
Comment: Thanks for suggesting this; I don't think this is what I'm after.   I could be wrong, and I tried to read up more on this tax_code field ,but... ultimately, Recurly does tax correctly; it just won't display the correct tax through the JS API.  So, the system has the info it needs.  It just doesn't show anything but $0.00.
Answer: Recurly support says that this is because my application is in sandbox mode.
From their docs:

"When your site is in sandbox mode, the rates used for taxes is an
  estimate and is based off a semi-static internal tax table that's
  updated periodically. When your site is enabled for production mode,
  the final rates used for purchases and recorded in your invoices are
  provided directly from our sales tax partner, Avalara, whose tax
  engine feeds the rates real-time on each request. Also while in
  production mode, any tax previews will use the internal tax table but
  will use the real-time rates when a preview goes to final billing."

This does not really add up to me.  Getting 0.00 is not an estimate, but that's what support says, so I'll accept it.

Preview taxes for Recurly


Stop JetBrains IDEs from expanding collapsed code blocks after using 'Find & Replace' feature

Question: I collapse code blocks before hand, to see an overall picture of everything, before using the "Find & Replace" feature to update a lot of code at one time. It drives me crazy that as soon I hit "Replace All", it expands all the code blocks that included the word I was replacing! Is there anyway to stop it from doing and leave the code I had collapsed as collapsed?
Find & Replace.... code to stay collapsed
Comment: Found a really old ticket that was declined: https://youtrack.jetbrains.com/issue/IDEA-88088 . Then found https://youtrack.jetbrains.com/issue/IDEA-177247 -- no activity of any kind for 6 years... Maybe there is a better ticket .. but I could not locate it with my quick search: https://youtrack.jetbrains.com/issues/IDEA?q=%23%7BUser%20Interface.%20Find,%20Replace%7D%20expand%20replace
Comment: @LazyOne is right, https://youtrack.jetbrains.com/issue/IDEA-177247 is the correct bug report to upvote. No workaround for it unfortunately.
Comment: There are keyboard shortcuts/actions for collapsing multiple blocks at once. Does that work for you?
Answer: For sure that's the bug.
Please, upvote the issue IDEA-177247


Why do MIDI note off messages have velocities?

Question: I understand why note on messages have velocities, but surely note off messages just turn them off - why do they also have a velocity?
Equally, I checked if these velocities match up to the corresponding note_on message, but they don't.
Is it a measure of how much the velocity decreases from the time you play the note to the time it stops being heard?
Answer: Note-off velocity means the speed with which a pressed-down key is released back up. This information can be used for at least Rhodes electric piano sounds, so that the keys make a different release sound depending on if the keys are released softly or "hard". The difference in sound isn't big, but there is a difference. An experienced player can notice the difference in sound, and loud key releases can be used for certain types of rhythmic "barking" comping.
If you read the MIDI Implementation Chart of instruments, you'll notice that many, or most keyboards don't send note-off velocity. Even the Nord Electro keyboards, which are supposed to specialize in accurate emulation of Rhodes elecric pianos and other comparable keyboard instruments. Some sample libraries have multiple layers of sampled note-off i.e. key release sounds, so by using a keyboard which doesn't transmit note-off velocity you'll miss out on that dimension of expression.
Comment: Sloppy Midi timing is *always* the user's fault ;-) I spent the entirety of the 90s coaxing good performance out of barely adequate chips. I used to be responsible for most of the onboard & downloadable demos for Yamaha's keyboard & tone generator range. *That* teaches you how to keep your data stream lean ;) I was always rather proud of this one - https://soundcloud.com/graham-lee-15/ohmss-orig-propellerheads-used-with-permission-mu100-demo
Comment: That's a new one on me! Thanks. Do you know if either Roland or Alesis use that feature? When I fire the studio up in a bit, I'll have a play!
Comment: @Tim - high-end keyboards are more likely to have it, or VSTis, as they don't have to rely on literal MIDI transmission so can pass data much quicker internally. I'd bet most DAWs would strip it & use running status unless told otherwise, so even if your keyboard sends it, it might not either pass-through or necessarily even be recorded.
Comment: There's a good user-level explanation of Running Status [here](http://www.muzines.co.uk/articles/running-status/457). I've always thought it was what confused people into believing certain sequencers were "tighter" than others. The other reason is that 99.999% of people never learned how to shift controller data out of the way, or slide slow attacks early to make this even tighter.
Comment: @Tetsujin good point about Running Status that Note-Off velocity and the data reduction benefits of running status are kind of mutually exclusive, at least partly. But could _that_ be a reason for a keyboard not sending note-off velocity? Anyway, sloppy MIDI timing can be partly the user's fault. Back when I used Cakewalk for DOS and external modules, I used to plan things like channel and note ordering, manually thin out CC data, and even re-order individual events to get important things out first... it kind of sucked but at least it taught me how hardware MIDI worked.
Answer: The note off velocity is basically how "hard" you release the key. Like, if you let it up gently or suddenly. Some synthesizers/patches may use this information to change the release, cutting off the sound more gradually or suddenly.
Not all MIDI controllers will transmit this. Many will simply send a fixed velocity. Also, an annoying detail of the MIDI spec is that it's also valid to signal note off via a note on message with velocity zero. I just happen to have a MIDI processing app running in dev right now and the controller I'm using does just that.
Comment: Note On = 0 is a running status message. You can, on some devices, tell it whether to use that or not. Running status streamlines transmission quite significantly by not having to send the status byte each time, like with discrete note-offs.
Answer: Accordion buttons make noise on attack and release, as do the keys on many wind instruments.  If you want to use a keyboard controller for generating sounds of that kind, having note-off velocity is part of the job description.  Not to mention things like closing a foot-pedal hi-hat (though I don't really know how that is usually mapped to MIDI messages).


Proof that there exist an open set with compact closure explanation

Question: I'm reading Rudins "Complex Analysis". There's a theorem that goes like this.
Theorem: Let $U$ be open, in a locally compact Hausdorff space. Let $K\subset U$ and $K$ be compact. Then there exist an open set $V$ such that
$$K\subset V\subset \overline{V}\subset U $$
Proof:
Because every point of $K$ has a neighbourhood that's closure is compact, and we can cover $K$ with finite amount of such neighbourhoods, then there exist a set $G$, that has a compact closure, and is a subset of $K$. If $U=X$ then we can take $V=G$.
If not, define $C$ as the complement of $U$. From theorem $2.5$, for every point $p\in C$, there exist an open set $W_p$, such that $K\subset W_p$, and $p\notin\overline{W_p}$.
And the proof goes on.
Theorem $2.5$: Suppose that $X$ is a Hausdorff space, $K\subset X$ is a compact set, and $p\in K^c$. Then there exist open sets $U$ and $W$, such that $p\in U$, $K\subset W$, and $U \cap W = \emptyset$.
My question is, how we can use this theorem in the proof, so that we can state the existence of such sets $W_p$. Mainly, where does $p\notin\overline{W_p}$ come from. Thank you.
Another question that might help me. If $U$ and $V$ are open, $U\cap V=\emptyset$ holds, does $\overline{U}\cap V=\emptyset$?
I've found a similar question here. In the comments, Andreas says that if $p$ was in closure of $W_p$, then every neighbourhood of $p$ would have to meet $W_p$. Why is that?
Comment: @DanielWainfleet Thank you! I get it now.
Comment: Re: "Another  question" : If $V$ is open then its complement is $V^c$ is closed and disjoint from $V $. So if $ V $  is open and is disjoint from $U$ then $V\cap \overline U\subset  V \cap \overline V^c=$ $V \cap V^c=\emptyset.$... Another way to see this is that if $V$ is open and $U\cap V= \emptyset,$ then every $p\in V $ has a  nbhd (namely, $V $ ) that's disjoint from $U,$ so  $p\not \in \overline U.$
Comment: The theorem, with  $\overline V$  compact,  directly:   (1). In a Hausdorff space if $C$ is compact and $p\not\in C$ than $p, C$ are completely separated. (2). If $D$ is open and $ \overline D$ is compact then $\partial D= \overline D$ \ $ D$ is compact. (3). We use (1) and (2) to prove that a compact $T_2$ space is regular..... Then  for each $p \in K$ let $V_p, U_p$  be open  sets containing $p$ such that $\overline V_p$ is compact and $\overline U_p\subset  U. $ Now  $A=\{V_p\cap U_p: p\in K\}$ is an open cover of $K.$  Let $B$ be a finite sub-cover of $A$  and let $V=\cup B.$
Comment: ERRATUM: In my previous comment , (3) should say  that a LOCALLY compact $T_2$ space is regular. I ran out of editing time .
Answer: Use the Hausdorff condition. For each $a\in K$ there are disjoint
open neighbourhoods $U_a$ and $V_a$ of $p$ and $a$ respectively.
Finitely many of the $V_a$ will cover $K$; let $W$ be their union,
and $U$ the intersection of the corresponding $U_a$.
Comment: Yes, that's how the proof of **Theorem $2.5$** is stated. My question is how to use this theorem
Comment: The point is that $U$ and $W$ are **disjoint**.
Comment: $U$ and $W$ are disjoint, does that imply that, for example, $\overline{U}$ and $W$ are disjoint?
Comment: $W$ is **open**


Probability of drawing cards in ascending order

Question: Given 200 cards where each card has a unique number from 1 to 200.
We randomly pick 30 cards (the order we pick them matters). What is the probability the unique numbers of the cards we pick are in ascending order?
Comment: There are $30!$ possible orders and all are equally likely....so $\frac 1{30!}$ (not a very large number).
Comment: If you want to proceed by force:  the probability that the least card is in slot $1$ is $\frac 1{30}$.  The probability that the second smallest card is in slot $2$ (given that we know it isn't in slot $1$) is $\frac 1{29}$.  And so on.
Comment: @lulu: can you please explain why? Why we don't use the 200 anywhere?
Comment: The $200$ is a red herring.  When you say you randomly choose cards I interpret that to mean that every (ordered) set is equally likely.  That is to say $\{1,2,3\}$ is exactly as likely as $\{3,2,1\}$.
Comment: @lulu: thank you very much of your help! {1,2,3} is not the same as {3,2,1} that's why i said order matters.
Comment: To expand on @lulu comment. Pick 30 cards from the 200. Now, keeping them in the same order, renumber them 1-30, based on how large the number is. What is the chance that the sequence is 1,2,...,30? Clearly, it's 1/30!
Answer: Just to elaborate on the comments, I'll give two different arguments.  The first, based purely on symmetry, and the second based on counting.
I. One way to get a uniform distribution is to select an unordered subset (with $30$ elements) and then choose a random permutation of it.  Here, we don't care which unordered subset we choose and we only want one of the $30!$ permutations.  As the permutations are equally probable, the answer is $ {\frac 1{30!}}$.
II. First we count the number of ordered subsets. As noted in the posted solution of @Hamid there are $$\frac {200!}{(200-30)!}$$
How many are in ascending order?  Well as any unordered subset can be put in ascending order in exactly one way there are $$\binom {200}{30}=\frac {200!}{(30!)\times (200-30)!}$$  Hence the probability is the ratio $$\frac {200!}{(30!)\times (200-30)!}\times \frac {(200-30)!}{200!}=\frac 1{30!}$$
Comment: could you explain the meaning of the 2nd term? The 1st term is the number of ways to select 30 cards out of 200. What is the 2nd term?
Comment: @Marco That's the (reciprocal of) the number of ordered subsets with $30$ elements.
Comment: ok so it is the probability of selecting an ordered set?
Comment: @Marco.  Not following.  You asked about the second term.  That's the reciprocal of the number of ordered sets.  It's not meant to be a probability.
Comment: @Marco  My second method starts with the remark that the desired probability is $\frac {\text {number of increasing subsets with 30 elements}}{\text {number of ordered subsets with 30 elements}}$.  That's all that's going on there.
Comment: yeah sorry I misunderstood one thing. It is clear now.
Answer: This answer is for the case when cards are required to be "consecutive", not in "ascending order"
The total number of possibilities is
$$
\frac{200!}{(200-30)!}
$$
The possible number of ordered choices is $200-30+1 = 171$$^*$. So the probability should be
$$
\frac{200-30+1}{\frac{200!}{(200-30)!}}
$$
$^*$ This comes from $1\to 30$, $2\to 31$, $\cdots$, $171\to200$.
Example: let it $4$ and $2$, your choices are $12,13,14,21,23,24,31,32, 34, 41,42,43$. What you are looking for are $12,23,34$. So the probability is
$$
\frac{4-1+2}{\frac{4!}{(4-2)!}}=\frac{3}{12}
$$
Comment: The OP specified "ascending order" not "consecutive".
Comment: Oh, I see! Thanks for the comment, I will just leave it and make a note about this.
Comment: So you are right, it is $\frac{1}{30!}$


Why is my image not scaled correctly when hovered?

Question: I'm building a website for a side project and I need to have 2 cards, presenting someone with an image on the left and some text + another image on the right.
I want that card to be 1.1 times scaled when hovered or focused but when I do the usual method (as in the snippet), somehow the image on the right shifts a bit to the top.

/* GÉNÉRAL */

:root {
  --color-accent: #4e6eff;
  --color-accent-dark: #3a56d3;
  --color-black: #252728;
  --color-white: #fdfdff;
  --color-blacker: #0c0d0d;
}

html {
  scroll-behavior: smooth;
  scroll-padding-top: 0;
}

body::-webkit-scrollbar {
  display: none;
}

* {
  font-family: Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

*::selection {
  background-color: #4e6effba;
}

body {
  background-color: var(--color-black);
  color: var(--color-white);
}

/*  COMMON STYLE */

.bg-accent {
  background-color: var(--color-accent);
  color: var(--color-white);
}

a {
  color: var(--color-white);
  text-decoration: none;
}

img {
  width: 100%;
}

/*  */

.select-membres__row--2 {
  display: flex;
  justify-content: space-evenly;
}

.membre-carte {
  display: flex;
  padding: 1em;
  width: 400px;
  height: 200px;
  gap: 8%;
  border-radius: 25px;
  background-color: var(--color-blacker);
  text-align: center;
  scale: 1;
  transition: scale 100ms ease-out;
}

.membre-carte:hover {
  scale: 1.1;
  transition: scale 150ms cubic-bezier(0.22, 0.47, 0.35, 0.92);
  border: 3px solid var(--color-accent);
}

.membre-carte>* {
  width: 50%;
}

.membre-carte .carte-pp {
  border-radius: calc(25px - 0.5em);
}

.perso-cont {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.carte__nom {
  font-size: 1.2rem;
}

.perso-cont .img-cont {
  width: 120px;
  margin-inline: auto;
  display: flex;
}

image 1

lorem

image 2

lorem

Answer: The border in .membre-carte:hover consumes an extra 6px (top 3px and bottom 3px) from the total height of the cart leaving less room for the content to fit in.
Add a transparent border like .membre-carte { border: 3px solid transparent } to you CSS and the movement will disappear, because now both the unhovered vs. hovered state consume the same amount of space again.
Be aware that you will lose 6px of the carts spaces for their content to fit in.
Comment: Thx, this perfectly fixes the issue !
I just noticed that replacing the `.membre-carte:hover` border to a `box-shadow: 0 0 0 3px var(--color-accent)` also fixes the problem.


What is the meaning of `private` attribute in `tfstate` (for a DynamoDB instance)?

Question: I'm bootstrapping my terraform remote state by storing the tfstate of creating an S3 bucket and a DynamoDB lock table and storing it in git. My organisation scanned the repository using  Yelp/detect-secrets and flagged the line containing private as a Base64 High Entropy String.
# excerpt from `tfstate` file
    {
      "mode": "managed",
      "type": "aws_dynamodb_table",
      "name": "state-lock",
      "provider": "provider.aws",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "arn": "arn:aws:dynamodb:eu-west-1:111:table/terraform-state-lock",

           ...

            "write_capacity": 1
          },
          "private": "<long string>"
        }
      ]
    }

https://www.terraform.io/docs/providers/aws/r/dynamodb_table.html does not export the field as an attribute, and I can't find documentation on the meaning of the field.
What does it contain?
Answer: The "private" property is a place where providers can retain any metadata they need for internal lifecycle tracking, separately from the actual data in "attributes".
From Terraform Core's perspective it's just an arbitrary sequence of bytes, base64 encoded. You can base64-decode it to see what the provider is storing there.
A provider is free to store whatever it wants in principle, but in practice today this is most commonly used by the Terraform SDK to track schema versions. That is likely what you'll find if you decode this one, in JSON format. The Terraform 0.12 state snapshot format has a first-class property for schema version which you can see further up in that object, so in this case that data is redundant but the SDK is retaining it in two places so that providers can remain compatible with Terraform 0.10 and 0.11.
"private" in this context means "for use by the provider only", not "secret". Therefore from the perspective of the detect-secrets tool this is an unfortunate false-positive. It is possible in principle for a provider to store private data in there -- just as it's able to do so in the "attributes" object too -- but that's not what this property is designed for.
Comment: Thank you. This should help make my case. Is there a public documentation of the `tfstate` schema? Out of even more curiosity - could you possibly link to code that generates the content for the `private` field? I searched through the [terraform-provider-aws](https://github.com/terraform-providers/terraform-provider-aws/search?l=Go&p=14&q=private) but could not see any usage.


What is the box cyclists wear in their back?

Question: I just saw Romain Bardet in the live stream of the Tour de France stage. In the image, I can see there is a box-like form in his back.

What is it? Is it maybe a transmitter for the radio to communicate with his team?
Answer: It is the body pack for the radio. The body pack contains the antenna (or more precisely, the antenna attachment), receiver, transmitter, microphone preamplifier, headphone amplifier, and all the other electronics that make up a modern digital two-way radio.
Here you can see a cyclist demonstrating all components of a typical cycling-oriented two-way radio pack: radio body pack, headphones, throat microphone, and push-to-talk button.

Source: https://retevis.com/rbc01-bicycle-riding-gmrs-two-way-radio-bundle
This is the first image / product I could find. The body packs used by top-tier pro cycling teams would be a lot smaller, thinner, and lighter, and would have a flexible wire antenna or even one integrated into the casing of the body pack instead of the thick, fixed rubber stub.
Also, sometimes the lead rider of a team could maybe not have a PTT button but instead their microphone would always be open, so that the entire team hears them all the time. Same for the rider in an individual time trial. This is basically to free them from having to press the button.
Comment: @RockPaperLz-MaskitorCasket: They don't. It's the same for the head referee at football games. The line referees have PTT buttons built into the flag grips, but the head referee's microphone is always open and the line referees, video referees, and "fourth official" just have to deal with it. It is considered too much of a workload for the head referee to have to push the button, especially while running when you usually use both of your arms for balance and momentum.
Comment: Thanks! Interesting the issue with the PTT button. On Jul 21th 2022 stage, it was clear from the stream that Pogacar did need to use the button to communicate, for example.
Comment: Without a PTT button, I wonder how they avoid transmitting much of their panting and grunting. Any ideas?
Comment: Thanks Jörg. Makes sense, but wow, that must be distracting for the others listening to all that panting and grunting! Officiating football is strenuous activity.


Seeking to understand asymmetry in hypothesis testing

Question: I need to have one understanding on statistical hypothesis testing. In a typical hypothesis test, we have 2 opposite hypotheses; namely Null and Alternative. Here my textbook says that "those 2 hypotheses are not symmetrical in the sense that if we swap the hypotheses then the result will alter".
Here I am unable to grasp the point which that textbook wants to say. Can somebody explain to me in detail? It would be helpful if someone can give some example of that asymmetry as well.
Appreciate your help.
Thanks,
Comment: It's not clear to me either what your text book means here.  Could you add a bit more detail to your question - perhaps a longer quote from the book?
Comment: [Related Q & A](https://stats.stackexchange.com/questions/540574/whats-wrong-with-this-hypothesis-test-statement-why-not-another-way-around/540610#540610).
Answer: Suppose you have a random sample of uncirculated US double eagle gold coins which you have assayed for gold content.  Although manufacturing variations precluded the US Mint from guaranteeing that every double eagle had exactly 0.9675 Troy ounces of gold, the Mint tried to achieve this as an average value.  If they succeeded, the distribution of weights in your sample should be centered close to this value.  A sample average that is sufficiently far from 0.9675 (compared to the spread of your measured values) would be evidence that these coins are not honest double eagles.
In this example the null hypothesis is that the population of double eagles averages 0.9675 ounces and the alternative is that the average differs from 0.9675.  Suppose you were to swap these two statements and instead tried to test whether the population mean differs from 0.9675.  You cannot test this hypothesis with data because (literally) any set of values would be consistent with it.  (If you always obtained 0.9675 in every assay, your measurement procedure itself would be called into question because the results would be too consistent!)  There is an inherent, profound, asymmetry between the two hypotheses because one of them makes a specific quantitative prediction about how the data might be distributed but the other does not.
There's another asymmetry in hypothesis testing.  In the same situation, you might be interested in assessing whether the population of US double eagles is underweight.  A sample average that is sufficiently low would be good evidence of that.  The average would have to be substantially lower than 0.9675, though: how much lower is the "critical value" for the test.  In this situation you can switch the null and alternate hypotheses.  The new null is that the population of US double eagles is overweight.  A sample average that is sufficiently high would be good evidence of that.  That average would have to be substantially higher than 0.9675, though: how much higher is the critical value for this reversed test.  In each case, the set of possible sample averages is partitioned into two parts: those less than the critical value and those greater than the critical value.  Because the two critical values are not the same, the partitions differ, too.  For instance, a sufficiently low sample average in the first case lets you conclude that the population mean is underweight, but in the second case it is consistent with the null hypothesis that the population mean is not overweight.  Notice the distinction between evidence that is consistent with a hypothesis and evidence that falsifies a hypothesis.  That asymmetry is inherent in the logic of hypothesis testing.
Comment: To continue with your last example, why can't you say the following: there are 2 critical values, c1 less than 0.9675, c2 greater than 0.9675; if the sample average is less than c1, then accept H0. If the sample average is greater then c2, then accept H1. If the sample average is between c1 and c2, we decide nothing?
Comment: @Ericj, there is no such thing as "deciding nothing.". That is not one of the options.
Comment: I meant: not accept H0. Or as I would say, because I do not understand the asymmetry, and not accept H1.
Answer: I suspect it means that if you perform a test for H1 with null H0 and are not able to reject the null hypothesis, that does not imply that if you performed a test for H0 with H1 as the null that you would be able to reject H1.
The reason is that failing to reject the null hypothesis does not mean that the null hypothesis is true, it could just mean that there isn't enough data to be confident that the null hypothesis is false.
Comment: BTW a nice feature of the Bayes factor, which is symmetric.  Exchanging the hypothesis just gives the reciprocal of the Bayes factor.
Comment: Yes, this is the obvious way hypothesis testing of this sort is assymetric - the burden of proof is all with the alternative hypothesis.  What do you think is meant though by "in the sense that if we change the hypotheses then result will alter" - which seems to be a) so obvious as to not need saying and b) not really relevant to the question of symmetry?
Comment: I suspect they meant "exchange the hypotheses", otherwise it is rather vacuous as you suggest.  That seems the smallest edit required for the statement to make sense!


Esvaziar múltiplas tabelas numa única execução

Question: Via PDO, consigo fazer o TRUNCATE (Inglês) de uma tabela da seguinte forma:
// Matriz de definições
$dbcon_new = array(
  "host"     => "localhost",
  "dbname"   => "bubu",
  "username" => "super_dragon",
  "password" => "balls"
);

// estabelece a ligação
$dbh = new PDO(
  'mysql:host='.$dbcon_new['host'].';dbname='.$dbcon_new['dbname'].';',
  $dbcon_new['username'],
  $dbcon_new['password'],
  array(
    PDO::ATTR_PERSISTENT               => false,
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
    PDO::ATTR_ERRMODE                  => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND       => "SET NAMES utf8"
  )
);

// esvazia a tabela xpto
$dbh->exec("TRUNCATE TABLE xpto");

Pergunta
Como posso numa única execução realizar o TRUNCATE a múltiplas tabelas?
Comment: @GabrielGartz Alterei a frase da secção de pergunta que havias editado pois ficou mesmo estranho (pelo menos para um Português de Portugal).
Comment: Sim, agora está mais claro, eu falo Português do Brasil e estava com dificuldade de compreender a pergunta por isso tinha editado, mas desta maneira ficou clara em ambos dialetos. :)
Answer: Segundo a própria sintaxe do TRUNCATE na documentação do MySQL, isso não é possível. O que você pode fazer é passar diversos comandos de TRUNCATE na mesma query, separados por ponto-e-virgula:
TRUNCATE tabela1; TRUNCATE tabela2; TRUNCATE tabela3; --etc...

Apenas se atente à ordem das tabelas para não limpar antes tabelas das quais outras tabelas dependem.
Answer: Não tem como você executar um truncate para várias tabelas, até porque podem existir triggers diferentes e respostas diferentes para cada tabela e não teria como a base de dados testar os comandos depois validar em todos e te retornar o ocorrido no final.
O que você pode fazer é ter vários comandos de truncate no mesmo exec:
$dbh->exec("TRUNCATE TABLE xpto; TRUNCATE TABLE xpty;");

Ou executar um loop para executar várias vezes até terminar a operação:
$arr = array('xpto', 'xpty');
foreach ($arr as $table) {
    $dbh->exec("TRUNCATE TABLE $table;");
}

Sendo que a segunda opção é mais aconselhável, pois na primeira se ocorrer uma falha durante o truncate, os próximos comandos poderão ser ignorados dependendo da engine da base de dados em uso.
Answer: Recomendo usar o DELETEao inves do TRUCANTE pois nao é possivel dar TRUNCATE em tabelas que possuem chaves estrangeiras(FK)
passe um array($tabelas).
function deleteTabela($tabelas){

    $db = new PDO();

    forach($tabelas as $item){
        $item = limparEntrada($item);
        $sql  = "DELETE FROM $item";
        $db->query($sql);
    }

}

Comment: Na verdade é possível dar o `TRUNCATE`, desde que não haja entradas na tabela com chaves estrangeiras, correto?


Python, SQlite and string substitution

Question: I got a question, maybe it answered somewhere but I can't find answer.
So I got Sqlite db with one table consist, let say of phone models and manufacturers:
Samsung
Apple
Iphone
Apple
Galaxy
Samsung
Ipod
Nexus

so what I trying to achieve is make a script to substitute:
Iphone or Ipod -> Apple
Galaxy or Nexus -> Samsung

I would like to have an data structure like dictionary (I know that example is impossible, but only for illustration) that I can read from file to make an UPDATE query:
{
'Apple':'Iphone','Ipod'
'Samsung':'Galaxy','Nexus'}

so when script find any of values it substitutes it with key
values can be quite an few - let say about 10 so using if/or statements will be unpractical and I don't everytime I need change something go to the code and correct it - so that's why I want to keep my "dictionary" in text file and read it from an script.
I will be appreciated for any ideas that point me in right direction
Thank You.
Answer: First, you can make a dict that maps replacement values to lists of 'original values':
replacements = {
    'Apple':['Iphone','Ipod'],
    'Samsung':['Galaxy','Nexus']
}

You can just put that into a file like mapping.py and do from mapping import replacements. JSON would be a reasonable serialization format, too. Once you get the dictionary, you can iterate over all fields, generate a parametrized query fitting the length of strings to replace.
for replacement, replacables in replacements.iteritems():
    query = 'update foo set value=? where value in ({})'.format(",".join("?"*len(replacables)))
    c.execute(query, [replacement]+replacables)

This way you don't get SQL injections. When I tried, it worked up to 100 variables, didn't with 1000. I haven't checked how far exactly it works.
Answer: Beware: The following is not safe agains SQL injection!
The database before:
$ sqlite3 foo.db .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE t (f varchar);
INSERT INTO "t" VALUES('foo');
INSERT INTO "t" VALUES('bar');
INSERT INTO "t" VALUES('baz');
COMMIT;

The JSON file for the mapping:
{"B": ["bar", "baz"], "F": ["foo"]}

The Python code:
import json
import sqlite3

d = json.loads("d.json")

con = sqlite3.connect("foo.db")
cur = con.cursor()

# Loop over the keys in d.
for k in d:
    # Build the SQL clause that matches all recordss for d[k].
    clause = " or ".join(" f = '{}' ".format(v) for v in d[k])
    # The SQL for the update.
    sql = "update t set f = '{}' where {}".format(k, clause)
    cur.execute(sql)

con.commit()

The database after:
$ sqlite3 foo.db .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE t (f varchar);
INSERT INTO "t" VALUES('F');
INSERT INTO "t" VALUES('B');
INSERT INTO "t" VALUES('B');
COMMIT;

Answer: If you have to do a lot of substitution in one go i would suggest to use a temp table with columns old and new
so your dictionary will look like
Iphone, Apple
Ipad,Apple
Nexus,Samsung
Galaxy,Samsung
You can upload this dictionary to the temp table using a bulk loader
Bulk load data into sqlite?
And then run a single update command to update all the old values in one go
the gist of the SQL in Oracle will be
update yourtable
set yourtable.phone = (select temp.new
from yourtable , temp
where
temp.old = yourtable.phone)
where exists
(
select 1 from yourtable , temp
where
temp.old = yourtable.phone
)

Comment: This does not answer the concrete question. Besides, 10 is is not "a lot".
Comment: SQLite != Oracle. Do you know Python or SQLite?
Comment: Let the user who asked the question decide...i know SQLite..just that i am more comfortable with oracle... i dont know python..also i think of a different approach where things can be done with sqls
Comment: Well, the question clearly stated that it is about both Python and SQLite. So an answer about Oracle and nothing dosn't quite answer the question.

Python, SQlite and string substitution


Why does this work for $ i^{2i} $?

Question: I'm finding the principal value of  $$ i^{2i} $$
And I know it's solved like this:
$$ (e^{ i\pi /2})^{2i} $$
$$ e^{ i^{2} \pi} $$
$$ e^{- \pi} $$
I understand the process but I don't understand for example where does the $ i $ in $ 2i $ go?
Is this some kind of a property of Euler's number? if so please explain to me.
Comment: Hint: what is $i^2$? and do you know what $(a^b)^c$ equals?
Answer: $$\bigl(e^{i\pi /2}\bigr)^{2i} = e^{(i\pi /2) \cdot 2i}  = e^{i^2\pi}.$$
This is just an application of the exponent laws. Don't overthink it!
Answer: The $i$ in $2i$ was combined with the $i$ inside the parentheses. Hence, you got $$i\cdot i = i^2$$ which is due to exponent laws. More applied to your case:
$$(e^{ i\pi /2})^{2i}=e^{i \cdot i \cdot \pi}=e^{i^2\cdot \pi}.$$
Comment: you missed a 2.
Answer: Also remember that
$i = e^{\pi i/2+2\pi i k}
=e^{\pi i(\frac12+2k)}
$
for any integer $k$,
since $e^{2 \pi i k} = 1$.
$k=0$ gives the usual principal value.
Therefore,
$i^{2i}
=(e^{\pi i(\frac12+2k)})^{2i}
=e^{2\pi i^2(\frac12+2k)}
=e^{-2\pi (\frac12+2k)}
=e^{-\pi (1+4k)}
$.
So,
thanks to the joy of
infinite valued complex logarithms,
your expression has an infinite number of
distinct values.
Note that,
for large negative $k$,
the value is quite large.

Why does this work for $ i^{2i} $?


itext, Flying Saucer: xhtml to pdf ClassCastException

Question: <code>public void createPDF() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpSession session = (HttpSession) externalContext.getSession(true);
    String url = "http://localhost:8080/comap/pages/admin/student.xhtml";
    try {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition","C://user//first.pdf");
        java.io.OutputStream browserStream = response.getOutputStream();
        renderer.createPDF(browserStream);
        browserStream.close();
        session.invalidate();
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    facesContext.responseComplete();
}
</code>
here is the exception..

java.lang.ClassCastException: org.xhtmlrenderer.render.BlockBox cannot be cast to org.xhtmlrenderer.newtable.TableBox
Comment: It looks like data error in the XHTML. Run the above code on ever smaller XHTML files, till you find what XML caused the error. Validate the XHTML.
Comment: Great. Now only please add where exactly is the exception thrown, what is your question, what is the expected output... you know, the standard stuff.
Answer: This commit has fixed the issue. You can download the Class and place it in your src directory so that you don't have to rebuild the jar.


How do I open a file with tkinter and save the data to another variable?

Question: I am learning to use tkinter and I cannot figure out how to open a text file and save the data so that I can use the data in other calculations. In my code below a button is created that when pressed asks for and opens a file. It then prints the content of the file in the console.  If the file contains for example a single number, say 100, I can't figure out how to save that number as a variable like "a."
from tkinter.filedialog import askopenfile

root = Tk()
root.geometry('200x100')

# This function will be used to open
# file in read mode and only Python files
# will be opened
def open_file():
    file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
    if file is not None:
        content = file.read()
        print(content)
        a = content

btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)

Comment: You have already done this inside `open_file()`.  So what is your problem actually?
Answer: You are assigning the contents of the file to a variable declared within the function. It will be destroyed after the function finishes.
Declare the variable before the function
data = []

Append the content of the file to the container value within the function
def open_file(container):
    file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
    if file is not None:
        content = file.read()
        print(content)

        # give the content to the data
        data.append(content)

However if you are going to give the data to another widget using a instance of tk.StringVar() might be better as most widgets have a textvariable option.
data = StringVar()

And instead of appending StringVar uses the set() method.
data.set(content)

Resources for you:
https://www.pythontutorial.net/tkinter/tkinterstringvar/
And:https://www.delftstack.com/howto/python-tkinter/how-to-change-the-tkinter-button-text/


Any way to attach specific CSS styles to specific groups?

Question: I have li already styled in a stylesheet. I need it to stay a specific style. It is styled without using a class, so for example
    .selectors{width:50px;}
    li{
        padding:10px;
    }
Now i have run into a problem. I am trying to style the li again, without any classes like what i have in the example code. For example
    .options {width:30px;}
    li{
    padding:50px;
    }
What i was wondering is, is there any way to attach certain elemnts to another element. I'm not sure if this is making any sense, but I am trying to have one LI only be applied to a certain part of the page, and the second be applied to another part of the page. Is this possible without using classes? I can't modify the code or add classes otherwise the script doesn't work. Can someone help if I am making any sense at all.
Comment: Take a look at Selectors:
http://www.w3.org/TR/CSS2/selector.html

http://www.w3.org/TR/css3-selectors/

there are many more combinations you could use.
Answer: A very common way to do this is
#content li { ... }
#sidebar li { ... }

so the li will behave differently inside two different elements with different IDs.  Say, if content is a div, and sidebar is a div, then the li will behave differently inside these two divs.
It is also possible to be "within a class":
.items-to-watch-out-for li { ... }

This is a good way to avoid "too many classes", which is called "classitis", like in this article:
http://www.ehow.com/how_2284990_classitis-html-css-descendant-selectors.html
Comment: By the way, the `#` sign grabs the element by its ID.
Answer: It's never going to be the nicest way if you can't add classes.
Potentially if the uls are in the same container you could try:
ul:first-child li {}

This will allow you to style the first ul however you want then the generic:
ul li {}

Will take care of the second.
This method should work in all browsers apart from IE6.
http://www.quirksmode.org/css/contents.html#t17
動靜能量 solution is the ideal way.


How do I prevent the automatic removal of a database table when a module is uninstalled?

Question: In Drupal 7, a database table created through hook_schema() gets created on module installation, and gets deleted on uninstallation.
I would like to prevent the removal of a database table when the module defining it is uninstalled, because the data which I am storing is very important so I want to make sure that even if someone even uninstalls the module for certain purpose than also data retains. Backing up the table before is certainly one solution but I am looking for some better alternative.
Answer: Uninstall is there just to delete changes made to database. If you do not want that deletion to happen, do not uninstall. If you need only one table, back it up before uninstallation and restore it after. If you want to remove module from uninstall list, simply delete it's files.
If you need selected module to be always on, you can use hook_modules_disabled() in a helper module, to display message like "Disabling of this module is not permitted" and instantly re-enable it. If module is never disabled, there will be no option to uninstall it. Of course if someone with admin privileges will want to destroy your data, he will, so don't give those privileges to those who can't be trusted with them, but at least it should prevent accidental module removal by developer who is not bright enough to stop and think.
Last but not least, if module's data is of significant importance, you have daily or maybe even hourly backups anyway, so accidental deletion is not a problem at all. Backup and Migrate and Elysia Cron are great help with setting up backups like this, but you should also ask your sysadmin to provide automatic copy to another physical machine, if possible.
Answer: I would implement hook_install and hook_uninstall and not use hook_schema.
In hook_install you can use the database api to create the table. Then leave your hook_uninstall blank, thus preserving the table and data.
Comment: You cannot: Drupal uses `hook_schema()` in different functions. Without that, the database table doesn't exist, for Drupal.
Answer: I had the same problem, i solved implementing the hook_schema and hook_uninstall in this way
/**
 * Implements hook_uninstall().
 */
function my_module_uninstall() {
    drupal_static( 'my_module_uninstall', true );
}

/**
 * Implements hook_schema().
 */
function my_module_schema() {
    if( drupal_static( 'my_module_uninstall', false ) ){
        return null;
    }

    return array(
        'my_table' => array(
            // table definition
        ),
    );
}

When the module will be uninstall the hook_schema will be executed again (after the hook_uninstall), the schema will not be returned hence it will not be deleted by the drupal_uninstall_schema function.
However this is a sort of workaround: the response of @Mołot is more useful if you have to redistribute your custom module. But for my needs I prefered my approach as my module will not be used outside my project, and I wanted to be sure that the table will be there even after an accidental uninstall.


Obtain the coordinates of one point (X1,Y1) where it is maximum the change of the curve

Question:
(source: biomedcentral.com)
Dear community,
I used a figure obtained from internet to illustrate what I would like to solve. Imagine this exponential regression curve.
How can I get the exact point of the curve where it is maximum the change of the it?
Observing the figure, it should be placed between 1 and 2 in the X axis and between 0.04 and 0.08 in the Y axis. But where it is exactly?
Thanks in advance
Comment: maximum of the 2nd derivative?
Comment: If this is truly exponential, then the maximum of any odd-order derivative (such as its slope) is attained at 0 and the maximum of any even-order derivative is asymptotically reached at $\infty$: no calculation is needed.
Answer: You need to compute the second derivative = 0, which is called an "inflexion point".
To make things clear, let's take the Gauss curve as an example: the inflexion points are at $x = \pm\sigma$.
(Since the second derivative gives the concavity, an inflexion point is a point where the convexity of the curve changes.)
Comment: It is likely I did not write well what I wanted. In this figure there is only one concavity curve. Which is the point in that curve, I mean it's coordinates X and Y, where the curve is stronger? Here, there is not an inflexion point because there is not a change in the curve pattern (concavity-convexity or vice versa). Thanks in advance!
Comment: Hello. Yes, you wrote correctly. I think that you should have a look at wikipedia article about inflection points, there's a video where you see the progress of the slope, explaining your issue.


Help with interpreting the regression

Question: This is the first time I'm using regression analysis and I'm not sure what I need to write for my interpretation that would make sense.
I'm trying to write about the impact of oil price changes on the stock market. I've used the daily data for the last 15 years.
Any help is appreciated.
Comment: It is a good idea to start with writing down the regression equation something like $y_t = \beta_0 + \beta_1 * x_t + \epsilon_t$ and then explain in your question what the dependent variable measures and what the independent variables measures. Remember to specify the units. This is essential to get anywhere with respect to interpreting the coefficients.
Comment: Please add self-study tag. Please read https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions#10812 and edit your question to show your efforts.
Answer: The R square  is called the coefficient of determination. It is the degree to which the model predicts the dependent variable with the given independent variables. In short, R is calculated as the correlation between the actual dependent variable and the predicted dependent variable using this regression model. The adjusted R square is the adjustment made into R square for the number of predictor variables.
The R Square value closer to 1 denotes the model is able to predict the dependent variables much closer to the actual and model is fit. Here, R Square value is almost zero, which means that your model will be of much use for prediction.
The ANOVA tests the assumptions the the coefficient of the predictor is equal to zero. The regression sum of squares is the total variance in the dependent variable explained by the regression model. The Residual sum of squares is the total variance in the dependent variable that is unexplained by the regression model. The mean sum of squares are the sum of squares of each divided by their corresponding degrees of freedom.
Assuming your model has high R square (not TRUE in this case)
The intercept is the value of % Change in Daily StockMarket Index, when the change in WTI Close Price is zero. Here, it is 0.03161. The coeffient of WTI Close Price Daily % change denotes the amount of % change in Daily StockMarket Index, when the % change in WTI Close Price is 1.
You can frame the regression equation as
StockMarket Daily % Change = 0.03161 + (0.06857*WTI Close Price Daily % change)
Even though, significance of the intercept is greater than 0.05, it is important to have the intercept in the model.

Help with interpreting the regression


PHP return value to div value

Question: Hello i am having trouble with passing a php return value to the innerHTML method to change my div's value on a fixed interval.
this is my code, i inclue the php file containing the method, and then create an object of the class containing the method, then i want to echo the return value to the innerHTML function. but is does not work.
var t = setInterval(function() {
  document.getElementById("content").innerHTML = "\
    <? include_once("php/functions.php");         \
       $cont = new Content();                     \
       echo ($cont->getPosts());                  \
    ?>";
}, 1000);

However this works so a php value can be echod to the innerHTML function.
var t = setInterval(function() {
  document.getElementById("content").innerHTML = "<? echo "Some Text"; ?>";
}, 1000);

there is noting wrong with the  <? include_once("php/functions.php"); $cont = new Content(); echo ($cont->getPosts());?> statement, because when i put it outside of the

PHP return value to div value


Joblib nested Parallel execution not making use of available cores

Question: By using nested Parallel statements with n_jobs>1 on the outer statement, the nested Parallel function appears to be restricted ressources available from 1 thread instead of 4.
I.e. consider the following strongly simplified script to reproduce the problem:
from joblib import Parallel, delayed
import numpy as np

def parallel_in_parallel_test(i):
    a = np.ones((1000,1000))
    for j in range(2000):
        a *= np.random.randn(1000,1000)
    return a.sum()

def parallel_in_parallel_wrapper(j, n_threads=4):
    out2 = Parallel(n_jobs=n_threads)(delayed(parallel_in_parallel_test)(i) for i in range(100))
    return np.array(out2).sum()

out = Parallel(n_jobs=3)(delayed(parallel_in_parallel_wrapper)(j, n_threads=4) for j in range(100))

I would have expected that 3 parallel processes produce 4 processes that yield a CPU usage of 400% ie 4 cores/threads per "parent-process". However, instead these 4 "child-processes" run not in parallel. Each "parent-process" uses 100% of the CPU instead of 400% (only a single core/thread)
Consider the following screenshot from htop:

I can reproduce the issue with a minimalistic environment:
conda create --name py39 python=3.9
conda activate py39
conda install numpy joblib

My OS: Ubuntu 18.04.5 LTS
A not-nested approach is not feasible with my specific code as the nested parallel sits in a method of a class.
Any suggestions how to properly make use of the available ressources? Is it just a simple mistake?
Answer: Apparently changing the inner_max_num_threads limit of the backend used in the nested statement works - still it is not clear to me why this is neccessary in the first place.
from joblib import Parallel, delayed, parallel_backend
import numpy as np

def parallel_in_parallel_test(i):
    a = np.ones((1000,1000))
    for j in range(2000):
        a *= np.random.randn(1000,1000)
    return a.sum()

def parallel_in_parallel_wrapper(j, n_threads=4):
    with parallel_backend("loky", inner_max_num_threads=n_threads):
        out2 = Parallel(n_jobs=n_threads)(delayed(parallel_in_parallel_test)(i) for i in range(100))
    return np.array(out2).sum()

out = Parallel(n_jobs=3)(delayed(parallel_in_parallel_wrapper)(j, n_threads=4) for j in range(100))


How to pass object (table or column) names into a stored procedure

Question: As far as the specs to get out of the way, it is PostgreSQL 9.2, with the database through PgAdmin3, and the format of the table as a shapefile. If there are any additional details necessary I will edit and provide.
I essentially want to update integer values in a column of integer values based on whether string values in some other columns are null or not. I eventually want to port my stored function to execute in a java app using jdbc, but I first want to test my function within pgadmin3. I have very little experience with postgresql and am a little fuzzy on the syntax.
So the parameters that I've got somewhat of an idea on needing and what to put in thus far are: name, argmode, argname, argtype, column_name, and lang_name.
I understand that if I'm not returning anything I can either include RETURNS void as $$ or simply not include a return statement. I don't think I need result sets, I just want to replace integer values in a column. I'm not sure how to reference the table that I need in order to pass in the columns I want to process.
Here is the code I have cobbled together thus far:
CREATE [OR REPLACE] FUNCTION handle_malformed([[VARIADIC][]
table_name.column_name, table_name.column_name, table_name.column_name, table_name.column_name, table_name.column_name, table_name.column_name, table_name.column_name, table_name.column_name])

BEGIN
LOOP
IF NAME_1 IS NULL THEN
IF LEVEL_DEPT != 0 THEN
    UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 0;
ELSE IF NAME_2 IS NULL THEN
    IF LEVEL_DEPT != 1 THEN
        UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 1;
ELSE IF NAME_3 IS NULL THEN
    IF LEVEL_DEPT != 2 THEN
        UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 2;
ELSE IF NAME_4 IS NULL THEN
    IF LEVEL_DEPT != 3 THEN
        UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 3;
ELSE IF NAME_5 IS NULL THEN
    IF LEVEL_DEPT != 4 THEN
        UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 4;
ELSE
    IF LEVEL_DEPT !=5 THEN
        UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 5;
EXCEPTION
END LOOP;
END PROCEDURE;
$$ LANGUAGE plpgsql;

update handle_malformed(AdminBoundaries.NAME_5, AdminBoundaries.NAME_4, AdminBoundaries.NAME_3,
AdminBoundaries.NAME_2, AdminBoundaries.NAME_1, AdminBoundaries.NAME_0, AdminBoundaries.WIKI_URL, AdminBoundaries.LEVEL_DEPT)

The logic that I put in is the logic that I put in between the loop and end loop is the logic I want to accomplish.
My specific question is, how do I use the column names from arguments in the SQL?
Comment: The capitalised identifyers are supposed to be column names ? Why do you repeat the argument ten times ? What is the intention of the arguments, the function does not appear to use them ?
Comment: Yes. I'm not sure what you mean by repeat the argument 10x. The intention of the arguments? The arguments are essentially the capitalized identifiers. What I was trying to do was pass in column names and the table name, but I wasn't sure how to do so
Answer: Based on the comments I have edited the question to include a question....  As I understand it, you want a value from an argument to be used in the query.  To do this, use EXECUTE and assemble the query as a string.  Note that you cannot parameterize identifiers of this sort and so you must concat them in, and use quote_ident() to prevent in-stored-proc sql injection.
So instead of:
 UPDATE AdminBoundaries SET \"LEVEL_DEPT\" = 1;

use:
 EXECUTE $e$ UPDATE AdminBoundaries SET $e$ || quote_ident(LEVEL_DEPT) || $e$ = 1 $e$;

You can use execute to handle dynamic checks as well:
 EXECUTE INTO my_bool $e$ SELECT a.$e$ || quote_ident(level_dept) $e$ is not null $e$;

I think this answers your question based on the comments.  If not, feel free to clarify.


Shortening a link using HTML/JS/CSS

Question: I am trying to change the design of the navigation on my site.
We have some products with really long names and I want to cut them short and maybe add (...) or something similar at the end.
So something like this should look like abcdefg... instead of abcdefghijklmnopqrstuvwxyz

a{
  width:50px;
  overflow:hidden;
}
abcdefghijklmnopqrstuvwxyz

A JS solution is welcome.
I would also like to know why the width isn't being applied?
Comment: https://www.w3schools.com/cssref/css3_pr_text-overflow.asp also anchor by default displays inline so add display: block / inline-block if you want overflow property to be used
Answer: Use white-space combined with overflow & text-overflow. And don't forget to add display: inline-block to the a element, so you can apply width to it.

a {
  display: inline-block;
  width: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
abcdefghijklmnopqrstuvwxyz
Comment: had tried this with no success. it was the inline-block that was throwing me off
Comment: @PaddyHallihan Yep, I will include that to the answer.
Answer: Anchors are inline elements by default and any width set on an anchor is ignored. Change the display to inline-block:

a {
  width: 50px;
  overflow: hidden;
  display: inline-block;
}
abcdefghijklmnopqrstuvwxyz

As MDN states:

Inline elements are those which only occupy the space bounded by the
  tags defining the element, instead of breaking the flow of the
  content.

and...

You can change the visual presentation of an element using the CSS
  display property. For example, by changing the value of display from
  "inline" to "block", you can tell the browser to render the inline
  element in a block box rather than an inline box, and vice versa.
  Hovewer, doing this will not change the category and the content model
  of the element. For example, even if the display of the span element
  is changed to "block", it still would not allow to nest a div element
  inside it.

Shortening a link using HTML/JS/CSS


How do I make my Python program search up my questions on Google (based on a certain input)?

Question: I am trying to make a voice assistant like program, in which questions are asked, and questions that cannot be answered by the program are searched by Google.com. So I was simply wondering what softwares I would have to install to make this work? And what would I generally have to do to?
For more information, I am using Raspbian on my Raspberry Pi 3 B, and I am using Python 3.9.2
Thank you!
Comment: use Google API, also you can't seek recommendations for software and tools here
Answer: All you need is a few libraries and nothing else to install. A great tutorial is found here: https://www.geeksforgeeks.org/performing-google-search-using-python-code/
The two libraries needed are:
pip install beautifulsoup4

and
pip install google

Comment: @RyanShirvani I'm not sure if this is what you need but I found this article: https://towardsdatascience.com/scrape-and-summarize-news-articles-in-5-lines-of-python-code-175f0e5c7dfc

In the article, they are able to load the website with just the link.
Comment: @RyanShirvani I found a 2nd article that uses a different library to display the website:https://www.codegrepper.com/code-examples/python/how+to+display+a+webpage+in+python


Plotting an animated hypocycloid

Question: I want to animate a Hypocycloid using computer code.  So far i have drawn the circles here.
I have found this definition on wikipedia and I want to animate the image that is on the right.
I did something similar here with a sine wave.  I used a counter and changed the position of the shapes using cos and sin to plot the changing shapes on each change of the counter.
This new graph is infinitely more complicated.
Wikipedia gives the following equations:
$x(\theta) = (R - r) \cos \theta + r \cos((k - 1) \theta)$
$y(\theta) = (R - r) \sin \theta - r \sin((k - 1) \theta)$
I do not know how to solve these equations.
Why is it $x(\theta) = $ and not just $x =$ ?
How do I find $\theta$ when it occurs on both sides of the equation ; besides, I do not understand what $k$ is.
Comment: What is the software you use ?
Comment: @JeanMarie I use d3.js , the source code for all the charts is here https://github.com/dagda1/d3-geometry
Answer: You misunderstand the meaning of $x(\theta)$.  The parentheses do not indicate multiplication; they instead indicate that $x$ is a function of the parameter $\theta$.  To plot this curve for a given $R$, $r$, and $k$, all you need to do is plug in various values of $\theta$ into each equation on the RHS, and the first equation gives you the $x$-coordinate and the second gives you the $y$-coordinate.
Comment: great, what is k in this instance.
Comment: @dagda1 $k$ is just another fixed constant, in this case the number of windings.  It is related to the symmetry of the resulting figure, so when $k = 5$ for example, you should get a figure with fivefold symmetry.

Plotting an animated hypocycloid


Use the Extension method instead Built-in method in C#

Question: Some Built-in methods are not working for me, I' m using old version of .NetFramework for my application which is not having some new methods. So, I' m trying to create extension methods that overrides the built-in methods. But I' m facing some issues with. Here is the code:
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.Collections.Generic;
namespace API{
public static class Retrive
{
    // some variables

    public static void CopyTo(this Stream input, Stream output)///Extension method
    {

        byte[] buffer = new byte[32768];
        int read;

        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write (buffer, 0, read);
        }
    }

    public static void Main ()
    {
          string url = "https://";
          string baseURL = "";
          string authenticateStr = "";

        try
        {
            ///
            }

        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                ////
            }
        }
    }  // end main()
}  // end class

}//end name space
The errors I' m getting are

1) Extension methods must be defined in a top level static class;
  'Retrive' is a nested class .

I don' t understand why 'Retrieve' class became nested.

2) Extension methods must be defined in a non-Generic static class

How to solve these issues? Please help me.
Thank you.
Comment: I have the feeling we are missing parts of the codefile. Is that correct? Are you defining a namespace? And why did you move the Main-function from Program to Retrive? Is the Program-class actually removed?
Comment: if I am not mistaken your extension [will not be called](http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx) as it has the same signature as [Stream.CopyTo](http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx)
Comment: Based on the errors you're reporting, it seems we're not looking at your whole code.  I don't see any other way to get the errors you're seeing.
Comment: I cannot reproduce your problem. Your code does not compile, because of a type (character 's' between "responseText = sr.ReadToEnd();" and "List uriList = new List();
". Second, not all your namespaces are complete, because List should use namespace System.Collection.Generic. Third, not all variables are declared, like "url" and "baseURL".
 and
Comment: I don' t need the Directives and namespaces to be defined, when I compile the code in my application the code gets decorated with the required Directives and namespaces. So, I missed namespace. Now I added namespace to the code.
Comment: But I' m facing issues with the class structure, AS I mentioned in the question.
Answer: non generic static class means you are creating a class that is not using template.
e.g. List is a generic class but MemoryStream or alot of class are not generic.
nested class answer is already given in this thread.
Answer: Try keeping "static void Main()" in any other class. I mean other than the one you are trying to use for creating extensions.
Comment: Yes, it is recommanded to seperate them, but since both Main and CopyTo can co-exist in the same static class, this is no way an answer to the question.
Answer: It looks like your main methods is also in the Retriev class. I recommand to create a seperate class for extensions methods as shown below:
public static class ExtMethods
{
  public static void CopyTo(this Stream input, Stream output)///Extension method
  {
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
       output.Write (buffer, 0, read);
    }
  }
}

Comment: Yes, it is recommanded to seperate them, but since both Main and CopyTo can co-exist in the same static class, this is no way an answer to the question.


How to get credit memo created date magento?

Question: How to get credit memo created date time in magento transnational email ?
<code>{{var creditmemo.getCreatedAtFormatedHideTime('short')}}
</code>
Comment: which transactional email you are looking for?
Comment: order transnational email template
Comment: Are you talking about email which send when order is placed?
Comment: after order i have create credit memo that order, then customer got a credit memo email, how to set credit memo created time on that email template.
Answer: You can get creditmemo created date and time using this code.
<code>{{var creditmemo.created_at}}
</code>
Comment: If my answer help you, please accept it so it will help other community as well.
Comment: it works for me but need to change formate 2020-04-24 17:18:34==>April 24, 2020 at 9:07:42 a.m. MDT