Allocating space for type within a function with malloc

Question: I wrote a type
typedef
  struct matrix_s {
    int size;
    float *values;
  } matrix_t;

which I allocate in a function like this :
matrix_t *matrix;
genmat(mat, afloatarray, thesize);

//Function
void genmat(matrix_t *mat, float *_values, int _size) {
  mat = (matrix_t*) malloc(sizeof(matrix_t));
  mat->values = _values;
  mat->size = _size;
}

Shouldn't matrix and mat have the same pointer, because I pass a pointer and work with a pointer.
Comment: You shouldn't use identifiers beginning with an underscore; they're reserved in many contexts. You also should **not** cast the malloc return in C. You also should refer to the pointer to be allocated in the sizeof, as in `mat = malloc(sizeof (*mat))` as this *always* gets the type right. Last, but most important, you should read and understand the answers below :-)
Comment: Do not cast the result of `malloc` & friends in C.
Comment: Should `genmat()` make a copy of the array pointed to by `_values`?
Answer: You need to pass the address of the pointer or return the newly allocated one.
matrix_t *genmat(float *_values, int _size)
{
    mat = malloc(sizeof(*mat));
    if (mat == NULL)
        return NULL;
    mat->values = _values;
    mat->size = _size;

    return mat;
}

And then
matrix_t *matrix;
matrix = genmat(afloatarray, thesize);

Or
void genmat(matrix_t **out, float *_values, int _size)
{
    *out = malloc(sizeof(**out));
    if (*out == NULL)
        return;
    (*out)->values = _values;
    (*out)->size = _size;
}

And then
matrix_t *matrix;
genmat(&matrix, afloatarray, thesize);

The reason for this is that in c parameters are always passed by value, and while you can modify the data the pointer points to, you cannot reassign the pointer inside the function because it will not affect the pointer of the caller function, since the parameter pointer and the pointer in the caller function have different addresses, although they both store the same address.
In the second of my sample solutions, the function takes the address of the pointer, and it can then modify the pointer from main() by dereferencing the double pointer.
Comment: That has done it, thanks. But why does matrix not hold the adress to the type?
Comment: @risingprogrammer I don't understand. Does my explanation at the end of the answer explain that?
Comment: I asked the question before you edited your answer. My bad
Comment: @risingprogrammer Also, I intentionally removed the `(matrix_t *)` cast since it's not needed and it just makes the code harder to read. And used the `sizeof` operator in a way that is more maintanable, since if you change the type of the `mat` parameter/variable you don't need to fix the `malloc()`, another thing that would make you need to fix the `malloc()` is the cast of course.
Answer: You need to pass a pointer the pointer for matrix to genmat().
This would look like:
matrix_t *matrix;
genmat(&mat, afloatarray, thesize);

//Function
void genmat(matrix_t **mat, float *_values, int _size) {
  *mat = malloc(sizeof(matrix_t));
  if (*mat == NULL) // Do not dereference a NULL poitner
      return;
  (*mat)->values = _values;
  (*mat)->size = _size;
}


Como uso um Remote Event para duas coisas?

Question: Eu estou tentando refazer um jogo de poderes no Roblox, estou usando uma place antiga Uncopylocked como base, e tudo lá é non-fe.
Eu queria usar só um evento remoto para vários códigos (já que todos são bem parecidos), mas não faço ideia de como fazer isso.
Esse é um script de exemplo, ele esta dentro de um botão.
    local player = game.Players.LocalPlayer
    local Open = false
    function MouseClick()
        if Open == false then
            Open = true
            script.Parent.Text = "Learned"
            script.Parent:FindFirstChild("Flame Armor"):clone().Parent = player.Backpack -- Essa é a parte que eu usaria o remote
        end

    end
    script.Parent.MouseButton1Down:connect(MouseClick)

Alguém poderia me dizer o que mandar no remote e o que colocar no script server-side?
Answer: Bem... Voltei!
Ontem eu estava conversando com meu amigo sobre, até que chegamos em uma conclusão.
Primeiro nós criamos um evento no ReplicatedStorage chamado "Dar o bagulho" (Ele estava dentro de uma pasta)
Depois criamos uma pasta no ReplicatedStorage chamada Poderes
Aí colocamos o evento no LocalScript e mandamos ele enviar o caminho do Poder para o servidor
evento = game.ReplicatedStorage.Events["Dar o bagulho"] -- O evento
player = game.Players.LocalPlayer
Open = false
function MouseClick()
    if Open == false then
        Open = true
        script.Parent.Text = "Learned"
        evento:FireServer(game.ReplicatedStorage:WaitForChild("Poderes").Phoenix) -- Envia o nome da pasta do poder para o servidor, nesse caso estamos fazendo com o Phoenix
    end

end
script.Parent.MouseButton1Down:connect(MouseClick)

