The permission to run 'ls' is denied

Question: I'm running my server as a root user but despite that, when I run the command ls I get this error:
bash: /bin/ls: Permission Denied.

I tried to change this file's permissions with chmod but the permission is denied as well. What's the cause of this?
Comment: Is it possible that your filesystem was mounted with `-o noexec`? Or does not support the executable flag which would tell Linux that a file is executable (e.g. NTFS)?
Comment: When you changed the `/bin/ls` file's permissions, what did you change them *from* and what did you change them *to*?
Comment: You're probably going to have to boot from rescue media and fix enough permission to make the system manageable.
Comment: Silly question, but kind of mandatory when running Linux. Have you tried sudo ls?
Answer: There are several potential causes for this.

The filesystem is mounted noexec.
Filesystem corruption that needs to be fixed with fsck.
The filesystem is foreign and improper translation of permissions results in denied privileges.
The directory holding the binary does not have the execute bit set (causing an issue with traversal)
A sub-directory in the directory does not have the execute bit set (only applies if the binary is nested in more than one directory)
The binary does not have the read and execute bits set for your user ID or group ID.
You are not really root (UID 0), even though the account name says root.  While improbable, this is possible.  Note that root is not 100% the same as UID 0, which is a "special" ID that bypasses privilege checks.  The root account, however, is mapped to UID 0.
SELinux/grsecurity rules denying everything. (thanks Janne Pikkarainen! had a little mental block about that annoyance.)
One or more binaries are compromised.  In which case, you can't trust anything you are running.

More information is needed to really understand what is happening.
Comment: Could you please elaborate why a read only filesystem would result in that error (I think that is plain wrong as I have run a couple of systems with solely RO mounted partitions and everything works as expected -- I'd think you wanted to write `noexec` instead of `read-only`)
Comment: 9. SELinux/grsecurity rules denying everything.
Comment: noted and fixed.

The permission to run 'ls' is denied


Verificar janela popup aberto ou fechado

Question: Tenho duas páginas, a página teste, e a verifica.
Gostaria de abrir um popup com o windows.open na página teste.html, e este popup vai se chamar verifica.html.
A página verifica.html tem que verificar se a página teste.html esta closed=true ou false.
Já fiz muitos códigos, más não consegui nada, podem me ajudar?
Comment: Eu tenho um codigo q faz isso. Vou procurar nos meus arquivos aqui.
Answer: Crie uma variável que será atribuída ao popup:
var minhaPopUp;

Ao abrir a popup usando window.open, atribua o comando à variável:
onclick="minhaPopUp=window.open('verifica.html','verifica','width=400,height=200')"

E uma função que irá verificar se ela está aberta:
function ver_PopUp(){
        if (!minhaPopUp || minhaPopUp.closed) {
            alert('Popup fechada');
        }else{
            alert('Popup aberta');
        }
}

Teste no Fiddle
Answer: Porque não tenta armazenar o valor em um cookie?
Assim que enviar o evento pra abrir o pop up você cria o cookie e no evento de fechar a janela você remove o cookie.
Encontrei este código pode ser útil também(Execute o código e veja como ele se comporta):

<title>Minha página</title>

Contato 1

<input type="button" value="Verificar se a janela de número 1 está aberta" onclick="VerificaJanela('contato1')">

Fonte: https://www.scriptbrasil.com.br/forum/topic/128757-resolvido%C2%A0verificar-se-popup-est%C3%A1-aberto/
Comment: Excelente, acho que pode resolver meu problema, vou testar e já te digo.


Prove that $A^n=0$ if and only if $A^2=0$

Question:
Let $A$ be a $2×2$ matrix and $n$ be an integer exceeding $2$. Show that $A^n=0$ if and only if $A^2=0$ where $0$ denotes null matrix of second order.

Proving the 'if part' is easy.
Given, $A^2=0$
Then, pre-multiplying(or post-multiplying) both sides by $A$ for $n-2$ times consecutively, we get
$A^n=0$.
But I cannot prove the 'only if' part, i.e., given $A^n=0$, how can I show that $A^2=0$?
Please anyone help me solve it. Thanks in advance.
Comment: Think of it as $A^n=A^m$ if and only if $n=m$.
Comment: Show that the kernel of $A$ has dimension either $1$ or $2$, and that if $\ker{A^2}$ has dimension $1$, then, for all $p \geq 1$, $A^p$ and $A$ have the same kernel.
Comment: https://math.stackexchange.com/questions/3014429/all-nilpotent-matrices-2-times-2-satisfies-a2-0 https://math.stackexchange.com/questions/1200829/all-nilpotent-2-times-2-matrices
Comment: @Jean-ClaudeArbaut Thanks, I got my answer there.
Answer: Since $A$ has an eigenvalue of $0$, the characteristic polynomial is of the form
$$x(x-a)$$
for some $a$. Thus
$$A^2-aA = 0$$
If $a\neq 0$, then
$$A^2=aA$$
And therefore
$$A^n=a^{n-1}A$$
hence is never $0$. Thus $A^2=0$.
Comment: @J.W.Tanner Right, if $A=0$ there is nothing to prove.
Comment: @Ekhin Well it seemed not to answer your question since it was something you already knew.
Comment: $A^n=a^{n-1}A$ is never $0$ assuming $A\ne 0$, but if $A=0$ then $A^2=0$ and we are done, right?
Comment: Why did you delete your answer [here](https://math.stackexchange.com/q/3427397)?
Comment: @MattSamuel However the 'no subset homeomorphic to $\mathbb R^n$ is an embedded Lie subgroup' part is not something new, as I was about to further comment on. Are you answering 'no' to both questions?
Comment: @EkhinTaylorR.Wilson It can be an embedded Lie subgroup, but it is a subgroup at all only if the connected components of $G$ are all homeomorphic to $\mathbb{R}^n$.


Allow node creation only via services

Question: Is there a way to allow the creation of nodes only via services and not via node/add?
I want that nodes are created by the users of a mobile application, and not using the web interface.
Is this possible?
Comment: Matt, do you want unauthorized (not logged in) users to create nodes using services? Do your mobile app users log in in order to publish or not ? Can you clarify that?
Comment: Yes, so each user has to be logged in to be able to create a node
Answer: I have created a module that only allows logins through services.. therefore, you can only create a node through services if you use it in conjuction with a Session Limit, or other module which prevents multiple sessions.
http://drupal.org/sandbox/tpainton/1851382
Still experimental but please try, and if you find bugs, report.  Hope it works for you.
Answer: Content Access allows you to manage permissions for content types by role. It allows you to specify custom view, view own, edit, edit own, delete and delete own permissions for each content type.
You can restrict access to a content type by not assigning the content type permissions to the user role.
Comment: but the user still needs that role to be able to add content via services i.e. they still need to log in to post nodes
Answer: Using refineo's answer for inspiration and expanding you could :
1) setup a new roll X
2) Set permission on node creation such that only a user of roll X can create nodes
3) use Services via mobile to obtain a session
4) Grant a roll X to the user that just logged in via Services
5) Allow user to create node via Services
6) revoke roll x from user on logout
Granting and revoking rolls might be easier with Rules module
You'll want to expire sessions such that someone on their mobile app will not be logged in on the website (on a browser) at the same time because this way they will have access to node/add.  Take a look at Session Limit
Answer: You could create the following rule.
Event: Drupal is initializing (though there is a performance consideration here - this will fire on every request).
Condition: Data Comparison: Compare the current path (using the pattern [site:current-page:path]) to the value node/add/article (or whichever content type you want to prevent browser users accessing).
Actions: Page Redirect to a node telling the user that access is denied.
Users will still be able to add content via the service url.
Adding another condition to filter for roles would allow admins or other roles to create new content in the browser.

Allow node creation only via services


ANOVA to compare models

Question: I'm looking at this site for a workshop on GAM in R: http://qcbs.ca/wiki/r_workshop8
In the end of the section 2. Multiple smooth terms they show an example, where they use anova to compare three different models to determine the best fit model. The output is
  Analysis of Deviance Table
  Model 1: y ~ x0 + s(x1)
  Model 2: y ~ x0 + s(x1) + x2
  Model 3: y ~ x0 + s(x1) + s(x2)
    Resid. Df Resid. Dev      Df Deviance  Pr(>Chi)
  1    394.08     5231.6
  2    393.10     4051.3 0.97695   1180.2 < 2.2e-16 ***
  3    385.73     1839.5 7.37288   2211.8 < 2.2e-16 ***
  ---
  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Based on this they conclude that model 3 is best. My question is how they see that?
