Regression with percentage points

Question: Suppose I want to find out how growth in average income affects the growth in income of the poor. For this I have 60 countries and for each country the income of the poor and average income for 6 years. I am unsure on how to perform a regression of this.
I have been calculating the average annual growth in percentage for average income and income for the poor. From what I understand this gives me percentage points change instead of percentage change, thus it would be a simple linear regression.
Yet I have seen some tutorials that log the percentage points, creating a log-log regression. Which of these two methods are correct?
EDIT: Example values:
Country A:

Average income for the poor for 4 years: 1990:150, 1991: 260, 1992:300, 1993: 400
Average income for 4 years:     1990:340, 1991:600, 1992:710, 1993:1000

Compound annual growth poor: 38.67%
Compound annual growth all: 43.28%
Say I do this for 60 countries, so i will get for average annual growth of income of the poor (in percent):
21.10 , 16.23 , 12.34 , 23.25 , 11.12 , 13.55 etc
and for average annual growth if income of all:
43.13 , 35.31 , 56.31  etc
and I do a regression on them and get say y = 2.433 + 0.6 x
.   So if income of all increases one unit, the income of the poor increases 0.6 units.
Is it correct to say than that a 1 percent change increase in average income of all will result in 0.6 percent change average income of the poor?   Or is it percentage points change?
Answer:
Say I do this for 60 countries, so i will get for average annual
  growth of income of the poor (in percent):
21.10 , 16.23 , 12.34 , 23.25 , 11.12 , 13.55 etc
and for average annual growth if income of all:
43.13 , 35.31 , 56.31 etc

as I said:
I consider you put in the values as 21.10 and not as 0.2110?

So if income of all increases one unit, the income of the poor
  increases 0.6 units.

Wrong, remeber your variables, these are not income variables but annual growth rates!
So if the average annual growth rate of the income of all increases by one unit, the annual average growth rate of the income of the poor will increase by 0.6 units on average.

Is it correct to say than that a 1 percent change increase in average
  income of all will result in 0.6 percent change average income of the
  poor? Or is it percentage points change?

I suppose you put in the values as 21.10 and so on. The regression output is
y = 2.433 + 0.6 x

where x is the average annual growth rate of the income of all and y is the average annual growth rate of the income of the poor. You put in the values, as e.g. 21.10. If x (average annual growth rate of the income of all) is increased by one unit (from e.g. 21.10 to 22.20, so from 0.2110 percent to 0.2220 percent, this is a change by 0.01 percentage point) the y (average annual growth rate of the income of the poor) will increase by 0.6. So from
$y = 2.433 + 0.6 * 21.10=15.093$
to
$y= 2.433 + 0.6*22.10= 15.693$
so from 15.693 to 15.093, which is from 0.15093 percent to 0.15693 percent, which is a change by 0.006 percentage point. Or an increase by $(0.15693-0.15093)/0.15093= 0.03975353$. So an increase by about 4 percent.
Comment: I noticed, that the value of 21.10 in your statement above belongs to y and not x. But this does not matter, since it is just an example, so imagine it is a value for the x variable.
Comment: I edited my answer, since I had a typo, when calculating the values with R.
Answer: I am not really sure, if I got your right......
Just to have a specification, you have:
income of the poor, given in "normal" (not percentage) values for 6 years
average income, given in "normal" (not percentage) values for 6 years
so with this, you have calculated:
y = average annual growth of income of the poor
x = average annual growth of income
So y and x are univariate? Like
y             x
value 1      value 1
value 2      value 2

Did you use the geometric or arithmetic mean?
I would suggest using the geometric, look at a simple example for this (consider this to be e.g. income values):
40000, 42000, 45000 and 47000
This gives the percentage values: 0.05, 0.07143, 0.0444
the geometric mean is: $(1.05 * 1.07142857 * 1.04444)^{(1/3)}= 1.0552257$
This is a factor, whereas 0.0552257 is percent
i.e.
each year, the income increases by 5.52257 percent on average:
40000*1.0552257=42209.028
42209.028*1.0552257=44540.05112
44540.05112*1.0552257=46999.8 (difference due to unprecisely rounding)