Depois no script do servidor nós colocamos isso
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local itens = ReplicatedStorage.Poderes
local dador = game:GetService("ReplicatedStorage").Events["Dar o bagulho"]

local function poder(client, nome) -- Client é o LocalPlayer, nome é o caminho que passamos pra ele
    local tool = itens:FindFirstChild(tostring(nome)) -- Da o find first child no nome da pasta do poder

     if tool then -- Se tudo der certo/Se ele achar
        tool:FindFirstChild("Flame Armor"):Clone().Parent = client.Backpack -- Ele procura a skill dentro da pasta e te da
    end
end

dador.OnServerEvent:Connect(poder)

Espero ter ajudado você, caso tinha a mesma dúvida que eu :)


Multidimensional distributions and rectangles

Question: Let $\mathbf{X}$ be a random vector whose distribution function is $F$.

Is there a simple way to prove that, if $A:=\prod_{i=1}^n(a_i,b_i]$, and $V=\prod_{i=1}^n\{a_i,b_i\}$ then
  \begin{equation}
P(A):=\sum_{\mathbf{v}\in V}\sigma(\mathbf{v})F(\mathbf{v})
\end{equation}
  being $\sigma(\mathbf{v})=(-1)^{\#a_i\in\mathbf{v}}$?

My idea approach is really messy, dividing the rectangle $\prod_{i=1}^n(-\infty,b_i]$ in $2^n$ disjoint rectangles, being $A$ one of them and then trying to prove that $F(\mathbf{b})-\sum_{\Gamma_1}\cdots\sum_{\Gamma_n}P(\mathbf{X}^{-1}(\prod_{i=1}^n\Gamma_i))=2P(A)$, and I'm having a really hard time trying to make it work. Any ideas?
Answer: If you start by thinking about it in two dimensions, what you want to show is that $P(A) = F(b_1,b_2)-(F(a_1,b_2)+F(b_1,a_2))+F(a_1,a_2)$.
You can think of this as follows: Let $B$ be $(-\infty,b_1] \times (-\infty,b_2]$, $A_1$ be $(-\infty,b_1] \times (-\infty,a_2]$ and $A_2$ be $(-\infty,a_1] \times (-\infty,b_2]$. Then $P(A) = P(B) - P(A_1 \cup A_2)$, which is easy to see by drawing a picture.
You can then compute $P(A_1 \cup A_2)$ by using the inclusion-exclusion principle as follows: $P(A_1 \cup A_2) = P(A_1) + P(A_2) - P(A_1 \cap A_2)$. Since $A_1 \cap A_2 = (-\infty,a_1] \times (-\infty,a_2]$, you see that $P(B) = F(b_1,b_2)$, $P(A_1) = F(b_1,a_2)$, $P(A_2) = F(a_1,b_2)$ and $P(A_1 \cap A_2) = F(a_1,a_2)$, so $P(A) = P(B) - P(A_1 \cup A_2)$ will give you what you want.
I think you can extend this argument to higher dimensions by using the general version of the inclusion-exclusion principle. The idea is to start with $P(b_1,b_2,\ldots,b_n)$ and then use inclusion-exclusion to sequentially subtract-and-correct.


Can QTP select object by ANY property?

Question: I would like to know whether the QTP is able to select object of given type by any propety that it can see (when using the ObjectSpy). I assume it cannot, but needs to make sure.
Thanks
Answer: You assume incorrectly, any property that shows up in the spy can be used for object identification.
It may not be a good idea to use some of the properties (abs_x springs to mind) but all should work (AFAIK).

Can QTP select object by ANY property?


IE issues with Drop Down menus

Question: I have coded that template to be installed in some sort of CMS. Here is the link http://amtcdiecasting.com/demo/cobb-county/.
It's menus and sub-menus are not working in IE and on the other side they are perfect in all other browsers.
I have also deleted the sub menus but it still don't works as it is in Chrome and FF.
Design after deleting sub menus :
http://amtcdiecasting.com/demo/cobb-county-new/
Comment: Working fine for me, IE9, 10 and 11.
Comment: @Niet: Sir the problem is with IE8
Answer: You used HTML5 tags for menu(nav). that will no support below IE8 version.
Use normal HTML tags (link div ,span , p, ul , li) to make menu instead of HTML5 tags. It will support in IE 7, 8 also.
Comment: Its not working. I am using IE 8 it hides all the elements on that page except the background of the main wrapper.
Please have a look:
http://amtcdiecasting.com/demo/cobb-county-new/
Comment: yeah its done. Thankyou.
Another Question: Why clients insist to use IE when on the other side the whole world is using chrome and FF. lol..:)
Comment: Because IE is the default browser for Windows and some people don't care to change it.

IE issues with Drop Down menus


Change the name of a tab

Question: I have a group made from Organic groups, and it has these two tabs.