My current understanding is: The Pr(>Chi)-value is small for both model 2 and 3, so these are better than model 1. However, what other variable are they using to determine that 3 is better than 2?
Comment: Hint: what variable(s) appear in Model 3 that do not appear in Model 2? To answer this, you need to know what "s(x2)" means--and that depends on how the function `s` is defined.  (I presume it's some kind of spline, but I am reluctant to presume any more than that.) We can tell from the output that it's fairly complicated--the move from `x2` to `s(x2)` adds $7.37288$ degrees of freedom--but that's all we can determine about it from this output.
Comment: The huge difference in deviance between models (2) and (3) is compelling.
Comment: Doing `AIC(model1, model2, model3)` reveals that model 3 has a lower `AIC`. This could be a further proof that it is the optimal model among the three
Answer: The output from anova() is a series of likelihood ratio tests. The lines in the output are:

The first line in the output corresponds to the simplest model with only a smooth of x1 (I'm ignoring the factor x0 as it isn't up for consideration in your example) — this is not tested against anything simpler hence the last few column entries are empty.
The second line is a likelihood ratio test between the model in line 1 and the model in line 2. At the cost of 0.97695 extra degrees of freedom, the residual deviance is decreased by 1180.2. This reduction in deviance (or conversely, increase in deviance explained), at the cost of <1 degree of freedom, is highly unlikely if the true effect of x2 were 0.
Why 0.97695 degrees of freedom increase? Well, the linear function of x2 would add 1 df to the model but the smoother for x1 will be penalised back a little bit more than before and hence use slightly fewer effective degrees of freedom, hence the <1 change in overall degrees of freedom.
The third line is exactly the same as I described above but for a comparison between the model in the second line and the model in the third line: i.e. the third line is evaluating the improvement in moving from modelling x2 as a linear term to modelling x2 as a smooth function. Again, this improvement in model fit (change in deviance is now 2211.8 at the cost of 7.37288 more degrees of freedom) is unlikely if the extra parameters associated with s(x2) were all equal to 0.

In summary, line 2 says Model 2 fits better than Model 1, so a linear function of x2 is better than no effect of x1. But line 3 says that Model 3 fits the data better than Model 2, so a smooth function of x2 is preferred over a linear function of x2. This is a sequential analysis of models, not a series of comparisons against the simplest model.
However…
What they're showing is not the best way to do this — recent theory would suggest that the output from summary(m3) would have the most "correct" coverage properties. Furthermore, to  select between models, one should probably use select = TRUE when fitting the full model (the one with two smooths), which would allow for shrinkage of terms that would include the model with linear x2 or even no effect of this variable. They're also not fitting using REML or ML smoothness selection, which many of us mgcv users would consider the default option (even though it isn't the actual default in gam())
What I would do is:
library("mgcv")
gam_data <- gamSim(eg=5)
m3 <- gam(y ~ x0 + s(x1) + s(x2), data = gam_data, select = TRUE,
          method = "REML")
summary(m3)

The final line produces the following:
> summary(m3)

Family: gaussian
Link function: identity

Formula:
y ~ x0 + s(x1) + s(x2)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   8.4097     0.2153  39.053  < 2e-16 ***
x02           1.9311     0.3073   6.284 8.93e-10 ***
x03           4.4241     0.3052  14.493  < 2e-16 ***
x04           5.7639     0.3042  18.948  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
        edf Ref.df     F p-value
s(x1) 2.487      9 25.85  <2e-16 ***
s(x2) 7.627      9 76.03  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.769   Deviance explained = 77.7%
-REML = 892.61  Scale est. = 4.5057    n = 400

We can see that both smooth terms are significantly different from null functions.
What select = TRUE is doing is putting an extra penalty on the null space of the penalty (this is the part of the spline that is perfectly smooth). If you don't have this, smoothness selection can only penalise a smooth back to a linear function (because the penalty that's doing smoothness selection only works on the non-smooth (the wiggly) parts of the basis). To perform selection we need to be able to penalise the null space (the smooth parts of the basis) as well.
select = TRUE achieves this through the use of a second penalty added to all smooth terms in the model (Marra and Wood, 2011). This acts as a kinds of shrinkage, pulling all smooth terms somewhat towards 0, but it will pull superfluous terms towards 0 much more quickly, hence selecting them out of the model if they don't have any explanatory power. We pay a price for this when evaluating the significance of the smooths; note the Ref.df column above (the 9 comes from the default value of k = 10, which for thin plate splines with centring constraints means 9 basis functions), instead of paying something like 2.5 and 7.7 degrees of freedom for the splines, we're paying 9 degrees of freedom each. This reflects that fact that we've done the selection, that we weren't sure which terms should be in the model.
Note: it is important that you don't use anova(m1, m2, m3) type calls on models using select = TRUE. As noted in ?mgcv:::anova.gam, the approximation used can be very bad for smooths with penalties on their null spaces.
In the comments, @BillyJean mentioned using AIC for selection. Recent work by Simon Wood and colleagues (Wood et al, 2016) derived an AIC that accounts for the extra uncertainty due to us having estimated the smoothness parameters in the model. This AIC works reasonably well, but there is some discussion as to the behaviour of their derivation of AIC when IIRC smooths are close to linear functions. Anyway, AIC would give us:
m1 <- gam(y ~ x0 + s(x1), data = gam_data, method = "ML")
m2 <- gam(y ~ x0 + s(x1) + x2, data = gam_data, method = "ML")
m3 <- gam(y ~ x0 + s(x1) + s(x2), data = gam_data, method = "ML")
AIC(m1, m2, m3)

> AIC(m1, m2, m3)
          df      AIC
m1  7.307712 2149.046
m2  8.608444 2055.651
m3 16.589330 1756.890

Note I refitted all of these with ML smoothness selection as I'm not certain what the AIC does when select = TRUE and you have to be careful comparing models with different fixed effects, that aren't fully penalised, using REML.
Again the inference is clear; the model with smooths of x1 and x2 has substantially better fit than either of the other two models.

Marra, G. & Wood, S. N. Practical variable selection for generalized additive models. Comput. Stat. Data Anal. 55, 2372–2387 (2011).
Wood, S. N., Pya, N. & Säfken, B. Smoothing Parameter and Model Selection for General Smooth Models. J. Am. Stat. Assoc. 111, 1548–1563 (2016).
Comment: @DeltaIV Sorry, that was poor wording on my part. What `select = TRUE` does is fully penalize all smooth terms, which AFAIU makes comparisons using REML OK. I haven't looked at the detail of the new AIC for GAMS to see what it would do with the extra penalties added when using `select = TRUE`. So if we drop `select = TRUE` to be on the safe side, we have the problem that REML is not a true likelihood and is not used in AIC comparisons because it is dependent upon the fixed effects in the model. Accounting for both concerns means I used `method = "ML"` (not `method = "REML"`) when refitting.
Comment: +1 for the detailed answer with code and reference. I will read and learn this answer in detail later. One question, you said it is likelihood ratio test. but in `?anova.lm` there is no such option, can be F chisq or CP
Comment: @hxd1011 this is using `mgcv:::anova.gam` not the method for `lm` models. These are analysis of deviance tests but that's the same thing as likelihood ratios.
Comment: Thanks. Could you answer my question [here](https://stats.stackexchange.com/questions/274152/why-anova-can-be-used-to-compare-models) with some high level summary? Or your answer is here is already covered.
Comment: @hxd1011 You'd need to be more specific. What kinds of models? There are a lot of assumptions behind `anova()` but which ones depends on what the model is. Often for non-Gaussian models these are performing likelihood ratio tests or similar tests, but the assumptions will vary; they do vary even for GLMs and GAMs. `anova()` is a convenience function but it isn't doing ANOVA sensu the general linear model for anything but a general linear model (fitted via `lm()` say).
Comment: Thank you for educating me. I do not have the knowledge of asking a good and specific question. Your comments here is already helped me! If you have time could you tell me anova.lm?
Comment: +1 impressive answer, like your other answers concerning `mgcv`: you truly are an expert. I understand now why `m2` doesn't need to be nested in `m3`, in order for `anova` to work: the point is that the test being used here is not an analysis of variance as for `anova.lm`, but it's an analysis of deviance. Just a doubt: for AIC you say that "I refitted all of these with ML smoothness selection as I'm not certain what the AIC does when `select = TRUE`". However, in the following `gam` calls, you set `method = "ML"` but not `select = TRUE`. Did you forget it, or am I misunderstanding you?
Answer: You may want to test the two models with lrest.
lrtest(two_term_model, two_smooth_model)

Model 1: y ~ x0 + s(x1) + x2
Model 2: y ~ x0 + s(x1) + s(x2)
      #Df  LogLik    Df  Chisq Pr(>Chisq)
1  8.1107 -995.22
2 15.0658 -848.95 6.955 292.55  < 2.2e-16 ***

While adding a smooth function to both terms indeed complicate the model, the improvement in the log-likelihood is significant. This shouldn't be surprising because the data was generated by a GAM simulator.
You may also want to print out the summary statistics:
Link function: identity

Formula:
y ~ x0 + s(x1) + x2

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  11.6234     0.3950  29.429  < 2e-16 ***
x02           2.1147     0.4180   5.059 6.48e-07 ***
x03           4.3813     0.4172  10.501  < 2e-16 ***
x04           6.2644     0.4173  15.010  < 2e-16 ***
x2           -6.4110     0.5212 -12.300  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
        edf Ref.df     F p-value
s(x1) 2.111  2.626 64.92  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.583   Deviance explained = 58.9%
GCV = 8.7944  Scale est. = 8.6381    n = 400

and
Family: gaussian
Link function: identity

Formula:
y ~ x0 + s(x1) + s(x2)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   8.3328     0.2074  40.185  < 2e-16 ***
x02           2.1057     0.2955   7.125 5.15e-12 ***
x03           4.3715     0.2934  14.901  < 2e-16 ***
x04           6.1197     0.2935  20.853  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
        edf Ref.df     F p-value
s(x1) 2.691  3.343 95.00  <2e-16 ***
s(x2) 7.375  8.356 85.07  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.796   Deviance explained = 80.2%
GCV = 4.3862  Scale est. = 4.232     n = 400

Note the difference in deviance explained (it's huge). The more complicated model also has better R-sq.(adj). The second smoothing term is highly significant and fits nicely with the data.
Comment: Doesn't this just produce another example like that in the question?  Could you indicate more explicitly how it responds to the question?

ANOVA to compare models


How is Bavuma the first black South African cricketer to make a test century?

Question: I may be missing something but it's all over the news. I don't understand because JP Duminy has scored 4 test centuries. Is there something here I'm missing ?
Answer: JP Duminy is from the Cape Coloured ethnic grouping (see http://www.cricketwa.com/370/player/jean-paul-duminy.aspx), hence is not considered Black African.
Note: I'm not commenting on whether these ethnic groupings are appropriate or even palatable. They're what's in use in South Africa today. I'm not South African, or resident there.
Comment: None taken. You asked why JP Duminy's centuries didn't count, and I explained - he's not considered, in South African parlance, as Black African. Discussing whether this is a correct judgement, or if the categories are even valid, is not a topic for this forum.
Comment: No offence but what is the difference ?
Comment: I am neither asking if the judgement is correct nor if the categories are valid. I'm merely asking for more information about what Duminy's race is because I never heard that word before today.
Comment: The link in my answer states "The Cape Coloured ethnic group of South Africa comprises of people belonging to mixed race."
Comment: Can you tell me who are the black Africans to play for South Africa ? Which category do Ntini, Prince, Philander, Tsosobe, Piedte fall under ?
Comment: This information would be available from a Google search.
Comment: Most coloured people would take offense to being categorized as black. There culture is totally different to that which is considered black. There is more to definition of culture groups in South Africa than just skin colour.
Comment: and even among the term "black" there are cultures among them that differ as well. Xhosas,and Zulus are not the same.


Atom pylinter not working

Question: I just started using Atom, and I was trying to set up a linter using pylint, however each time linter activates I get:
<code>linter-registry.js:137 [Linter] Error running Pylint Error: Failed to spawn command `C:\WINDOWS\system32\cmd.exe`. Make sure `C:\WINDOWS\system32\cmd.exe` is installed and on your PATH(…)
</code>
Three Times.
Comment: Have you installed [`linter`](https://atom.io/packages/linter) first? Also, [this issue](https://github.com/AtomLinter/linter-pylint/issues/80) may help you.
Comment: Yes, I Have the extension, and I also have pylint.exe.  Also I have already looked at that page, and it did not help.
Comment: What about [`linter-ui-default`](https://atom.io/packages/linter-ui-default)?
Comment: That is just the graphic system, it does not really lint.
Comment: I know, you still need it for `linter` to work. If you can't find a solution, you might as well use [`linter-pyflakes`](https://atom.io/packages/linter-pyflakes) where you need to install `pyflakes` by typing `$ pip install pyflakes`.
Answer: For those who are working with Anaconda, I found this helpful.
Go to Anaconda Prompt and type this: where pylint

You will probably get the two results below:
C:\Users\USERNAME\anaconda3\Scripts\pylint.bat
C:\Users\USERNAME\anaconda3\Scripts\pylint.exe
Copy the one with pylint.exe and paste it in the executable path of the Pylint package in Atom.
If you are a complete beginner to Atom like me, the executable path of a package can be found by going to: File -> Settings -> Packages -> type Pylint in the search bar -> click on settings and scroll down to find the Executable Path and paste the path with pylint.exe

Atom pylinter not working


Display text in a div based on inner.HTML value of another div

Question: I have the following script:
  function showstatus()
  {
  var inputbedtwo = document.getElementById("bedtwostatus");
  var inputliving = document.getElementById("livingstatus");
  var inputkitchen = document.getElementById("kitchenstatus");
  if(inputbedtwo.innerHTML == "A"){
    document.getElementById("statustop").innerHTML = "Danger";
  }
  else if(inputliving.innerHTML == "A"){
    document.getElementById("statustop").innerHTML = "Danger";
  }
  else if(inputkitchen.innerHTML == "A"){
    document.getElementById("statustop").innerHTML = "Danger";
  }
  else{
    document.getElementById("statustop").innerHTML = "Normal";}
  }

The trouble with this is that it is only outputting Normal text in
When the status is changing to "A", it does not output Danger.
I would like it to output Danger when status is "A".
Thanks.
Comment: We don't have enough information. We don't know when or how this function is called, and in response to what. Do some debugging; is the function being entered when you think it is? Are the values what you think they are? Basic debugging can help here.
Comment: Can you include the markup ?
Comment: I think the problem is in HTML code, could you share it with us?
Answer: I think you are missing a change event.

<input id="bedtwo" type="text" name="" value="">

Answer: From the title, I Added three divs with A,A,B as their innerHTMl and it works fine.
Now if you could include your markup that would be helpful to find the problem, if not just take a look at what i did here and adjust your own.

document.getElementById("btn").addEventListener('click',showstatus);

function showstatus() {
    var inputbedtwo = document.getElementById("bedtwostatus");
    var inputliving = document.getElementById("livingstatus");
    var inputkitchen = document.getElementById("kitchenstatus");
    if (inputbedtwo.innerHTML == "A") {
        document.getElementById("statustop").innerHTML = "Danger";
    } else if (inputliving.innerHTML == "A") {
        document.getElementById("statustop").innerHTML = "Danger";
    } else if (inputkitchen.innerHTML == "A") {
        document.getElementById("statustop").innerHTML = "Danger";
    } else {
        document.getElementById("statustop").innerHTML = "Normal";
    }
}

A

A

B

<button id="btn">SUBMIT</button>
Comment: Yeah, this is working fine. I will try and troubleshoot it and see when the function is being called. Thanks for your help.


What is the place holder glyph for a set?

Question: What glyph do set theorists use to denote an unspecified set?
For example, logicians use φ to talk about an unspecified sentence in first order logic. Does set theory have a comparable glyph?
Thank you.
Comment: "Let $S$ and $T$ be sets and $f$ be a function $f: S \rightarrow T$..." You can name things whatever you want.
Answer: Technically you can name a set anything you want, but some names are more conventional than others. In my experience, mathematicians often use capital letters in the upper part of the English alphabet -- $A$, $B$, $C$, etc. -- to name sets, at least in elementary treatments. A good way to determine the "standard" notational convention for something like a set is to find books or articles which use sets in the same context as you. The context is important because almost every mathematical object is a set: "$1$" is the name of a set, for example, although you would confuse everyone greatly if you wrote "let $1$ be a set . . ."


Determine if a point is within a region

Question: I have a kml file that contains many regions (say buildings or properties). The shapes might be complicated (not just rectangles, but potentially n sided, or even convex), but for the most part they will be small (none more than a km a side). There are potentially tens of thousands of coordinates and hundreds (maybe thousands) of regions.
I want to know if any coordinate of a set of coordinates is inside one of these regions, and if so, what coordinate(s) and what region(s). This could be done by finding all the points within each region one region at a time, or by finding out if each point lies within a region one point at a time.
I hope for a database driven solution of some kind, but am open to any solution.
The application will be launched on a Amazon EC2 instance, so something compatible with RDS would be nice)
Tentative solution would be the ST_WITHIN or ST_CONTAINS or ST_INTERSECTS in mysql, but I am unclear about the difference between them.
I have also looked at Google Fusion Tables, and cannot find an SQL query that does what I want (doesn't mean that there isn't one - I just missed it).
Answer: For the record, I ended up using geodjango with a backing mysql database.
RegionContainer.objects.filter(region_area__contains=Point(longitude, latitude))

Gives a list of regions that which contain the point with the given latitude and longitude coordinates. The python/django code becomes the sql query.
SELECT `locationapp_region_container`.`id`,
       `locationapp_region_container`.`profile_id`,
       AsText(`locationapp_region_container`.`region_area`)
       FROM `locationapp_region_container`
       WHERE MBRContains(`locationapp_region_container`.`region_area`,
       GeomFromText(POINT (80.6123000000000047 -43.2349804300000002)))

Because the backing database is MySQL, it is RDS supported.
Answer: For anyone interested in using Fusion Tables to solve this problem, you can use ST_INTERSECTS:

Used in the WHERE clause. The syntax is: ST_INTERSECTS(<location_column>, <geometry>)
  For <location_column>, use a <column_name> in your table that
  contains location data.
For <geometry>, use one of the following:

<circle>
<rectangle>

ST_INTERSECTS cannot be combined with ORDER BY ST_DISTANCE.

Unfortunately, you can't use LATLNG directly. However, CIRCLEs can be as small as 1 meter. The following should be good enough:
select * from
 where st_intersects(<column>,
circle(latlng(<latitude>, <longitude>), 1))

Comment: I did end up using fusion tables as part of my solution, however not the part related to this question. I am also trying to move away from ft altogether because the extra latency involved in sending a secondary request to fusion tables is not desirable. I do like that this solution allows for the point to be slightly inaccurate (as is often the case with gps results).

Determine if a point is within a region


Covariance matrix of multivariate normal when negative values are made zero

Question: Let $x$ be $n$ dimensionally multivariate normally distributed with mean $\mu$ and covariance matrix $\Sigma$. Now let $y$ be random variables defined by
\begin{equation}
 y_i= \begin{cases}
      0, & x_i\leq 0 \\
      x_i, & x_i>0
   \end{cases}
\end{equation}
What is the mean and covariance matrix of $y$? Can we get an analytic solution? If not, what about in some special cases.  For example, where $\mu=\bf{0}$ and $\Sigma$ has a diagonal of one and all other entries the same value $\rho$?
Comment: iterated expecation might be the play https://en.wikipedia.org/wiki/Law_of_total_expectation
Comment: Because this question generalizes (in two different ways) https://stats.stackexchange.com/questions/356023 and https://stats.stackexchange.com/questions/552561, the techniques described in those threads will be helpful here.  They already give the answers to your special cases.
Answer:
I think just dealing with the bivariate case is all that is necessary as you're only interested in covariances.  I also think that there is likely no analytic solution when the means of the $X$'s are not zero.  Here is an approach using Mathematica:
For the bivariate case $Y_1$ and $Y_2$ both have means that can be calculated by integrating over 0 to $\infty$ using the marginal densities of $X_1$ and $X_2$, respectively.
Find the means of $Y_1$ and $Y_2$:
mean1 = Integrate[y1 PDF[NormalDistribution[0, σ1], y1], {y1, 0, ∞}, Assumptions -> σ1 > 0]
(* σ1/Sqrt[2 π] *)

mean2 = Integrate[y2 PDF[NormalDistribution[0, σ2], y2], {y2, 0, ∞}, Assumptions -> σ2 > 0]
(* σ2/Sqrt[2 π] *)

Now the covariance depending on if $\rho$ is positive or negative:
pdf = PDF[BinormalDistribution[{0, 0}, {σ1, σ2}, ρ], {y1, y2}];

covρPositive = FullSimplify[Integrate[y1 y2 pdf, {y1, 0, ∞}, {y2, 0, ∞},
  Assumptions -> {σ1 > 0, σ2 > 0, 0 < ρ < 1}] - mean1 mean2,
  Assumptions -> {σ1 > 0, σ2 > 0, 0 < ρ < 1}]
(* (σ1 σ2 (-1 + π ρ + Sqrt[1 - ρ^2] - ρ ArcCos[ρ]))/(2 π) *)

covρNegative = Integrate[y1 y2 pdf, {y1, 0, ∞}, {y2, 0, ∞},
  Assumptions -> {σ1 > 0, σ2 > 0, -1 < ρ <= 0}] - mean1 mean2 // FullSimplify
(* (σ1 σ2 (-1 + π ρ + Sqrt[1 - ρ^2] - ρ ArcCos[ρ]))/(2 π) *)

As a check one can set values for $\sigma_1$, $\sigma_2$, and $\rho$ and take random samples:
n = 10000000;
parms = {σ1 -> 1, σ2 -> 7, ρ -> -1/2};
x1x2 = RandomVariate[BinormalDistribution[{0, 0}, {σ1, σ2}, ρ] /. parms, n];
x1x2[[All, 1]] = Max[0, #] & /@ x1x2[[All, 1]];
x1x2[[All, 2]] = Max[0, #] & /@ x1x2[[All, 2]];

(* Sample estimate *)
Covariance[x1x2][[1, 2]]
(* -0.7329134893798569 *)

(* True covariance formula *)
(σ1 σ2 (-1 + π ρ + Sqrt[1 - ρ^2] - ρ ArcCos[ρ]))/(2 π) /. parms // N
(* -0.7325923679884647 *)

The results are consistent for this example.


Como retornar dados do usuario que efetuou o login?

Question: Preciso que alguém me ajude com o seguinte problema. Eu quero realizar um select em um banco de dados MySQL, o select sera feito via Web service com PHP retornando um Json para o meu app Android.
O que acontece, o usuário digita login e senha e o app reconhece o usuário  e abre uma segunda tela, nessa segunda tela tem um listview e nesse listview deveria conter todas as empresas desse usuário, e é neste ponto que esta o problema. Para eu fazer isso eu realizo um select em PHP no banco de dados, porem, o select me retorna todas as empresas do banco de dados e não só a do usuário que efetuou o login. Eu tentei salvar o código da empresa utilizando SESSION no PHP porem  não deu certo  gostaria que alguém me ajudasse, obrigado.
Segue o código em PHP:
<?php

SESSION_START();
echo $_SESSION['Cod_Empresa'];
mysql_connect('localhost','','');
mysql_select_db('bd') or die (mysql_error());

$result = mysql_query( "SELECT UC, Instalacao, Nome_Logo FROM Tab_UC where Cod_Empresa ='".$_SESSION['Cod_Empresa']."'") or die('Could not query');
 for($rows = array(); $row = mysql_fetch_object($result); $rows[] = $row);
 {
    echo json_encode($rows);
 }

?>

Answer: Bom, pelo que entendi você deseja buscar as empresas de um usuário logado.
Olhando tua query vi que tem uma tabela Tab_UC, deduzo que seja a tabela responsável pelas empresas cadastradas. E em sua cláusula where Cod_Empresa ='".$_SESSION['Cod_Empresa']."' vocẽ está filtrando pelo código da empresa. Não deveria filtrar por ID do usuário logado?
Ao meu ver, este código retorná apenas uma empresa.
Comment: e como seria filtrar pelo ID...   poderia me retornar um exemplo...   obrigado


Why does spark-submit fail with "IllegalArgumentException: Missing application resource."?

Question: When I create the jar of my Spark application and try to run it using spark-submit, I am getting the following error.
This is the command I used to run.
spark-submit --executor-memory 1g --jars s3://test-data-lab-users/spachari/test/test_2.10-1.0.jar

This is the error i am getting. Does this mean I have not passed correct parameters in my spark-submit?
Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:276)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)
Command exiting with ret '1'

Answer: tl;dr Remove --jars option and start over.

java.lang.IllegalArgumentException: Missing application resource.

You missed your...well...Spark application that the message refers to as "application resource".
That's more obvious when you execute spark-submit and see the different command-line options and their meanings.
./bin/spark-submit
Usage: spark-submit [options] <app jar | python file | R file> [app arguments]

That part <app jar | python file | R file> is what you missed.
To reproduce your issue you can simply execute spark-submit with --jars options without specifying the main jar or class of a Spark application.
$ ./bin/spark-submit --jars target/spark-parent_2.11-2.3.0-SNAPSHOT-tests.jar
Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:274)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)

Quoting spark-submit --help, --jars is...

--jars JARS Comma-separated list of jars to include on the driver and executor classpaths.

--jars can be very helpful when a Spark application depends on additional jar files (aka dependencies), i.e. mysql-connect.jar that you cannot (or most likely don't want to) "assembly" to your uber jar.
Comment: I never use `--jars` (I directly specify path to `JAR`), but still one fine day `Spark` started giving me this error. Converting the entire `spark-submit` command into single-line (removing **back-slashes** and **new-lines**) solved the issue. Strange. (`Spark 2.3.0` on `emr-5.13.0`)
Answer: --jars option is added when you've to supply supporting jars to your application jar.
Application resource missing implies that your main jar is missing as you've passed it with --jars option. It's looking for your main jar and since it couldn't find it, it throws that error.
Answer: This is because main Jar is missing in spark-submit. Check at --class argument. It should be like:
--class "your class name with package" "main jar path" "jar parameters"


DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'CityNameHotel_Name'

Question: I am getting this error when ever i try to bind two database table columns to single dropdown list.
here is code that i used :
GetHotelNames.DataSource = bh.GetHotelNamess();
GetHotelNames.DataTextField = "CityName"+"Hotel_Name";
GetHotelNames.DataBind();

It works fine if i try to get single column values but when i want to concatenate two columns with DataTextField it shows error.
i have searched this from different stack questions and found only one relevant link
but i did not get any success with this.
What should i do if i want to get two database table column values to one single dropdown?
Comment: What is the return type `bh.GetHotelNamess()`?
Comment: How your fetching records the data in your GetHotelNames() function , can you post the code?
Comment: @mshsayem DataSet is return type
Answer: You can't specify multiple columns in DataTextField, instead you can create a new concatenated column in your DataSource based on above two columns and then specify that as the DataTextField.
For example if at the backend your query is like:
Select CityName, Hotel_Name, otherField
From yourtable
....

Then create a new column using concatenation (if its Sql Server then):
Select CityName, Hotel_Name, otherField, CityName + HotelName as CombinedColumn
From yourtable
....

Then you can specify CombinedColumn as the DataTextField
Currently you are getting the exception due to string concatenation of "CityName"+"Hotel_Name" results in "CityNameHotel_Name" , and there is no column in your DataSource with the name "CityNameHotel_Name"
EDIT:
Based on the comment, you are not concatenating your column in the query it should be like:
select
Hotel_Info.Hotel_Name ,
City.CityName + ',' + Hotel_Info.Hotel_Name as CombinedColumn
FROM Hotel_Info LEFT OUTER JOIN City ON Hotel_Info.CityID = City.CityID

Comment: @aami, look at the code example in the code, You can't specify multiple columns as `DataTextField`.
Comment: you mean to say that i have to change my stored procedure for  this? i did that and make a combined column but it is only showing city names instead of showing city and hotels in drop down.
Comment: @aami, Modify your select query like: `select Hotel_Info.Hotel_Name ,City.CityName + ',' + Hotel_Info.Hotel_Name as CombinedColumn FROM Hotel_Info LEFT OUTER JOIN City ON Hotel_Info.CityID = City.CityID`
Comment: Thank you so much , you are king of this.....it works now.
i was missing " + ',' + " in my procedure query
Answer: You need to create these concatenate column in your data source itself, for example if you are getting your data from a store procedure than create a new column by concatenate CityName  & Hotel_Name and then assign this column to your DataTextField
Comment: here is my procedure code
 select Hotel_Info.Hotel_Name ,City.CityName as CombinedColumn
 FROM         Hotel_Info LEFT OUTER JOIN   City ON Hotel_Info.CityID = City.CityID
Comment: Change your query to `select
 Hotel_Info.Hotel_Name ,
 Hotel_Info.Hotel_Name + '_' + City.CityName as CombinedColumn
FROM Hotel_Info
LEFT OUTER JOIN City ON Hotel_Info.CityID = City.CityID` and assign `CombinedColumn` to your `DataSource`
Answer: Try this:
GetHotelNames.Items.Clear();

foreach(DataRow item in bh.GetHotelNamess().Tables[0].Rows)
{
    GetHotelNames.Items.Add(new ListItem(item["CityName"] + " " + item["Hotel_Name"]));
}


Botão "Curtir" Facebook customizado

Question: Existe alguma maneira de customizar ou construir o botão "Like/Curtir" (para uma página) do Facebook?
Gostaria de um customizado, pois o original não se encaixa no design do app mobile que estou desenvolvendo.
Answer: Existe um plugin chamado Fancylike que deve servir para o propósito.
Inclua o plugin:

Criar um conteiner para o botão:

Chamar o plugin, com a detecção automática da URL a curtir(ou seja url atual):

Botão "Curtir" Facebook customizado


Create user profile using content type or add additional fields to the default registration form

Question: I am good enough to build an entire drupal 7 website but my problem goes below:
I am in the process of building a very simple drupal website for all volunteers in my country.
So every volunteer will have a profile page on the website where volunteers can search for each other, send emails to each others and even send sms to each other in addition to other basic features.
And so to create such website there is two way that i am little bit confuse which one to use: (any suggestion please)
Method 1:
Add any additional field such as city ,district, bio, age, birtbday, phone number, profile picture, blood type, education degree, languages spoken.... directly inside the registration form by going to account settings in configuration page.
And so i will use the "User" entity to pull out the information required for the creation of blocks, views....
Method 2:
Let the volunteer register to the website by using the default registration form where only email address and password are required.
And after completion of registration the user will be redirected to create a node of content type "Volunteer" where all the required fields mentioned above will be available.
Also i will use the node limit module to limit the creation of 1 node per content type per user.
And so i will use the "Volunteer" content type to pull out the information requited for the creation of blocks, views....
Which one is the best to go with ?
Are there any limitation for any of the above method in case i need to expand the website in the futur ?
Please note that i know how to do everything mentioned above, only i need suggestion about what method is the best and why ?
Thank you,
Answer: I think there are two more possibilities. One, use social media integration to get as much information as possible to pre-fill the profile. Two, use panels to create a form that will collect a minimal number of required fields from your user profile. Overall, reduce the number of required fields and let users fill out their profiles gradually, with a little nudge from your site. If you ask them to fill out a large number of fields just to get started you may end up with a high form abandonment rate.
I would avoid creating a new Volunteer content type. It may just be my opinion, but I like to follow Occam's razor and avoid the proliferation of entities.
Answer: Please try to use Profile 2 Module or Add fields to default registration form.
When i am facing same issue i tried to create a new content type called "profile" so when user logged in at first time i redirect them to the Profile add form with node limit module and Rules module.
will explain you brief if Profile 2 module will not suit for you.
cheers!


SQL - Select com possível concatenação

Question: Criei uma consulta que faz uma concatenação dos meus resultados. É uma tabela com nomes e a qual faixa (quadrado) elas estão classificadas. A tabela se chama consulta_prontidao e os campos são nome e quadrado:
Select Main.Quadrado,
   Left(Main.Nome,Len(Main.Nome)-1) As "Nome"
From
(
    Select distinct ST2.Quadrado,
        (
            Select ST1.Nome + ','
            From dbo.Consulta_Prontidao ST1
            Where ST1.Quadrado = ST2.Quadrado
            AND ST1.codigoUnidade = 45
            AND ST1.codigoPeriodo = 5
            ORDER BY ST1.Quadrado
            For XML PATH ('')
        ) [Nome]
    From dbo.Consulta_Prontidao ST2
) [Main]

Sendo que eu tenho apenas a opção de 9 quadrados possíveis, a consulta vem assim, por exemplo:

Quadrado | Nomes
-------- | -----
1        | NULL
2        | Maria,Tamiris
3        | Kellen
4        | Elis
5        | Paulo,Alex
6        | Mauro,Rodrigo,Elaine,Gabriela
7        | NULL
8        | Teixeira,Luis
9        | NULL

Mas eu gostaria de fazer um pouco diferente: que houvessem nove colunas de resultado chamadas Quadrado 1, Quadrado 2, Quadrado 3, ... , Quadrado 9. A consulta SELECT viria só com uma linha assim, por exemplo:

Quadrado 1 | Quadrado 2    | Quadrado 3 | Quadrado 4 | Quadrado 5 | Quadrado 6                    | Quadrado 7 | Quadrado 8     | Quadrado 9
---------- | ------------- | ---------- | ---------- | ---------- | ----------------------------- | ---------- | -------------- | ----------
NULL       | Maria,Tamiris | Kellen     | Elis       | Paulo,Alex | Mauro,Rodrigo,Elaine,Gabriela | NULL       | Teixeira, Luis | NULL

Alguém tem ideia como eu posso fazer? Também é uma espécie de concatenação, eu acho. Mas não descobri o melhor modo ainda.
Comment: isso se chama pivot, você pode dá uma olhada nesse link https://www.google.com.br/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=0ahUKEwjx16TG49jRAhXCF5AKHT_RCkoQFggaMAA&url=http%3A%2F%2Fwww.devmedia.com.br%2Fpivot-no-sql-server-invertendo-linhas-e-colunas-em-um-exemplo-real%2F28318&usg=AFQjCNHgEUfsOkw_TNcpiiVUK5do79NqsQ&bvm=bv.144686652,d.Y2I&cad=rja
Comment: De maneira mais clara, deseja transformar linhas em colunas? Acho que tem algo sobre isso aqui no SO. Está usano MySQL?
Comment: Pesquise por PIVOT e CASE , https://learn.microsoft.com/pt-br/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver16 , mas vai precisar também de um STRING_AGG ... https://learn.microsoft.com/pt-br/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver16
Answer: Creio que você queira transformar linhas em colunas. Já existem vários topicos que abordam o mesmo assunto. Veja um deles aqui.
Fiz um exemplo utilizando oracle, que você pode usar como base para seu banco:
create table consulta_prontidao(nome VARCHAR(30), quadrado VARCHAR(30));

insert into consulta_prontidao values ('1', NULL);

insert into consulta_prontidao values ('2','Maria');
insert into consulta_prontidao values ('2','Tamiris');
insert into consulta_prontidao values ('3','Kellen');
insert into consulta_prontidao values ('4','Elis');
insert into consulta_prontidao values ('5','Paulo');
insert into consulta_prontidao values ('5','Alex');
insert into consulta_prontidao values ('6','Mauro');
insert into consulta_prontidao values ('6','Rodrigo');
insert into consulta_prontidao values ('6','Elaine');
insert into consulta_prontidao values ('6','Gabriela');
insert into consulta_prontidao values ('7', NULL);
insert into consulta_prontidao values ('8', 'Teixeira');
insert into consulta_prontidao values ('8', 'Luis');
insert into consulta_prontidao values ('9', NULL);

Depois da tabela montada, basta fazer a concatenação de string (nesse caso, o LISTAGG) junto com o pivot
select * from consulta_prontidao
pivot (
       LISTAGG(quadrado, ',') WITHIN GROUP (ORDER BY quadrado)
       for nome in ('1'  as QUADRADO_1,
                    '2'  as QUADRADO_2,
                    '3'  as QUADRADO_3,
                    '4'  as QUADRADO_4,
                    '5'  as QUADRADO_5,
                    '6'  as QUADRADO_6,
                    '7'  as QUADRADO_7,
                    '8'  as QUADRADO_8,
                    '9'  as QUADRADO_9
      ));

Resultado

EDIT:
Aparentemente você trabalha com MySql, então sugiro a utilização do GROUP_CONCAT()
Ficando assim:
select * from consulta_prontidao
pivot (
       group_concat(quadrado ',')
       for nome in ('1'  as QUADRADO_1,
                    '2'  as QUADRADO_2,
                    '3'  as QUADRADO_3,
                    '4'  as QUADRADO_4,
                    '5'  as QUADRADO_5,
                    '6'  as QUADRADO_6,
                    '7'  as QUADRADO_7,
                    '8'  as QUADRADO_8,
                    '9'  as QUADRADO_9
      ));

Não tenho como testar nesse momento a implementação no MySql. Teste e avise se tiver problema que eu dou um jeito de corrigir.
Em SqlServer 2016 utilize STRING_AGG:
select * from consulta_prontidao
pivot (
       STRING_AGG (quadrado, ',')
       for nome in ('1'  as QUADRADO_1,
                    '2'  as QUADRADO_2,
                    '3'  as QUADRADO_3,
                    '4'  as QUADRADO_4,
                    '5'  as QUADRADO_5,
                    '6'  as QUADRADO_6,
                    '7'  as QUADRADO_7,
                    '8'  as QUADRADO_8,
                    '9'  as QUADRADO_9
      ));

Comment: Não, eu trabalho com SQL Server nesse site. Não é MySQL.
Comment: Adicionei um exemplo utilizando `SqlServer`

SQL - Select com possível concatenação


Fitting a sinusoidal function to three known points separated by $30$ degrees

Question: I have three data points measured at $-30$, $0$, and $30$ degrees, respectively. I would like to fit these points to a sinusoidal function of the form:
$$f(\theta)≈A\sin(\theta + B) + C$$
Is this possible? If so, what would be the best approach?
I saw a similar post here, however this assumed that the measurements were $90$ degrees apart which helps to simplify things greatly.
Thanks,
Answer: Yes, of course it is possible. Proceed in the following way:
Let the three values at $-30,0,30$ be $y_1,y_2,y_3$ repec. Then you get three equations in $A,B,C$ \begin{equation}
\begin{split}
A\sin (-30+B)+C=&y_1\\
A\sin (B)+C=&y_2\\
A\sin (30+B)+C=&y_3
\end{split}
\end{equation}
From the first and last equation, after some trigonometric manipulation you get $$2A\sin B \cos 30=y_3-y_1\Rightarrow A\sin B=\frac{y_3-y_1}{\sqrt{3}}$$
Then from second equation you get $$C=y_2-\frac{y_3-y_1}{\sqrt{3}}$$
Now from the last equation you get after using the $\sin(A+B)$ expansion formula $$A\sin B \cos 30+A\cos B \sin 30=y_1\\ \Rightarrow \frac{(y_3-y_1)}{2}+\frac{A\cos B}{2}+y_2-\frac{y_3-y_1}{\sqrt{3}}=y_3$$ So you can find $A\cos B$ from here. So, now you can use $\displaystyle \sin^2B+\cos^2 B=1$ to get $$A=\sqrt{(A\sin B)^2+(A\cos B)^2}$$ Once you get $A$, then you can get $B$ from $$B=\tan^{-1} \left(\frac{A\sin B}{A \cos B}\right)$$ restricting $B$ in $[-\pi/2,\pi/2]$, you can get $B$.
Note: This procedure is valid for arbitrary angles, they need not be necessarily $30^\circ$ apart.
Comment: Great! Thanks! This works perfectly.
Comment: Welcome! @user1799178
Comment: I'm trying to generalize this to arbitrary angles (say $ \theta_1 , \theta_2 & \theta_3 $ ), but am having trouble figuring out those initial "trigonometric manipulations" in the general case. I think you're using a sum expansion and a sum-to-product formula, but I'm getting bit different result. Mind expanding a little?
Comment: @GabrielGrant, just write the three equations with $\theta_1,\ \theta_2,\ \theta_3$ and use the expansion formula for $\sin(\alpha+\beta)$ for equations $(1),(3)$ and subtract them, then you'll get an expression for $\tan B$ which, along with, $(1),(2)$ will give you solutions for $A,B$
Answer: First try to fit $f(\theta) = a\sin\theta+b\sin \theta+c$ (three linear equations in three unknowns), then use $\sin(\theta+B)=\cos B\sin\theta+\sin B\cos\theta$ to bring this into the form desired.


Where did I go wrong computing the cross product

Question:
If $u=(-2,0,\sqrt2)$ and $v=(0,-4,-\sqrt2)$, then $u\times v=(2\sqrt2,-\sqrt2,8)$.

I got $(4 \sqrt2, 2\sqrt2,0)$ for the cross product but the answer is saying I'm wrong and I don't know why
Answer: The correct answer is that
$$ (-2,0,\sqrt{2}) \times (0,-4,-\sqrt{2}) = (4\sqrt{2}, -2\sqrt{2}, 8) \,. $$
Since you have not written out your calculation, there is no way for us to know where you got it wrong.
Comment: I realized where i went wrong with the 8 I accidentally put 0 in the question when I had got 8 in my working out it was just the first part of the vector confusing me how in the answer sheet its 2root2 but I got 4root2


Help with event signup module

Question: I'm looking for a module that allows registered users to signup to events with a few options. I found the "Signup Module" but I can't figure out how to make it work, at least to try it out. So two questions:

Does the Signup Module allow for getting different input depending on the event type? For example, if an event is a dinner, I would need to get the menu choice and any dietary requirements.
If the above is a yes, how can I make it work? I can't find much documentation around and I'm still a Drupal newbie. If the above is no, can you please recommend a more adeguate module?

Thanks in advance for any hints!
Answer: I think you can use the Signup Module for this. The Signup form itself can be modified and changed for your needs. Have a look at the file signup_form.inc in the signup/theme folder. Copy the theme_signup_user_form($variables) function to your template.php in your theme and start modifying the form.
Comment: Great, this seems like the way to go. The only problem is that I have to modify the file every time the event type changes, in order to present the correct fields. Any workarounds?
Comment: Do you have different Content Types which are allowed to signup or do you have one Content Type which you modify for an Event? Or what do you mean by "event type changes"?
Comment: Different event types require different fields. For example, a dinner event requires a "menu type" select box, while a talk event doesn't.
Comment: OK, but then you create different content types. Then you check on the form what content type the signup belongs to and modify the form output as needed.
Comment: Alright! One last thing: how do I check the content type?
Comment: You should find the node type in the $variables array. Check the comments of this function.
Answer:
Install Date module
Create a content type "event" and add a date field.
Go to admin/structure/types/manage/your_content_type and in the
SignUp settings select enabled and for the Date field to use with
signup choose the one you have in your content type.
The options in the menu admin/config/people/signup are pretty
straightforward.
Create some content for your event content type to see the behaviour
of signup

That along with signup documentation should be enough to test the module.

Help with event signup module


Is perceived progress in singing performance necessarily a good indicator of the quality of the teaching method?

Question: I'm taking singing lessons from a few teachers; I am trying to figure out, in a reasonable way, which teacher to stick with.
I'm in a situation though, when I don't have a way to evaluate the quality of the teacher (eg. credentials, renowned school, etc.).
Generally speaking, is perceived progress in singing performance necessarily a good indicator of the quality of the teaching method?
I have experience in other fields (eg.) sports, but progress doesn't always implies learning a correct structure (eg., in a given sport, one may increase strength, but not technique, and lead to the false impression that the increase in performance is appropriate).
How easy is to develop "hidden" or subtle bad habits, in singing?
If I (perceivedly) improve using a given method, is that a good enough reason to stick with it?
Answer: This is very subjective. The quality of a particular teaching method is only one factor. It may be very good quality but not necessarily suit all students, or teachers, for that matter. Teachers of experience will have developed their own strategies (hopefully) and so be able to adapt to the individual pupils. So there may not even be what you call a 'quality method' that fits all.
Your 'perceived progress' is rather dependent, too. It may well not only be the method one teacher uses, but the personal reaction between the two of you. If it's good, you'll want to do more, and the progress will be better. How that progress is quantified is another issue. Just feeling that you're getting better is o.k., but it's not much of a yardstick.
Taking exams is the tried and tested method to check progress, but in your case, that's not easy with several teachers. Which one was most responsible for your pass? Who knows!
How would you know that a particular method works best? Maybe stick with only one for a few months, recording yourself regularly. Listen back to judge improvements. Then try another, then another. But time is passing by. If you have the time to do all that each tutor is asking of you, keep going to all, and use what you consider the best bits from each. I don't think there is an absolute answer to your question in the circumstances.
Comment: ok, I understand that examining the "end result" of the voice is crucial regardless of the methodology.


Intermediate steps to illustrate No-Ponzi condition for budget constraint of infinite horizon model (Ramsey Model)

Question: I am reading Chapter 8 (Ramsey Model) of Introduction to Modern Economic Growth by Daron Acemoglu.
At section 8.1 (page 377), the text introduces a boundary condition for infinite-horizon case, known as No-Ponzi condition. It provides the outline of derivation to illustrate that the boundary condition is necessary, but I am not sure about the intermediate steps (which I appended below).
May I ask how to derive the RHS of equation from the LHS of equation please?
$$\int_0^T c(t) * e^{nt} * e^{-\int_0^t r(s) ds} dt = \int_0^T c(t) * e^{-\int_0^t (r(s) - n) ds} dt$$
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: Use $e^a e^b = e^{a+b}$ and $nt = -\int_0^t -n \; ds$
Answer: $$
\int_0^T c(t) e^{nt} e^{-\int_0^t r(s) ds} \; dt = \int_0^T c(t) e^{-\int_0^t (r(s) - n) ds}  \;dt
$$
using $e^a e^b = e^{a+b}$
$$
\int_0^T c(t) e^{nt-\int_0^t r(s) ds} \; dt = \int_0^T c(t) e^{-\int_0^t (r(s) - n) ds}  \;dt
$$
$$
\int_0^T c(t) e^{\int_0^t n \; ds-\int_0^t r(s) ds} \; dt = \int_0^T c(t) e^{-\int_0^t (r(s) - n) ds}  \;dt
$$
$$
\int_0^T c(t) e^{-\int_0^t -n \; ds-\int_0^t r(s) ds} \; dt = \int_0^T c(t) e^{-\int_0^t (r(s) - n) ds}  \;dt
$$
because integration is a additive operation, for well behaved integrands we can merge the integrals
$$
\int_0^T c(t) e^{-\int_0^t (r(s) -n) \; ds} \; dt = \int_0^T c(t) e^{-\int_0^t (r(s) - n) ds}  \;dt
$$


Guitar scales further up the fret board

Question: I'm hoping someone can help me. Ι've been playing guitar for a while and mostly kept myself confined to chords/rηythm, but now I want to explore some lead styles to add to my skills.
So I began with some scales - I don't really read music or study theory, so I know my chords mainly by shape - and the same with scales, I know the 'shape' of a basic major scale using open strings and 2nd/3rd/4th fret (I don't even know what key thats in, but hey!).
I also know a basic pentatonic shape (on 5-8, 5-7, 5-7, 5-7, 5-8, 5-8) which I know is A Minor because I looked it up, so that I could play along with one of my favourite songs.
I seem to have run out of notes however, once i'm on the 8th fret on the last string, I want to go a bit higher to add some more variation, but I don't know where to take it / which notes are right, and I can't seem to find a resource online (that doesn't want to charge me at least) to just tell me how to continue the scale i'm playing in different positions.
Can anyone show me a good resource, or offer me handy tips on how to work it all out?
Comment: I won't answer because the correct answers are already up there, but I think it is self-evident that there is a lot of overlap and repetition of the notes on the strings of the guitar (5-8,5-7 is the same as (5-8-10-12). Once one realizes this, one can find virtually the same order of notes in different pattern shapes at different points in the guitar. Once you hit 12th fret, you are "back at the nut" and the patterns all repeat.
Comment: i think what is actually needed (and I fell down this same rabbit hole) is to learn to connect those shapes, rather than to see them as a fixed pattern of boxes with overlaps try this guy's view https://lincolnmckenzie.com/the-pentatonic-scale-part-3-slides/
Answer: There are a bunch of answers already on this website which will help you; what you are looking for is how to play pentatonic modes (as a starter).  A mode is a scale which begins on some interval of a scale and ends on its corresponding interval an octave higher (containing only the notes in the original scale but starting and ending on a different interval).
Your example is A minor, the notes of the A minor pentatonic scale are:
A - C - D - E - G
With that in mind consider these modes of the A minor pentatonic:
Playing through from A  (the one you already know)
<code>$6.5  $6.8  $5.5  $5.7  $4.5  $4.7  $3.5  $3.7  $2.5  $2.8  $1.5  $1.8
</code>
From C
<code>$6 8 10  $5 7 10  $4 7 10  $3 7 9  $2 8 10  $1 8 10
</code>
From D
<code>$6 10 12  $5 10 12  $4 10 12  $3 9 12  $2 10 13  $1 10 12
</code>
From E
<code>$6 12 15  $5 12 15  $4 12 14  $3 12 14  $2 13 15  $1 12 15
</code>
From G
<code>$6 15 17  $5 15 17  $4 14 17  $3 14 17  $2 15 17  $1 15 17
</code>
Then from here, you are back to your original shape an octave higher, starting on the 17th fret.
After learning all the in between shapes you should be able to creatively traverse the neck in a particular key without too many problems.  Remember that on the guitar the shapes never change, but the key you are in might.
So if you needed to use B minor pentatonic, you would apply the same shapes but starting on B - D - E - F# - A respectively.
When practicing the shapes i would suggest using a backing track and try playing the different shapes over different chords and see how they sound.

Additional useful reading on this site:
What is the first scale to learn on the guitar
Hand position while practising scales
What are modes and how are they useful
Also check out Dave Weiner's Youtube channel for excellent free lessons from an awesome player, he has sections on there covering modes, pentatonics and a bunch of other stuff.
Answer: You need to start learning music theory.  Learning about notes and scales won't take you very long at all, and instead of needing to buy chord books and struggle with trying to figure out what shapes/positions sounds good, you'll already know.  Continuing a scale higher up the neck will be dead simple if you just put a little time into learning the basics.
Another good answer that talks about this: Are there any books or videos out there that teach you SLOWLY and do not focus on learning TABS?
Comment: I did a whole 24 week 'beginner' community course at the dedicated music college a year or so ago.  While it definately helped me - with the introduction to scales, a bit of feedback, there were parts which didn't quite sink in - i'm one of those people that finds it easier to try stuff first, and then work out 'why' it is later.  Backwards, I know - but thats just me!
Answer: Get this book. It's $20 and it has every scale imaginable, with exercises to help learn them. It's crazy good. You can order it from their website, from Amazon, or pick it up at guitar center.
P.S. - I own this book and the rest of their guitar series, so I'm speaking from experience.
Comment: As great a tool a good scale compendium can be, I would not recommand any of them to a beginner. It's way too easy to be intimidated, confused and lose the musicality of it all. My advice :  at the very least learn the patterns and sound of the pentatonics before delving into that.
Answer: As a sidenote to position playing (and the good, accpeted answer), don't forget that in standard tuning an octave is two strings up and two (until the G string) or three frets away.
...Which means that any two-string pattern can be repeated, in the case of pentatonics either by learning full pentatonics on two strings (warm up your pinky) or by sliding into the next position. It will help you move from position to position confidently.
Answer: Kipper, you're at a great spot now. There's alot to discover and it will all be fun and hard work - but worth it.
Learning theory will help - definitely, but you said it: "I'm one of those people that finds it easier to try stuff first".
High Level summary of what can help:

ABSOLUTELY know all your first position chords and barre chords.
MUST MUST MUST!
Learn the CAGED system (this will lead to Point #3)

Don't get too hung up on this.  You can revisit this. Just get the basics.  (side note: I am writing an article about this as it's been asked so many times but the Google answers I get are all the same and seem to answer it in isolation to everything else on the guitar)
Tip. You don't have to start with C to use CAGED.  ie.  Start with the E and move to D then C then A then G then E (octave 12th fret) then D then C etc etc until you run out of frets!)
By knowing CAGED and CAGED+ (my term for the various sub/part shapes eg. D shape related to C shape using the D/G/B strings) you can expand on the notes you are able to include in your solos.
If you started with the A minor Pentatonic, fantastic!
Instead of playing the scale in a box from E string to E string on frets 5 to 8.... see if you can do a Blues Run beginning from 3rd fret, 6th string and work your way up by playing the following sequence on the following strings:
 - (6th) 2 notes
 - (5th) 3 notes [slide from fret 5 to 7]
 - (4th) 2 notes
 - (3rd) 3 notes [slide from fret 5 to 7]
 - (2nd) 2 notes
 - (1st) 3 notes [slide from fret 8 to 10] and the go backwards
This should form a diagonal pattern that goes from lower bass strings to higher treble strings but gradually goes up the neck.
Sorry I can't post a tab for this right now but I may do in the near future.

Guitar scales further up the fret board


On two conceptions of measurability

Question: This is a very broad question about two conceptions of a measurable function. Let $(X, \mathcal X)$ be a measurable space, and let $f$ be a real-valued function of $X$. Throughout the post, I assume that $\mathbb R$ is equipped with its Borel $\sigma$-field.
According to the standard conception of measurability, which I'll call the measure-theoretic conception, $f$ is measurable just in case $\{x: f(x) \leq r\} \in \mathcal X$ for every $r \in \mathbb R$. (There are several well known equivalents of this definition of course. The one that carries over to arbitrary measurable spaces is: $\{x: f(x) \in B\} \in \mathcal X$ for every Borel subset $B$ of $\mathbb R$.)
Why is this a natural definition? In measure theory we want to "ask questions" about $f$ and "answer" them using a measure $\mu$ on $(X, \mathcal X)$. For instance, we might want to ask, How big is the set of points on which $f$ vanishes? In other words, we want to evaluate
$$\mu\big(\{x: f(x) = 0\}\big).$$
And in order to do that, we of course need the set $\{x: f(x)=0\}$ to be in the domain of $\mu$. The measure-theoretic conception ensures that this is the case.
There's another conception of measurability that isn't motivated by thinking about measures. I'll call this conception information-theoretic (perhaps there's a better name for this; this is just the first thing that came to mind). The information-theoretic conception is often used in probability texts as a heuristic for thinking about conditional expectations (for example, see Probability and Measure by Billingsley).
On the information-theoretic conception, we start by thinking of $X$ as a state of uncertainty. To be more concrete, think of $X$ as the unknown outcome of some experiment. A $\sigma$-field $\mathcal X$ on $X$, then, is thought of as "partial information" about the experimental outcome. The idea is: if you "know the information in $\mathcal X$", then, for every $A \in \mathcal X$, you can say whether or not the actual experimental outcome is in $A$.
A function $f$ is measurable on this conception if it is "determined by" or "a function of" the information in $\mathcal X$. How to make this idea precise?
Start with the simplest kind of $\sigma$-field, namely one generated by a finite partition. The obvious way of formalizing the assertion "$f$ is determined by the information in $\mathcal X$" is then:

$f$ is constant on the cells of the partition that generated $\mathcal X$. In other words, if $\mathcal P$ is the finite partition that generates $\mathcal X$, we say that $f$ is measurable in the information-theoretic sense just in case for all $A \in \mathcal P$ and all $x,y \in A$, $f(x)=f(y)$.

There is a straightforward way of generalizing this conception of measurability to arbitrary $\mathcal X$. First, call $a$ an atom of $\mathcal X$ if for some $x \in X$, $a = \bigcap_{x \in A \in \mathcal X}A$. Note that atoms of $\mathcal X$ are not generally members of $\mathcal X$ because they are defined using intersections that are potentially uncountable. Note also that if $\mathcal X$ is generated by a finite partition, then the atoms of $\mathcal X$ are precisely the cells of the generating partition. Generally, then, we have the following definition.

$f$ is measurable in the information-theoretic sense just in case it is constant on the atoms of $\mathcal X$, i.e. for all atoms $a$ of $\mathcal X$ and all $x,y \in a$, $f(x)=f(y)$.

My main question is:

What happens to measure theory if we use the information-theoretic conception of measurability instead of the usual measure-theoretic one? Are there any advantages to doing this? Or do certain important results break down?

Also:

If $\mathcal X$ is countably generated, then every atom of $\mathcal X$ is a member of $\mathcal X$. In this case, I believe the two conceptions of measurability coincide. Is that right?

If so, in order to tease apart the two conceptions of measurability, we will need to consider measurable spaces that aren't countably generated.
Answer: Let $\left(\mathbb{R},\mathcal{B}(\mathbb{R})\right)$ be the standard (Borel) measurable space. Then it is countably generated (by family of open intervals with rational endpoints). Moreover, the family of its atoms consists of all singletons of $\mathbb{R}$ and they are members of $\mathcal{B}(\mathbb{R})$.
This implies that the class of information-theoretic measurable functions on $\left(\mathbb{R},\mathcal{B}(\mathbb{R})\right)$ coincides with the class $\mathrm{Map}(\mathbb{R},\mathbb{R})$ of all functions. It also provides negative answer for your second question.

On two conceptions of measurability


lxc bandwidth control using tc

Question: I am trying to restrict bandwidth inside my containers.
I have tried using the following commands , But I think it is not getting effective.
cd /sys/fs/cgroup/net_cls/
echo 0x1001 > A/net_cls.classid   # 10:1
echo 0x1002 > B/net_cls.classid   # 10:2
tc qdisc add dev eth0 root \
           handle 10: htb
tc class add dev eth0 parent 10: \
           classid 10:1 htb rate 40mbit
tc class add dev eth0 parent 10: \
           classid 10:2 htb rate 30mbit
tc filter add dev eth0 parent 10: \
           protocol ip prio 10 \
           handle 1: cgroup

Here A and B are containers created with this command.
lxc-execute -n A -f configfile /bin/bash
lxc-execute -n B -f configfile /bin/bash

Whereas configfile contains only this entry:
lxc.utsname = test_lxc

AFter starting the container , I have started vsftpd inside container A and try to access the files using the ftp client from another machine.
Then I killed vsftpd in container A and started vsftpd in container B and try to access the files using ftp client from another machine.
I cannot observe any difference in performance, for that matter it is nowhere nearer to 40mbit/30mbit.
Please correct me whether anything wrong here.
Answer: The problem here is not well documented but I've experienced it before.
On 64 bit systems, the value you echo is not represented as a 16bit integer but a 32bit integer.
Try replacing:
echo 0x1001 > A/net_cls.classid   # 10:1
echo 0x1002 > B/net_cls.classid   # 10:2

With
echo 0x00100001 > A/net_cls.classid   # 10:1
echo 0x00100002 > B/net_cls.classid   # 10:2

This should fix your problem.
Note: Its not actually necessary to provide the leading zeroes at the start but for clarity I added them.
Answer: Many of the non-hypervisor containers (lxc, jails) tend to have dodgy/incomplete metering (disk iops, net) that impacts other containers.  If limiting external transit is the main concern, stick a transparent firewall (i.e., ArmorLogic, Barracuda, etc.) in front of these first.
In any case, definitely load test to see if it makes a difference.
(ProTip: Heroku runs LXC.  heroku run bash)

lxc bandwidth control using tc


Expected length of randomly generated decreasing sequence

Question: Let $p_0\in(0,1)$ and let $s>0$. Consider the sequence with terms $p_k$ generated randomly as follows:
$$
p_{k+1}=\left\{
\begin{array}{ccl}
p_k & \mbox{if} & r_k\leq p_k\\
p_k-s & \mbox{if} & r_k > p_k
\end{array}
\right.,
$$
where $r_k\in[0,1]$ is uniformly randomly chosen at each step. We stop whenever $p_k\leq 0$.

What is the expected length of the generated sequence (taking $p_0$ as
  the first term and the last strictly positive $p_k$ as the last term)?

I can make some simulations and some computations by hand, but I don't really know about any more sophisticated tool to approach such questions. I'm doing this for fun, so any help that might make me learn new stuff will be very welcome.
Answer: You can use linearity of expectation. Let $q_0 = p_0, q_1 = p_0-s, q_2 = q_1-s$,... $q_l = q_{l-1}-s$ where we stop so that $q_l-s < 0$. Note this is a pre-determined, deterministic sequence. The expected number of times we see $q_j$ arise in the sequence $(p_0,p_1,\dots,p_k)$ is $\frac{1}{1-q_j}$, so the expected value of $k$ is $\sum_{j=0}^{l-1} \frac{1}{1-q_j}$.
Comment: Thanks for your answer: I made some computations and it looks like the -1 should not be there (meaning that the expected length is $\sum_{j=0}^{l-1}\frac{1}{1-q_j}$ instead). Do you agree?
Comment: I debated putting the $-1$ there. If $q_j = \frac{1}{2}$, then the expected number of times we see $q_j$ should be 1 rather than 2, no?
Comment: Ohhh, nevermind. We see $q_j$ at least once just automatically. Then the expected number of times we see it again is $\frac{1}{1-q_j}-1$, so the total is $\frac{1}{1-q_j}$. I'll edit my answer.
Comment: Great. I already accepted your answer. I like to write $p_0-js$ instead of $q_j$ and $\lfloor p_0/s\rfloor$ instead of $l-1$ (although one should be careful here because we have to take $\lfloor p_0/s\rfloor-1$ when $s|p$) to better reflect the dependancy on $p_0$ and $s$.


Java - Sorting a String array by word length

Question: I need to sort the String array into least to greatest order by wordlength. I then need to print out the words next to their value.
Example Output:
1: I, U, K
6: Joseph, Delete
But I need help sorting the array first.
Code:
package Objects;

import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.lang.Object;

public class WordLength {

public static void main(String[] args) throws Exception{

    Scanner scan = new Scanner(new File("wordlength.dat"));
    int thresh = scan.nextInt();   //Scans the first integer
    String[] array = new String[thresh];   //Creates an empty array with length of the threshold

    for(int i = 0; i < array.length; i++) {
        array[i] = scan.nextLine();

        /* I need to sort the array from least to
        greatest here so I can use the if statement
        below.
        */

        //Prints the word array from least to greatest by length
        if(array[i].length() == i) {
            System.out.print(i + ": " + array[i]);
        }
    }
}

}
Comment: Use Java Comparator for this.
Answer: You can use a custom comparator to sort the String array. For example
        String [] arrr = {"World","Ho","ABCD"};
        Arrays.sort(arrr,new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        System.out.println(arrr[0]); \\ Output Ho

Answer: One of Arrays.sort overloads accepts Comparator as the second parameter, in which you can implement your own custom comparison function to determine whether a string should be placed before or after another simply by implementing the compare method.
Answer: I don't code in Java, but would this pseudocode work?
Grab the list of words.
Loop through them.
   Get the length of the current word.
   Add that word to that array number:  a 5-letter word would go in array element 5.
Continue the loop until all the words have been added to the proper array.
Display each of the array elements.

Comment: Downvoter, this works in other languages. What's the problem with Java?


Insert several lines in field collection programmatically

Question: I have a problem with field collection and entity reference fields. I have a field collection called 'field_co_intervenant' and i want to add several entities in this field collection and after saved my node. But i got an error with the index i think, because when the node is saved, there is just one reference entity in my field collection. You can see the code here :
$intervenant is the array of my 'nid'.
if(!empty($intervenant)) {
    //Create entity
    $fieldcollection = entity_create('field_collection_item', array('field_name' => 'field__doc_fc_intervenant_tab'));
    //Attach entity
    $fieldcollection->setHostEntity('node', $node);
    //Fill field
    $i = 0;
    foreach ($intervenant as $val) {
        if($val != null) {
            $fieldcollection->field_fc_intervenant_tab[LANGUAGE_NONE][$i]['target_id'] = $val;
            $i++;
        }
    }

    //Save entity
    $fieldcollection->save();
}

How can i save all my values in the field collection and not just one ?
Thanks
Answer: First be sure that that field in your field collection field setting accept multi value then try save your item with
  $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,);

and finally be something like
if(!empty($intervenant)) {

    // you should have $node here
      $field_collection_item = NULL;
      $field_collection_item = entity_create('field_collection_item', array('field_name' => ''field__doc_fc_intervenant_tab '));
      $field_collection_item->setHostEntity('node', $node);
      $field_collection_item->save(TRUE);
          foreach ($intervenant as $val) {
             if($val != null) {
      $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
        'revision_id' => $field_collection_item->revision_id,);
}
}
    $fieldcollection->save();
}

Comment: @Remi you're welcome ;) +1 it :D


Prove that $p(x)$ is a irreducible in $A[x]$.

Question:
Let $A$ be an integral domain. Let $P$ be a ideal prime of $A$ and $p(x)\in A[x]$ be a monic polynomial
  $$p(x)=x^{n}+a_{n-1}x^{n-1}+\ldots+a_1x^{}+a_0$$
Assume that all the coefficients $a_i\in P$ but $a_0\notin P^2$. Then $p(x)$ is a irreducible in $A[x]$.

any suggestions please.
Comment: I think you mean $I$ instead of $P$. This result is know as "Eisenstein criterion". Look it up. Or try looking at what happens modulo $I$
Comment: You may want to google "Eisenstein Criterion"
Answer: Consider a reduction $p(x)=q(x)h(x)$. Then we note that since $P$ is prime, $A/P$ is an integral domain, so that $A/P[x]$ is to. Now let $\bar{p}(x)=\bar{q}(x)\bar{h}(x)$ be the image in $A/P$. We have $\bar{p}(x)=x^n$, so that $\bar{q}(x)=x^m$ and $\bar{h}(x)=x^{n-m}$, since if they had any lower, nonzero terms, there product would yield a nonzero term in $\bar{p}(x)$ of sub-maximal degree. Namely, if we assume that $n-m, m>0$, then we have that the constant terms of $q(x)$ and $h(x)$ are in $P$, so that the constant term of $p(x)$, which is the product of constant terms in $q(x)$ and $p(x)$, is in $P^2$, a contradiction.


Estou tentando tirar o box-shadow do meu accordion-item, mas não consigo

Question:

.col-flex {
  display: inline-block;
}

.accordion-item {
  box-shadow: none !important;
}

.button1 {
  text-transform: uppercase;
  font-family: 'Arial';
  font-weight: 500;
  padding-left: 2rem;
  padding-right: 2rem;
  color: var(--primary);
}

.button-bol {
  background-color: transparent;
  border-color: #84C226;
}

.button-bol:focus {
  background-color: transparent;
  border-color: #84c226;
  color: #808191;
  box-shadow: 2px 2px 10px #84c226;
}

.button-bol:hover {
  background-color: transparent;
  border-color: #84c226;
  box-shadow: 2px 2px 10px #84c226;
}

Boletim Informativo

    <button class="btn btn1 button1 button-bol col-5" data-bs-toggle="collapse" href="#collapse8" role="button" area-expanded="false" aria-controls="collapseExemple">Agosto - 2021</button>
    <button class="btn btn2 button1 button-bol col-5" data-bs-toggle="collapse" href="#collapse7" area-expanded="false" aria-controls="collapseExemple">Julho - 2021</button>

Eu quero tirar essa linha que esta abaixo dos buttons. a linha fica assim quando os buttons não esta ativo

Nessa imagem da pra ver as imagens dentro do button collapse. Não estou conseguindo anexar as fotos para ver melhor no codigo
Comment: no HTML que você partilhou não aparece essa linha. Não consegue postar mais codigo e imagens que funcionem para vermos melhor?
Comment: vou tentar postar ele todo
Comment: sou nova nesse site, e estou apanhando tentando colocar o codigo com as imagens.
Answer: A linha cinza abaixo dos botões está na div que tem a classe "accordion-item", você pode escondê-la sobrescrevendo esta regra css:
.accordion-item {
  border: 0 !important;
}

Lembrando que essa regra css vai sobrescrever todos os elementos que tiverem esta classe, o ideal seria definir uma classe em alguma div mais acima deste item, neste caso ficaria algo assim:

  ...

.accordion-modificado .accordion-item {
  border: 0;
}

Comment: Funcionou Diego, muito obrigada.


Pegar valor de um atributo na td

Question: Eu tenho uma tabela dinâmica onde existe 9 colunas
Em uma das últimas colunas existe um botão de reprovação, e quando eu clicar nele, queria pegar o nome que está dentro de uma td na mesma tr dinamicamente.
SCRIPT
    $(document).on("click", ".btn-danger", function(){
        var nomePessoa = $(this).parent().parent().find("td").attr("nomePessoa");
        alert(nomePessoa);
    });

TABELA
Comment: Acho que usar `.closest('tr')` é mais seguro do que `.parent().parent()` n vezes.
Answer: Para utilizar um atributo "personalizado" você deve utilizar o data-, montei um exemplo para você entender melhor.
HTML

        Nome attr data-
        <button class="btn-danger">Recuperar nome</button>

Note que criei o atributo data-nome será onde iremos armazenar o nome para capturar depois com o JQuery (código abaixo).
JQuery
$(function(){
    $(document).on('click', '.btn-danger', function(e) {
        e.preventDefault;
        var nome = $(this).closest('tr').find('td[data-nome]').data('nome');
        alert(nome);
    });
});

Créditos ao Sergio (otimização do código)
Você pode ver o exemplo funcionando nesta DEMO
Comment: @Sergio muito obrigado pelo toque, código alterado.
Comment: Bem útil esta informação.
Comment: Diego, já que a sua resposta foi a aceite, se concordar mude/adicione `.closest('tr')` em vez de `.parent().parent()`. Assim evita uma chain de `.parent()` _n vezes_ e a resposta fica melhor a meu ver. Outro problema que tem na sua resposta/exemplo é que ele não funciona com a tabela que o Tafarel mostrou. Se adicionar a primeira coluna que ele mostra o seu código não funciona (http://jsfiddle.net/4ZEx2/1/). Mas se usar `.find('td[data-nome]')` ai já vai funcionar bem (http://jsfiddle.net/4ZEx2/2/). Aí a minha sugestão seria assim: http://jsfiddle.net/4ZEx2/3/
Answer: Consegui resolver colocando ao invés de um atributo, uma classe chamada "nome" no td com a informação de pessoa. O código ficou da seguinte forma:
    $(document).on("click", ".btn-danger", function(){
        var nomePessoa = $(this).parent().parent().find(".nome").text();
        alert(nomePessoa);
    });

Answer: Sugiro usar o .closest('tr') para subir no DOM até ao
 e depois usar o .find('td[nomePessoa]) para encontrar somente tdcom um atributo "nomePessoa".
Assim:
$(document).on("click", ".btn-danger", function () {
    var nomePessoa = $(this).closest('tr').find('td[nomePessoa]').attr('nomePessoa');
    alert(nomePessoa);
});

Deixo também um conselho, que é uma norma adotada na comunidade, use campos data-. Assim o seu código HTML seria <td data-nomePessoa="Antonio" ... etc e no javascript/jQuery .data('nomePessoa')em vez de .attr('nomePessoa')
Answer: Gostei da resposta do Diego Vieira(+1) pois não conhecia esse atributo data-qualquercoisa que pode ser criado.
No entanto, fui por um caminho diferente, pois vi que o nome já se encontrava escrito dentro da td e fui tentar pegá-lo com innerHTML. Não consegui com o código utilizado pois trata-se de um objeto JQuery e não é assim com .innerHTML que funciona a manipulação com Jquery. O Jquery cria um encapsulamento para conteúdo que é diferente de usar elemento = document.getElementById("iddoelmento");.
Daí me surgiu uma curiosidade: Como poderia fazer para pegar os nomes das propriedades e métodos de objetos de qualquer natureza, seja jquery ou não? Descobri a existência do Object.getOwnPropertyNames(nomedoobjeto) ao pesquisar no Stack Overflow em inglês.
No teste em questão o objeto localizado com Jquery tinha as seguintes propriedades:
 0,1,length,prevObject,context,selector
Comecei testando o 0 e era o elemento que precisava. tdobj[0].innerHTML retorna o conteúdo da célula localizada.
Gostaria de compartilhar a experiência, segue o código executável abaixo.

$(function(){
    $(document).on('click', '.btn-danger', function(e) {
        e.preventDefault;
        //tdobj = $(this).parent().parent().find('td');
        tdobj = $(this).closest('tr').find('td');

        // lalala = Object.getOwnPropertyNames(tdobj);
     // alert(lalala);
        //  0,1,length,prevObject,context,selector

        alert("[0]: "             + tdobj[0]);
        alert("[0].innerHTML:\n"  + tdobj[0].innerHTML);

        alert("[1]: "             + tdobj[1]);
        alert("[1].innerHTML:\n"  + tdobj[1].innerHTML);

        alert("length: "     + tdobj["length"]);

        alert("prevObject: " + tdobj["prevObject"]);

        alert("context: "    + tdobj["context"]);

        alert("selector: "   + tdobj["selector"]);

    });
});

        Teste Nome do Cara
        <button class="btn-danger">Recuperar nome</button>

Referência: https://stackoverflow.com/questions/2257993/how-to-display-all-methods-of-an-object-in-javascript?answertab=active#tab-top
Answer: Eu consegui retornar o resultado de uma forma mais simples.
determina um id dentro de cada  e utiliza a função .text().
var tamanhopage = $("#tamanhopage").text();
Valor.
Funcionou pra mim aqui! Boa Sorte.
Comment: Agradecemos sua vontade de compartilhar conhecimento, mas isso não responde à pergunta. Sendo um usuário novo, recomendo que comece fazendo o [tour] para conhecer melhor o sistema. Em respostas futuras, tente explicar melhor o desenvolvimento, explicando o que cada função faz e, de preferência, citando a fonte das mesmas na documentação.

Pegar valor de um atributo na td


Geometric intuition behind inverse matrix restrictions

Question: We know that for an invertible matrix $A$, $A^{-1} = \frac{\mathrm{adj}(A)}{\det{(A)}}$. We can see algebraically that this is undefined when $\det(A)=0$, but it is cryptic what this means geometrically. Is the following intuition valid? This is not meant to be rigorous.
Define a matrix $A:\mathbb{R}^n \rightarrow \mathbb{R}^{n}$ (e.g. mapping 3D space onto the X-Y plane). Because this maps the $n$-dimensional parallelepiped such that it does not occupy the $n$-th dimension, it's $n$-dimensional "volume" is $0$. Hence, $\det(A)=0$. Now, define another matrix $T:\mathbb{R}^{n-1}\rightarrow\mathbb{R}^{n-1}$ that maps the $(n-1)$-dimensional parallelepiped such that it coincides with the parallelepiped that $A$ acted on. When viewing in $\mathbb{R}^{n-1}$ space, $A$ and $T$ are indistinguishable, so there is ambiguity as to what the initial state was. Therefore, $A^{-1}$ is undefined. $\blacksquare$
EDIT: 3Blue1Brown articulates this point better than I do. I just found this. I was trying to say that essentially, if you squish space down into a smaller dimension, there is no way to distinguish squishing higher dimensional space and transforming space of the same dimension. There is ambiguity as to what the initial state was, so $A$ is not a bijection.
https://youtu.be/uQhTuRlWMxw?t=403
Comment: For a "matrix" $A:\Bbb R^n \to \Bbb R^{n-1}$, does $\det A$ make sense?
Comment: @Pendronator We would still say that $A$ represents a map $\Bbb R^n \to \Bbb R^n$, but the map fails to be onto (surjective)
Comment: $\det A$ is the volume of the image of the unit $n$-cube under $A$.  If $A$ is non-singular the image is an $n$-dimensional polytope with non-zero volume.  So, if $\det A=0$, $A$ is not invertible.
Comment: @AryamanMaithani Could it work if $A:\mathbb{R}^n \rightarrow \mathbb{R}^n$? For example, mapping the unit cube to the X-Y plane? Would that still be valid, or would $A$ still be $\mathbb{R}^n \rightarrow \mathbb{R}^{n-1}$?
Comment: @Pendronator It would help if we could nail down exactly what it is that you're trying to explain geometrically. Would you say that you're trying to find an argument that if $\det(A) = 0$, then $A^{-1}$ does not exist?
Comment: @Omnomnomnom Yes. My argument is that you can map (I'll use 3D and 2D space as an example) 3D space onto the X-Y plane so that $\det(A)$ is $0$. However, you can also map 2D space onto the same orientation such that the two modified coordinate systems coincide. Because they're indistinguishable, there's ambiguity as to the initial state, so $A^{-1}$ doesn't exist.
Comment: @Omnomnomnom I found that 3Blue1Brown articulates my point better than I do. https://youtu.be/uQhTuRlWMxw?t=403
Comment: Ultimately, the issue is that a linear transformation from $\mathbb R^3 \to \mathbb R^2$ gives rise to a $2 \times 3$ matrix (or a $3 \times 2$ matrix, if you prefer), hence there is no notion of determinant. Determinant only makes sense for square ($n \times n$) matrices.
Comment: @Carlo I changed the question. The matrix $A$ is now $\mathbb{R}^n \rightarrow \mathbb{R}^n$. I meant that $A$ maps 3D space to the X-Y plane, but it is still in 3D space. Hence, all points look like (x, y, 0).
Answer: It's not clear what you mean by "Now, define another matrix $T:\mathbb{R}^{n-1}\rightarrow\mathbb{R}^{n-1}$ that maps the $(n-1)$-dimensional parallelepiped such that it coincides with the parallelepiped that $A$ acted on."
That said, you seem to have already accepted that if $\det(A) = 0$, then the image of $A$ is at most $(n-1)$-dimensional (i.e. $A$ fails to be surjective/onto). From this alone, it is clear that $A$ cannot have an inverse.  After all: for any $b \in \Bbb R^n$, $x = A^{-1}b$ is supposed to satisfy $T(x) = b$. However, if $b$ lies outside the "squished" subspace of outputs from $A$, then we can never have $T(x) = b$.

Another geometric argument: note that $|\det(A)|$ is the "volume stretch factor" of the transformation associated with $A$. It follows that for $A,B$, we have $|\det(AB)| = |\det(A)| \cdot |\det(B)|$.  Now, because the identity mapping has a stretch factor of $1$ and $AA^{-1} = I$, it follows that $|\det(A)|\cdot |\det(A^{-1})| = 1$.
So, if $\det(A) = 0$, then whatever the inverse $A^{-1}$ is would have to satisfy $0 \cdot |\det(A^{-1})| = 1$, but that's impossible.
Comment: By the first part, I meant that $T$ maps the X-Y plane such that the image of the X-Y plane under $T$ is indistinguishable from the image of 3D space under $A$.
Comment: @Pendronator Fine, but how do you know that this is the case? How do you show that there is an X-Y plane inside the domain that gets mapped onto the image?
Comment: I was just using 3D and 2D space as an example.
Comment: My point is, whatever the dimensionality, how do you find the subspace in the domain that gets faithfully mapped to the image, or at least show/argue that such a subspace exists?
Comment: I'm not sure. Maybe we could define $T$ as the projection of $A$ onto $(n-1)$-dimensional space? I don't have a ton of experience in this stuff.


BIND DNS Forwarder Performance

Question: Does anyone know how to measure the performance of forwarders that are configured on a BIND DNS (may be in terms of RTT, SRTT)?
This will help to know which forwarders are working optimally, I tend to script this so as to get a trend over a particular period of time.
Answer: BIND uses SRTT as a variable to decide which DNS to use, so you can get access to it dumping the cache with the command rndc dumpdb will dump the cache in bind's directory (or the directory specified by the dump-file configuration directive).
In that file named_dump.db you will be able to get the SRTT of each nameserver, just grep the file for srttp and you will find the interesting lines, then filter with the IPs of the forwarders you want to look at.
Comment: Many thanks Pablo.... Below is the output from one of the DNS servers: ;       83.1xx.8.2xx [srtt 28209] [flags 00002000] [ttl -16542]
;       83.1xx.8.2xx [srtt 28209] [flags 00002000] [ttl -16542]
;       188.8.131.52 [srtt 0] [flags 00000000] [ttl 224] ....... Any idea about the negative TTL value? Also is srtt 0 for 220.127.116.11 make sense?

BIND DNS Forwarder Performance