So this is not percentage point? Or what did you mean? Percentage point is:
If the annual growth rate of 5% increased to 7%, this is an increase of 2 percentage point or an increase by 40 percent!
So you have now the geometric annual growth rate of the income in percent (let's say you use the percent value and not the factor value) and the geometric annual growth rate of the income of the poor, right?
If you use the values as following:
y     x
5.5   4.5
6.5   5.5
and so on

and not
y    x
0.055 0.045
and so on

Now, you do the regression of y,x and you have a regression coeff of e.g. 0.7.
This means, if you increase x by one unit the variable y will increase by 0.7 on average.
So if the annual growth rate of the income is increased by one unit, e.g. from 5 to 6, the y variable will increase by 0.7.
So if the annual growth rate of the income is increased from 5% to 6%, the y variable will increase by 0.7% (on average).
Did you mean this?
Depending on log on one side or taking log-log on both side, the interpretation changes. This basically depends on the dependence of your data. If you take the x as log values, this gives not a linear dependence anymore, but a logarithmic dependence. You have to do model identification to see, what would be appropriate. Plot y and x in a scatter plot, is it a linear dependency or logarithmic?
In case of the interpretation look at this thread: In linear regression, when is it appropriate to use the log of an independent variable instead of the actual values? , especially the second answer with 17 thumps up.
Comment: maybe also this paper will help you:
http://www-stat.wharton.upenn.edu/~stine/stat621/handouts/LogsInRegression.pdf
Comment: @Crazzzy12 or specify the problem more detailed, give example values or originial values
Comment: I have used the geometrical average and calculated as you did. But is it then defined as percentage change or percentage point change in the end? If average annual growth rate income increases 1 unit and average annual growth of income of the poor increases 0.7 units, it is a change in percentage points right? I've plotted y and x in a scatter and it seems to be a linear dependency.
Comment: I will give example values in the text to make it clearer!
Comment: @Crazzzy12 I added an answer.

Regression with percentage points


Multiple imputation: Pooling t statistics

Question: I have conducted analyses to compare dependent correlations (Steiger, 1980) using multiply imputed data. The statistics follow a t distribution.
Question: What is the correct way to pool these statistics, with the goal of generating a p-value?
Here is what the results look like (from 20 imputations): -2.938462 -2.627696 -2.562013 -2.354825 -2.542520 -2.442978 -2.583879 -2.421124 -2.746131 -2.936789 -2.328653 -2.884968 -2.423605 -2.567752 -1.787200 -2.675324 -2.815900 -2.307922 -2.968579 -2.299145
Comment: What is your question and what is the design of the experiment? Also, can you post a sample of your data?
Answer: Take a look at the following paper, it talks about conducting inference when you have multiply imputed data.

Schafer, J. L. (1999). Multiple imputation: a primer. Statistical
  Methods in Medical Research, 8(1):3-15.


Oracle: Is there a way to encode a value using the unix crypt method?

Question: Is there a way to encode a value using the unix crypt method in oracle 10g?
(Other DBMS like MySQL support this)
Answer: The DBMS_CRYPTO PL/SQL package has encryption, but none using the native weakness of the Unix crypt(1).  It's much more analogous to crypt(3).
If you need the exact crypt(1) implementation, you're going to have to code it yourself.  Here's the C code for it.
Comment: Unfortunately, I need the exact crypt encoding.
Answer: Provided you are one Oracle8i or higher this is possible.
The solution is to write a Java Stored Procedure which can execute OS commands, and use that to run Unix crypt.  Tim Hall's Oracle-Base site has an example of how to code one of these things.  Find it here.
Comment: Hope he's not on windows; if so, he's going to have to install POSIX to boot.
Comment: I'm not on windows, but unfortunately this is not an option for me. anyway, i'll accept the answer. Thanks


flattened-seventh chord function

Question: I this post, I received some information on the usage of a flattened-seventh chord in progressions, which, along with the flattened-third, seem to be popular choices in the rock world to add flavor.
I have come across another example, and I could use some help breaking it down.  The progression (in B major) is:
I - iii - bVII - V

Now, I understand that a common technique is to dip into chords from the parallel or relative minor.  In the case of B minor, the bVII chord is A dominant seventh, and it is the VII chord (is that redundant?  I'm not used to talking about minor keys).  In the case of the relative minor, g-sharp minor, the above chord is iidim – A sharp diminished.  So, either I am missing something, or there are no clues there.
Another possibility I considered was the secondary dominant chord.  In B major, the V chord is F# major.  So, the V/V would be C sharp major.  So, that can't be it.
Finally, because this chord is featured in a descending bassline that goes: B(I) A#(iii-inversion) A(bVII) G# G F#(V), I could understand viewing it as a passing chord thrown in sort of by feeling and instinct rather than arising from consideration of the functional purpose.
Regarding function, this chord does set up the stage for the V chord nicely.  I am not sure if that is a harmonic relationship (if the bVII behaves like a sort of secondary dominant) or if it is just because of the flow of the descending bassline.
I would really appreciate anyone's input so that I can lay this to rest.
Thank you!
-286642
Answer: This is an interesting progression, and that move from D♯ minor to A major is pretty jarring!
I understand this in at least two ways:

First, as you said, is the obvious result of the chromatic voice leading in the bass. We call this a lament bass, and although this is an uncommon harmonization of it, it's not completely unheard of: a famous prelude by Rachmaninoff begins with i to a III64 (!), quite similar to this example.
The second is the notion of an unfolding. This is more of a "scholarly" explanation, influenced by Schenkerian theory. But basically, an unfolding is when a harmony is prolonged by other chords built on the prolonged harmony's chordal members. For example: we're setting up V, as you said. The chordal third of that V is some kind of A (technically A♯), and so thus this A chord "unfolds" the V chord by arpeggiating through a type of third and then moving to the root of F♯. This interpretation is buttressed by the fact that this VII chord often functions as a dominant in this style, so obviously two dominant functioning chords will prolong the dominant function.

One other comment I want to make:

Now, I understand that a common technique is to dip into chords from the parallel or relative minor.

I would say that borrowing from the parallel minor is far more common that borrowing from the relative key. This is because the chords of the relative key are mostly exactly the same as the ones in the original key; for instance, that iio chord you mention in G♯ minor is simply viio in B!
Answer: The bVII is probably the most used non-diatonic chord in music. So much so that it's the only non-diatonic chord included in Apple's GarageBand chord palette. As for its function there are many different and valid explanations as to why it works. For me one of the most important reasons it works so well is it mimics the parallel whole step movement between IV and V chords, subdominant to dominant in either direction. We are so used to hearing that parallel sound between IV and V chords that it also sounds good and natural going to a I chord.
It is also the V of the relative major of the parallel minor (did I just write that?) Basically in your sample key A goes to D which is the relative major of B minor so it's also sort of a borrowed cadence. When you go from A to D it's a similar sound as A to Bm because D and Bm have 2 common notes. You're just substituting major for minor.
There are other valid reasons, it's like a subdominant of the IV chord, etc. There is an excellent online article about this chord here that talks about it both historically and theoretically in contemporary music, enjoy!
http://www.icce.rug.nl/~soundscapes/VOLUME22/Magnificent_flat-seventh.shtml
Comment: @MichaelCurtis actually no, I'm referring to D major as the relative major to B minor, the parallel minor.
Comment: @MichaelCurtis I'm simply showing the relationship of the bVII chord to the parallel minor. The OP is looking for ways that the bVII functions. I think it's relevant.
Comment: Interesting concepts! Makes a mockery of 'parallel fifths'! Music moves on...
Comment: @Tim Parallel 5ths were already mocked 70 years ago, lol! The first time a guitar player put down a 1 and 3 finger and moved it up and down the neck it was all over!
Comment: Look, I'm a bit slow, but I'm catching up..... aren't I?
Comment: I think you're mistaking the `iii` for `D` major instead of `D#` minor.
Comment: Well, yes, I read that in your answer. But how does it relate to the question? The progression you describe isn't in the question.
Answer: Not really an answer, but I want to add a diagram to go with @Richard's answer.
I didn't really understand the Schenkerian part, but I found a diagram that made it clear to me...

RODNEY GARRISON, Unrolling Schenker's Ideas of Musical "Unfolding". Theory and Practice, Vol. 37/38 (2012-13), pp. 111-138
In lots of rock music there are progressions like I V bVII IV :|: I... which can be seen as sequential harmony, or a IV/IV thing. I bVII I treats bVII as a kind of modal substitute of V. But those don't seem the right comparisons. I assume your progression goes ...V :|: I... in which case "unfolding" the dominant seems a much better description.
Answer: I've already declared in other answers (to other questions) that I interprete the bVII like a kind of suspension of the V. This theory of mine has been denied by others - but may be I can convince you ...
The use of bVII preceeding the dominant is very common in pop music. Also it is quite common to introduce the dominant by its secondary dominant and the parallel of this secondary dominant which is actually the ii7-V progression, which latter can be considered as a V with a double suspension ( do-ti and la-so = 4-3 and 9-8 )
I can hear the flat 7th (ta-ti) resolving to the 3rd of the dominant (ti)  analog to  the suspended 4th (do) resovling to the lead tone (ti):
So we have two similar suspensions of the lead tone: from up do-ti, from down ta->ti (whereby I ignore that bVII doesn't contain the root tone of the dominant.
I have no theoretical source than my own impression and my own experience with this phenomenon.
Answer: This is possibly a tangential answer, but just to make the point that the flattened seventh arguably has quite a strong relationship to the tonic compared to the major seventh...

If we consider C as a tonic on the circle of fifths, the flattened seventh (Bb) is very close - only two fifths away - while B is way over on the other side of the circle. The Bb major chord also consists of notes all quite close on the circle to a C tonic.

If we consider harmonic frequencies, the minor / flattened 7th is found much earlier in the harmonic series than the major seventh.

In a way, it isn't news that B is very dissonant with a tonic C - that's part of why it has that 'pull' as the leading note. But I think you could consider that it's the major seventh, and the diminished chord that is built on it in major harmony, that's the 'flavourful' one; the flattened seventh is quite tame and safely 'close' to the tonic in terms of harmonic relationship by comparison!
Answer: Just allow ♭VII honorary membership of the 'diatonic' club.  It's been used this way in popular music for at least 50 years. Then a whole lot of special-case 'theory' becomes unnecessary.
Comment: It's clearly not diatonic, because there's a temporary scale change. But I agree with the special-case theory being unnecessary. If one is not able to use something as simple as this without having a fancy label for it, there is a problem somewhere. But calling it diatonic doesn't help IMO.

flattened-seventh chord function


Does a given positive measure set in $\mathbb{R}^2$ contains product of two 1 dimensional positive measure set?

Question: In $\mathbb{R}^2$ consider the 2 dimensional positive Lebesgue measure set,
$$D=\{re^{it}:t\in[0,2\pi),r\in[0,1]\setminus\mathbb{Q}\}  .   $$
Does there exist sets $A,B\subset\mathbb{R}$ of 1 dimensional positive  Lebesgue measure such that $$A\times B\subset D?$$
Note: The above is not true if $$D=\{(x,y)\in [0,1]\times [0,1]:x-y\notin\mathbb{Q}\}.$$
Answer: No, it there were two such sets $A$, $B$,  then with the map $(x,y) \mapsto (x^2, y^2)$ ($t \mapsto t^2$ bi-Lipschitz on compacts inside $(0, \infty)$) , it would transform into $A_1$, $B_1$ of measure non-zero inside $\{(x,y)\ | \ x+y \not \in \mathbb{Q}^2\}$, which is not possible.
Comment: $r\notin \mathbb{Q}$ doesn't imply $r^2\notin \mathbb{Q}$. Then how we conclude that $D$ maps inside $\{(x,y):x+y\notin \mathbb{Q}\}?$
Comment: I guess of I defined $D$ to be $\{re^{it}:r^2\notin \mathbb{Q}\}$ then your argument works perfectly. Am I right?
Comment: @Oh, I see, it transforms into $x + y \not  \in \mathbb{Q}^2$, and again get a contradiction ( only use $\mathbb{Q}^2$ is dense, and nothing else)
Comment: I am not getting why you need to take $A,B$ away from 0?
Comment: @Prof.Hijibiji: You want to the image not to be of measure $0$. You guarantee that if the inverse $t\mapsto\sqrt{t}$ is Lipschitz.
Comment: is that mean I could get positive measure set $A,B$ (essentially containing 0) such that $A\times B\subset D?$
Comment: @Prof.Hijibiji: No, you can't. If you have some containing $0$, then for sure you will have some away from $0$. Not that hard to see.
Comment: Right you are. Thanks.
Comment: Sorry to bother you again. Just wanted to tell that $0\notin D$ ao we don't need to worry about it.
Comment: @Prof.Hijibiji: No worries!  I modified the answer a bit, hope it is clearer.
Comment: Thanks @orangeskid: bi Lipschitz argument makes it easier to prove but I guess in general if $A$ is positive Lebesgue measure then $A^2=\{a^2:a\in A\}$ is also positive Lebesgue measure.
Answer: Let $A$ and $B$ be defined by
\begin{align*}
  A & =\big\{a\in\mathbb{R}: a^2=\sum_{i=1}^\infty a_i10^{-2i},
a_i\in\{1,2\,\dots,9\}, a^2\not\in \mathbb{Q}\big\} \\
B & =\big\{b\in\mathbb{R}: b^2=\sum_{i=1}^\infty b_i10^{-2i+1},
b_i\in\{1,2,\dots,9\}, b^2<\frac12, b^2\not\in \mathbb{Q}\big\}.
\end{align*}
Note that if $r^2=a^2+b^2\in \mathbb{Q}$ then the decimal expansion of
$r^2$ will eventually have a finite length repeating sequence. Any
such sequence would have to come from a unique repeating sequence of
even place decimals from $a^2$ and repeating odd place decimals from
$b^2$. Since $a^2,b^2\not\in \mathbb{Q}$, such repeating sequences do
not exist, thus $r^2\not\in\mathbb{Q}$.  Not entirely sure about the
measure of $A$ and $B$, but for their squares, I think the measures
are positive.
Comment: Actually you need to show that $A\times B\cap D$ is positive Lebesgue measure in $\mathbb{R}^2$ which could not be true as we can see from the other answer. Thank you for your participation. Appreciation


HTTP connections are fast from local network, very slow from the outside world

Question: I setup a Wordpress server in a Raspberry Pi with nginx, MariaDB and ufw. I also setup the No-IP service. When I access the server from my local network (192.168.0.173) I get a fast response but when I try to access from the outside world the response is very slow (aarroyoc.noip.me). It loads, as I can see the title bar in the browser but it just keeps loading and loading.
I think Wordpress isn't the problem because when I access from local network the speed is fine. My router bandwith can't be a problem, I usually run game servers and I didn't experienced such problems.
I downloaded the frontpage using cURL and the response was fast, so the problem might be in the browser but I don't know what is making the web so slow.
Why do I get a fast response from local network browsers and cURL outside Internet but it's so slow on outside Internet browsers?
EDIT
Doing more tests I've found that PHPInfo is fast (http://aarroyoc.noip.me/phpinfo.php) from outside network but the Wordpress panel is slow (http://aarroyoc.noip.me/wp-admin/) only from the outside.
Comment: Have a look at this test - looks like the server is responding quite quickly and external resources are slowing it down. Not sure why it'd be fast inside the network and slow outside http://www.webpagetest.org/result/160613_3C_e7172af91c81953d60b2392fb6db275f/
Answer: That's because you set up your Wordpress server to redirect to your internal IP, 192.168.0.173. So when external clients try to reach your Wordpress server, they are being redirected to http://192.168.0.173/wp-login.php which will, of course, fail after a timeout. The same goes for your Wordpress homepage, there are a number of resources, like CSS and image files, that are being served from http://192.168.0.173 instead of http://aarroyoc.noip.me.
The reason why PHPInfo works, is because it's completely self-contained. Even the PHP logo is embedded into the HTML. Check the source to see what I mean.
Comment: No, the site is slow, because the browser is trying to download items from the site that reside on an IP address it can't contact.
Answer: I don't know if this will help some people, because i got the same problem when i was setting up my wordpress and couldn't get around the problem. This was very annoying to me but i remember that i sucessfully configured without any problems once.
Whoever with researching and trying stuff to see what went wrong i've tried to configure the wp-config.php to use the database created with mysql/mariadb.
sudo mv /var/www/html/wp-config-sample.php /var/www/html/wp-config.php
sudo nano /var/www/html/wp-config.php

 define( 'DB_NAME', 'wordpress' );

/** MySQL database username */ define( 'DB_USER', 'yourusername' );

/** MySQL database password */ define( 'DB_PASSWORD', 'yourpassword!' );

/** MySQL hostname */ define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */ define( 'DB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */ define( 'DB_COLLATE', '' );

and accessed https://api.wordpress.org/secret-key/1.1/salt/
Got my secrets key, deleted the lines and pasted the new ones.
And that got it working for me.
Hope this helps someone.


Getting response 444 when making request to a webpage

Question: I am trying to make a request to a webpage using the code below and i am getting response 444.
Is there anything i can to about it?
<code>import requests

url = "https://www.pseudosite.com/"
response = requests.get(url)
print(response) # <Response [444]>
</code>
http.dev website says the following:

When the 444 No Response status code is generated, the server returns
no information to the client and closes the HTTP Connection. This
error message can be found in the nginx logs and will not be sent to
the client. It is useful for dealing with malicious HTTP requests,
such as one that includes an illegal Host header.

I am trying to webscrape that website using python, but I am blocked at first step.
Comment: post the real webpage that you want to crawl.
Answer: I believe that you need to add headers to view this webpage. If you open devtools on your browser, then you should see a 'get' request; if you now click on the 'Headers' tab, you can create a dictionary with the data.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


If you roll a fair die 3 times, what is the probability that all 3 rolls will come up a value less than 4

Question: If you roll a fair die 3 times, what is the probability that all 3 rolls will come up a value less than 4 ?
Answer: The desired probability is $\frac{1}{8}$. To see why, note that the probability of the number being less than $4$ is $\frac{1}{2}$ in each roll of the dice. These can just be multiplied to give the probability of $\frac{1}{8}$.


Passing argument to nrpe

Question: Remote hosts nrpe.conf
command[check_users]=/usr/lib64/nagios/plugins/check_users -w $ARG1$ -c $ARG2$

Monitoring host:
define command{
        command_name check_nrpe
        command_line /usr/lib64/nagios/plugins/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$
       }

define service{
        use                             local-service         ; Name of service template to use
        hostgroup_name                  linux-servers
        service_description             Current Users
        check_command                   check_nrpe!check_users!15!20
}

I getting usage error with this configuration , please help
Answer: Change check_nrpe!check_users!15!20 to check_nrpe!check_users!"15 20".
With your current config, as far as Nagios is concerned:
ARG1 = check_users
ARG2 = 15
ARG3 = 20

But then your command only uses ARG1 and ARG2, so the 20 isn't passed to NRPE.
You want ARG2 to be "15 20", which NRPE will then split into two ARGs on the receiving side.
Answer: You can try passing the actual values as thresholds in nrpe.cfg/nrpe.conf on remote host in place of $ARG1$ and $ARG2$.
Eg : command[check_users]=/usr/lib64/nagios/plugins/check_users -w 15 -c 20
Along with this just to be sure, do check if :

Check_Users command defined properly in commands.cfg on monitoring host.
check if path of plugin(check_users) used in config files is correct and permissions are setup properly.

Rest seems to be fine and if above doesn't work, then paste the actual error.

Passing argument to nrpe


check_mk: global name 'entry' is not defined

Question: I'm having a ton of trouble with a nagios installation I've been working on powered by check_mk and OMD. When using the web gui to manage check_mk, the notifications page displays the following Python error:
<code>Traceback (most recent call last):
File "/omd/sites/keck/share/check_mk/web/htdocs/wato.py", line 304, in page_handler
modefunc("content")
File "/omd/sites/keck/share/check_mk/web/htdocs/wato.py", line 9000,  in mode_notifications
statename = _(entry.get("HOSTSTATE")[:4])
NameError: global name 'entry' is not defined
</code>
For the life of me, I can't figure this error out. I even wiped my installation and tried setting it up from scratch and got the same problem. Any ideas?
Comment: That's a Python error, not PHP.
Comment: Good point, I updated to reflect.
Answer: try removing the file "/omd/SITE/var/check_mk/notify/backlog.mk" and create an empty one. Then restart the core. This fixed the issue for me.


Gradle Project sync failed Android Studio (e.g. editing, debugging) will not work

Question: This is the first time i work with Android studio, and i'm facing this problem with says Cradle Project Sync Failed (e.g. editing, debugging) will not work properly.
Comment: Sure i will keep you posted
Answer: Go to

Tools--> Android - > Sync Project with gradle

if it does nt work try

File -> Invalidate Cache and Restart


How to remove the sound driver from CentOS 7?

Question: I have a centOS minimal installed and it the sound drivers loaded. I would like to remove all the sound drivers from my server. How can I do that? following are the command outputs from my server.
cat /proc/asound/cards
 0 [AudioPCI       ]: ENS1371 - Ensoniq AudioPCI
                      Ensoniq AudioPCI ENS1371 at 0x2080, irq 17
lsmod | grep 'snd'
snd_ens1371            25243  0
snd_rawmidi            30871  1 snd_ens1371
snd_seq_device         14356  1 snd_rawmidi
snd_ac97_codec        130605  1 snd_ens1371
ac97_bus               12730  1 snd_ac97_codec
snd_pcm               105835  2 snd_ac97_codec,snd_ens1371
snd_timer              29639  1 snd_pcm
snd                    83425  6 snd_ac97_codec,snd_timer,snd_pcm,snd_rawmidi,sn _ens1371,snd_seq_device
soundcore              15047  1 snd
lspci | grep -i audio
02:03.0 Multimedia audio controller: Ensoniq ES1371 / Creative Labs CT2518/ES1373 (rev 02)
Comment: What output give you commands `systemctl | grep alsa` `systemctl | grep sound` `systemctl | grep pulse` ?
Comment: `systemctl | grep sound
  sys-devices-pci0000:00-0000:00:11.0-0000:02:03.0-sound-card0.device                              loaded active plugged   ES1371 / Creative Labs CT2518/ES1373 (AudioPCI 64V/128 / Creative CT4810/CT5803/CT5806 [Sound Blaster PCI])
  sound.target                                                                                loaded active active    Sound Card`
Comment: The other two commands are not displaying any information
Answer: You can add such lines to /etc/modprobe.d/disable-sound.conf
blacklist snd_ens1371
blacklist soundcore
blacklist snd


Why does Fux use F# in his counterpoint to a firmus written in G mixolydian

Question: In the given image below, Fux writes a counterpoint to a cantus firmus given to him as part of his studies by his fictitious teacher Aloysious.
A rule that is often emphasised is that one should remain in the mode (in this case, the mixolydian mode), and there should be NO accidentals, except in the second to last bar where the 7th has to be raised.
Note that the cantus firmus is in the upper stave and the counterpoint in the lower. Also this, if not evident, is Second Species CounterPoint

Thus, the question is as follows. In the fourth to last bar Fux raises the 7th - why? By doing so he has exited the mode
Comment: He's just Fuxing with your head, that's all.
Comment: Looked it up in the original 1725 edition, http://imslp.org/wiki/Gradus_ad_Parnassum_(Fux,_Johann_Joseph) p. 61 -- it's definitely there in the original. My guess is that since each of the last two Fs move up to G it may have been considered a cross-relation to make the first F-natural and the second F#.
Comment: Hmmmm, interesting. There's also a conspicuous voice crossing in the 6th bar. The CF itself isn't explicitly in Mixolydian, but it's been too long since I've done species stuff to know if that loosens things up at all. Obviously in some sense the reason is because the note is ultimately leading to the G of the next bar as a sort of pre-cadence, but it does seem like a strange move in modal species terms. Could it have anything to do with the fact that the next CF note would have been a tritone away from an F natural?
Comment: The cadence approach and prominent B naturals were what I was thinking of, too...
Comment: in bar 10 the CF is at C, the very next bar F# (the CP) is the highest tone (a sort of leading up to a tritone), that alone would turn me off. If he were to use F natural the interval would have been a minor 3rd which is a valid (and preferred) imperfect consonance.

I too considered the cadence as a possible explanation, however, this is according to Fux, not allowed.
Comment: Oh yeah, good call. What a strange choice…
Comment: There's no reason to consider any supposed master to be fully bound to the rules he devises, fully consistent with a style he espouses, or fully convinced of the merits of his own system. It seems quite likely that this is merely an inconsistency, despite being one penned by a recognized master of counterpoint. Or you could look at this as a sort of extended cadence beginning two measures early.
Comment: You would outline a tritone if you used F natural. In the next bar, the cantus firmus moves to b natural.
Answer: First of all, the clefs are not quite right and the bottom part should be an octave lower (this is inferrable from the illegal 4th in the penultimate bar).
Modes in Renaissance style are not the strict collections of 7 notes used in "modal" pop and jazz songs. Instead, a mode tells us where the tonic is located within a field of 11 notes, 7 diatonic and freely used (A,B,C,D,E,F,G) and 4 chromatic (B-flat, F-sharp, C-sharp, and G-sharp).
Flats are used primarily to avoid the tritone; thus if your melody wants to go to B but the cantus firmus is on an F, you can use B-flat instead. (Flats are used for other purposes too, such as the "una nota super la" rule and certain cadences in Dorian, but that's another story.)
Sharps are used primarily in cadences, as you correctly point out, and also in cases which at the time were caused "causa pulchritudinis": using a major third in a triad which would normally be minor for its richness of sound (an epic example is the opening phrase of Palestrina's "Stabat Mater").
It appears that Fux is trying to achieve the latter category of effect but, as is clear from reading an updated counterpoint manual such as Jeppesen or Gauldin, he got a few things slightly wrong. A sharped note should function melodically as a leading tone to the next higher note; in this case, the F-sharp would be correct if followed by G, although that would cause problems in the next bar.
Answer: I know it's an old discussion, but I thought I might add my five cents:
I'm working on the "Gradus" these days (Mann's translation) and have asked myself the same question. Then I remembered that in footnote 9 to Chapter one Mann says that "the tritone is to be avoided even when reached stepwise (f-g-a-b) IF THE LINE IS NOT CONTINUED STEPWISE AND IN THE SAME DIRECTION". Could it be that Fux simply wanted to avoid the melodic tritone in bars 7-9 of the tenor voice (b-a-g-f) by sharpening the f, since he did not continue stepwise to e but skipped to d instead?
Answer: A possible explanation would be that the F# in the fourth bar from the end in the counterpoint is sharped so that there is no tritone with the B in the third bar from the end in the cantus firmus. The unaccented D that follows F# in the counterpoint would not alleviate the formation of the tritone.
Comment: not really a valid comment since Fux could have replaced the 'B' with an 'E' such that the passage would be G -> E -> D -> F#. The latter makes more sense since the motion would still be similar, however, the interval would be a minor third (from E to G) - which is an imperfect consonance, thus... better
Comment: @AidenStrydom I am speaking of the relation of the quarter note F# in the fourth bar from the end in the counterpoint, with the whole note B in the third bar from the end in the cantus firmus, not the unaccented quarter note in the counterpoint.
Comment: i know... and you're still wrong. had he made the B in the third to last bar an E he wouldn't have needed to raise the fourth to last bar's F to an F#
Comment: You seem to find the cause of this F# to be the B in the second quarter of the third bard from the end in the counterpoint while I think that the whole note B in the CF would be the problem, even though it is in another voice. Mostly because it is an accented B and it comes before the B in the CP. Even if, like you propose, he substituted the B with the E (therefore changing a minor 6th with a minor 3rd, both imperfect consonances), a tritone would be sounded in the outer voices. Could you care to define what counterpoint rule/guideline are you following?
Comment: @AidenStrydom but the CF is given.  He uses the same CF in the first species eight pages earlier.  On top of that, the resulting descending fifth in the CF would be uncharacteristic.  Replacing the B in the third to last bar with an E is not an option.


Firebase Google sign in : This domain is not authorized to run this operation

Question: I am having trouble getting the Firebase Google sign-in to work with a custom domain.
This functionality works when running the app on localhost.
I have added the custom domain on the Authorized domains under the Authentication and Sign in methods

I have initialized the app with the below config in the app module.

What am I missing here, could it be that I have deployed the Angular app in Heroku with an Express server?
Any assistance is appreciated.
Answer: My mistake was that I did not include the Firebase config in the environment.prod.ts as I was building with the --aot --prod flags for the production build. ♂


checkbox whit React js and state undefined Value

Question: I am creating a filtering form to filter my data based on the checkboxes which will have a value of true or false but I don't know why I have the value undefined.
My code:
The Constructor:
constructor(props){
    super(props)
    this.state={
      rfp:false,
      rfx:false,
      rfp_x:false,
      allclassification: false,
    }
this.onChange =  this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
   }

onChange:
onChange(e){
    this.setState({ [e.target.name]: e.target.checked });
}

onSubmit:
onSubmit(e){
    e.preventDefault();
    const FilterClassification = {
        // classification
        rfx:this.state.rfx,
        rfp:this.state.rfp,
        rfp_x:this.state.rfp_x,
        allclassification:this.state.allclassification,
    }
    console.log(FilterClassification)

    axios.post("http://localhost:8080/MenuFiltre/filtreregioncloser",FilterClassification )
}

HTML:
<form onSubmit={this.onSubmit}>
<fieldset>
<legend>RFX/RFP:</legend>

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfx} name="rfx" id="rfx" />
  RFX

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp}  name="rfp" id="rfp"  />

  RFP

  <input type="checkbox" className="form-check-input" onChange={this.onChange}  value={this.state.rfp_x}  name="rfp_x" id="rfp_x"/>
  RFP(X)

  <input type="checkbox" className="form-check-input"  onChange={this.onChange} name="allclassification" id="allclassification" />
  ALL

</from>

undefined  value
False value
Answer: I just checked your code and everything looks normal and working.
I created a example on codesandbox.io and paste your code here to double check and everything works like you wanted?
Example: codesandbox.io example


Como aplicar opacidade em um elemento DOM - createImage(); - através de um editor em javascript?

Question: Estou usando o p5.js - uma biblioteca javascript - para capturar imagens de uma API de notícias. Gostaria que essas imagens fossem sobrepostas, mas com opacidade, de forma que as imagens se mesclem.
Não estou conseguindo aplicar a opacidade direto pelo código javascript. Consigo alterar a posição das imagens ( fotos.position(x ,y); ), mas não encontro o caminho para aplicar a opacidade.
function setup() {
createCanvas(900,600);
loadJSON("https://newsapi.org....ec6490",gotData);
}

function gotData(data) {
console.log(data);

var img = data.articles;
var imgs = [];

for (var i = 0; i < img.length; i++) {
imgs.push(img[i].urlToImage);

var fotos = createImg(img[i].urlToImage);

fotos.position(0, 0);
}
}

Uma solução que encontrei lendo alguns posts aqui no stackflow, foi alterar manualmente a opacidade das imagens, uma por uma, através do inspetor HTML do browser, mas isso serve apenas para poucas imagens.

Mas isso fica impossível no caso de 2 mil imagens, por exemplo. Preciso automatizar esse processo.
Portanto, como faço para aplicar opacidade numa imagem - elemento DOM direto pelo código javascript?
Comment: Já tentou pelo CSS? `img{ opacity: .3; }`.. isso irá aplicar a opacidade em todas as imagens dentro do body.
Comment: Ainda não sou familiarizado com CSS, comecei a estudar javascript há pouco. Vou dar uma olhada essa semana e retorno aqui, mas pelo que diz, parece ser uma boa solução!

Obrigado, dvd!
Comment: Mas você quer sobrepor 2000 imagens no canvas com transparência? Não sei se o browser daria conta de tudo isso não.
Comment: realmente, 200 fotos sobre postas acho que dá um resultado ilegível. tô puxando de 20 em 20, e mesmo assim só as de cima aparecem.

de toda forma, de 20 em 20 chega rápido em duzentas, vai além.

valeu, abs!
Answer: Pelo visto na sua imagem da pergunta, todas as imagens que você adiciona estão dentro do body, então basta adicionar no seu CSS a opacidade que você deseja que irá ser aplicada a todas as tags , sem a necessidade de recorrer ao JavaScript:

Comment: valeuzaço. ótima solução. ficou como esperava. agora é ir desenvolvendo. vou dar uma olhada no CSS, já ví q vai ser de grande ajuda.

abs!


Theming translatable nodes in D7

Question: We used i18n module to have our nodes as translatable.
However we also themed a specific nid with e.g node--9.tpl.php.
Problem is that i18n creates separate nodes(this separate nids), for each translation language, thus the theme file only applies to 1 version of that particular node.
How can I handle this?
Answer: Add following code to template.php and clear cache
function <THEME_NAME>_preprocess_node(&$vars) {
    if(!empty($vars['node']->tnid) && $vars['node']->tnid !== 0){
        $vars['theme_hook_suggestions'][] = 'node__'.$vars['node']->tnid;
    }
}

Comment: thanks, I'd add that in my case *$vars* was *$variables* and that if you already have the above *preprocess_node* function in your code you should just put the inner code within the already existing function. Thanks, it works like a charm
Comment: I know this is outside the scope of the question, but do you know what happens with blocks that are listed to appear only on particular nodes? How do I cover that scenario?
Comment: @NicholasKyriakides Please explain in detail or add new question

Theming translatable nodes in D7


Como remover um "href" de uma tag  com JQuery/JavaScript?

Question: Eu tenho uma tag  com hiperlink devidamente setado. Porém, gostaria de removê-la ao disparar de um evento. A mesma tag tem um ID devidamente setado, também (único, válido, e afins).
Gostaria de saber se existe uma função para remover o atributo href e assim tornar o link inválido, ou se existe uma forma de apenas desativar esse link.
Answer: A solução moderna para desativar um link é somente CSS: (para Browsers modernos)
$('#minhaID').css("pointer-events", "none");

// e para re-activar basta usar:
$('#minhaID').css("pointer-events", "");

Demo
Pode usar tambem assim:
$('#minhaID').attr("href", "");

Ou ainda:
$('#minhaID').removeAttr('href'); // note que esta opcção remove algumas caracteristicas importantes do elemento como focus.

dependendo da utilização que quiser dar.
Nota: O Chrome tem uma discussão aberta sobre a possibilidade de deixar de suportar pointer-events.
Comment: Solução interessante, também. Parabéns!
Comment: @DennisBraga, sim, é fácil, basta usar `$('#minhaID').css("pointer-events", "");` - Exemplo: __http://jsfiddle.net/Tn52U/1/__
Comment: Edita a tua resposta e adiciona isso. É muito legal isso de poder retirar o link sem perder informação e poder, simplesmente via CSS, reativar. :D
Comment: @DennisBraga, feito! boa ideia.
Comment: sabe me dizer se é possível reverter esse processo e se sim, como?
Comment: Essa solução em css é suportada por navegadores antigos?
Comment: @JoaoPaulo não. Juntei um link para dar essa informação.
Comment: Só tomem cuidado ao usar o pointer-events, pois ele só funciona em 3 navegadores... conforme a especificação: http://caniuse.com/#search=pointer%20events
Answer: Seria apenas isso?
$('a').removeAttr('href');

Comment: Faz parte, acontece ^^
Comment: Teoricamente, sim... mas não funfou comigo! Pensei que estivesse fazendo errado, ou coisa do tipo. Estou chamando pelo ID do link, mas acho que esse não é ponto.
Comment: UPDATE: Funcionou. Era exatamente isso, mas outra parte do meu código tava atrapalhando isso de funcionar corretamente. Me sinto até meio tapado por ter perguntado isso agora! ¬¬'
Answer: Existem várias maneiras, pelo javascript puro o ideal é que você use a referencia do seu elemento e nele use o método removeAttribute, exemplos:
document.querySelector('#minhaAncora').removeAttribute('href');
document.getElementById('minhaAncora').removeAttribute('href');

Porém quando você remove essa propriedade da ancora, essa ancora deixa de funcionar como ancora, perdendo as características dos pseudo seletores :hover, :active, :focus e :visited o que pode ser um comportamento indesejado.
Neste caso você pode substituir o valor do atributo por uma hash, exemplo:
document.querySelector('#minhaAncora').setAttribute('href', '#');

Porém isso pode influenciar o scroll do navegador dependendo dos elementos e tamanho da página, então uma outra solução é colocar no lugar um script que não faz nada, exemplo:
document.querySelector('#minhaAncora').setAttribute('href', 'javascript: ');

Ele vai manter as propriedades da ancora mas não irá fazer nada ao ser clicado. Pois o browser interpreta isso como uma "evaluação" de código durante o evento de click, porém como não há código, ele ignora o comando.
Dica para quem usa o jQuery ficaria assim:
$('#minhaAncora').attr('href', 'javascript: '); // modifica pra não fazer nada
$('#minhaAncora').attr('href', '#'); // faz o scroll mover-se para inicio do documento, mas não muda de página
$('#minhaAncora').removeAttr('href'); // remove o atributo da tag

Caso você não queira remover, pode usar o pointer-event do CSS para invalidar o uso de eventos de cursor na tag, porém isso não remove o link que ainda pode ser acessível com focus (use tab) em seguida enter, apenas browsers modernos tem suporte.
Caso você não queira remover o atributo, mas apenas remover o evento deles, é possível prevenir a ação padrão com seguinte código:
document.querySelector('#minhaAncora').addEventListener('click', function (e) {
    e.preventDefault();
});
// Compatível com todos browsers modernos, IE antigos precisa retornar false
// e a forma de adicionar eventos é por outro método.
// No caso use o jQuery:
$('#minhaAncora').on('click', function (e) {
    e.preventDefault();
});

Comment: Resposta bem sólida, também. Bom trabalho.
Answer: Sugiro, além de remover o atributo, adicionar um estilo para ficar visível ao usuário:
$('#link').removeAttr('href').css({
    'cursor': 'not-allowed',
    'color': '#AAAAAA',
    'text-decoration': 'line-through'
});

Exemplo no jsfiddle.
Answer: Utilizando javascript puro:
document.getElementById('id').removeAttribute('href');

Answer: Se for o seu caso, você também pode cancelar o evento padrão de redirecionamento da âncora com o próprio evento:
$('a[href]').on('click', function(event) {

    event.preventDefault();

});

Comment: Porque não editar a sua resposta e adicionar esse conteúdo ao invés de criar outra resposta?
Comment: Desta forma quando a âncora for clicada (se for o seu caso) ela não vai redirecionar para a referência.
Comment: Essa função é bem mais interessante, assim não perco a informação do meu link.


When the human voice changes pitch are certain interval changes physically easier?

Question: I'm wondering along the lines of physics and how things resonate.
I don't know how pitch changes work when something vibrates, especially the voice or wind instruments. I sort of understand that a vibrating air column - like in a flute - has to be forced to vibrate differently and certain changes are hard to do resulting in register breaks.
With singing I generally understand that changes by step are easier to perform than leaps, or at least so I've heard. Perhaps that isn't really true?
But what is happening with the vocal cords and voice box when pitch changes? I assume everything has to readjust to start vibrating at the new pitch. Are certain changes easier to make? Like the sound waves are more similar so the change is easier?
In other words, is there any physical reason that a change by octave of perfect fifth is easier that a whole tone or tritone? Or is there no such thing happening at all?
Comment: Based on my experiences singing, I'd suspect that a change by a perfect fifth is more difficult than a change by a whole tone. It's easier to sing a whole-tone trill than a fifth-tremolo, I find.
Comment: On the flip side, a poorly controlled trill or vibrato is disparaged (in German) as a *quintenschwabel*!
Answer: Increasing tension in a particular muscle raises pitch.  (Secondary effects apply, too, but they really are secondary for this question.)
The larger the leap, the harder it is to hit the target pitch accurately and quickly.  This trade-off between leap distance, pitch accuracy, and speed is just an application of Fitts's Law.
"Visualizing" a pitch before singing it is then visualizing how much to tense that muscle, quite like preparing for any other sudden action: throwing a basketball, hitting a drum, aiming a computer mouse.
Resonance in the mouth, nose, and throat doesn't really apply like with a flute.  A closer model is a muted trombone:  a buzzing input signal, filtered and amplified by a peculiarly shaped and peculiarly controlled tube.
If it feels easier to leap by a fifth or an octave than by a smaller interval, it may merely be because it's easier to compare the target pitch to the remembered starting pitch, easier and faster to correct for overshoot or undershoot.
Comment: But aren't these muscle movements in the throat so miniscule as to not work like the sports examples like throwing a ball?
Comment: Yes, that muscle moves very little, but its *tension* changes a lot.  Exactly like a tuning peg on a violin or piano.  (See isometric vs. isotonic contraction.)  The sports analogy is only about aiming at a target: how much muscle tension, how large and fast a motion is needed.  We directly control only a muscle's tension;  its side effects like elbow angle or sung pitch are things that we learn as infants and toddlers.  The tradeoffs of Fitts's law still apply.
Answer: I could explain all the basic models of vibrating systems, string under tension, stiff rods and plates with boundary conditions, air columns, etc.  But I am not sure that would answer you question.  For one thing one of your basic statements is simply not true (and I think you suspected it).
"With singing I generally understand that changes by step are easier to perform than leaps, or at least so I've heard. Perhaps that isn't really true?"
This depends on so many factors, some of which may be psychological or slight physiological differences among humans.  For example, I am a natural "leaper" as my vocal coach says.  She (my coach) is more able to sing scale melodies (and always has been), yet I can jump up a tower of 4ths or 5ths easily (within range of course).
There are two potential interpretations of the qualifier "Easy".  If you mean easy to hear in your head then this may not have anything to do with physics.  On the other hand if you mean easy on the throat + diaphragm + sinus system then some of it may have to do with physics but also physiology (which one could argue can be modeled with physics).  In a nut shell we need to be able to hear where we want to go, and be able to adjust our body to go there.  These "two minds" in a sense need to be in sync.
The amazing thing about singing is that you don't really need to change anything consciously to change pitch, even though something is changing.  What I mean is that you don't need to consciously squeeze or tighten anything in your neck or throat to change pitch, if you do you will likely hurt yourself.  With some training you should be able to slide (siren) up and down scales and arpeggios smoothly.  The real issue is will you "stop" at the right places.  If you have a hard time being in tune then you just need ear training and practice.  But if you have real physical problems getting good tone etc then this is physical and would likely be the result of not have a good support from the diaphragm, running out of air, etc.  Again, not a problem with vocal fold tension or anything like that, but an air flow problem.
Most people have a "transition" note where one can feel the resonance in the head more pronounced.  At this point it becomes physically more difficult to move smoothly up and down the scale near the transition note.  However, once you are out of that region it becomes easy again.  Being in tune is not so much the problem as having a shaky sounding voice, almost like a pre-teen whose voice is changing and cracking.  It is common to feel the resonance of lower pitch notes in the chest and higher pitch notes in the head but in fact all notes are resonating through the entire column.  With training one learns to feel head resonance without cutting off the chest resonance and vice verse.  This provides the proper support for those transition notes.
I do not believe that larger jumps would naturally be harder to get accurately as the previous answer states.  In my case, first day of lessons I could nail large jumps.  To the point about being able to hear the target note better, past exposure to those intervals helps (it gives you a mental frame of reference).  Since I've played guitar (and violin) for 40+ years I can hear the tower of 4ths (one 3rd) and 5ths in my sleep.  So in a sense I have those intervals memorized.  While the muscles do have to increase tension I do not think this is the reason why some intervals may seem more or less difficult to hit in general.
Another thing to consider in your question is not whether a 5th is easier than (or harder than) a half step but whether the situation changes in different octaves.  At the low end of our range (especially if you are a bass) you may not even be able to hear or feel the difference between two notes a half step apart, while a fifth may be easy.  2 or 3 octaves higher the situation may flip.


Updating a docker image without the original Dockerfile

Question: I am working on Flask app running on ec2 server inside a docker image.
The old dev seems to have removed the original Dockerfile, and I can't seem to find any instructions on a way to push my changes into to the docker image with out the original.
I can copy my changes manually using:

docker cp newChanges.py doc:/root/doc/server_python/

but I can't seem to find a way to restart flask. I know this is not the ideal solution but it's the only idea I have.
Answer: There is one way to add newChanges.py to existing image and commit that image with a new tag so you will have a fall back option if you face any issue.
Suppose you run alpine official image and you don't have DockerFile
Everytime you restart the image you will not have your newChanges.py
docker run --rm -name alpine alpine

Use ls inside the image to see a list of existing files that are created in Dockerfile.
docker cp newChanges.py alpine:/

Run ls and verify your file was copied over
Next Step
To commit these changes to your running container do the following:
Docker ps

Get the container ID and run:
docker commit 4efdd58eea8a updated_alpine_image

Now run your alpine image and you will the see the updated changes as suppose
docker run -it updated_alpine_image

This is what you will see in your update_alpine_image with having DockerFile

This is how you can rebuild the image from existing image. You can also try @uncletall answer as well.
Answer:
If you just want to restart after docker cp, you can just docker stop $your_container, then docker start $your_container.
If you want to update newChanges.py to docker image without original Dockerfile, you can use docker export -o $your_tar_name.tar $your_container, then docker import $your_tar_name.tar $your_new_image:tag. Later, always reserve the tar to backup server for future use.
If you want continue to develop later use a Dockerfile in the future for further changes:

you can use docker commit to generate a new image, and use docker push to push it to dockerhub with the name something like my_docker_id/my_image_name:v1.0
Your new Dockerfile:

    FROM my_docker_id/my_image_name:v1.0
    # your new thing here
    ADD another_new_change.py /root/
    # others
Answer: You can try to examine the history of the image, from there you can probably re-create the Dockerfile. Try using docker history --no-trunc image-name
See this answer for more details


Display first X elements obtained from a json if press a button

Question: I'm noob in Javascript and I want to make a button for load images, my idea is.. Get the Json data from an url and save it in a js array.. if the user press the button, show the ten first images, and if press again show the next ten images, this to the end..
$(document).ready(function(){
    var a = [""];

    $.each(tumblr_api_read.posts, function(i, item) {
        a[i] += '

';
    });

    $(".portfolio-margin").on("click", ".read-more", function(){
        var i, b = "";

        for (i = 1; i < 10; ++i) {
            b += a[i];
        }
        $(".grid").append(b);
    });
});

The code is not finished, but the problem.. I don't know how load the next images, and the var "b" returns "undefined" in the beginning of each li: undefined

undefined
..
Answer: The value of
a[i] +=

is considered as
a[i] = a[i] + new value
//      ^ undefined initially

Initially, a[i] will always be undefined. So you are getting undefined.
Change that line to as I dont' see any reason to concatenate(+=). Iterator i will always occur once.
a[i] = '

';
//   ^ Here

Comment: @ShaunakD, its always that little detail that some forget ;)
Comment: Previously I didn't used an array on the each and I forgotten :c @ShaunakD You really helped me, I'm so stupid.. *facepalm*
Comment: Happens. Everyone has been through it . :D


How to run php scripts from c++ via fastcgi

Question: I am writing a C++ webserver for a high(er) performance CMS. We first used PHP for everything but we noticed performance issues. However I can not ask the front-end developers to write the views / templates in C++ code. So I want to run a FastCGI server (I dont know the right name) which holds a PHP FastCGI app. So when the application needs to render a View, the views passes data to a PHP script via FastCGI, PHP renders the HTML (or something like that), sends it back to the View, via FastCGI, and the C++ application sends the HTML back to the client.
Does somebody knows a better solution or where i can find a good FastCGI server or keywords so i can find it my self (on Google).
Comment: Please don't write tags in question titles.
Comment: Sorry, i am used to it (on forums). Dont going to happen again.
Comment: Err isn't this what Apache does?
Comment: Yes, sort of. But write my own C++ server because i cant use the normal vhost system of apache etc. So i write the whole http server in C++ and have to include php in a way. (so sort of the other way around :P)
Comment: Cool at least you have a reason! Have a look at the ngnix source code. It should give you a few pointers on how to implement FastCgi.
Answer: Is this what you're looking for?
http://php-fpm.org/

PHP-FPM (FastCGI Process Manager) is
  an alternative PHP FastCGI
  implementation with some additional
  features useful for sites of any size,
  especially busier sites.


CircleCi 2.0 Workflow requires option is not working

Question: I ran into a problem where I wanted to have a sequential workflow in my CircleCi 2.0 config. I wanted to have build->test->deploy, and used the requires option, but it kept giving me a config error.
Here's an example script:
version: 2
jobs:
  build:
    ...
  test:
    ...
  deploy:
    ...

workflows:
  version: 2
  myapp_ci:
    jobs:
      - build
      - test:
        requires:
          - build
      - deploy:
          requires:
            - test
          filters:
            branches:
              only: master

Answer: The issue is actually indentation...even though I ran it through a yml parser, you need a second indentation for the requires tag.
So
workflows:
  version: 2
  myapp_ci:
    jobs:
      - build
      - test:
        requires:
          - build

Becomes
workflows:
  version: 2
  myapp_ci:
    jobs:
      - build
      - test:
          requires:
            - build

Hopefully this saves someone else some time!
Comment: Good catch. I would run it through CircleCI's own parser called the CircleCI Local CLI.
Comment: @FelicianoTech Good idea, but that didn't help either at the time. It actually sent me down the wrong path looking at where I had a syntax error. `Error: Error parsing config file: yaml: line 70: did not find expected '-' indicator`
Comment: it still does not work. something is wrong with circle ci. this is a super critical bug. version 1.0 was superior.


Is there a good resource for learning about the sum-of-digits functions?

Question: The digit sum with respect to a base $n$ of a natural number $r$ is defined as the sum of the digits when $r$ is written in base $n$. Lets write this $\sigma_n(r),$ which gives us a family of functions $\mathbb{N} \rightarrow \mathbb{N}$, one for each $n$. For instance, $\sigma_2(4) = 1$, because $4$ written in binary is $100$, so the sum of the digits is $1$. It seems to be hard to get information about these $\sigma_n$ functions.

Question. Is there a good resource for learning about the digit sum functions?
For instance, I'd like to know the following kinds of things:

What can we say about $\sigma_n(a+b)$ and $\sigma_n(ab)$?
If $p$ is prime, can we say anything about $\sigma_p$?
Are there interesting properties of numbers can be characterized in a natural way by the properties of $\sigma_n$?
etc.

I'm also interested in the generalization of these maps in which the digits are weighted, so that rather than just summing them up, we take some kind of a linear combination.
Comment: If you know German, there is
Jan-Christoph Puchta, Jürgen Spilker, Altes und Neues zur Quersumme,
http://www.math.uni-rostock.de/~schlage-puchta/papers/Quersumme.pdf
Answer: Only few facts seems to be known. You can have a look at:
A. Balog and C. Dartyge, On the sum of the digits of multiples, Moscow J. Comb. Number Th. 2 (2012), 3–15.
L. E. Bush, An asymptotic formula for the average sum of the digits of integers, Amer. Math. Monthly 47 (1940), 154–156
Or this curious reference where I found the two others: Journal of Integer Sequences, Vol 15, Article 12.8.1 by Carlo Sanna


Covariance of log-transformed variable

Question: Consider a model with parameters $a,b$. We know the priors for the parameters are $b\sim\mathcal{N}(\mu_b,\nu_b^2)$ and $g=log(a)\sim\mathcal{N}(\mu_g,\nu_g^2)$.
Using observed data we produce maximum-likelihood estimates $\hat{b}, \hat{a}$ and their estimated covariance matrix $\hat{\Sigma}=\begin{bmatrix} \hat{\sigma}_a^2 & \hat{\sigma}_{ab} \\ \hat{\sigma}_{ab} &  \hat{\sigma}_b^2\\ \end{bmatrix}$.
What would be the covariance matrix for $b$ and $g$? How can I express it using the abovementioned terms?
Answer: If $g$ and $b$ are jointly normal with means $\mu_g, \mu_b$ and covariance matrix
\begin{pmatrix}
q & r \\
r & s \\
\end{pmatrix}
then $a=\exp(g)$ and $b$ have covariance matrix
$$
\begin{pmatrix}
(e^{2q}-e^q)\exp(2\mu_g) & r \exp(\mu_g+\frac{q}{2}) \\
r \exp(\mu_g+\frac{q}{2}) & s \\
\end{pmatrix}
=
\begin{pmatrix}
\hat{\sigma}_a^2 & \hat{\sigma}_{ab} \\
\hat{\sigma}_{ab} & \hat{\sigma}_b^2 \\
\end{pmatrix}
$$
We can solve this and get
\begin{align}
q &= \log\left(\frac12+\sqrt{\frac14+\hat{\sigma}_a^2\exp(-2\mu_g)}\right)\\
r &= \hat{\sigma}_{ab}/\exp(\mu_g+\frac{q}{2})\\
s &= \hat{\sigma}_b^2\
\end{align}
Comment: You are correct; I fixed it.
Comment: Well, I've ran it in `SAGE` and got almost exactly the same, except for the variance of $a$. We agree on $exp(2\mu_g+2q)$ but the first moment squared should be $(exp(0.5q+\mu_g))^2=exp(q+2\mu_g)$ rather than $\mu_g^2$. Could you please check it again?
Comment: The correlation matrix comes from integrating expectations of $b, e^g, b^2, be^g, e^{2g}$ in Mathematica, and the only unusual one is the expectation for $be^g$.
Comment: Thanks a lot. Where did you take this formulae from?

Covariance of log-transformed variable


Swift Widget: getTimeline with completion handler

Question: I have a iOS Widget that I am trying to update every 5 or 15 minutes.
I am new to widgets and do not understand how to loop the timeline with an async call.
struct SimpleEntry: TimelineEntry {
    let date: Date
    let configuration: ConfigurationIntent
    let price: Double
}

func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {

        networkManager.fetchData { price in

            var entries: [SimpleEntry] = []
            let currentDate = Date()

            for hourOffset in 0 ..< 5 {

                let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
                let entry = SimpleEntry(date: entryDate, configuration: configuration, price: price)
                entries.append(entry)

            }

            let timeline = Timeline(entries: entries, policy: .atEnd)
            completion(timeline)
        }

    }

I have a completion handler that passes in the price from the async api call.
networkManager.fetchData { price in
}

Comment: Have you tried a timer?
Comment: "I have a iOS Widget that I am trying to update every 5 minutes." Umm... that's not how widgets work. You don't get to decide how often it updates, unless you "know the future". See [this](https://developer.apple.com/documentation/widgetkit/keeping-a-widget-up-to-date)
Comment: i want the api called frequently
Answer: It looks like your networkManager.fetchData is providing only one price value at a time.
In such cases, when only one entry is provided at a time then the following should be enough:
func getTimeline(for configuration: ConfigurationIntent,
                 in context: Context,
                 completion: @escaping (Timeline<Entry>) -> ()) {
  networkManager.fetchData { (price) in
    let currentDate = Date()

    //create the entry for the given price
    let entry = SimpleEntry(date: currentDate,
                            configuration: configuration,
                            price: price)

    /*
     If you can predict price values then you need the loop for multiple entries.
     However in your case, it seems this one entry is sufficient
     */
    let entries = [entry]

    //next reload date; 15mins in this case
    let reloadDate = Calendar.current.date(byAdding: .minute,
                                           value: 15,
                                           to: currentDate)!

    //your timeline with one entry that will refresh after given date
    let timeline = Timeline(entries: entries, policy: .after(reloadDate))
    completion(timeline)
  }
}

By specifying after(_ date:) as the TimelineReloadPolicy, iOS will refresh the widget after the given date.

The timeline's refresh policy specifies the earliest date for WidgetKit to request a new timeline from the provider. The default refresh policy, .atEnd, tells WidgetKit to request a new timeline after the last date in the array of timeline entries you provide. However, you can use .afterDate to indicate a different date either earlier or later than the default date. Specify an earlier date if you know there's a point in time before the end of your timeline entries that may alter the timeline.

Ref: Apple Documentation on Timeline

This solution was to address the core issue, so finally I would like to add a disclaimer that reloading every 15mins might be overkill. Hence tweak your logic to specify the TimelineReloadPolicy intelligently. If you can predict values & create a timeline of multiple entries with fewer network calls then great! If not then... well... best of luck :)

Important
Plan ahead if your widget makes requests to a server when it reloads, and uses afterDate() with a specific date in timeline entries. WidgetKit tries to respect the date you specify, which may cause a significant increase in server load when multiple devices reload your widget at around the same time.

Ref: Keeping a Widget Up To Date
More Read:

Apple Documentation on TimelineProvider


Problem 20 from Putnam and Beyond

Question: I encountered into problem from book "Putnam and Beyond" which seemed to me quite interesting. However, After a long meditation I can not solve it.
Let $x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$ be positive integers, $n,m>1$. Assume that $x_1+x_2+..+x_n=y_1+y_2+\dots+y_m<mn$. Prove that in the inequality $$x_1+x_2+..+x_n=y_1+y_2+\dots+y_m$$ one can suppress (but not all) terms in such a way that the equality is still satisfied.

I read the solution which is attached above. However, I have couple of questions.
1) WLOG they assume that $x_1\geqslant y_1$. However, I dont know how to work with the inverse inequality $x_1\leqslant y_1$. Can anyone explain how to work with it?
2) They state that $y_1$ should be moved back to the right-hand side? What if $x_1-y_1$ is already suppressed by induction hypothesis?
3) Why in the case $y_1<n$ this argument does not work? I can not even understand what namely does work.
The solution, in general, is written in unclear way.
Would be grateful for clear explaining.
Comment: 1) If you have the reverse case, change the name of all the $x_i$ to $y_i$ and all the $y_i$ to $x_i$. Now it is true that $x_1\geq y_1$. If you don't like to change the name of the variables, you can keep them as they are, and just change every single mention of $x$ in the proof text into a $y$, and every $y$ into an $x$.
Comment: For $1)$ you can just swap the $x$s and $y$s.
Answer: For $2)$ if that term is already suppressed you don't need to do any more - you have a sum of $x$s $=$ a sum of $y$s.
For $3)$ if $y_1\lt n$ the remaining sum might be too large to apply the inductive hypothesis.
Comment: @RFZ Well that exchanges $m$ and $n$ as well, but there is no assumption on these. So you have two sets of numbers whose sum is equal, and you choose the one with biggest number in it for the $x$ set (and if they have the same largest number, you are done anyway).
Comment: Hmm yes. And they estimate the remaining sum $y_2+\dots+y_m\leqslant (m-1)y_1<(m-1)n<mn$ and apply the induction hypothesis.
Comment: Am I right in the above comment?
Comment: @RFZ You just need $\lt (m-1)n$ because the induction hypothesis applies to the case of $m-1$
Comment: Relating question 1 is it correct to change variables, i.e. writing $x$ instead of $y$y and vice versa?
Comment: Maybe my words sound weird. We are going to understand the case $y_1\geqslant x_1$ but we are changing the variables and are working with above case. This transition seems quite unclear and difficult
Comment: @RFZ It is just renaming the two sets, which we are entitled to do before we've done anything with them.
Comment: I will rethink on the problem. Anyway thanks a lot for clear answers to unclear questions :)