I want to change the name of "View", but can't figure out where to do that.
Even better would be if I could delete that little menu. Ideas?
Answer: The Tab Tamer module should do everything you need.

Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.
Comment: What if i need to change the title for a particular content type and not everything on the site ?
Comment: @Jayaram It'd be better if you opened a new question with your use case.  That way other people could benefit :)

Change the name of a tab


Assessing Logistic Regression and Determining if Splines Are Appropriate

Question: I'm working on building a logistic model which will be used to estimate the probability that an account will skip on their monthly payment. My dataset roughly includes 50,000 observations with 15% of the observations skipping their regularly scheduled payment. My explanatory variables include the age of the account,  Incentive (which is described as the account's interest rate minus the market rate) and finally their original balance amount.
My first attempt: My logit model results below
Call:
glm(formula = Level ~ Age + Incentive + log(OriginalBalance),
    family = binomial(link = "logit"), data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.7633  -0.5788  -0.5335  -0.4777   2.3131

Coefficients:
                      Estimate Std. Error z value Pr(>|z|)
(Intercept)          -0.226113   0.138865  -1.628    0.103
Age                  -0.009313   0.001007  -9.245  < 2e-16 ***
Incentive             0.043627   0.009537   4.574 4.78e-06 ***
log(OriginalBalance) -0.124829   0.012034 -10.373  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 36449  on 44945  degrees of freedom
Residual deviance: 36168  on 44942  degrees of freedom
AIC: 36176

Number of Fisher Scoring iterations: 4

I then proceeded to plot the individual explanatory variables against the dependent variable using a gam smoothing function within R's ggplot2 package. See plot 1. Looking at this plot suggest nonlinearity and thus the need for transformations or to use splines. My question is whether these plots are evidence enough for needing to transform/include splines? Are there any statistical tests that I may find useful?
Additionally I ran an HL test and the results indicate that my current model fits poorly or my model is not well specified. This further leads me to believe that I need to transform/include splines or that I may potentially need to use interaction variables.
 hl <- ResourceSelection::hoslem.test(q6$Level, fitted(m))
> hl

    Hosmer and Lemeshow goodness of fit (GOF) test

data:  q6$Level, fitted(m)
X-squared = 31.238, df = 8, p-value = 0.0001274

Answer: First, the Hosmer-Lemeshow test is considered obsolete.  With 50000 observations and only a few predictors you could use cross-validation to evaluate and compare models. And, yes, your plots indicate that using splines could be a good idea.
There are many posts discussing cross-validation for logistic regression models, see for instance How should two cross-validated logistic regression models be compared?,  How to include an interaction term in GAM?,   Cross-Validation in plain english?,   How to reduce predictors the right way for a logistic regression model   and search this site.


Can't Change Select Item in Table with Selenium Python

Question: I'm working with a really outdated site that's giving me issues. What I'm trying to do is select the "Judgement/Lien Search" tab as seen on: page
The issue is that there are no identifiers. No name, ID, etc.

        Case Search
        Judgment/Lien Search
        Property/Lis Pendens Search

I've tried using xpath, css selector, and even just executing the script. I've been using ChroPath to get the correct info. When Judgment/Lien Search is selected ChroPath gives me these options:
Rel XPath: //td[2]//a[1]
Abs Xpath: /html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[2]/a[1]
CSS Selector: table:nth-child(5) tbody:nth-child(1) tr:nth-child(1) td:nth-child(2) > a:nth-child(1)
None of which have actually worked when using driver.find options
When I try to just execute the javascript driver.execute_script("javascript:submitJudgementSearch();") I get error: "selenium.common.exceptions.JavascriptException: Message: javascript error: submitJudgementSearch is not defined".
Any ideas on other ways to select it? Or am I looking at something wrong? This bump in the road really has me stumped. Thanks!
Answer: What about using Attribute Starts With Selector ?
Since your anchors seems to have unique href values this could work as a selector for the anchor itself. From there you could move up the dom to the parent if the  is indeed what you need.
$('a[href^="http://example.com/external/link"]').click(function() {});

Comment: I'm not quite sure where to start with this one.I played around with the code a bit and the one that gave me the least errors was: `driver.execute_script("$('a[href^=\"javascript:submitJudgementSearch();\"]');")`

Error: `selenium.common.exceptions.JavascriptException: Message: javascript error: $ is not defined`
Answer: You could use document.querySelector to get the job done potentially, refer to the snippet below. I was able to select that element using document.querySelector

document.querySelector('td a b').style.color = "red";

      Case Search
      Judgment/Lien Search

          Property/Lis Pendens Search

Theres another example here
And the Mozilla docs
Comment: What should document be set as? With that I think I'd get an error because 'document' hasn't been defined.
Comment: With javascript document is a default identifier for the page itsself, i don't have too too much experience with Selenium but judging off of this [webpage](https://dzone.com/articles/perform-actions-using-javascript-in-python-seleniu) you should be able to use the `document.querySelector` as one of the examples provided on that pages does just that. Sorry if this doesn't work though, most of my experience is with javascript, but based on my research on this problem this solution should work. [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document) on `document`
Comment: Okay, that makes more sense. I tried `driver.execute_script("document.querySelector('td a b').style.color = \"red\";")` which resulted in error `selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'style' of null`

I added in the \'s because of having quotes inside of quotes.
Comment: Really? Huh, Based on my code pen and the html you provided that should have worked in this specific situation because the element conveniently has a `` element after the `` and nothing else in the html you provided has elements nested similar to that and from there you could have selected the [parent elements](https://www.w3schools.com/jsref/prop_node_parentelement.asp) but if that is coming up as `null` then I cant currently think of a better solution than what i provided to select that specific element, unless I'm overthinking the problem.
Comment: I know what the real problem is. Everything is inside of a frame and I'm not sure how that changes things. I've never dealt with frames before. So I assume I have to get into the frame first before I can run any code.


Cox regression with two-way interaction and interaction p value

Question: Hi I am using Cox regression to do some survival analysis.
I have one continous predictor variable called "biomarker" and two binary categorical variables sex and diabetes.
I want to get the interaction p-values between sex and "biomarker", in both non-diabetics and diabetic patients.
I am currently using the following code:
<code>coxph(
  Surv(days2death, death) ~
  factor(diabetes) :
    (factor(male)  * biomarker) +
    factor(diabetes), data = df.cox.testing).
</code>
Am I correct in thinking that the last two rows correspond to interaction p-values between biomarker and sex at different levels of diabetes?
<code>                                                 coef exp(coef)  se(coef)      z Pr(>|z|)
factor(diabetes)1                         -1.682469  0.185914  1.116110 -1.507    0.132
factor(diabetes)0:factor(male)1           -0.168605  0.844842  0.879000 -0.192    0.848
factor(diabetes)1:factor(male)1           -0.271691  0.762089  1.013834 -0.268    0.789
factor(diabetes)0:biomarker                0.108440  1.114538  0.130682  0.830    0.407
factor(diabetes)1:biomarker                0.224785  1.252054  0.145329  1.547    0.122
factor(diabetes)0:factor(male)1:biomarker -0.045544  0.955477  0.168073 -0.271    0.786
factor(diabetes)1:factor(male)1:biomarker -0.008174  0.991859  0.166480 -0.049    0.961
</code>
I created a forest plot with the results. However the overlap of the confidence intervals doesnt seem to fit visually with the extracted p-values. (Blue is female, red is male)
Comment: Is there some reason why you omitted `male` as a predictor in its own right, outside of the interaction? It can be confusing to interpret interactions when one of the included predictors doesn't have its own term in the model.
Comment: No I just prefer the output more, when including only the variable that I want to stratify for (here diabetes) as a predictor. When I do the same for ```male``` it does not change anything about the model/output/p-values. But I can see how that can be confusing.
Comment: Please look at [this page](https://stats.stackexchange.com/q/11009/28500). You shouldn't choose a model based on how its initial summary report of coefficient values looks. You can always use post-modeling tools (e.g, those in the [`emmeans` package](https://cran.r-project.org/package=emmeans), or those built in to the [`rms` package](https://cran.r-project.org/package=rms) for its own functions, to make any comparisons or display that you want from the correct model.
Answer: Short answer: Yes.
Longer answer: First, R in general puts interactions on the bottom of these tables (and higher order actions below lower order, if you have them) and second, the fact that two variables are listed on those lines (along with the value of the categorical variable) should tell you that.
Comment: I did not want to open a seperate thread but I have edited my post.


Reserva temporária

Question: estou com o seguinte problema:
Estou criando uma aplicação de reservas e assim que um usuário clicar num produto para reservar, esse produto deve ser retirado da lista dos disponíveis temporariamente para que ele finalize a reserva. Se ele não finalizar em 5 minutos, esse produto volta a ficar disponível.
Consegui realizar essa reserva prévia fazendo um update na coluna 'status' do produto, mas não tenho ideia de como fazer ele voltar a disponibilidade após 5 minutos.
Alguém pode me ajudar?
Comment: Eu utilizaria um evento agendado no mysql que rodasse a cada 5 minutos e faria uma validação de acordo com a hora de agendamento e a hora atual.
Comment: Você pode utilizar um Cron para atualizar novamente todos os itens que tiveram seu status marcados para reserva e não foram confirmados nos últimos 5 minutos e voltar eles para o status de disponível. Inclua o seu código à pergunta.
Answer: Você pode usar o EVENT do MySQL, para isso primeiramente precisa ativar o recurso no seu banco de dados:
SET GLOBAL event_scheduler = ON;

Criar o evento:
CREATE EVENT mudar_status
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 MINUTE
DO
UPDATE tabela_status
SET status = 1
WHERE status = 0

Comment: E se a compra for realizada, como cancela o evento?
Comment: Isso vc determina no WHERE, quando for feita a reserva, por exemplo, vc coloca um status = 2, e quando confirmada status = 0, entende? Mas ai vc altera ali, antes de criar o evento, qual status é o da reserva

Reserva temporária


Find the values of $k$ so that the matrix is not invertible

Question: So, the question is indeed asking for what you just read. I have the following matrix for which  I have to find the values of $k$ in order to make it not invertible. I have understood that the inverse of a matrix is the result of $[A | I]$, so since I have to solve in row echelon form in order to find its inverse, I got stuck when the time came to put it from row echelon to reduced row echelon form because I have $k$ in the lowest right-hand corner.
$$A=\begin{bmatrix}1&2&-1\\2&0&2\\-1&2&k\end{bmatrix}$$
This is how the matrix looks like in row echelon form. The problem is that I don't know how to continue, even if I was to know how to get into reduced row echelon form, I wouldn't know how to find a number that would make the matrix not invertible. Am I supposed to give the value of k that would be anything but one? (because the matrix in the end has to be equal to the identity right?)
Please, I would greatly appreciate your help.
Comment: When you reduce, matrix is not invertible if we get a row of all zeros.
Comment: I actually don't know how to get the determinant for a 3x3 matrix, and so if I get for example k-1 and have to add another number, the one that changes is only the number 1? Thank you for your prompt replies!
Answer: The determinant is given by
$$\det A =
\begin{vmatrix}
1 & 2 & -1 \\
\color{red}2 & \color{red}0 & \color{red}2\\
-1 & 2 & k
\end {vmatrix} =
-\color{red} 2\begin{vmatrix}2 & -1  \\ 2 & k \end {vmatrix}
+\color{red} 0\begin{vmatrix}1 & -1  \\ -1 & k \end {vmatrix}
-\color{red} 2\begin{vmatrix}1 & 2  \\ -1 & 2 \end {vmatrix}
\\= -2(2k+2) - 2(2 + 2) = -4k - 12$$
Now $A$ is not invertible $\Leftrightarrow \det A = 0$. Then $k = -3$.
Comment: Colored to explain the process.  @Aaron: feel free to [rollback](http://math.stackexchange.com/posts/1000707/revisions) to the previous version.
Comment: thank you, though i don't get the process, the final answer helped me to understand better!
Comment: Great idea pointing out the process, @Omnomnomnom, thanks.
Answer: The determinant is equal (e.g. from the Rule of Sarrus) to $(0-4-4)-(0+4+4k)=4(-3-k)$. It is equal to 0 for $k=-3$ and then $A$ is not invertible.
Comment: thank you! though I had to find out the reason behind those numbers, it helped me a lot!


Transcribing as music and relative pitch practice?

Question: I've read some good transcriptions recently and watched transcribe videos from 8-Bit Music Theory on YouTube and I was thinking if it's considered to be a good relative-pitch / interval / music practice if I try to transcribe songs? At first the ones I consider relatively easy than more complex ones.

I would hear the intervals and more and more "get used to them" with every step on the sheet.
I would see the structures of the songs I like so I could learn how it works and maybe get some inspiration.
I would hear more and more precisely the note in itself approximetly. For example I hear a note and I "it's definitely below D but I think it's above A" but instinctively.

Is this considered to be a normal, benefiting practice in general or I just need to practicing intervals and relative-pitch in its own?
- Sorry if I made grammar mistakes. -
Answer: Transcribing music is EXCELLENT ear training practice. I like to tell students that transcribing one song to completion is like an entire semester of ear training.
Don't just listen for intervals and notes, but form, where tension is created and released, see if you can name all the instruments, sounds, or stereo techniques (panning, phasing, etc).
Everyone should do more transcribing; I wish it was a core part of college / university study. They'll have you transcribe 4-part harmony excerpts and rhythm excerpts, and sometimes melodies, but that's it.
It's normal and good and everyone should do it. Go forth and be merry.
Comment: Thank you! I like the idea to transcribe favourite or liked songs so after your answer I just find myself want to do it even more.

On the other hand, I beleived it's part of the college / university study at least sometimes as some form of test or at least "homework". It's a bit sad to read the state of this subject.
Comment: There is nothing better for your ears than using your ears. Transcribe away. It's so good. But it is hard to do. Don't get discouraged. Write down what you can hear and move on. As your ears get better go back and fill in the stuff you couldn't hear before.
Answer: Transcribing is a different type of practice than practicing recognizing isolated intervals, and it's also different from sight-singing, which is going the opposite way (from symbols to sounds). All three of these activities can be useful, and they all complement each other.
Transcribing is in some ways easier than hearing isolated intervals. Part of this is because if you know where you are in the key, you can usually rule out a lot of possibilities. E.g., if you're in C, and the tune moves up a step from F, you can pretty much anticipate that it's a whole step to G, not a half step to Gb. There is also usually a huge amount of repetition in music, and a huge amount of real-world music is certain patterns that you can recognize, e.g., a major scale, an arpeggiated minor triad in first inversion, a fragment of a chromatic scale, or a descending 8-5-1 (dropping an octave).
Another thing that tends to make transcribing easier is that you have two strategies for recognizing a note: you can recognize it relative to another note, or you can recognize it relative to the tonality. For instance, the sound of 7 going up a half-step to 1 is very easy to recognize, because you have that feeling of landing on the tonic. Another example is that often in major, you'll get sort of a pop-music cliche where minor iv is substituted for major IV. This is a very distinctive sound, and when you hear it in the melody, you pretty much know you have a b6.
Because the tonal context makes interval recognition easier, there is a pitfall, which is that people will learn to recognize intervals by memorizing how they occur in certain songs, e.g., "My Bonnie Lies Over the Ocean" for a major 6th. The problem here is that in this tune, the major sixth is the 5th scale degree going up to the 3, but what happens when your brain has to recognize a major 6th that occurs as 1 going up to 6? It may refuse to recognize it because of the different tonal context.
Compared to transcribing isolated intervals, transcribing tunes is more relevant to real-world practice if you're a jazz musician. On the other hand, if you want to, e.g., learn to sight-sing atonal opera music, you probably want to make sure you can also recognize intervals without any tonal context.


Solaris 10: OpenBoot setenv set-defaults

Question: I was trying to change the default mountpoint for /usr in /etc/vfstab. I am running Solaris 10 on a Sun Fire 480R.
Unfortunately, I made an error with editing the /etc/vfstab so I could no longer access /usr. I tried booting to cdrom as single user but could not access the original /etc/vfstab from there, nor find the hard drive where the original was mounted on.
I enlisted the help of a network admin with some Solaris experience. While I watched he tinkered around and finally decided it would be best to try 'setenv set-defaults' to revert to factory settings.
I am definitely more of a software than a hardware person so I blindly agreed, figuring he ought to know more what he is doing than me.
Since we rebooted after resetting defaults, though, we can't get the display to show up. The server starts up, to the point that we can ping it and its host name resolves, but I can't SSH to it or telnet to it. We have tried to connect various monitors but none we've tried so far work. We suspect it is possibly because we need a serial port, since the machine is old enough that this could very well be the factory default.
The machine is a test server, but is still a pretty critical one as the data and services would have eventually been migrated to new hardware. So... I have some obligation to get it back up and running.
Thanks in advance for any help or guidance.
Answer: The answer was exactly what we suspected. We needed to connect a console, so we got a RJ45 to DB9 cable, connected to the back of the Sun Fire 480R and connected the 9pin end to a laptop. Connected via HyperTerm to COM1, then it worked.
After I fixed the /etc/vfstab issue, I realized the real problem why the display terminal didn't show up  was because of a zfs mount error. I'd created a conflict between a legacy mount point in /etc/vfstab and a new zfs mountpoint I made just before my failed reboot.
I found out the hard way that starting up the usual init scripts / services relies on completing all auto mounts at boot without error first.


DPM Setup: The evaluation copy of DPM has expired. (ID: 3751)

Question: When I evaluated System Center Data Protection Manager (DPM/SCDPM) TP5 I stumbled across this problem: Because TP4 was previously installed on this server, and expired, I couldn't start the TP5 setup:
Answer: Just delete this registry key:
<code>HKCR\Licenses\830D982D-9ADC-4479-85CE-6474F7D00BB1
</code>


Generate realizations of X random variable

Question: Let $X,Z,U$ be a random variables where $X= \frac{Z}{U}$ , $Z \sim N(0,1)$ and $U \sim U(0,1)$.
Let $Z,U$ be indenpendent.
The task is to generate realizations of X.
Is it okay to take a realization of $Z$ and divided by one from $U$?
Should I obtained the distribution of X first?
Thanks in advance!
Comment: $N(0,1),U(0,1)$ denotes normal and uniform standard distribution.
Comment: Since $Z$ and $U$ are independent, yes your approach will work fine.
Comment: Well, maybe not quite so 'fine'. Be careful. Your denominators will often be very near $0,$ so $X$ will be heavy tailed. Maybe ponder Cauchy distribution $\equiv$ Student's t with DF=1.
Answer: Simulation in R: For clarity of plotting, truncated
simulated values to $(-20,20).$ Boost Cauchy density
by constant $c$ to account for omitted observations.
The median of this Cauchy distribution is 0. Its mean does not exist.
The summary below is for all 100,000 values generated.
<code>set.seed(2020)  # for reproducibility
u = rnorm(10^5); z = rnorm(10^5)
x1=z/u; x = x1[abs(x)<20]
summary(x1)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-606391.4      -1.0       0.0      -8.9       1.0  180980.7

c = 10^5/length(x);  c
[1] 1.033891
hist(x, prob=T, br=70, col="skyblue2", ylim=c(0,.35))
 curve(c*dt(x,1), add=T, col="red", n=10001)
</code>


Probability of 20 consecutive success in 100 runs.

Question: Suppose a chess player have a win rate equal 90%, what is the chance to have 20 consecutive wins (successes) playing 100 games? Consider that lose/draw = fail.
I've studied basic statistics in college and it seems like a binomial distribution problem (right?), but honestly I can't figure out a way to solve this problem considering "consecutive" successes.
Is there a statistical distribution for this kinda problem?
Thanks very much! I really appreciate any thoughts!
Comment: There is a formula here: http://math.stackexchange.com/questions/59738/probability-for-the-length-of-the-longest-run-in-n-bernoulli-trials
Comment: I believe it is a Bernoulli trial.
Comment: @SujaanKunalan Bernoulli trials don't require each success to be consecutive.
Comment: @ByronSchmuland: why not $80p^{20}(1-p)^{80}$?
Comment: Related: http://math.stackexchange.com/questions/4658/what-is-the-probability-of-a-coin-landing-tails-7-times-in-a-row-in-a-series-of and http://math.stackexchange.com/questions/261261/finding-the-probability-of-getting-5-consecutive-heads-from-flipping-a-coin-200?lq=1
Comment: @Alex:  that is the chance of winning exactly 20 or 80 (depending on the definition of $p$), but ignores "in a row"
Answer: Feller has this all worked out on p. 325 of An Introduction to Probability Theory and Its Applications, 3rd Edition, equation 7.11:
$$q_n \sim \frac{1-px}{(r+1-rx)q} \cdot \frac{1}{x^{n+1}}$$
where $q_n$ is the probability of no success run of length $r$ in $n$ trials, $p$ is the probability of success, $q=1-p$, and $x$ is the root near 1 of
$$ 1-x + q p^r x^{r+1} = 0 $$
With your data, we find $x \approx 1.017502$ and $q_{100} \approx 0.2247$.
So the probability that the chess player will have at least one run of 20 successes is $0.7753$, approximately.

Edit: Actually "$x$ is the root near 1 ..." is slightly misleading. The equation has two positive roots, and we must peak the one that is not $1/p$. Details here.
Comment: Thanks so much, awkward! This approximation is quite useful and easier to calculate. I was looking for something like that, I really appreciated!
Comment: @awkward I made an edit to clarify a step in the original recipe, that [lead to misleading results](https://math.stackexchange.com/questions/2348880/does-fellers-success-run-approximation-work-for-p-0-8/2348947#2348947). Feel free to edit or undo.
Comment: What do you mean by "peak"?
Comment: @Kurren You should direct that question to leonbloy, since he is the author of the remark about a peak.
Answer: To support @awkward, I have cut and paste a Matlab code that computes the probability values; it is consistent in solution with inputs p = 0.9, r = 20, and n = 100 with the solution provided by awkward. I removed my help menu so the formatting does not interfere with the paste.
function pr = fellerconsecPdf(p,r,n)
d   = [size(p(:),1), size(r(:),1), size(n(:),1)];
id  = setdiff( unique(d), 1);
if(numel(id) > 3/2)
erorr('MATLAB:fellerconsecPdf.m: non-scalar inputs must match in size');

end
m   = max( d );
p   = repmat(p(:), m - (size(p(:),1)-1), 1);
r   = repmat(r(:), m - (size(r(:),1)-1), 1);
n   = repmat(n(:), m - (size(n(:),1)-1), 1);
if(isscalar(p))
q       = (1 - p);
c       = zeros(r+2,1);
c(1)    = q.*(1 - q).^r;
c(r+1)  = -1;
c(r+2)  = 1;
xsol    = roots(c);
xsol    = xsol( abs(imag(xsol)) < eps );
xsol    = xsol(xsol>0);
[~,ii]  = max( abs(xsol - 1./p) );
x       = xsol(ii);

else
q       = (1 - p);
x       = [];

for k = 1:length(r)

    c           = zeros(r(k)+2,1);
    c(1)        = q(k).*(1 - q(k)).^r(k);
    c(r(k)+1)   = -1;
    c(r(k)+2)   = 1;
    xsol        = roots(c);
    xsol        = xsol( abs(imag(xsol)) < eps );
    xsol        = xsol(xsol>0);
    [~,ii]      = max( abs(xsol - 1./p(k)) );
    x           = cat(1,x,xsol(ii));

end

end
pr  = ( (1 - p.*x)./((r + 1 - r.x).(1-p)) ).x.^(-1(n + 1));
return;
Please not that star-dot-star does not show up in the text correctly, but it should be clear from context that that I intend point-wise multiplication of vectors.
Answer: I realize this is an old question - the only reason I'm answering is that recent similar questions are being tagged as a duplicate of this one. I wanted to point out a simplification to the first answer here by @awkward that might yield a better understanding for some people.
There's a pretty simple recurrence relation that yields the same result. Let f(n) be the possibility of getting a string of at least r successes in n trials where the possibility of success in one trial is p.
The next value of f(n+1) is the possibility of starting a new string of r successes $(p^r)$ preceded by a failure $(1-p)$, but you don't want to double count any sequence that already had a string of r successes. That double counting is removed by multiplying by $(1-f(n+1-r-1))$.
So the recurrence relation is:
$$f(n+1) = f(n) + (1-p) * (p^r) * (1-f(n-r))$$ for n > r
and
$$f(0)=f(1)=...=f(r-1)=0$$
and
$$f(r)=p^r$$
Substituting r = 20, and p = .9 yields the same answer as @awkward above. i.e. f(100) = 0.7752991959
Answer: The probability of getting $20$ consecutive wins is:
$$0.9^{20}$$
The first win of these consecutive wins can be at any trial from $1$ to $80$, and the probability of it being any on any of these trials is evenly distributed, so the probability of getting $20$ consecutive wins out of $100$ is:
$$\frac{80}{100}*0.9^{20}$$
A generalization for this formula would be:
$$\frac{n-k}{n}p^k$$
Where $p$ is the probability, $n$ is the number of trials, and $k$ is the number of consecutive wins.
Comment: It is not correct.  $0.9^{20}\approx 0.12158$.  The formula as given says the chance in a run of $100$ games is less than the chance in a run of 20 games, which is clearly wrong.
Comment: That makes total sense to me, but is it correct? I'm just asking because I read the posts that Byron posted (thanks so much, by the way), and I found some really really really tough things to understand - the generating functions by de Moivre in 1738 seems beautiful, but hard to understand intuitively.
Comment: @Anthony I agree, that's why I tried to come up with an alternative method. Still trying to re-work my current solution because as Ross pointed out, it doesn't work...


Postfix configuration;

Question: I cofigure a postfix/dovecot. I'm using default dovecot certificate for testing. but when i try to restart service integrity fail. But I'm not sure where is the problem.
I followed DigitalOcean guide. Where the problem, what parameter must be changed? Thanks in advance!
<code>/usr/lib/postfix/post-install: Error: "no smtpd_tls_cert_file=/etc/dovecot/dovecot.pem         smtpd_tls_key_file=/etc/dovecot/dovecot.pem smtpd_use_tls=yes smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes" should be "no" or an absolute path name.
postfix/postfix-script: warning: unable to create missing queue directories
postfix/postfix-script: fatal: Postfix integrity check failed!
</code>
Comment: `no smtpd_tls_cert_file=/etc/dovecot/dovecot.pem` ---> maybe postfix can't find the certificate. Permission issue maybe?
Answer: It seems the error was a blank space at beginning the line and I can't see it in nano editor.
Thanks.

Postfix configuration;


Multiple dex files define in Google Play Services

Question: I am having the following dependencies in the build.gradle file. Note that I am using Ionic/Cordova mobile app.
dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile project(path: "CordovaLib", configuration: "debug")
    releaseCompile project(path: "CordovaLib", configuration: "release")
    compile "com.google.android.gms:play-services-analytics:+"
    compile "com.onesignal:OneSignal:3.3.0@aar"
    compile "com.google.android.gms:play-services-gcm:+"
    compile "com.google.android.gms:play-services-location:+"
    compile "com.google.android.gms:play-services-ads:8.4+"
    // SUB-PROJECT DEPENDENCIES END
}

I get the below error during the build process.
Error: cmd: Command failed with exit code 1 Error output:
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Dex: Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzah;
    UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzah;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:591)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:546)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:528)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:164)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:504)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
        at com.android.dx.command.dexer.Main.run(Main.java:277)
        at com.android.dx.command.dexer.Main.main(Main.java:245)
        at com.android.dx.command.Main.main(Main.java:106)

FAILURE: Build failed with an exception.

I read the below SO links. It says about app level and module level gradle files. I am not sure which 2 files are those.
Version conflict updating to 8.4.0
Multiple dex files define Lcom/google/android/gms/internal/zzim;
Multiple dex files define Lcom/google/android/gms/internal/zzau
Answer: That error occurs when you have the same library/directory included more than once in your build.gradle's dependencies. This looks also to be conflict with another plugin your using as stated in this thread.
You can check these links:

UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define

Check all your dependencies in your build.gradle file. Are you referencing a dependency that also includes a dependency you have already included? For example, if your including appcompat-v7 there is no need to include appcompat-v4 since v7 includes all features from v4.

DexException: Multiple dex files

This error is caused by having too many method referenced in your project. You can read more here. Generally it means that you need to remove unused libraries or use proguard even on debug build to reduce the number of method referenced. You may also go with the multi-dex approached mentioned in the article but it makes your project more complicated.
Answer: I am not sure about the reason, but adding Google Admob library plugin the build was successful.
NOTE: I am using cordova plugin for Admob.