How to compare Likert ratings for multiple methods in a usability study

Question: I am designing a questionnaire to compare user experience of usage of a two prototypes of a software - prototype A and B. Users will rate prototype A for a task and then prototype B for performing the same task based on a 5 point Likert scale. The questionnaire will contain 5 questions related to the various measures of user experience and contain ratings for each measure. How can i compare the Likert ratings for the two prototypes using statistical tests?
Comment: Median for central tendency, inter-quartile range for dispersion, [Wilcoxon's signed-rank test](http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) for testing median difference.
Comment: @Penguin_Knight; i was reading the wikipedia article on the Wilcoxon signed-rank test..is there an example with a software package that i can follow such as Matlab/Excel/SPSS, particular to my case? i am getting confused by the volume of stats jargon(being a software dev and not a ux specialist)..thanks
Comment: Here is a site on [how to do it in four common software](https://wikis.uit.tufts.edu/confluence/display/SSSI/Wilcoxon+Signed-Rank+Test)
Answer: Just to summarize the comments into an answer.
For comparing ordinal variables like Likert's scale, you may consider using median to represent the central tendency, and inter-quartile range to show the dispersion.
If you would like to formally test the difference in mean rank, you can use Wikcoxon's signed-rank test. Here is a wiki describing how to do it is SPSS, Stata, SAS, and R.
If you would like to test if the medians are equal, sign test is another option, as suggested by ttnphns in the comment.
Comment: **Wilcoxon sign-rank test** is a 2-related-samples test which tests H0 that the difference between the two variables is symmetric about 0. **Sign test** tests H0 that this difference has median 0.
Comment: @ttnphns Thanks for the correction. I have edited the answer to reflect the difference.
Comment: Please don't be hurry. `difference in mean rank`, `the medians are equal`. How do you see it with a _paired-sample_ test?
Comment: @ttnphns In that case I am probably confused by your phrase "between the two variable is symmetric about 0." Since this is a wiki, please feel free to edit my answer.
Comment: @Penguin_Knight do i have to do  a-priori power analysis for determining the sample size for administering 5 Likert scale questionnaire..or can i randomly choose the number as 10 participants?
Comment: @iceman I do believe so. I am not very familiar with effect sizes of non-parametric tests, it is certainly possible. Here is a [SE thread](http://stats.stackexchange.com/questions/30455/how-to-determine-the-effect-size-of-a-wilcoxon-rank-sum-test-in-r) and an [article](http://onlinelibrary.wiley.com/doi/10.1111/j.1541-0420.2008.01062.x/abstract;jsessionid=2F19AE99435F55C2C460D0CFC3C39182.d01t02) for your reference.
Comment: I found a link mentioning the statistics to calculate:http://www.icbl.hw.ac.uk/ltdi/cookbook/info_likert_scale/index.html . is there a simple worked out example for Likert items treated as ordinal data?
Comment: @iceman, try Google [wilcoxon's Signed-rank test example](https://www.google.com/search?q=wilcoxon+signed+rank+test+example&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) and [sign test example](https://www.google.com/search?q=sign+test+example&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a). Good luck!


Sequential linear estimation: Is MSE non-increasing?

Question: Suppose we estimate $x$ from $y_1=ax+z_1$ and get $x_1$. Then suppose we receive $y_2=bx+z_2$ and reestimate  $x$ using both $y_1$ and $y_2$ and get $x_2$. Is the means squared error (MSE) of $x_2$ always lower than MSE of $x_1$. In other words is $$E(x-x_1)^2\geq E(x-x_2)^2?$$ Here $a,b$ are know constants and $z_1$ and $z_2$ are Gaussian errors and the estimation is linear minimum mean squared error. The equations can also be vectors in that case error is the trance of the error covariance matrix. By this wiki it seems to be decreasing.
Edit: explanation
At time $t=0$ a real value $x$ is generated by a random process $X$. Then at time $t=1$, I receive a noise corrupted and scaled version $y_1$ of $x$ denoted by $y_1=ax+z_1$. From $y_1$ I do linear minimum mean squared error (LMMSE) estimation and estimate $x$ and get $x_1$ and the corresponding LMMSE is $E(x-x_1)^2$. Here $a$ is a constant and is known, $z_1$ is Gaussian noise with known mean and variance. LMMSE estimation is straightforward.
Then at time $t=2$, I receive another noise corrupted and scaled version $y_2$ of that same $x$ which is denoted by  $y_2=bx+z_2$. Again $b$ is a known constant and $z_2$ is Gaussian noise with known mean and variance. Now I simultaneously use both $y_1$ and $y_2$ to estimate $x$ by LMMSE estimation and I get the value $x_2$ and the corresponding error $E(x-x_2)^2$. My question: is $E(x-x_1)^2\geq E(x-x_2)^2?$. i.e., the time actually does not matter the question is does LMMSE estimation using $n+1$ samples always give a less error than estimating only using $n$ samples out of that $n+1$ samples?
Thanks.
Comment: Could you please explain the kinds of data and the process used to "estimate" a value $x$ from equations of the form $y=ax+z$?
Comment: I am using linear minimum mean squared error estimation. I receive two corrupted copies of the same sample value $x$ and want to compare the estimate of $x$ with respect to one observation against both observations. The process which generated $x$ can be assumed to be Gaussian and we know all covariances matrices. Thanks.
Comment: Thanks, but what you're doing is still not quite clear. It would seem that in the first case you have triples of data in the form $(y, a, z)$ and you are estimating the *parameter* $x$ using least squares, but this does not match your question or the description in your comment.  Including a small example of a dataset and the estimates within your question might help overcome these difficulties in communicating the context of your problem.
Comment: @whuber I included an explanation. But I don't have data. This is a theoretical question. Is this question not valid? Thanks.
Comment: I cannot say whether it is valid until it becomes understandable. Your recent edits help somewhat, but you refer to "corrupted and scaled." Presumably this means $a$ and $z_2$ are unknown and somehow are being considered as realizations of random variables. Precisely what do you assume about these variables and specifically how do you use this assumption to estimate $x_1$?
Comment: $a,b$ are constants and known. $z_1,z_2$ are Gaussian noise with known mean and variance. And LMMSE is very straightforward method and I have all the information i.e., variances and co variances of $X$, $z_1$, $z_2$ to do LMMSE. There is no question about feasibility. Only question is about the two errors. Thanks.
Comment: Yes, OLS is straightforward: the issue here is whether you are truly applying in the way you describe (and whether you are applying it correctly). Your explanation of this point would help, because in this situation the result is so simple that one begins to suspect there may be a miscommunication. For instance, in the case of one observation, the OLS estimate of $x$ is $y/a$ and its estimation variance is Var$(z_1)/a^2$, calling into question the applicability and meaning of "$E(x-x_1)^2.$" We will be able to discuss the two errors whenever you disclose the details of your calculations.
Comment: I write the error estimation variance as $E(x-x_1)^2$ because in my application $x$ is a vector so the error variance is the trace of error covariance matrix. But I just want to try my hypothesis for single variable case. Thanks.
Answer: The question asks about how the estimation variance of the parameters in least squares fitting changes when an additional observation is included in the data.
Letting $A$ be the model matrix ($A = (a)$ or $A=(a,b)'$ in the examples in the question), $X$ be the parameter vector ($X = (x)$ in the question), and $Y$ be the response vector ($Y = (y_1)$ or $Y=(y_1,y_2)'$ in the question), and introducing a variance-covariance matrix $\Sigma = \sigma^2\mathbb{I}$ for the responses ($\mathbb{I}$ is an identity matrix), the model can be expressed as
$$\mathbb{E}[Y] = AX;\quad\text{Var}[Y] = \Sigma = \sigma^2\mathbb{I}.$$
The least-squares solution is
$$\widehat{X} = (A'A)^{-1}A'Y$$
from which its variance-covariance matrix can be computed as
$$\text{Var}(\widehat{X}) = (A'A)^{-1}A'\text{Var}(Y Y')\left( (A'A)^{-1}A'\right)'= \sigma^2  (A'A)^{-1}A'\left( A (A'A)^{-1}\right) = \sigma^2  (A'A)^{-1}.$$
For the examples in the question (assuming $a\ne 0$) these values are $\sigma^2 / a^2$ and $\sigma^2 / (a^2 + b^2).$  Obviously, because $a^2+b^2\ge a^2,$ the variance does not increase in this case when the second observation is added.

In general, let $\vec{a}$ be a new row to be adjoined to $A$.  This changes the precision matrix $A'A$ into $A'A + \vec{a}'\vec{a}$.  The original precision matrix is positive-semidefinite, which means that for all vectors $u$
$$u' A'A u \ge 0.$$
Now for an arbitrary vector $u,$
$$u'(A'A + \vec{a}'\vec{a}) u = u'(A'A)u + u'(\vec{a}'\vec{a})u =  u'(A'A)u + (\vec{a}u)^2 \ge u'(A'A)u.$$
In this sense $A'A$ becomes "more" positive-definite when another observation is adjoined to it.  We might say, in somewhat descriptive language, that the estimate $\widehat{X}$ becomes more precise as new observations are added.  Indeed, it becomes strictly more precise whenever any nonzero observation is added.  This is merely the vector analog of the earlier argument that $a^2+b^2 \ge a^2.$
A similar analysis can be carried in the generalized least squares setting when arbitrary variance-covariance matrices $\Sigma$ describe the distribution of the $z_i$ (the "error structure"), with the same conclusion: including additional nonzero observations always increases the precision of the parameter estimates.
Comment: Thanks. I have a few clarifications please. Why are the noise terms $z_1,z_2$ not in the model? And Wikipedia gives the linear minimum means squared error estimate as $\hat{x}=C_XA^T(AC_XA^T+C_Z)^{-1}(y-AE[X])+E[X]$, where $C_X$, $C_Z$ is the covariance of X and covariance of $Z$ and $E$ is expectation. I can get to you answer by assuming many $C_X=1$, $C_Z=0$ and $E[X]=0$. Is your answer still valid for the general case?
Comment: And next question is why do you consider $Var(X)$ and not the error variance $Var(X-\hat X)$? Thanks. http://en.wikipedia.org/wiki/Minimum_mean_square_error#Linear_MMSE_estimator_for_linear_observation_process
Comment: The "noise terms" *are* in the model: I have stipulated their means ($0$) and covariances ($\Sigma$). The rest of your comment is inconsistent with your question: the "covariance of $X$ and ... $Z$" makes no sense in this context because $X$ is a *parameter*, not a random variable.
Comment: But my model is the same model as shown in the wikipedia article. $X$ is not a parameter it is a random variable. I am trying to estimate the current sample value of $X$. I am doing linear minimum mean squared estimation, not least square, and I know they have lot in common but in LMMSE $X$ is always a random variable, right? Could you please explain what changes in your answer then? I am not very familiar with stat so may be my terms are confusing. Thanks a lot.


Erro de Redirect Loop em aplicação Rails

Question: Estou trabalhando em uma aplicação em Rails e fazendo testes via Postman, a aplicação costuma funcionar normalmente após ter logado em algum usuário, consigo testar os endpoints corretamente. Porém quando fico com o usuário logado por um certo tempo, coisa de 5 minutos as vezes, eu passo a receber esse erro de Redirect Loop:

E no terminal do Rails recebo diversos erros Unauthorized:

Não tenho ideia do que pode ser o problema e não consegui achar outros parecidos para tentar resolver. A aplicação utiliza Rails 126.96.36.199 e Devise 4.8.0.
Comment: Verifique qual é a rota de logout automático sua. Você deve está sendo redirecionado para uma rota que necessita de login então fica nesse loop eterno
Answer: O devise é uma autenticação para uso em páginas no navegador, com autenticação via cookie e tendo uma sessão persistente no servidor. Para as API's o ideal é que vc. utilize uma outra forma de autenticação que a gente chama de stateless (onde o servidor não guarda sessão do seu lado, ele valida toda vez a cada request) como basic_auth, informar um header com uma API_KEY e lidar de forma manual.
Na wiki do devise ele até fala que consegue suportar algo via API, porém não conheço muito. Vale olhar.
Contudo deixo uma sugestão de você tenta usar uma autenticação diferente para sua API usando um JWT, ou até mesmo um basic-auth, ou um header específico com API_KEY. Todos são formatos conhecidos de autenticação via API.


Are inverses of groups unique in general?

Question: A group is a mathematical construct having closure, inverse, identity and Associativity.
I am having trouble in proving (or disproving) if the inverse of an element are unique?
I have tried to prove $b=c$ in the following cases:
Here $a$ and $b$ belong to the set and $\cdot$ is used to show the operation
1.
$$a\cdot b=e_1$$
$$a\cdot c=e_1$$
where $x\cdot e_1=x$ (right identity, i.e., $e_1$ is multiplied to the right hand side to get $x$)

$$a\cdot b=e_2$$
$$a\cdot c=e_2$$

$e_2\cdot x=x$ (left identity, i.e., $e_2$ is multiplied to the left hand side to get $x$)
In which case and why, we can say that $b=c$?
Comment: Yes the inverse is always unique. Suppose $x_1$ and $x_2$ are inverses of $x$. Then $(x_1 * x) * x_2 = x_1 * (x *x_2) = x_2 = x_1$
Comment: You say you don't know what $e_2 e_1$ is; I think that's a good thing to settle first. (1) In your post, you wrote that $e_1$ is a right identity. Does that help you to deduce what $x \cdot e_1$ is equal to (for any given $x$)? And can you apply that to simplify $e_2 \cdot e_1$? (2) Next, I see that you also wrote that $e_2$ is a left identity. Does that help you to deduce what $e_2 \cdot y$ is equal to (for any given $y$)? And can you apply that to simplify $e_2 \cdot e_1$?  (3) Can you put together the results of (1) and (2) to deduce any further conclusion regarding $e_1$ and $e_2$?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Also, your use of $e_1,e_2$ seems to indicate two distinct identities; but in a group the identity is always unique. (Can you see why?)
Comment: Yes, I am able to show that the left and right identities of Non-Abelian group are unique by using the Associativity property. For Abelian grous, they are the same. However, I do not get why the two identities must be the same in general
Comment: @Curious_To_Know If a group has both left and right identities, then what is $x x^{-1}$?
Comment: What's $e_2\cdot e_1$?
Comment: xx−1 I don't know what this is.  But if we take $x.l^{-1}x=e_2$ and x.xr-1=e1, we get $xl^{-1}$ as $xr_{-1}$. to be equal.
Comment: e2 . e1 is I don't know. I was not able to reduce it to something.
Comment: x $x_r^{-1}$ is the real problem. I don't know how it is defined. It may either be equal to e1 or e2. If it is equal to e1, then there is no issue;One is easily able to show (by a method similar to Shaun) that both left and right inverses are unique and equal. The problem arises if we define x $x_r^{-1}$=e2 and  $x_l^{-1}$ x = e1 and I am not able to reduce it further.
Answer: The trick here is to pit two inverses $s,t$ of an element $x$ against each other. Let $e$ be the identity element.
By definition, $s\cdot x=e=x\cdot s$ and $t\cdot x=e=x\cdot t$.
We have
$$\begin{align}
s&=s\cdot e\\
&=s\cdot (x\cdot t)\\
&=(s\cdot x)\cdot t\\
&=e\cdot t\\
&=t.
\end{align}$$
Comment: If you wish to ask something else, @Curious_To_Know, please ask it in a new thread; I have answered this question as it was asked.
Comment: Then $e_1=e_2*e_1=e_2$, @Curious_To_Know.
Comment: I don't understand your question, @Curious_To_Know. In a group, left inverses are right inverses. Which definition of a group are you using?
Comment: Thanks. I got it now @Shaun
Comment: But here we have shown that left and right inverses are equal. And that too when e1 is equal to e2.(better from is left inverse * no = e2 and right inverse * no. = e1). Choosing 1 of many right inverses and then equating all left inverses to these, we can show uniqueness of left inverse. Using the same we may show uniqueness of right inverse. But what if we did not take the above conditions?
Comment: I have edited my answer to include some details, @Curious_To_Know.
Comment: I have use the standard definition of groups except the fact that the left and right identities may not be equal in general i.e. x*$e_1$=x     &     $e_2$*x=x. ; where e1 and e2 may not be equal in general.
Comment: You're welcome, @Curious_To_Know. After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).


Ransack search string arrays stored in db

Question: I'm trying to search using ransack for articles.
In one of my question in how to get the articles based on their tags, I found out how to do so:
Find articles where array
Now I just want to do the search with ransack but I get an error
I have it like this
<%= search_form_for @q do |f| %>

            <%= f.label :tags_in %>
            <%= f.search_field :tags_in, class: 'form-control' %>

            <%= f.submit 'Buscar', class: 'btn btn-primary m-t-large' %>

      <% end %>

the error I get when performing this searching for xbox is the following:
PG::InvalidTextRepresentation: ERROR:  array value must start with "{" or dimension information
LINE 1: ...es".* FROM "articles" WHERE "articles"."tags" IN ('xbox')  O...

heres the controller:
def index
    @q = Article.ransack(params[:q])
    @articles = @q.result.paginate(page: params[:page], :per_page => 10).order('created_at DESC')
  end

How can I search for the articles using their tags?
Thanks!
Answer: As discussed on this issue you need to add the gem postgres_ext to your project:
# Gemfile
gem 'postgres_ext'

And add this to an initializer:
# config/initializers/ransack.rb
Ransack.configure do |config|
  %w[
    contained_within
    contained_within_or_equals
    contains
    contains_or_equals
    overlap
  ].each do |p|
    config.add_predicate p, arel_predicate: p, wants_array: true
  end
end

After that you'll be able to use contains in a serialized array.


Placing Inner Join Linq Query Into View Model

Question: Viewmodel:
public IEnumerable<Telephone_Search.Models.tbl_users> users;
public IEnumerable<Telephone__Search.Models.tbl_pics> images;
public IEnumerable<Telephone__Search.Models.tbl_locations> branches;

Controller:
public ActionResult Index()
{
    var users = from a in db.tbl_users
                where a.userid == 6
                select a;

    var branchjoin = (from e in db.users
                      join c in db.tbl_locations on e.address equals c.location
                      where e.userid == 6 && e.emp_address == c.location
                      select c).ToArray();

    return this.View(new ViewModel
                     {
                         branches = branchjoin // Error here
                         users = users,
                     });
}

How do I out c.location into razor view within MVC? The most common error I get is can't do conversion from IQueryable to System.Generic.Collection. The error is stated within the code.
Answer: Replace .ToArray(), with .ToList().AsQueryable(), does this do the trick?


Inherit page id for drupal node

Question: I am trying to make a node inherit the url of where it is clicked form.
eg : .com/blue-work/node-1
not .com/node-1
This is so when a link is clicked from a certain destination the node inherits its parents block settings. Is this possible with Drupal?
Answer: That sounds like fun.
First, a question: In your example, do you mean that the source page is /blue-work, and you're clicking a link on /blue-work to go to node-1? And you want the destination URL to become /blue-work/node-1 ?
If so, that sounds difficult b/c you'd have an open-ended number of different paths and you'd be telling Drupal to behave differently, paying attention to the tail only (and how is Drupal to know what, exactly, is the tail?). I think it would still be possible, though.
Instead, you could go with what currently works: if you click a link on /source-page to go to /destination-page, then this URL works: /source-page/destination-page.  However, I'd sooner use: /source-page?context=destination-page.
Regardless, you might start with hook_page_alter so you can edit all the links on the source page before it's rendered, adding the source page's url to (the end of) the links.
Then, of course, you're going to have to check the requested URL to get the 'source-page' context and apply it. Perhaps with hook_page_alter again.

Inherit page id for drupal node


Como fazer o Nginx fornecer conteúdo pré compactado?

Question: Já habilitei o modulo HttpGzipStaticModule, e defini a variável
gzip_static on;

Mas nos cabeçalhos de resposta de uma requisição GET não aparece
Content-Encoding    gzip

Comment: O link do módulo que você adicionou acima, diz que é necessário que os arquivos compactados estejam no mesmo diretório dos não-compactados e possuam extensão `.gz`. Talvez o que você esteja procurando seja o [HttpGzipModule](http://wiki.nginx.org/HttpGzipModule) que faz a compactação no momento da requisição. Contudo, acredito que não faça sentido adicionar mais essa compactação em imagens, dado que esse tipo de arquivo já possui compactação própria.
Comment: você enviou o cabeçalho ```Accept-Encoding: gzip, deflate```?
Comment: sim estou recebendo `Accept-Encoding:gzip,deflate,sdch`, verifiquei isso usando o firebug no firefox e as ferramentas para desenvolvedores do chrome
Comment: Se os arquivos estão possuem extensão ```.gz```, os cabeçalhos estão certos e o você já reiniciou o nginx, tudo deveria funcionar. Pra ajudar mais do que isso, só olhando os arquivos de configurações, logs e a saída do comando ```curl -v -H "Accept-Encoding: gzip,deflate,sdch" "URL_destino"```, em que o ```-v``` pede a saída verbosa e o ```-H``` envia o cabeçalho como parâmetro.
Comment: Não estou usando arquivos em .gz, apenas hospedando imagens png, jpg e gif
Answer: Olha, acho que você confundiu de módulo. O HttpGzipStaticModule serve arquivos pré-compactados se eles existirem. Ou seja, se você tem image.png e image.png.gz e o cliente pede image.png, o módulo vai servir o image.png.gz no lugar. Quem faz a compressão é você.
Para compactar na hora, use o NginxHttpGzipModule. Note, no entanto, que por default ele comprime só text/html. Preste atenção nos parâmetros desse módulo para configurar direito.
Outra coisa: imagens já são pré-compactadas em sua grande maioria (e em todos os casos que você citou). Tentar compactá-las vai ser inútil. Existem algumas ferramentas que podem ajudar, como OptiPNG (veja esse artigo com uma lista). O Google também tem dicas a respeito. Mas ativar o gzip vai ser inútil.
Comment: No final das contas acabei criando uma versão compactada de cada arquivo (.gz), pois lembrei que tenho outros arquivos de texto como .css .js .html
Answer: Bom, eu compacto os arquivos assim que subo as atualizações do site e executo este script que gera os *.gz que o NGINX vai buscar.
#! /bin/bash

FILETYPES=( "*.woff" "*.css" "*.jpg" "*.jpeg" "*.gif" "*.png" "*.js"  )
# specify a list of directories to check recursively
DIRECTORIES="/www/siteX/static/"

for currentdir in $DIRECTORIES
do
   for i in "${FILETYPES[@]}"
   do
      find $currentdir -iname "$i" -exec bash -c 'PLAINFILE={};GZIPPEDFILE={}.gz; \
         if [ -e $GZIPPEDFILE ]; \
         then   if [ `stat --printf=%Y $PLAINFILE` -gt `stat --printf=%Y $GZIPPEDFILE` ]; \
                then    echo "$GZIPPEDFILE antigo, atualizando"; \
                        gzip -9 -f -c $PLAINFILE > $GZIPPEDFILE; \
                 fi; \
         else echo "$GZIPPEDFILE estah faltando, criando..."; \
              gzip -9 -c $PLAINFILE > $GZIPPEDFILE; \
         fi' \;
  done
done


Is posting your personal information and asking for job in reply to the question allowed?

Question: I noticed some of the answers, where it were not actually answers but was something like

I can do this job for you. Contact me as firstname.lastname@example.com etc.

Should this be allowed on Stack Exchange? I think If we allowed such answers the site instead of becoming Q&A will become a publicity sites.
In such cases what should be done? Should I downvote the question or flag it?
Answer: This is not allowed.
Such answers/questions/comments has to be flagged.


Email misses fields from form

Question: This is regarding a Drupal 8 site, specifically Drupal 8.7.1 and the "Contact" module (with Contact Emails, Contact Storage enabled).
The issue that I'm running into is some of the fields are not included in the email that's sent out when the form is submitted. No Swiftmailer or other HTML email packages involved here, my ultimate goal is just to include all fields that were filled out.
I narrowed the situation down to this - when logged in, the resultant email sent out after form submission always contains all of the correct fields. If not, or in other words an anonymous user fills out the form, some fields are missing from the email entirely.
The aforementioned missing fields are actually paragraphs, or entity revisions, that I made use of to get access to the add / remove paragraph functionality on the front end. They work great, with a bit of preprocessing, but absolutely refuse to be included in email messages when the submitter is an anonymous user.
Sanity check - The fields are all there and filled out as part of the Contact Storage module, so that's not the issue. Anonymous users obviously do not have any kind of access to administer paragraph types, but this is not needed when the paragraphs are fields in a contact form(?).
I've checked around the various stack exchanges and other sites, but I can only find vaguely relevant issues, such as Theme contact emails. Using paragraphs in Contact does not appear to be a popular thing to do.
They are embedded as subforms, but I can't find anyone else who has asked this question.
The site is hosted on Acquia Cloud, PHP 7.2, if that helps. Short of digging through the module's entire codebase or setting up HTML mail with something like Swiftmailer, I'm stumped.
Any help is much appreciated, please let me know if you need any more detail on something - I know this is a lot to read without code or screenshots.
Answer: After working with JDev518 on this we discovered this was a permissions issue with paragraphs. Although this should have worked as is, we ended up installing Paragraph Type Permissions" and assigning specific permissions to create/edit/view the paragraph fields in question for anonymous. This "forced" the permission check to work and started including the submitted values in the email. However the contact module is determining the view permissions on those paragraph fields when it's building the email seems to be the cause of this issue.

Email misses fields from form


A Question of Memory for an Apache server

Question: Mem:   8176880k total,  8059736k used,   117144k free,    93040k buffers
Swap:  1004052k total,      108k used,  1003944k free,  7257056k cached
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 4992 mysql     20   0  291m 115m 5380 S   65  1.4 739:54.71 mysqld
20260 apache    20   0 43032  18m 3964 S   27  0.2   0:02.50 apache2
20154 apache    20   0 41588  16m 3964 S   10  0.2   0:00.40 apache2
<snip>

Is this: Mem:   8176880k total,  8059736k used; anything to be worried about!?
And ideas?
many thanks
edit: forgot to say I know nothing about servers, I've been landed with this...
answer:
> free -m
             total       used       free     shared    buffers     cached
Mem:          7985       7665        320          0         89       6942
-/+ buffers/cache:        633       7352
Swap:          980          0        980

doesn't look like I have a memory issue after all
Answer: This is fine - the VIRT value is often around this figure when using prefork.c (which I assume you are):
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
10385 apache    15   0  376m  48m 3932 R 20.3  1.2   0:01.34 httpd
10423 apache    16   0  376m  46m 4576 S 15.0  1.2   0:01.09 httpd
10153 apache    15   0  337m  61m 4672 S 11.6  1.6   0:03.94 httpd
10419 apache    15   0  383m  54m 4696 S 11.6  1.4   0:01.00 httpd

The value you want to monitor is RES - this is the size of the greatest amount of memory that child thread has consumed (in my case, PHP is run as part of that thread, hence the "bloat" as libraries and data are loaded). The thread will not release the allocated memory, however when the apache process kills the thread after its maxrequests as per
<IfModule prefork.c>
MaxRequestsPerChild  1000

the thread will return to its native memory consumption.
To lower these values, ensure you are only loading the apache modules you require, and monitor apache's threads while you run a very large PHP script (ini_set('memory_limit', '128M');then recursively load data into an array - that should do it). Then, during real world usage, lower the MaxRequestsPerChild value until you see your apache RES at a reasonable level.
Here are some useful parameter tuning articles:

OnLamp LAMP stack tuning
Low apache memory usage
Apache max performance
High server memory usage tips
Comment: Well the RES seems OK, what worries me is the Mem:   8176880k total,  8059736k used, stated at the top.

You mentioned apache not releasing the mem reserved? How do I find out!?

Thanks
Comment: After looking on your articles I can see it isn't a memory issue (i think)
Comment: As HD says, top doesn't report memory usage in the traditional sense, there is a very well written response to that particular query http://www.linuxforums.org/forum/linux-newbie/890-top-command-memory-question.html
Answer: It's ok. Free memory means RAM that is not used by systems, applications and cache. You can consider "Buffers" and "Cached" as another free RAM. So you have around 7 GB of free ram. With the command:
free

you can see the "real" free RAM in the line: -/+ buffers/cache. Also you can use htop.
Comment: Thanks HD, I've already figured it all out as you can see in my edit :)


iPhone Accelerometer in Background

Question: I am creating an app which checks car's speed continuously. Is it possible to check speed using accelerometer in Background ?
Comment: You can certainly get accelerometer data, but I would think that it would be inefficient to try and calculate the speed using it. Have you considered using CoreLocation to calculate the speed?
Answer: You should use core location and Yes you can use core location in background mode.
Just remember to switch on location updates in target -> capabilities -> background modes.
There is easy to find some tutorials online how to works with core location.

iPhone Accelerometer in Background


Existe um pacote serviços no padrão MVC?

Question: Existe um pacote de serviços no padrão MVC? Seria um MVCS?
Por exemplo, tenho uma classe ConnectionFactory - que serve para conectar ao banco de dados. Isso seria uma serviço. Onde coloco isso no padrão MVC? Seria no pacote Controlador ou criaria um novo pacote chamado Servicos?
Outra dúvida: e as exceções, em que pacote coloco?
Answer: Geralmente este tipo de serviço fica em uma pasta chamada config, ou app->config. As exceções, que ao meu ver seria arquivos de um framework por exemplo, ficária em vendor.
Esse tipo de modelo é muito utilizado por frameworks, como Zend e Laravel (Frameworks PHP).
Estrutura de pasta do Zend:
<code>-config
     -autoload
-data
     -cache
-module
     -Application
-public
     -css
     -js
     -image
-vendor
     -zendframework
     -bin
</code>
Sendo que a pasta config fica responsável pelos arquivos de configuração de toda aplicação. A pasta data, para os arquivos salvos na aplicação. Module fica com os arquivos responsável pelo mvc de cada modulo da aplicação. Public é a pasta responsavel pelos aquivos publicos, muito desses arquivos utilizados nas views. E vendor, onde fica o framework e váriados.


Fazer requisição em um intervalo de tempo definido

Question: Meu aplicativo deve atualizar uma lista de dados que vem do servidor a cada 5 minutos. Usando Retrofit para requisição HTTP, qual a melhor maneira de fazer isso?
Answer: Você pode usar o recurso Alarm do Android e definir de quanto em quanto tempo ele deve ser chamado.
Primeiro você precisa criar um broadcast receiver que será chamado quando o alarme for executado:
public class AlarmReceiver extends BroadcastReceiver {

    private static final String TAG = AlarmReceiver.class.getSimpleName();

    public AlarmReceiver() {
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.d(TAG, "onReceive()");

        // Aqui você coloca o código que deve ser executado a cada X minutos
    }
}

Não esqueça de adicionar o receiver no seu arquivo AndroidManifest.xml (dentro da marcação application):
<receiver
    android:name=".AlarmReceiver"
    android:exported="false"></receiver>

Agora você precisa criar uma classe customizada que estenda a classe Application (caso você já não possua no seu app). Recomendo você criar o alarme dentro do método onCreate:
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);
    }
}

Agora é só adicionar a classe customizada no AndroidManifest.xml:
<application
        android:name=".MyApplication"

Adicione a permissão WAKE_LOCK no AndroidManifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK" />

Answer: Existem diversas formas de fazer isso, antes de optar por uma, é necessário conhecer o que cada uma nos oferece e escolher aquela que mais se adequa às nossas necessidade.
A principal vantagem do Alarm é que opera fora do contexto da sua aplicação, permitindo fazer a requisição, mesmo que a aplicação não esteja em execução.
No entanto, ela pode ser também a maior desvantagem. Depois de iniciar o Alarm ele irá fazer uma requisição a cada 5 minutos enquanto o dispositivo não for desligado, com o correspondente custo de bateria e recursos.
Caso apenas necessite de actualizar a lista enquanto a aplicação estiver a correr, não use um Alarm.
Nessa situação a utilização do Timer poderia ser uma possível opção.
No entanto, o código executado pelo Timer corre numa background thread, como o Retrofit também corre os seus métodos numa Thread própria, não faz sentido usar uma background thread para correr outra background thread.
Além de que teria de resolver o problema de os métodos onResponse() e onFailure() serem executados na thread criada pelo Timer e não na UIThread.
Por outro lado o Timer não deve ser utilizado em tarefas demoradas.
Assim, caso apenas necessite de actualizar a lista enquanto a aplicação estiver em execução, sugiro que utilize um Handler.
Declare um campo para guardar a referência ao Handler
private Handler handler;

No onCreate() crie o Handler e de imediato faça a requisição:
handler = new Handler();
handler.post(new UpdateData());

Para evitar memory leaks declare a classe UpdateData num arquivo java à parte ou como uma static inner classe da Activity.
private static final class UpdateData implements Runnable{
   @Override
   public void run() {
      //Faça aqui a requisição via Retrofit
      .....

      //agenda nova requisição daqui a 5 minutos
      handler.postDelayed(this, 5*60*1000);
   }
}

No método onDestroy() remova o pedido a novas requisições:
@Override
protected void onDestroy(){
    super.onDestroy();
    handler.removeCallbacksAndMessages(null);
}

Answer: Um timer é mais fácil de ser implementado:
 private final Timer myTimer = new Timer();

     public class myClass {

     @Override
     public void onResume() {
            ...
            myTimer.scheduleAtFixedRate(new myTask(), 0, (long) (18000000));  // Tempo em milisegundos.

        }

        private class myTask extends TimerTask {
            @Override
            public void run() {
                ... execute os procedimentos.
            }
        }

    }

https://stackoverflow.com/questions/15571169/i-need-help-understanding-the-scheduleatfixedrate-method-of-thetimer-class-in-ja
http://www.iitk.ac.in/esc101/05Aug/tutorial/essential/threads/timer.html


Users complain they can't "click on anything" on my Pressflow site

Question: The users of my site complain they cannot click on anything on my site, which runs Pressflow.
If that makes any difference, I am using some Nginx Caching, and the server config from the Barracuda Aegir project.
I can't seem to figure this out, or reproduce it in another site.
Comment: I fixed the issue (which was general)

I was using a microsoft css filter to scale the background image, it somehow made the whole page render incorrectly. removed filter, problem solved. can live without nice bg on IE for now.
Comment: To clarify, I have no idea what they are referring to, but 3 people have said it. I can go in FF/Chrome and click on any link, etc. to navigate, and it works fine. I looked through my error console, and there's a css issue that I can fix.but is that it?
Comment: I suggest ask to client be more specific/precise about the issue. I do not know if is related, but when I visited your site, the slider increase in an important level the load of CPU. Also, scroll down to the bottom seems not smooth.
Comment: Your users are talking about IE. No links work in IE8
Answer: I fixed the issue (which was general): I was using a Microsoft CSS filter to scale the background image. It somehow made the whole page render incorrectly. I removed filter, and the problem was solved. I can live without a nice background on IE, for now.
Comment: I've had a similar issue. I resolved the problem by having the IE filter on a separate, absolutely positioned div, behind the actual content.


Find the total number of factors (excluding $1$) of $2160$.

Question: Find the total number of factors (excluding $1$) of $2160$.
According to me it's just asking about total number of factors that is  $4+3+1=8$ ($2^4 \cdot 3^3  \cdot 5^1$).  I don't see any statement asking about number of ways of selecting its factors.
But solution of this question is given by taking number of ways of selecting some or all out of four $2$s,three $3$s and one $5$. Number of such ways is $(4+1)(3+1)(1+1)-1=39$.
Where am I wrong ?
Comment: The number of such ways is $5\cdot4\cdot2=40$.
Comment: @Bernard No sir it's answer is 39 only.
Comment: I'm sorry, but perform the multiplication. You've forgotten something on writing your argument.
Comment: @Bernard Oops!!! got it
Comment: Please typeset mathematical expressions using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Hint:
$$12=2^2\cdot3$$
The possible factors are
$$1,2,4,3,6,12$$
respectively $$2^0\cdot3^0,2^1\cdot3^0,2^2\cdot3^0,\\2^0\cdot3^1,2^1\cdot3^1,2^2\cdot3^1.$$
As you see, every prime factor is taken will all multiplicities, and all combinations ($(2+1)(1+1)$ of them) are possible.
Answer: Let's not work with such a big number, let's work with $6 = 2^1 \times 3^1$.
By your argument, you are claiming that there are only $1+1=2$ factors.  Perhaps you are just counting $2$ and $3$ and not counting that it is possible to select $6$ as a potential factor.
It seems that you are computing factors of the form of $p^r$ where $r \ge 1$ where $p$ is a prime which is not what the question is asking for.
In general if the prime factorization is $\prod_{i=1}^n p_i ^{m_i}$, then the number of factor is $\prod_{i=1}^n (m_i+1)$ . If you are not counting $1$ as a factor, then we subtract by $1$. The rationale of the formula is for each prime, we can consider how many of copies of a particular prime should be chosen and it is possible that we choose none.
Comment: we are counting number of ways to construct a factor. of which, we are just counting number of factors.
Comment: you are just not familiar with a particular concept yet, that has nothing to do with intelligence. It takes time and practices to learn.
Comment: sir, I don't see statement asking about number of ways.But in solution they are taking number of ways.Please explain this.
Comment: I got it sir.But  sir I still think that this question is not well illustrated .Do you agree or I am just stupid
Answer: Divide the prime factors into three groups:
$$2^\color{red}4=1\cdot 2\cdot 2\cdot 2\cdot 2; \ \ \ \ 3^\color{green}3=1\cdot 3\cdot 3\cdot 3; \ \ \ 5^\color{blue}1=1\cdot 5.$$
To form a factor you choose a number from each group. Here are the possible numbers in the groups:
$$\{1,2,2^2,2^3,2^4\}; \ \ \{1,3,3^2,3^3\}; \ \ \{1,5\}.$$
Note that choosing $1$ basically means you do not choose the prime number (in this case $2,3,5$).
So by the product rule in combinatorics and the fundamental theorem of arithmetic:
$$\begin{align}{5\choose 1}\cdot {4\choose 1}\cdot {2\choose 1}&=5\cdot 4\cdot 2=40 \ \ \text{OR}\\
{\color{red}4+1\choose 1}\cdot {\color{green}3+1\choose 1}\cdot {\color{blue}1+1\choose 1}&=5\cdot 4\cdot 2=40.\end{align}$$


Find the Maximum value of $\frac{x}{\sqrt{x+y}}+\frac{y}{\sqrt{y+z}}+\frac{z}{\sqrt{z+x}}$

Question: if $x$, $y$ and $z$ are positive real numbers such that $x+y+z=4$  Find the maximum value of $$S=\frac{x}{\sqrt{x+y}}+\frac{y}{\sqrt{y+z}}+\frac{z}{\sqrt{z+x}}$$
I tried as follows.
The given expression can be rewritten as
$$S=\sqrt{4-x}+\sqrt{4-y}+\sqrt{4-z}-\left(\frac{y}{\sqrt{x+y}}+\frac{z}{\sqrt{y+z}}+\frac{x}{\sqrt{z+x}}\right)$$
But by symmetry $$S=\left(\frac{y}{\sqrt{x+y}}+\frac{z}{\sqrt{y+z}}+\frac{x}{\sqrt{z+x}}\right)$$
so
$$2S=\sqrt{4-x}+\sqrt{4-y}+\sqrt{4-z}$$  and by Cauchy Scwartz inequality
$$2S \le \sqrt{4-x+4-y+4-z}\times \sqrt{3}$$ so
$$2S \le \sqrt{24}$$
so
$$S \le \sqrt{6}$$
Is this approach correct?
Comment: There's the approach of substituting $z=4-x-y$ and then find the maximum of the resulting surface. BTW if you set $x=y=z$, then $S=\sqrt{6}$.
Comment: $S=\sqrt6$ is maximum. $S(3,1,0)=\dfrac{3+\sqrt3}2<\sqrt6.$
Answer: I think it means that $x$, $y$ and $z$ are non-negatives such that $xy+xz+yz\neq0$.
If $x=3$, $y=1$ and $z=0$ then $S=\frac{5}{2}$.
We'll prove that it's a maximal value.
Indeed, we need to prove that:
$$\sum_{cyc}\frac {x}{\sqrt {x+y}}\leq\frac{5}{4}\sqrt{x+y+z}.$$
By Cauchy-Schwarz
$$\left(\sum_{cyc}\frac {x}{\sqrt {x+y}}\right)^2\leq\sum_{cyc}\frac{x(2x+4y+z)}{x+y}\sum_{cyc}\frac{x}{2x+4y+z}.$$
Id est, it remains to prove that
$$\sum_{cyc}\frac{x(2x+4y+z)}{x+y}\sum_{cyc}\frac{x}{2x+4y+z}\leq\frac{25(x+y+z)}{16}$$ or
$$\sum_{cyc}(8x^6y+72x^6z-14x^5y^2+312x^5z^2-92x^4y^3+74x^4z^3+$$
$$+122x^5yz+217x^4y^2z+143x^4z^2y+564x^3y^3z+1338x^3y^2z^2)\geq0$$ or
$$\sum_{cyc}2xy(4x+y)(x-3y)^2(x+2y)^2+$$
$$+\sum_{cyc}(122x^5yz+217x^4y^2z+143x^4z^2y+564x^3y^3z+1338x^3y^2z^2)\geq0,$$ which is obvious.
Done!
Comment: How did you come up with $3,1,0$?
Comment: @Χpẘ It's just trying only, but it helped.
Comment: @Χpẘ I have a version=)
Comment: @Χpẘ $S(3,1,0)=\dfrac{3+\sqrt3}2<\sqrt6.$
Answer: No, this approach is not correct, since
$$S=\left(\frac{y}{\sqrt{x+y}}+\frac{z}{\sqrt{y+z}}+\frac{x}{\sqrt{z+x}}\right)$$
does not necessarily hold. For example, consider $x=\frac12$, $y = \frac32$ and $z=2$, then $S=\left(\frac{x}{\sqrt{x+y}}+\frac{y}{\sqrt{y+z}}+\frac{z}{\sqrt{z+x}} \right) \approx 2.420$, but $\left(\frac{y}{\sqrt{x+y}}+\frac{z}{\sqrt{y+z}}+\frac{x}{\sqrt{z+x}}\right) \approx 2.445$.
Also, if this were correct, you would need to provide $x, y$ and $z$ such that $S = \sqrt{6}$.
Comment: Ok so can i have any hint after my first step
Comment: @Umeshshankar I'm sorry, I haven't found the solution of this problem myself yet.
Answer: $$\mathbf{\color{green}{New\ version\ of\ 10.02.2018}}$$
Let us find the greatest value of $\sqrt{x+y}+\sqrt{y+z}+\sqrt{z+x}$ under the condition $x+y+z=4.$
Substitutions
$$a=\sqrt{x+y},\quad b=\sqrt{y+z},\quad c=\sqrt{z+x}$$
lead to the task on the greatest value of $a+b+c$ under the condition $a^2+b^2+c^2=8.$
Stationary points can be found using Lagrange multipliers method with the function
$$f(a,b,c,\lambda)=a+b+c+\lambda(a^2+b^2+c^2-8)$$
via solution of the system $f'_a=f'_b=f'_c=f'_\lambda=0,$ or
\begin{cases}
1+2\lambda a = 0\\
1+2\lambda b = 0\\
1+2\lambda c=0\\
a^2+b^2+c^2=8\\
(a,b,c)\in \mathbb R_+.
\end{cases}
Summation of $(1.1)-(1.4)$ with factors $a,b,c,-\lambda$ gives
$$a+b+c=-16\lambda,$$ and after substitution of this to $(1)$ one can get the system
$$a(a+b+c)=b(a+b+c)=c(a+b+c),\quad a^2+b^2+c^2=8,$$
with the evident solution
$$a=b=c=\sqrt{\dfrac83},\quad x=y=z=\sqrt{\dfrac43},\quad f=\sqrt{24},$$
so
$$\boxed{S=\sqrt6\approx2.449490}$$
is the least value.
For example, in the point $(x,y,z)=(0,1,3)$
$$S_1=\dfrac{\sqrt1+\sqrt4+\sqrt3}2=\dfrac{3+\sqrt3}2\approx2.366025 < S.$$
Comment: @haidangel I have solved other task :(. BTW: giving the bounty award at the grace period, you will hold high publicity of the page per some days.
Comment: Shouldn't the maximum value be at $(3,1,0)$? $S(3,1,0) = \frac{5}{2}$.
Comment: I don't understand why they downvoted ??
Comment: Thanks a rl lot


Always show a DIV as soon as its not visible any more after scrolling down?

Question: I have an info box (div) on my screen when the user opens my website. As soon as the user scrolls down and the box is not visible to the user any longer, I want the box to appear in the top right corner all the time while scrolling.
I know how to make it visible all the time (position: fixed). The problem is, how do I know when its not visible to the user ans more while scrolling? I can also use JavaScript, if that helps. Id prefer Prototype JS.
Thanks!
Comment: Based on the scrollTop property you can determine whether the position should be fixed or not.
Answer: You need to make use of getBoundingClientRect(), which returns the element's positions relative to the viewport. If the top value is below 0, then it should be fixed.
HTML:

    I should be fixed… sometimes

CSS:
#stick {
    position: absolute;
    top: 60px;
}

#stick.fixed {
    position: fixed;
    top: 0;
}

JS:
var stick = document.getElementById('stick');

window.onscroll = function(){
    if(stick.getBoundingClientRect().top < 0){
        stick.className = 'fixed';
    } else if(stick.className.indexOf('fixed') < 0){
        stick.className = '';
    }
}

Here's a demo.


The birational positivity of a Line Bundle

Question: I have a question about F. Bastianelli's article: Measure of irrationality for hypersurfaces of large degree
We have the Definition 1.1.

A line bundle $L$ on $X$ satisfies property $(BVA)_p$ if there exists a proper Zariski-closed subset $Z = Z(L) \subset X$ depending on L such that
  $$ H^0(X,L) \to H^0(X, L \otimes \mathcal{O}_{\xi}) $$
  surjects for every finite subscheme $\xi \subset X$ of length $p+1$ whose support is disjoint from $Z$.

Thus $(BVA)_0$ is equivalent to requiring that $L$ be effective, and $(BVA)_1$ is what is often called "birationally very ample".
My question
I wanted to show that if $L$ is a line bundle on $X$ satisfying $(BVA)_p$ and $E$ is an effective divisor on $X$, then $\mathcal{O}_X(L+E)$ satisfies $(BVA)_p$.
What I did so far
By applying the definition above, since $L$ satisfies $(BVA)_p$ then there exist a Zariski-closed subset $Z$ such as for every finite subscheme $\xi \subset X$ of length $p+1$ whose support is disjoint from $Z$, the map
$$ H^0(X,L) \to H^0(X, L \otimes \mathcal{O}_{\xi}) $$
is surjective.
On the other hand, since $E$ is effective, then it verifies $(BVA)_0$ (i.e. there exist a Zariski-closed subset $Z'$ such as for every finite subscheme $\xi' \subset X$ of length $1$ whose support is disjoint from $Z'$, the map
$$ H^0(X,E) \to H^0(X, E \otimes \mathcal{O}_{\xi'}) $$
is surjective.)
Where I'm stuck
To show that $\mathcal{O}_X(L+E)$ satisfies $(BVA)_p$, which Zariski-closed subset that we'll take? My suggestion is $Z \cup Z'$, am I right? and if the answer is yes, can I take any subscheme $\Xi \subset X \backslash (Z \cup Z')$ for the finite subscheme of length $p+1$ whose support is disjoint from $Z \cup Z'$ ?
Thanks in advance for any hint or enlightement?
K. Y.
Answer: The answer is yes.
It is enough to see that since $E$ is effective, then $L + E_{|X \ Supp E} = L \otimes \mathcal{O}_X = L$.


Fingering for modes on the piano

Question: I'm a self-taught pianist. I know how to play all the major and minor scales, so I believe I can progress to modes.
How should I practice modes on the piano? Should I just use the fingering for the corresponding major scale, or are there special fingerings?
For example: In B flat major, technically to be consistent with the way the scale is played you would start on the 4th finger for the right hand, but I have heard it's ok and natural to start on the 2nd. Are there similar cases for modes?
Is there a book that will tell me the mode fingerings, perhaps a free pdf online? I don't have many musical resources at home.
Most importantly, and to reiterate, should I just use the fingering for the corresponding major scale?
Comment: There is a table of suggested fingerings for the various modes at:

https://www.thejazzpianosite.com/jazz-piano-lessons/the-basics/modes/
Answer: If you can play all major (ionian) and natural-minor (aeolian) scales, you can play already 24 of 84. I think this is a rather big question asking for fingerings of all the left 60 ones. Also we are not talking about melodic or harmonic minor, which have 7 modes too, times 12 times 2 equals 168 modes.
Not to discourage you: With your ability of already playing 24 keys I would say you have a pretty good start.
Also as for the major or minor scales you have quite a few fingerings in common. For example in C major you can play all modes with:
RH: 123-1234(5)-123-1234(5) etc.
LH: 54321-321-4321-321 etc.

As a rule of thumb:

try to avoid the thumb on black keys!

As you play F major on the right hand with: 1234-123-1234-1234 to not get the thumb on the Bb. As you know you can use the same fingering as for c major for the left hand in F major
As you mentioned the fingering for B flat major, you seem to be familiar with those fingerings that in the beginning need a little practice, but you should be able to adapt those to the modes too.
Not to forget:

"Fingering itself is an art, it needs time and practice."

For example: the fingering I wrote for the C major scale makes sense if you play from c to c, but what if you want to go one tone further and play from c to d? It surely depends on the run but here I would go this way:

the same applies for the modes too, as soon as you play more complex figures rather then just the scale from one octave to the other you might need to use different fingerings.
Comment: Would you recommend I use a book to learn mode fingerings, or can I just figure it out myself and mostly use the major key fingering?
Comment: honestly saying I don't know a book containing fingerings for all modes, I have been searching one for myself and my plan was to make one, but I did not find the time yet. I would say that by adapting the techniques used for playing the major scales you probably get very far. If there is a special mode that you have problems with, just post a new question. Also be aware of the fact that the fingerings used for scales are good practice, but in real music you often need to adapt them to the context.
Comment: That's very surprising - I thought it would be a common thing to find in more advanced music books. Thanks for the pointers!
Comment: @nath Did you get a chance to write that book yet? ;)
Comment: @robert thanks for asking. Straight answer: "NO" :-) I have been working on a bash script that circles you through the "Circle of Fifth" in the time-frame supplied by the user. But, I still have this one here in mind. I have been actually thinking of creating an answer to be edited as "Community Wiki" maybe using [LilyPond](http://lilypond.org/) syntax so one can make any book out of it quite easy.
Answer: @nath Already posted a great answer and I don't have much to add. I would like to elaborate on one thing though: at the most fundamental level, scales do not have dedicated fingerings.
@nath eluded to this with the C-D scale. The fingering depends on the context as a whole far more than the particular scale being played. Most scale exercises help to increase skill in 2 things: finger dexterity and fingering intuition. They help to build muscle memory and train your fingers to naturally find a comfortable fingering for whatever you happen to play.
What scale exercises are not meant for is dictating exactly what fingers to use for each key of the scale. The standard fingerings found in most scale exercise books are only there to help build good habits when it comes to fingering.
So, even if there is a book or something out there that explicitly lists out fingerings for every possible scale of every possible mode don't use it. You will be better off, at this point, by using the modes to practice the fingering techniques and guidelines you have picked up intuitively from practicing all of your major and minor scales.
Answer: I'm a self-taught pianist, too. And I am using a book that is more than 100 years old, namely James Francis Cook's Mastering the Scales and Arpeggios. Thousands of students have used this book in order to prepare for the examinations through the decades. It also contains an ingenious method for developing the greatest possible velocity of playing scales by means of so called pier notes (see page 51).
@WillRoss1: you are right with your statement in the first paragraph but if you are learning the scales for the first time you have to stick to a fingering, otherwise you are lost. The fingerings given in the above mentioned book really turned out to be the best for me and I soon was able to predict the fingering that was given in the book. If you really follow the anatomy of the hand there is not much choice, especially if you play multiple octaves.
All Jazzies know that mastering the major scale means mastering all the other six modes. But this is only true when you don't change the fingering! If, however, you change the fingering for all the modes, it will be difficult to remember for a beginner.
For example, take the A♭ major scale which starts with the 3rd finger in the right hand. The corresponding B♭ Dorian minor scale has the same keys as the A♭ major scale. Therefore, this scale begins with the 4th finger at B♭ in order to have the already familiar fingering of the A♭ major scale. The only thing to remember is that the B♭ major scale also begins with the 4th finger on B♭.
Of course, once you are familiar with the keyboard you will choose the fingering automatically and maybe won't follow the rules anymore.

Fingering for modes on the piano


Controller and Form

Question: What's the key difference between:
amazing_forms_contribute:
  path: 'amazing-forms/contribute'
  defaults:
    **_form: '\Drupal\amazing_forms\Form\ContributeForm'**
    _title: 'Conribute page'
  requirements:
    _permission: 'access content'

and
amazing_forms_contribute:
  path: 'amazing-forms/contribute'
  defaults:
    _**controller: '\Drupal\amazing_forms\Controller\ContributeForm::content'
link_id: 'arm.admin_product_variants_create'**
    _title: 'Conribute page'
  requirements:
    _permission: 'access content'

When I should use a controller? And when I should use a form?
Can I combine both (use controller and form)?
What is their limitation?
Answer: _form: We use this explicitly when one expects a classname
implementing FormInterface.
_controller:It is used when one needs to return a renderable
array or an object. Hence, here we call a method from its
class (classname::method)
And NO you cannot use _form and _controller at the same time under
defaults: since  one routing only provides one functionality at a
time.

See here to understand how the structure of routes are used and
  why they were used.Also see routing api for a more detailed
  understanding.
Comment: so, can i say, form is to make a form?
and _controller is just to present a content?
Comment: yes _form is to make a form and _controller is not only to present the method (in ur case content) its used to return renderable arrays and also response objects..should i add some links to the answer 2 make it clearer ?? @AnD
Comment: There is *always* exactly one controller. _form, _entity_form, _entity_view and so on are just short cuts that are mapped to a generic (entity) form controller.

Controller and Form


Adicionar imagens dinamicamente com JavaScript

Question: Como adicionar uma imagem dinamicamente dentro desta div com JavaScript ?
div class="toad" id="mushs">

Answer: Para criar elementos dinamicamente em JavaScript, basta utilizar a função createElement passando o nome da tag que deseja criar como argumento (no caso é a tag ).
Depois de ter criado o elemento de imagem, defina no atributo src o caminho da imagem e adicione o elemento que você criou dentro da div com o appendChild. Veja o exemplo abaixo:

function criaImagem(){
    const div = document.getElementById("imagens");

    const image = document.createElement("img");
    image.src = prompt("Digite o nome ou link da imagem: ");

    div.appendChild(image);
}

<button onclick="criaImagem();">Criar Imagem</button>
Comment: Não é bom esquecer de usar um `let` ou `const` ao declarar variáveis... :)
Comment: Costume de Python kkkk
Comment: Criei um botao para adicionar uma imagem usando teu codigo como apoio mas nao esta funcionando(a imagem esta na mesma pasta do arquivo js) function addImg() {
    const image = document.createElement('img');
    image.src = 'mush.png';
    document.getElementById('mushs').appendChild('image');
}
Comment: @DouglasKramer o problema é que você está passando uma string no método `appendChild` e não sua imagem.
Answer: Além do createElement, demonstrado em outra resposta, há o construtor Image, exclusivo para criar elementos img — HTMLImageElement.

const button = document.querySelector('button');
button.addEventListener('click', appendImage);

function appendImage() {
  const div = document.querySelector('#images');

  const image = new Image(200, 200); // Largura (width) e altura (height).
  image.src = 'https://i.stack.imgur.com/KPUgS.png';

  div.appendChild(image);
}
<button>Criar Imagem</button>

O construtor Image é similar à API document.createElement('img'), porém aceita como argumentos a largura e altura da imagem.


Show that $(27!)^6 \equiv 1 \pmod{899}$

Question: Show: $(27!)^6 \equiv 1 \pmod{899}$. Note: $899=30^2 - 1$.
Could anyone show me how to go through this please?  I think I have to use Wilson's theorem which is $(p-1)! \equiv -1 \pmod p$ but not exactly sure how else to tackle this.  Thanks!
Comment: No, but you could try thinking about it for more than three minutes.
Comment: Hints: $30^2-1=(30+1)(30-1)$; $30+1$ and $30-1$ are close enough to $27$ to make Wilson's Theorem an attractive option; $n\equiv-(p-n)\pmod p$.
Comment: could you expand on that a little please?  I still dont quite grasp the concept
Answer: Using Wilson's Theorem,  $28!\equiv-1\pmod{29}\implies 27!(28)\equiv-1$
$\implies 27!(-1)\equiv-1\implies 27!\equiv1\pmod {29}$
$\implies (27!)^6\equiv 1\pmod{29}$
Again $30!\equiv-1\pmod{31} \implies 27!(28)(29)(30)\equiv-1$
$\implies 27!(-3)(-2)(-1)\equiv-1\implies 27!(6)\equiv1 \implies 27!(30)\equiv5$ (multiplying either sides by $5$)
$\implies 27!(-1)\equiv5\implies 27!\equiv-5\pmod{31}$
So,$(27!)^6\equiv 5^6\pmod{31}$
Now, $5^3=125\equiv1\pmod{31} \implies (27!)^3\equiv -1\pmod{31}$
$\implies (27!)^6\equiv (-1)^2\pmod{31}\equiv1$
So, lcm$(31,29)\mid \{(27!)^6-1\}$ but lcm$(31,29)=31\cdot 29=899$
Comment: Thank you for insuring that OP will never have to think again.
Comment: @GerryMyerson, I completed the answer it to make things perfect and also because it was not marked 'homework'. But, I got your idea and will try to follow it sincerely.
Comment: @AndréNicolas, thanks for your observation. Rectified.
Comment: Wish I knew my fault here that has caused the downvote
Comment: Wasn't me downvoting, but did you give any thought to the comments I left?
Comment: @GerryMyerson, then, I'm not sure if I understood your point clearly. Would you please elaborate a bit?
Comment: lab, my point was that, by doing the entire problem, you left nothing for OP to do. You deprived OP of the joy of figuring out some details for himself (or herself). And if this was a homework problem, you enabled OP to copy your solution and hand it in without him having to think about it or learn anything from it. Is that clearer?

Show that $(27!)^6 \equiv 1 \pmod{899}$


How is local determined in ToLocalTime()

Question: When using ToLocalTime(), how is local time determined?  Is local time from the server or the client?  My assumption would be the server running the application.
Answer: It is the local time zone of the computer that code is running on.  In an ASP.Net application, the code runs on the server - so that's the time zone that it will return.
The behavior of this function is actually dependent on the .Kind property of the source value.  From the MSDN link you gave:

Utc - This instance of DateTime is converted to local time.
Local - No conversion is performed.
Unspecified -This instance of DateTime is assumed to be a UTC time, and the conversion is performed as if Kind were Utc.

This is non-obvious behavior.  You can read other related problems with the .net DateTime class here and here.
A few other points:

If you follow best practices, you will set the server's time zone to UTC.
If you are trying to display time in the user's timezone, you'll have to use one of these strategies.
Answer: ToLocalTime(), in this case, executes on the server. Therefore the time is evaluated on the server, and it'll return the server time to the client.
Answer: It is the local time on the server.
Answer: Local here is the timezone of the machine that the function executes on.


Ways to split nonlinear ODEs in linear part + nonlinearity that may work

Question: When one linearizes an ODE around an equilibrium point, say
$$\begin{pmatrix}x'\\
y'
\end{pmatrix}=\begin{pmatrix}x+y+e^{2y}-1\\
e^{2y}-1
\end{pmatrix}$$
around the point $(0,0)$, then one calculates the jacobian evaluated at the equilibrium, which gives a matrix $A$, and splits this equations in a linear part, give by $A$ and the nonlinear rest (some theorems then tell us, how the behaviot of the linear part governs the behavior of the whole ODE).
Why can't we do this splitting in a different way, e.g., by just collecting "linear terms" ?

Concrete example, to see what I mean:
The jacobian of the above system is
\begin{pmatrix}1 & 1+2e^{2y_{0}}\\
0 & 2e^{2y_{0}}
\end{pmatrix}
evaluated at $(x_0,y_0)=(0,0)$ being
\begin{pmatrix}1 & 3\\
0 & 2
\end{pmatrix}
So our original system we can rewrite as $$\begin{pmatrix}x'\\
y'
\end{pmatrix}=\begin{pmatrix}1 & 3\\
0 & 2
\end{pmatrix}\begin{pmatrix}x\\
y
\end{pmatrix}+r\begin{pmatrix}x\\
y
\end{pmatrix}$$
where $r$ is some nonlineare function.
But I could imagine other ways of separating the right-hand side into a linear and a nonlinear part, e.g. in the following way:
$$\begin{pmatrix}x'\\
y'
\end{pmatrix}=\begin{pmatrix}1 & 1\\
0 & 0
\end{pmatrix}\begin{pmatrix}x\\
y
\end{pmatrix}+\tilde{r}\begin{pmatrix}x\\
y
\end{pmatrix}$$
where I just colelcted the linear terms, corresponding to the "$x+y$" term in the original system and used a different nonlinearity $\tilde r$ that swallows all the other terms.
Why is this second way not possible (in the sense that I think the theorems that tell when the linear system governs the whole system, won't work now by applying them to the linear part obtained by this splitting), where lies the intuition behind it being necessary to split the equation using the jacobian into a linear+ nonlinear part ?
Comment: Because the "nonlinear perturbation" should vanish to first order at the point where you take the linearization, so that it is smaller than the linear part.
Comment: @Ian Can you please explain, what you mean by "vanish to forst order" ?
Comment: If your system is $x'=f(x)$ and $f(x_0)=0$ then linearization about the point $x_0$ means rewriting the equation as $x'=L(x-x_0)+N(x)$ where $L$ is linear and $N$ is nonlinear (or zero, if the original equation was linear to begin with). You then want $N(x)=o(x-x_0)$ as $x \to x_0$ so that the linear term dominates over the nonlinear term in a neighborhood of $x_0$.
Answer: It is possible but it depends upon objectives. The point is that you would like solutions of the original ODE and the linearized ODE to 'look alike'. And for this they should really have the same linearized part (in the first sense).
'Look alike' may be interpreted as describing same qualitative behavior, notably stability of fixed points (but many other things may be of interest). Example in dimension one:
$$ \frac{dy}{dt} = \sin(2y)-y . $$
$y=0$ is a fixed point and it is repulsive, i.e. if $y_0$ is any small initial value, then backward in time the solution $y(t)$ verifies $\lim_{t\rightarrow -\infty} y(t)=0$. This is seen by linearizing around the fixed point to
 $$ \frac{d \delta y}{dt} = 2\delta y - \delta y = \delta y $$
The solution is $\delta y(t) = y_0 e^t$ which indeed goes to zero as $t$ goes to $-\infty$. This implies the same for the genuine solution of the original equation. Indeed the set of solutions in a neighborhood of the fixed point are topologically conjugate (in this case also differentiably but this need not be the case in higher dimension).
If you made the suggested splitting and simply removed the $\sin$ then your 'linearized' equation would be: $\tilde{y}'= -\tilde{y}$ for which the solution is $\tilde{y}(t)=y_0 e^{-t}$ which has an attractive fixed point, precisely the opposite behavior of the real solution.
An example where linearization  does not give the qualitative behaviour near the fixed point:
$ y' = y^3 $ where again $y=0$ is a fixed point and it is repulsive as before. But alas, this is not seen in the linearized equation when you throw away the $y^3$ term and the solution is a constant. So these solutions do not ressemble. Reason: The linearization matrix is the zero matrix and this case does not work. More generally, when you have a linearization matrix $M$ things work 'nicely' when there are no zero eigenvalue, better when there are no imaginary evals, and even better when evals are either in the right (repulsive fixed point) or the left complex half plane (attractive fixed point).
V.I. Arnold explains all this quite nicely in his book 'Ordinary differential equations' (and there are many other such books).
Comment: For what objectives would one use a different linearization, like I did ?  Do you mean by "look alike" that the flow of the original and linear system are topologically conjugate ? Could you please give me (or reference to) an example, where a linearization different from the one via the jacobian does not "look alike" ?
Comment: @user52145 They won't look similar at all. In fact, you could even attempt your approach on a problem which is linear. You could split $x'=x$ into $x'=(-x)+2x$; just because you wrote the splitting doesn't mean that the linear term you selected is actually dominant.
Comment: @Ian Thanks (also for the above comment!). That finishes the last question. But "look alike" typically does mean topological conjugacy, right ? And do you happen to know  for what objectives would one a different linearization, like I did ? If you could post all of this as an answer, I could accept it ...


How to change WordPress website just with files

Question: How to change content of website build in WordPress when I only have access to files on hosting? I can't use wp-admin so that's what I'm left with.
Comment: Why can't you use `wp-admin`? - it is just a folder, right?
Answer: You Can't Do That™.
The only thing you can change without access to wp-admin is the contents of image files. Most of WordPress's content lives in the associated MariaDB or MySQL database.
Answer: Why can't you access wp-admin? if you lost access to it(like no username/pass etc), and since you do have access to the FTP server, then you can backdoor your way in. Check out this post here on SO. Should steer you in the right direction.
Create new user automatically via functions.php in WordPress
If you still can't get in for whatever reason, and since you want to primarily edit the content as you previously stated, then there is still a way.
Assuming you have access to the HOSTING server, you can still edit the content via the backend database itself. Again, assuming you have access, go ahead and log into the server, and find your way towards PHPMYADMIN.
Once you are in there, look for a database table called wp_posts:

All your content will be in there.
PLEASE NOTE: if you gain access to the backend MYSQL server, and cant tell which database is which, FTP in to the site, and find the wp_config.php file, and towards the top, you should see something like
DEFINE database name (or something like that, been a minute)
but you should see the database name there, to which you can match on the PHP MYADMIN side of things.
hope this steers you in the right direction.
Good luck.


Langrange multiplier, confusion at setting up the problem

Question: Question
Find the rectangular box with the largest volume that fits inside the ellipsoid x2/a2 + y2/b2 + z2/c2 = 1, given that it sides are parallel to the axes
Solution
Clearly the box will have the greatest volume if each of its corners touch the ellipse. Let one of the corners (x, y, z) be in the positive octant, then the box has corners (±x, ±y, ±z) and its volume is V = 8xyz.
I don't understand how they volume is equivalent to 8xyz, why isn't $V=xyz$?
Thank you very much
Answer: The length of sides are $x-(-x)=2x,y-(-y)=2y$ and $z-(-z)=2z$ so the volume is $$V=2^3xyz=8xyz.$$
Comment: It comes just from a choice of model : the question ask you to consider a box with sides parallel  to the axes, so you could have put a corner of your box at the origin and chose points $x,y$ and $z$ on each axes, which gives you your initial formula of volume $V=xyz$ or following the solution which centered the box at the origin (you can do a draw to realize it) ; you can of course chose an other representation but these two seems to be the easiest to me.
Comment: How did you calculate the length of sides? I can't seem to intuitively understand that bit
Comment: When you have a segment $[a,b],$ the length is given by $|b-a|.$ Here, the segments that define your box are given in your solution by $[-x,x],[-y,y]$ and $[-z,z],$ and I just compute $|x-(-x)|=2x$ ($x>0$), etc.
Comment: I understand that however I don't get where my solution obtained the segments from


Is a regression more accurate using age/sex/race normalized scores or raw scores, but controlling for age/sex/race?

Question: I am having trouble conceptualizing normalizing versus controlling for variables and would appreciate some education on the matter.
For example, you want to do a regression with two variables:

Hunger, which is how long you have gone without food.
Working Memory, which is your score on a test of working memory.

You hypothesize that the amount of time you have gone without food will result in worse working memory, thus a negative relationship will be created: The more more hungry you are, the worse your working memory will be.
So, say you have reason to believe that Age, Sex, and Race all could be influencing both your working memory score and how hungry your participants are. You also have access to a database that can norm your working memory score, based on a large sample of healthy controls. What would you say are the correct methods for further analysis?

You run a regression on the raw WM scores and the raw Hunger scores, but you control for Age, Race, Sex.
You run a regression with age/sex/race normalized WM scores and the raw hunger scores, but do not control for any variables.
You run a regression with age/sex/race normalized WM scores and the raw hunger scores, but you still control for age, sex, and race.

I would greatly appreciate the community's wisdom on this matter and references where you can supply them, so I can better understand what is going on.
Answer: If by "controlling" you mean put them in one multiple regression, and by "normalized WM scores" you mean WM scores that have, in some way, been adjusted for the effect other predictors, I would say 1) is clearly the best. Reason: you state you include the other predictors because they may be confounding = correlated with hunger. But this also means that, when trying to normalize the response without considering hunger, you also have a confounding problem, i.e. you could take out the effect of hunger through the normalization.


How do I programatically change default values in a contact form?

Question: I have a Drupal 8 contact form where the form's placeholder values are the default values of the fields. Unfortunately, this site is multilingual and I don't think it's possible to translate default field values.
Is there a way I can set the fields' default values equal to the (translatable) field labels in either a module or preprocess function?
Answer: You can override your contact forms(both the default and the custom ones) by adding a field widget hook.
Why a field widget hook and not the usual form alter hook like D7? Because overriding the default value of the field can be done only in the respective field widget and not at the form level.
Here's the sample code:
function <mymodule>_field_widget_form_alter(&$element,  \Drupal\Core\Form\FormStateInterface $form_state, $context) {
   $field_definition = $context['items']->getFieldDefinition();
   $entity = $context['items']->getEntity();
   if(($entity->getEntityTypeId() == 'contact_message') && ($entity->bundle() == '<your-custom-form-machine-name>')) {
     if($field_definition->getName() == '<your-field-machine-name>') {
       $element['value']['#default_value'] = 'Hi there!';
     }
   }
}

NOTE This has been tested with Drupal 8.1.1.
Answer: I managed to figure it out with a preprocess function using hook_form_id_alter. I got an array of the necessary field names, and looped through it assigning the field label value to the placeholder value. If this is bad form, let me know.
function yourtheme_form_yourformid_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $field_list = array_keys($form['#group_children']); //you might need to find a different array to get the names of your fields
  foreach ($field_list as $field) {
    $field_name = $field;
    $form[$field_name]['widget'][0]['value']['#placeholder'] = $form[$field_name]['widget'][0]['value']['#title'];
  }
}


Inverse Function Theorem - Challenging question

Question: I found the following question on the internet, and I think it would be useful to solve it as part as studying to my midterm:
Let $f:\mathbb{R}^n \to \mathbb{R}^n $ having continuous partial derivatives up to first order , such that:
$ \| f(x)- f(y) \| > \frac{1}{10} \|x-y\| $ for every $x,y\in \mathbb{R}^n $ such that $x\neq y$.

Prove that $J(f) \neq 0 $
Prove that $f$ sends $\mathbb{R}^n $ onto $\mathbb{R}^n $ .

Thanks in advance
Answer: Part 1:
Since $f$ is differentiable at $x$, for all $\epsilon>0$ there is some $\delta>0$ such that for all $\|h\| < \delta$, we have $\|f(x+h)-f(x) -DF(x)h\| \le \epsilon \|h\|$. Choose $\epsilon = \frac{1}{20}$.
Then
\begin{eqnarray}
\|Df(x)h\| &=& \|DF(x)h - (f(x+h)-f(x))+(f(x+h)-f(x))\| \\
&\ge& \|f(x+h)-f(x)\| - \|DF(x)h - (f(x+h)-f(x))\| \\
&\ge& \frac{1}{20} \|h\|
\end{eqnarray}
And so $DF(x)$ is invertible and $J(f(x)) \neq 0$.
Part 2:
Let $Y= f(\mathbb{R}^n)$.
Since $DF(x)$ is invertible, the implicit function theorem shows that $f$ has a local inverse, and hence $f$ maps open sets into open sets. Hence $Y$ is open.
Suppose $y_n \in Y$, and $y_n \to y$. Since $y_n \in Y$, there is some $x_n$ such that $y_n = f(x_n)$. Since $\|y_n-y_m \| = \|f(x_n)-f(x_m)\| \ge \frac{1}{10} \|x_n-x_m\|$, we see that $x_n$ is Cauchy, and hence $x_n \to x$ for some $x$. Since $f$ is continuous, we have $f(x) = y$, and so $y \in Y$. This shows that $Y$ is closed.
Since $\mathbb{R}^n$ is connected, and $Y \ne \emptyset$, we have $Y = \mathbb{R}^n$.
Comment: Hi copper.hat, Thanks for your answer .
Will you please explain to me why the fact that $||Df(x)h||\geq \frac{1}{20} ||h|| $ implies that $Df(x)$ is invertible ?
Thanks !
Comment: Sure; the inequality shows that if $h \neq 0$, then $Df(x)h \neq 0$. That is, $\ker DF(x) = \{0\}$. Since $DF(x)$ is square, it follows that it is invertible.
Answer: Since $f: \mathbb{R}^n \to \mathbb{R}^n$ has continuous partial derivatives, $f$ is differentiable. So we have
$$
\lim_{h \to 0} \frac{\|f(x + h) - f(x) - Df(x) \cdot h\|}{\|h\|} = 0.
$$
Triangle inequality gives
$$
\|f(x + h) - f(x)\| - \|Df(x) \cdot h\| \leq \|f(x + h) - f(x) - Df(x) \cdot h\|.
$$
Hence
$$
\lim_{h \to 0} \frac{\|f(x + h) - f(x)\|}{\|h\|} - \lim_{h \to 0} \frac{\|Df(x) \cdot h\|}{\|h\|} \leq 0 \\
\implies \lim_{h \to 0} \frac{1}{\|h\|}\frac{1}{10}(\|(x + h) - x\|) - \lim_{h \to 0} \frac{\|Df(x) \cdot h\|}{\|h\|} < 0 \\
\implies \frac{1}{10} < \lim_{h \to 0} \frac{\|Df(x) \cdot h\|}{\|h\|} \leq \lim_{h \to 0} \frac{\|Df(x)\| \cdot \|h\|}{\|h\|} \\
\implies \|Df(x)\| > \frac{1}{10}
$$
where $\|Df(x)\|$ is the operator norm. So $Df(x) \neq 0$.
Comment: Hi Pratyush, does $||Df(x)|| \neq 0 $ where $$||$$ is the operator norm imply that $J(f) \neq 0 $ ?
Comment: @homogenity You're right, it doesn't. Initially I thought you meant $Df$ by the notation $J(f)$, but now I realize you meant the determinant. You can just follow copper.hat's answer. My answer is essentially the same ... from the second last step you make the $\epsilon$-$\delta$ argument (with $\epsilon = \frac{1}{20}$) to get the same result as copper.hat.


vbscript : fso.opentextfile permission denied

Question: In my code segment, when I script the file name, it gives me a permission denied
on the following line:
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)

Here is the script
'output log info
Function OutputToLog (strToAdd)
    Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
    strDirectory = "c:\eNet"
    strFile = "\weeklydel.bat"
    'strText = "Book Another Holiday"
    strText = strToAdd

    ' Create the File System Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' Check that the strDirectory folder exists
    If objFSO.FolderExists(strDirectory) Then
       Set objFolder = objFSO.GetFolder(strDirectory)
    Else
       Set objFolder = objFSO.CreateFolder(strDirectory)
       'WScript.Echo "Just created " & strDirectory
    End If

    If objFSO.FileExists(strDirectory & strFile) Then
       Set objFolder = objFSO.GetFolder(strDirectory)
    Else
       Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
       'Wscript.Echo "Just created " & strDirectory & strFile
    End If

    set objFile = nothing
    set objFolder = nothing
    ' OpenTextFile Method needs a Const value
    ' ForAppending = 8 ForReading = 1, ForWriting = 2
    Const ForAppending = 2

    Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)

    ' Writes strText every time you run this VBScript
    objTextFile.WriteLine(strText)
    objTextFile.Close
End Function

I have assigned the vbscript domain administrator permissions.  Any ideas?
thanks in advance
Answer: I don't think this has to do with File Permissions per se.  It has to do with the fact that you've created the file using:
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)

That creates the file...and carries a reference to that file (objFile)
Then you don't close the file before you destroy the reference
...
'Missing objFile.Close here
Set objFile = nothing
Set objFolder = nothing
...

Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.
You are then proceeding to attempt to re-open the file while the file is already "open".  This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.
Answer: for what its worth...
I was convinced I had a permission error because of this line:
Set LogFile = LogFSO.OpenTextFile(LogFileName, ForWriting, True)

Because that's the line that the 'permission denied' error pointed to. But in fact, my permission error was a few lines further down:
WshShell.AppActivate(ScreensToRemove(i))
WshShell.SendKeys ("~")
WScript.Sleep(1000)

There was no screen with such a caption, so the SendKeys is what did not have permission.
The solution, of course, was:
If WshShell.AppActivate(ScreensToRemove(i)) = True Then
   WshShell.SendKeys ("~")
   WScript.Sleep(1000)
End if

Hope that might help.
Answer: Also, make sure that you don't have the file open in Excel (I had this problem with a .csv file)...
Answer: In my particular case the file which existed before and all I had to do was give permission to the Everyone user
Answer: balabaster is exactly right.  You either need to close the file before reopening it a second time for writing, or using the existing open handle.


How to fit Generalized Additive Model with gam() where always all columns are used as predictors (no hard coding part in model fitting)

Question: I have a train data table in R, which always have different columns, for example now the data table has the following column names:
library(mgcv)
dt.train <- c("DE", "DEWind", "DESolar", "DEConsumption", "DETemperature",
              "DENuclear", "DELignite")

Now I want to fit a Generalized Additive Model (= GAM) with integrated smoothness estimation that predicts the DE price. At the moment I fit the model as the following:
fitModel <- mgcv::gam(DE ~ s(DEWind)+s(DESolar)+s(DEConsumption)+s(DETemperature)+
                           s(DENuclear)+s(DELignite),
                      data = dt.train)

The column names are currently hard-coded, but I don't want to change this all the time, I would like to let the program recognize how many columns there are and fit the model with the existing columns. So, I would like to have something like this (which works for stats::lm() or stats::glm()):
fitModel <- mgcv::gam(DE ~ .-1, data = dt.train)

Unfortunately, this doesn't work with gam().
Answer: I don't recommend you do this for statistical reasons, but…
nms <- c("DE", "DEWind", "DESolar", "DEConsumption", "DETemperature",
              "DENuclear", "DELignite")
## typically you'd get those names as
## nms <- names(dt.tain)

## identify the response
resp <- 'DE'
## filter out response from `nms`
nms <- nms[nms != resp]

Create the right hand side of the formula, by pasting on the s( and ) bits, and concatenating the strings separated by +:
rhs <- paste('s(', nms, ')', sep = '', collapse = ' + ')

which gives us
> rhs
[1] "s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) + s(DENuclear) + s(DELignite)"

Then you can add on the response and ~:
fml <- paste(resp, '~', rhs, collapse = ' ')

which gives
> fml
[1] "DE ~ s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) + s(DENuclear) + s(DELignite)"

Finally coerce to a formula object:
fml <- as.formula(fml)

which gives
> fml
DE ~ s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) +
    s(DENuclear) + s(DELignite)


Canonical and terminal singularities

Question: Let $Y$ be a normal variety such that $K_Y$ is $\mathbb{Q}$-Cartier, and $f:X\to Y$ a resolution of singularities. Then,
$$
K_X = f^\ast(K_Y) +\sum_i a_iE_i
$$
where $a_i \in \mathbb{Q}$ and the $E_i$ are the irreducible exceptional divisors.  Then the singularities of $Y$ are terminal, canonical, log terminal or log canonical if $a_i > 0, \geq 0, >-1$ or $\geq -1$, respectively.
Question: Using this definition, can you give some examples of log terminal singularities that are not canonical and log canonical singularities that are not log terminal?
From Reid's "Young Peron's Guide to Canonical Singularities" I have nontrivial examples of the first two types:
A canonical singularity: Let $Y = \lbrace xz=y^2 \rbrace \subset \mathbb{A}^3$. There is an ordinary double point at the origin, and when we blow up we get a (-2)-curve $E$. By adjunction, $K_X = f^\ast K_Y$, i.e., $a = 0$, so by definition, $Y$ has a canonical singularity.
Terminal Singularities: The cone over the Veronese surface has a resolution $X$ with exceptional locus $E\simeq \mathbb{P}^2$. One can show (adjunction again) $K_X = f^\ast K_Y + \frac{1}{2}E$, and so the singularities are terminal but not canonical.
Answer: The book Birational Geometry of Algebraic Varieties by Kollár--Mori goes into these in some detail.
So for example they mention (Proposition 4.18) that canonical surface singularities (= du Val singularities) are (locally analytically) quotients of $\mathbf{C}^2$ by finite subgroups of $SL(2,\mathbf{C})$, whereas log terminal surface singularities are quotients by arbirtrary finite groups.
As for the other question, log terminal singularities are always rational. So it suffices to find a log canonical but not rational singularity: the classic example is the cone over an elliptic curve.
The recent book Singularities of the Minimal Model Program by Kollár--Kovács discusses these things in much greater detail, but I must admit I haven't read it.

Canonical and terminal singularities


Intersection of two polynomials in $F_p[x]$

Question: The number of intersections of two polynomials of degrees $m$ and $n$ in $R$ is at most $max(m, n)$.
Is this true in $F_p[x]$, being $p$ a large prime? How can it be proved?
Comment: consider how many zeroes of the difference there could be
Comment: @J.W.Tanner: The resulting polynomial of the difference would have at most $max(m, n)$ degree. According to the _Fundamental Theorem of Algebra_, "a degree $n$ polynomial with complex coefficients has, counted with multiplicity, exactly $n$ complex roots." So, in $F_p[x]$ it can never have more than $n$, right?
Comment: Yes, a degree $n$ polynomial over a field can't have more than $n$ roots
Answer: Just following up from the comments. The result is true for a simpler reason that the fundamental theorem of algebra, which doesn't apply to $F_p[x]$. The factor theorem. Let $R$ be an integral domain, then $R[x]$ possesses a division algorithm. Indeed, for all $f,g \in R[x]$, and $\alpha \in R$ the leading coefficient of $G$. Then there exists some integer $i$ and some $q,r \in R[x]$ with $0 \leq \deg{r} < \deg{g}$ such that $\alpha^i f = qg + r$. In particular suppose that $f(a) = 0$, and let $g = (x-a)$. Then there exists some $q,r \in R[x]$ with $f = (x-a)q + r$ such that $0 \leq \deg{r} < \deg{x-a} = 1$, and so $\deg{r} = 0$ and so $r \in R$. But then $0  = f(a) = (a-a)q(a) + r = r$, and so $r = 0$. Hence $f = (x-a)q$, but then clearly if $f$ has distinct roots it has most $\deg{f}$ roots, and so $f$ always has at most $\deg{f}$ roots.


Comparison of multiple means using summarized data

Question: I have means, variances, and sample sizes from three geographical sites but not their raw data such that:
     site1 site2 site3
N      120  150   160
mean   27.1 32.6  42.3
sd     5.5  7.1   6.8

I know we can do a pairwise z/t test just using these information. I'm wondering whether I can conduct a F test or Anova for a hypothesis $H_0: \mu_1=\mu_2=\mu_3$ vs $H_1:$ as least one pair of means are different.
Answer: Yes, you can. Please see this paper by Larson for reference.
Stata has a user-contributed aovsum command that allows recreating ANOVA analysis using just summary data. SAS has a macro and R has an
ind.oneway.second function in the rpsychi package for similar purpose.
If you don't know any of these software packages, online calculator like this is also available.
Comment: Thanks, Penguin_Knight. Do you know any R package for that purpose?
Comment: @DavidZ See `ind.oneway.second` in the [rpsychi](http://cran.r-project.org/web/packages/rpsychi/rpsychi.pdf) package.


SFML how to draw a Sprite(used as a player) on a Sprite(used as map)

Question: I'm not familiar with the SFML environment yet, we started learning it this year at school
I'm struggling to draw a sprite on another sprite using this method
I guess this s.~Drawable(); is used to draw on another windows but i couldn't find any example to implement it anyone could redirect me to a good documentation that is easy to understands for begginers.
Thanks.
PS: I found other methods but I need to load image everytimes to change the player's sprite image and I guess this would slow down the game fps depending on the user drive
<code>int sizeX = 1920, sizeY = 1080;
sf::RenderWindow window(sf::VideoMode(sizeX, sizeY), "Test");
window.setFramerateLimit(60); // max FPS a 60

sf::Vector2f player1(10, 10);
sf::Vector2f player2(590, 10);
sf::Sprite paddle1;
sf::Sprite paddle2;
sf::Texture t;
t.loadFromFile("Background.png");
sf::Sprite s(t);
//s.~Drawable();

// chargement du fichier .jpg dans un objet image de type Texture
sf::Texture imageBack1;
sf::Texture imageBack2;
sf::Texture imageForward1;
sf::Texture imageForward2;
sf::Texture imageLeft;
sf::Texture imageRight;
// PLayer2
sf::Texture imageBack1b;
sf::Texture imageBack2b;
sf::Texture imageForward1b;
sf::Texture imageForward2b;
sf::Texture imageLeftb;
sf::Texture imageRightb;

if (!imageBack1.loadFromFile("Back1.png"))
    printf("PB de chargement de l'image !\n");
if (!imageBack2.loadFromFile("Back2.png"))
    printf("PB de chargement de l'image !\n");
if (!imageForward1.loadFromFile("Forward1.png"))
    printf("PB de chargement de l'image !\n");
if (!imageForward2.loadFromFile("Forward2.png"))
    printf("PB de chargement de l'image !\n");
if (!imageLeft.loadFromFile("Left.png"))
    printf("PB de chargement de l'image !\n");
if (!imageRight.loadFromFile("Right.png"))
    printf("PB de chargement de l'image !\n");

//Player2 I guess this can be removed
if (!imageBack1b.loadFromFile("Back1b.png"))
    printf("PB de chargement de l'image !\n");
if (!imageBack2b.loadFromFile("Back2b.png"))
    printf("PB de chargement de l'image !\n");
if (!imageForward1b.loadFromFile("Forward1b.png"))
    printf("PB de chargement de l'image !\n");
if (!imageForward2b.loadFromFile("Forward2b.png"))
    printf("PB de chargement de l'image !\n");
if (!imageLeftb.loadFromFile("Leftb.png"))
    printf("PB de chargement de l'image !\n");
if (!imageRightb.loadFromFile("Rightb.png"))
    printf("PB de chargement de l'image !\n");

/* L'image doit être associée à un objet de type Sprite (équivalent à un rectangle) pour être dessinée. Ici , le sprite s'appelle bonhomme. Après, on ne travaille plus que sur le sprite… image ne sert plus à rien*/
paddle1.setTexture(imageBack1);
paddle2.setTexture(imageBack1);

// Start the game loop
while (window.isOpen())
{

    // Poll for events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window : exit
        if (event.type == sf::Event::Closed)
            window.close();

        // Escape pressed : exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
            window.close();
    }

    window.clear();

    // Draw the sprites
    window.draw(paddle1);
    window.draw(paddle2);
    window.draw(s);
    window.display();
}
</code>
Answer: You could draw to a sf::RenderTexture: https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1RenderTexture.php
And have this render texture be the texture of the Sprite.
Comment: Thanks you i just find out that there is several "layouts" of "textures" I thought i would have to make a new window and draw on it this should help a lot.


Second Derivative of Cusp

Question: I know the first derivative does not exist at a cusp.
Does this statement also hold for the second derivative?
Answer: No, the second derivative is found by differentiating the first derivative. If the latter doesn't exist, then the former certainly cannot.

Second Derivative of Cusp


Discard old build in multi-branch pipeline job, doesn't really delete builds from server

Question: I have multi-branch pipeline job in Jenkins:
http://illinXXXX:XXXX/job/OC/configure

and I checked the option for Discard old builds as below:

I would have expected, that each new run after this change, it will delete old build from the server for each Repository inside that pipeline. however, I see all builds are still there, which causing me a File system issue.
Jenkins link:
http://illinXXX:XXXX/job/OC/job/productconfigurator-ms/job/master/

From server:
jenkins@XXXXX:jenkins/jenkins-production/jobs/OC/jobs/productconfigurator-ms/branches/master/builds>

I see builds from 541 to 1039
Jenkins ver. 2.176.1
Comment: What's "MS" and "FS"? What exactly is "multi pipeline job"? If you mean Multibranch Pipeline, then I think these limits are per branch, not total. "Discard old builds" works perfectly here.
Comment: I clarify the terms. what do you mean by "these limits are per branch, not total"?
Comment: In Multibranch Pipeline with the above configuration, there would be up to 100 jobs up to 100 days old for branch "X", up to 100 jobs up to 100 days old for branch "Y" etc. What's Microservice? If you somehow mean docker images/containers/the likes, then no, Jenkins doesn't know anything about these.
Comment: I clarify the question. hope it's clear now
Comment: If you browse to `http://illinXXX:XXXX/job/OC/job/productconfigurator-ms/job/master/configure`, do you see a checkbox "Discard old builds" checked with the parameters in place?
Comment: as it's multi-branch pipeline, under http://illinXXX:XXXX/job/OC/job/productconfigurator-ms/job/master/configure I have only the option for 'View Configuration', and there it's not checked...
Comment: Then your configuration hasn't come into effect.
Comment: exactly, but why? I added PrtScn to the question, where you can clearly see its define
Comment: This is for the deleted branches, not for the active ones. There would be up to 100 jobs up to 100 days old for branch "X" once you delete that branch.
Comment: so it means I need to delete old build manually from the server?
Answer: The interface you pasted is for the Orphaned items. Orphaned items refer to deleted branches, where no Jenkinsfile is available.
For the Multibranch pipeline, the instructions to build each branch are inside that branch's Jenkinsfile. This is where you need to define these limits.
Use the following in your Jenkinsfile (from above, in master branch):
options {
        buildDiscarder(logRotator(numToKeepStr: "100"))
}

Make sure to use string (as in "100") and not number (as in 100).
Parameters:

daysToKeepStr: history is only kept up to this many days.
numToKeepStr: only this many build logs are kept.
artifactDaysToKeepStr: artifacts are only kept up to this many days.
artifactNumToKeepStr: only this many builds have their artifacts kept.

You may need to run your master pipeline manually once for it to work.
Comment: This is the right answer, but there are two big caveats:

1. "options" must be specified in their entirety. E.g. If you want to prevent a build from resuming, you must include THAT option here along with all others.

2. It's actually the `properties` step when using a scripted pipeline.

In a scripted pipeline you can change e.g. the numToKeepStr based on whether it's a master branch build or not.  Not clear that works well in declarative syntax.  Final caveat: what is available depends on what plugins are installed making it painful to try to boilerplate.
Answer: This is the equivalent of scripted-pipeline:
node('some-label') {
        properties([
                buildDiscarder(
                        logRotator(
                                artifactDaysToKeepStr: "10",
                                artifactNumToKeepStr: "50",
                                daysToKeepStr: "10",
                                numToKeepStr: "50")
                )
        ])

        stage('Maven Compile') {
        }

        stage('Some other steps') {
        }

}

Comment: Correct. But I think it is better to use "properties" outside of the node {}.