Problem 20 from Putnam and Beyond


Visual Code não mostra fechamento de tags HTML

Question: Colegas.
Instalei recentemente o Visual Code. Estou gostando do programa, porém reparei que quando criamos arquivos em PHP, algumas funcionalidades parece não funcionar. Por ex.: No código HTML, quando seleciono  ele não mostra o fechamento dessa tag . Vejam:

Estranho, pois os fechamentos em PHP ele mostra ou quando a página é HTML ele também mostra. Teria alguma configuração específica?
Peço apenas para que me ajudem nesse programa, pois já usei o Netbeans, Eclipse, Atom e Brackets, e gostaria de dar uma chance para ele.
Answer: Basta baixar e instalar a extensão highlight-matching-tag.
Abra o painel de extensões do Visual Studio (Ctrl + Shift + X) e procure a extensão highlight-matching-tag na barra de busca e faça a instalação.
Comment: Legal o esforço, mas a resposta está muito vaga, coloque exemplos.. mostre como instalar.
Comment: Melhorei resposta ...
Comment: Desculpe a demora Bruno. Funcionou! Obrigado!


Is a stable Metzler matrix minus a Metzler matrix with zero along diagonal also stable?

Question: A Metzler matrix is a matrix $A$ such that $a_{ij} \geq 0$ for any indices $i \neq j$ (i.e. non-diagonal entries are non-negative). A stable Metzler matrix is a Metzler matrix that has eigenvalues with negative real part.
Let $A$ be a $n \times n$ stable Metzler matrix and let $B$ be a $n \times n$ Metzler matrix with $b_{ii}=0$. If $a_{ij}-b_{ij}>0$, is the matrix $A-B$ Metzler stable?
What if the eigenvalues of $A$ are real and negative, is $A-B$ Metzler stable?
I believe the answer should be yes. By Gershgorin Circle Theorem, the eigenvalues of $A$ lie within discs centered at the values of $a_{ii}$ with radius equal to to the sum of the non-diagonal entries of row $i$. The matrix $A-B$ will have the Gershgorin discs also centered at $a_{ii}$, but their radius will be smaller. In the limit as the radius goes to zero, the eigenvalues of $A-B$ will tend to be equal to $a_{ii}$, which are negative. However, part of the rightmost disc could lie in the positive half of the plane and I am not sure how to show that the largest eigenvalue of $A-B$ will be negative.
Answer: I figured out a way to prove this. There are a few properties of Metzler matrices that we can use to show that this is true:
1) A Metzler matrix $M$ has a real eigenvalue $\lambda_{max}(M)$ such that the real component of any other eigenvalue of $M$ is smaller or equal than $\lambda_{max}(M)$. This is a result of extending the Perron-Frobenius theorem to Metzler matrices.
2) If a Metzler matrix $M_1$ is entry-wise smaller or equal than a Metzler matrix $M_2$, (i.e. $M_1 \preceq M_2$), then $\lambda_{max}(M_1) \leq \lambda_{max}(M_2)$.
3) If $M$ is a stable Metzler matrix, then $DM$ is also a stable Metzler matrix if $D$ is a diagonal matrix with positive diagonal entries (D-Stability).
Now, to show $A-B$ with $a_{ij}-b_{ij}>0$ for all $i,j$ pairs is stable, define a diagonal matrix $D$ with positive entries $$d_{ii} = \max_{j} \frac{a_{ij}-b_{ij}}{a_{ij}}$$ for all $i$. Then,
$$A-B \preceq DA$$ and $$\lambda_{max}(A-B) \leq \lambda_{max}(DA) < 0$$.
Therefore, $A-B$ is a stable Metzler matrix.


How to test H0: "this sample is drawn from a gamma distribution" against HA: "this sample is drawn from two different gamma distributions"

Question: This is a targeted follow-up to " all of these data points come from the same distribution." How to test?
I have a sample of strictly positive data. I fit a gamma distribution to it and obtain sample estimates for the shape and rate.
How can I test the hypothesis that all of the data points are drawn from this gamma distribution, against the alternative that some of the data points are drawn from a gamma distribution with different parameters?
Comment: I think you can estimate a mixture model with two states each constituting two seperate gamma distributions.  Where $P$ is the probability of belonging to the first gamma distribution, you can  test the null that $P=1$ against the alternative that $P\neq 1$. The parameters of the first distriburion can be fixed inputs from a seperate model or estimated simultaniously in the mixture model.
Answer: We can phrase this problem as follows, following Zachary's suggestion:

We are given a set of sampled points $X = \{x_1, \dots, x_n\}$.
We assume that $X \sim p \Gamma(\alpha_1, \beta_1) + (1-p) \Gamma(\alpha_2, \beta_2)$, where $p \in (0, 1]$ is the mixture weight of the first component. Denote the parameters of the mixture by $\theta = (p, \alpha_1, \beta_1, \alpha_2, \beta_2)$, which is in the space of possible parameters $\Theta$.
Our null hypothesis is $H_0: \theta \in \Theta_0$, where $\Theta_0$ is the set of parameters with $p = 1$. The alternative is $H_1: \theta \not\in \Theta_0$.

This fits the setup for a composite-hypothesis likelihood ratio test. That is, we want to find the likelihood ratio
$$
\Lambda(X) = \frac{\sup_{\theta \in \Theta_0} L(\theta; X)}{\sup_{\theta \in \Theta} L(\theta; X)}
.$$
Let's call the numerator $\lambda_0$ and the denominator $\lambda$ for convenience.
Note that $\lambda \ge \lambda_0$: any value that $L(\theta; X)$ can take on with $\theta \in \Theta_0$ is also a valid result for $\theta \in \Theta$. So the mixture model will necessarily fit the data better; the question is, how much better?
Well, it turns out that as $n \to \infty$, $-2\log\Lambda$ becomes $\chi^2$-distributed under $H_0$, with degrees of freedom $\dim \Theta - \dim \Theta_0 = 5 - 2 = 3$.1  So we can compute $-2 \log \Lambda$, compare to the (say) 95th percentile of the $\chi^2(3)$ distribution (let's call that threshold $c$), and then reject if $-2 \log \Lambda > c$ (i.e. the mixture model is much more likely than the simple model).
Now, how to compute $\Lambda(X)$?
First, the numerator $\lambda_0$. $\theta \in \Theta_0$ corresponds to a single gamma distribution, so $\sup_{\theta \in \Theta_0} p(X; \theta)$ is the likelihood of the maximum likelihood estimator for the gamma distribution. This is easy enough to find numerically to arbitrary precision.
Next, the denominator $\lambda$. Same thing, but for mixtures of two gammas. This is a harder problem; you should be able to get pretty good results with say EM, or there's some variants specifically for mixtures of gammas2, but you can't be sure that you got the best one. Instead, you get some $\hat{\lambda} \le \lambda$, and who knows how big that gap is.
Luckily, though, we don't actually need to find the best $\theta \in \Theta$ to be confident we should reject $H_0$. If we have a $\hat\lambda$ such that $-2 \log \frac{\lambda_0}{\hat \lambda} > c$, then since $\hat\lambda \le \lambda$ we know that $-2 \log \frac{\lambda_0}{\lambda} > c$. Not finding the best mixture reduces the power of our test but doesn't increase the probability of a false rejection.

1. As I've written it, $\dim \Theta_0$ is actually 4, but clearly the model under $H_0$ should be two-dimensional. We could alternatively have defined $\Theta$ that if $p = 1$, necessarily $\alpha_2 = \beta_2 = 0$, or something along those lines.
2. Schwander and Nielsen. Fast learning of Gamma mixture models with k-MLE. SIMBAD 2013. (doi) (author's site)
Comment: I think this is a good answer. The one concern I would have is that because $p=1$ occurs on the boundry of the parameter space, the asymptotic chi - squared no longer holds.  I have seen this problem come up in econometrics literature.  Whether or not it is a big concern here, I do not know.
Comment: @ZacharyBlumenfeld I didn't realize that would be a concern for the LR test. A source to demonstrate the problem would be great, if you have one in mind
Comment: This is really helpful, but I'm switching to @ZacharyBlumenfeld's answer because of the points he linked to about the boundary issue in LR tests
Answer: Sorry it took me a while to post this answer.
To re-phrase the question again; we are given the sample $X_1,...,X_n$ where $X_i \sim p \Gamma(\alpha_1, \beta_1) + (1-p) \Gamma(\alpha_2, \beta_2)$. The hypothesis test of interest is
$$
H_0:\; p=1\;\;\;\;\;H_1:\; p \in (0,1)
$$
A possible issue with using a likelihood ratio test in this setting is that the null hypothesis, $p=1$, lies on the boundary of the parameter space $p \in (0,1]$*, causing the asymptotic Chi-squared distribution to no longer hold.  This is a well researched topic and there are many papers discussing this issue and proposing new, more robust, hypothesis tests.  See here, here,here, and here for a few examples (google "likelihood ratio test boundary of parameter space" and many more results will pop-up).  The literature on this topic is very abstruse, but it still may be worth your time if the problem is important to you.
*In fact, the hypotheses are technically not even nested since the true parameter space for a two state mixture model is $p \in (0,1)$ (if $p$ was allowed to be exactly 1 then $\alpha_2$ and $\beta_2$ could change value without effecting the likelihood causing an identification problem) .
The purpose of my answer is to propose 2 alternative testing techniques which, although maybe not exactly what you had in mind, are easier to understand and circumvent the boundary issue.
1. Bayesian Model Comparison
This is not hypothesis testing in the way most people think about it. However, it can be used to accomplish the same objectives and many practitioners actually prefer this technique over traditional hypothesis testing, especially for problems related to the one you're asking about.
Instead of obtaining a p-value which tells you the probability of obtaining data that is "as extreme or more extreme" then that observed conditional on the null hypothesis; Bayesian model comparison uses the posterior probability of the hypothesis/model, $P(H_i|X)$.
The nice thing about Bayesian model comparison is that $P(H_i|X)$ is much easier to interpret than a p-value, it is simply the probability that the hypothesis/model $H_i$ is true given the data.  The bad thing about this  approach is that estimating the exact value of $P(H_i|X)$ can be extremely computationally burdensome and in some cases virtually impossible.
Fortunately you can approximate $P(H_i|X)$ with the Bayesian Information Criterion (BIC).  In the case of just two models, $H_0$ and $H_1$, The posterior probabilities can be approximated as
$$
P(H_0|X) \approx \bigg[1+\exp\bigg(\frac{B_0 -B_1}{2}\bigg)\bigg]^{-1}\;\;\;\;\;P(H_1|X)=1-P(H_0|X)
$$
where $B_0$ is the BIC of the model estimated under $H_0$ (a single gamma) and $B_1$ is the BIC of the model estimated under $H_1$ (the 2 gamma mixture).
The BIC approximation is an asymptotic one meaning that it gets better as the amount of data increases and may be very unreliable when the number of observations is close to the number of parameters.  See This question and answer and the references cited therein for more information on this technique and it's assumptions.
2. Simulate The Null Distribution
Where $\Theta$ is the parameter space, $\Theta_0 \subset \Theta$ is the parameter space under the null hypothesis, and $\hat \theta$ are the parameter estimates; the distribution under the null hypothesis is $f(\hat \theta | \theta \in \Theta_0)$.
The basic idea here is that if we can simulate draws from $f(\hat \theta | \theta \in \Theta_0)$ we can empirically estimate a p-value.
For this to work here, you have to make a more restrictive null hypothesis then the one given above, specifically
$$
H_0:\; p=1,\;\; \alpha_1=\alpha_0,\;\; \beta_1=\beta_0
$$
You would proceed with the simulation as follows

draw a sample of size $n$ from $\Gamma(\alpha_0,\beta_0)$
fit the sample with the mixture model $p \Gamma(\alpha_1, \beta_1) + (1-p) \Gamma(\alpha_2, \beta_2)$ and collect the point estimate $\hat p$
Repeat the above 2 steps until you have collected a large sample of estimates $\hat p_1,...,\hat p_G$

Once you fit the mixture model to your original data $X_1,..,X_n$ and collect the resulting point estimate $\hat p_{*}$, the p-value can be approximated as;
$$
Pr(\hat p_{*}|p=1)=\int_0^{\hat p_{*}} f(t|p=1)dt \approx \frac{1}{G}\sum_{g=1}^G I(\hat p_{*}>\hat p_g)
$$
The term on the right most side is called the Empirical Distribution Function. $I()$ is an indicator function that is equal to 1 when the statment inside it is true and zero otherwise.
Notice that if you were to replace $\hat p_{*}$ with $\hat p_{g}$ there is a $(1-\alpha)$% chance of falsely rejecting the null hypothesis for $\hat p_{g}$, reflecting a proper type one error rate.
The obvious downsides of this technique are it's computational burden and restriction of the null hypothesis.  This method is crude when compared to the techniques proposed in the references above.
Comment: (+1) Note that BIC has many alternatives which sometimes have better properties or seem to perform better, including its predecessor AIC or newer ones like WAIC. [Here](http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf) is a good, though lengthy, overview of some alternatives.
Comment: @Dougal Choice of information criteria for model selection can go either way. I chose BIC here because of its relationship to the marginal likelihood which allows you to compute a posterior probability. This cannot be done with AIC and it's variants.  Andrew Gelman (one of the authors in the paper you reference) argues against the use of posterior probabilities (and BIC) and has written multiple papers on the issue.  However, many other statisticians encourage it's use including Raftery, Hoeting, West, and others.  (Similar debate exists on the validity of all frequentist hypothesis testing)


Is the volta ONLY used to mark unique end of a section or can it mark unique verse content within a section?

Question: I have a three verse, two chord song:
Verses 1 and 2 are

a b c
a b c
d d e

Verse three is

a b c
a b c
a f g
d d e

Without writing everything serially, within a repeated section with lyrics listed as:

verse 1.  Initial blah, blah blah tah dah
verse 2.  Similar blah blah blah, tah dah (that follows melody)
verse 3.  More of blah blah and inserted deed dee dee, then tah dah

What marks do I use to show the unique structure of V1 and V2, vs V3?
Do I use volta 1 2, volta 3, within the section?
Answer: Most standard approach
The most straightforward thing to do is to use one volta for the "normal" verse, and one volta for the "extended" verse.

|: a b c a b c || Volta 1 & 2 = d d e :|| Volta 3 = a f g d d e ||
Verse 1 lyrics    V1 lyrics cont.
Verse 2 lyrics    V2 lyrics cont.
Verse 3 lyrics                            V3 lyrics cont.

Less standard approach
Another option if the "inserted" section is short would be

Play 3x
|: a b c a b c [3rd x only: a f g] d d e :|

In the score, it would look something like this:

This is risky, however, as it's prone to confusion or mis-reading. It could be combined with a "to 'location'" mark to help clarify. This is loosely what pit musicians do, for example, when marking cuts in their scores. The cleanest options would be "to 'rehearsal letter'" (as below) or "to 'measure number'".

Special case
When only a small number of measures is involved, an ossia could be used.
Comment: Your first solution is good. The "3rd x only" option is just asking for trouble.
Comment: I've seen manuscript dance band arrangements with mixed forward and backwards DS and DSS markings. They were horrible! It would make more sense to use a coda symbol for a forward DS, even if it is not a real coda. Coda and double coda signs can be nasty too, but at least you have an idea which way to look.
Comment: I was hoping that there was some mark, similar to volta, that says, play this, the 1st and 2nd verse, but insert this for verse three.  But for the 4 extra bars, it is straight forward.  But to have no special marks, it goes out to seven or eight pages. Not a problem in the ether, but harder to publish.  Thank you.
Comment: @RobertLang Understanding this context changes my answer. I'll update in a couple of hours.
Comment: Aaron.  That may work.  It looks like you used a closed volta bar and text as instruction to the player.  I am a novice so ask, is that correct?  Permitted?  No one will seek me out to beat silly for doing that?  If so, we are good.  Let me rewrite my work.  Is there a way to post it for review?  Thank you (unless that is not permitted by the rules).
Comment: @RobertLang There's not really a standard way to do what you're looking to do, but this bracketed approach is common enough. Yes, it's a closed volta plus text. No one will beat you silly, but you might get questions from anyone who hasn't encountered something like it before. If you'd like your work reviewed, post it in [The Auditorium](https://chat.stackexchange.com/rooms/126233/the-auditorium), which a chat room devoted to that purpose.
Comment: The bracket in the second option should be open on the right side
Comment: @ElementsinSpace Wouldn't that imply that everything after the bracket would be third time only?
Comment: @Aaron
- Hmm, maybe. But a closed bracket usually implies an end of some sort, that is if you follow the logic expressed in this post: [When should the last ending bracket(volta) be closed and when should it be open?](https://music.stackexchange.com/questions/113831/when-should-the-last-ending-bracketvolta-be-closed-and-when-should-it-be-open)
Comment: @JohnBelzaguy I'd be happy for your opinion on the "3rd x only" bracket option as well as the third "ossia" option I've added.
Comment: @Aaron Thanks for asking, I find the 3rd x only bracket and forward DS to be irregular and prone to confusion and misinterpretation. I don't believe I've seen a forward DS in the past. Regarding pit musicians, yes they make cuts when necessary but it is very rare to have a show book with road maps so cuts in that genre are straightforward. Your final solution is actually not bad. I wouldn't want to encounter it sight reading but it's the clearest solution short of just writing out the section entirely.
Comment: @Peter I've updated with what I think is a better solution, using a rehearsal letter or measure number.
Comment: @Aaron,  I agree this is probably the cleanest way to do it. If bar numbers are used it would be helpful to ensure the number is actually printed, not like bar 77 when only 75 and 80 have printed numbers.


Complex Analysis Integration & Branch Cuts

Question: Suppose that the curve $C$ is any path between $z=0$ and $z=1$ which does not go through any singularities of the function below.  I'm trying to show the following:
$$\int_{C} \frac{1}{1+z^{2}}\,dz = \frac{\pi}{4} + k\pi\,\,\mathrm{for}\,\,k = 0,1,2,\ldots$$
Unfortunately, I can only find the $\pi/4$ portion via direct integration.  Where exactly is this $k\pi$ term coming from?  Since its an integer, I'm guessing that it's some kind of branch cut, but isn't this function single-valued?  Any insight would be appreciated.
Answer: The function $\frac{1}{1 +z^2}$ is certainly single-valued, but it does not have a single-valued anti-derivative, because of the presence of poles. The situation is analogous to the function $1/z$, which is single valued on $\mathbb{C}\smallsetminus\{0\}$, but whose anti-derivative (the logarithm) is multiple-valued on $\mathbb{C}\smallsetminus\{0\}$. In fact, we can consider a similar question for the function $1/z$:

Analogous question: Suppose that $C$ is a loop in $\mathbb{C}\smallsetminus\{0\}$ that begins and ends at the point $1$. What are the possible values of $\int_C \frac{dz}{z}$?

The answer to this question is given by the residue theorem, which says that $$\int_C \frac{dz}{z} = 2\pi i\,\mathrm{Res}_0(1/z)W_0(C),$$ where $W_0(C)$ denotes the winding number of $C$ around $0$. The number $W_0(C)$ can be any integer. On the other hand, $\mathrm{Res}_0(1/z) = 1$. Thus we can conclude $$\int_C \frac{dz}{z} = 2\pi ik\,\,\,\,\,\,\mathrm{for}\,\,\mathrm{ some}\,\,k\in \mathbb{Z}.$$
Now perhaps you can apply a similar argument to your problem?
Comment: Alright, I see that, if I wrap around one of the poles, then I get an added pi term (used partial fraction decomposition and integrated).  That makes sense, but my curve is from 0 to 1, and I need not wrap around a pole.  Why would I even include it?...
Comment: @user108149: I agree, the direct path from $0$ to $1$ makes the most sense. Why would you take another weird path? I don't know, perhaps because it makes a good homework exercise :-)
Comment: I suppose haha, but should I have to worry about adding these k*$\pi$ terms (not the exact term...but terms using teh same idea) for other line integrals with this possibility?
Comment: @user108149: I think the important thing to remember is that the value of the integral *can* depend on the path you are integrating over if the integrand has poles. Thus when integrating such a function, you always have to take into consideration what the path is doing. For simple paths, probably you won't have to worry about these extra terms so much, but you should always check to be sure....


Echo A Link, Get A Trailing Slash?

Question: I've discovered that any time I do the following:
echo 'huzzah';

I end up with the following being rendered to the browser:
huzzah

This is particularly annoying when I link to a file with an extension, as it breaks the link.
Any ideas why this is happening and how I can fix it?
Update:
For those asking about my exact implementation, here it is. In my troubleshooting I've dumbed it down as much as I could, so please don't mind where I concat plain text to plaintext...
function print_it($item) {
    echo '
';
    echo '
';
    echo '';
    if(isset($item[6])) {
        echo '' . 'me' . '';
    }
    echo '';
echo '

';
}

Update:
In response to Matt Long, I pasted in your line and it rendered the same.
Update:
In response to Fire Lancer, I've put back in my original attempt, and will show you both below.
echo substr($item[6],13) . '
';
echo '' . $item[0] . '';

www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html

Employment Ontario

The reason for the substr'ing is due to the URL being run through rawurlencode() elsewhere, and linking to http%3A%2F%2F makes the page think it is a local/relative link.
Update:
I pasted the above response without really looking at it. So the HTML is correct when viewing source, but the actual page interprets it with another trailing slash after it.
Solution:
This was all a result of rawlurlencode(). If I decoded, or skipped the encoding all together, everything worked perfectly. Something about rawurlencode() makes the browser want to stick a trailing slash in there.
Comment: why does it matter? http:// is an invalid link anyway. put in a real link and forget about it.
Comment: there's 10 rep, have fun upvoting =)
Answer: Ive never had that, how ecactly are you echoing the link? All the following should work.
echo 'Link';
echo 'Some page';
echo 'Another page';
etc

edit, since you added the info.
You can't just have http:// as href, even entering that link directly into a html page has that effect.
eg:
html:
 huzzah

link (in FF3):
http:///

Answer: Firefox, especially, shows you the html source the way it's seeing it which is rarely the way you've sent it.  Clearly something about your link or it's context is making the browser interpret a trailing slash.
I wonder if it's a side effect of the url encoding.  If you rawurldecode it will that help.  If there are parts of the url that need to stay encoded you could search for the slashes and just put those back.
Answer: The error must be elsewhere. echo writes the string, verbatim. No post-processing is done on any part. The additional slash is therefore added elsewhere in your code (prior to passing the string to echo).
Answer: Do you get the same result if you use double quotes and escape internal double quotes like this?
echo "huzzah";

Answer: If I put that echo command in my PHP code, it outputs "http://" as expected (you can see that in the source of the generated output), but when I then mouse over the link in the resulting page (with IE7), it shows http:///.
My guess is, that that's browser behaviour, because there can't be a http:// link without a host name or IP address (you can't just access the protocol).
Answer: As some guys pointed out, 'http://' is not a valid link, so your browser adds the extra slash at the end. To view out it, try a lynx -dump http://yourdomain/yourfile.php (if you are fortunate enough to have a linux) or telnet from your box to your server in port 80, and typing this:
GET /path/file.php HTTP/1.0

and look at the result.
Answer: Have you looked into your PHP config settings?  It might be magic_quotes_gpc deciding to escape things for you (I've been bitten several times by that setting, especially when working with AJAX/JSON traffic).  Try making sure it is off and echoing again (you might need to edit your php.ini file, or add php_flag magic_quotes_gpc off to an .htaccess file in the directory you are working in, depending on your environment).

Echo A Link, Get A Trailing Slash?


What are all the hardwares/sensors can be accessed through React-Native without Third-Party libraries?

Question: At least on Android, Can I access Camera, Mic, Fingerprint sensor without any third party libraries help? How other Major Brands are doing it?
Answer: You can use the GPS location using navigator object.