emacs syntax highlight numbers not part of words (with regex?)

Question: I've moved to emacs recently  and I am used to/like numbers being highlighted. A quick hack I took from here puts the following in my .emacs:
(add-hook 'after-change-major-mode-hook
      '(lambda () (font-lock-add-keywords
                   nil
                   '(("\\([0-9]+\\)"
                      1 font-lock-warning-face prepend)))))

Which gives a good start, i.e. any digit is highlighted. However, I am a complete beginner with regex and would ideally like the following behaviour:

Also highlight the decimal point if it's part of a float, e.g. 12.34
Do not highlight any part of the number if it is next/part of a word. e.g. in these cases: foo11 ba11r 11spam, none of the '1's should be highlighted
Allow 'e' within two number integers to allow scientific notation (not required, bonus credit)

Unfortunately this looks very much like a 'do this for me' question which I am loathe to post, but I have failed thus far to make any decent progress myself.
About as far as I have got is discovering [^a-zA-Z][0-9]+[^a-zA-Z] to match anything but a letter either side (e.g. an equals sign), but all this does is include the adjacent symbol in the highlighting. I am not sure how to tell it 'only highlight the numbers if there isn't a letter on either side'.
Of course, I can't imagine regex is the way to go with complicated syntax highlighting, so any good number highlighting in emacs ideas are also welcome,
Any help very much appreciated. (In case it makes any difference, this is for use when Python coding.)
Comment: You can also use this new Emacs package available in MELPA: [highlight-numbers](https://github.com/Fanael/highlight-numbers)
Answer: Start by going to your scratch buffers and typing in a some test text. put some numbers in there, some identifiers that contain numbers, some numbers with missing parts (like .e12), etc. These will be our testcases and will let us experiment rapidly. Now run M-x re-builder to enter the regex builder mode, which will let you try out any regex against the text of the current buffer to see what it matches. This is a very handy mode; you'll be able to use it all the time. Just note that because Emacs lisp requires you to put regexes into strings, you must double up on all of your backslashes. You're already doing that correctly, but I'm not going to double them up in here.
So, limiting the match to numbers that are not part of identifiers is pretty easy. \b will match word boundaries, so putting one at either end of your regex will make it match a whole word
You can match floats just by adding a period to the character class you started with, so that it becomes [0-9.]. Unfortunately, that can match a period all on it's own; what we really want is [0-9]*\.?[0-9]+, which will match 0 or more digits followed by an optional period followed by one or more digits.
A leading sign can be matched with [-+]?, so that gets us negative numbers.
To match exponents we need an optional group: \(...\)?, and since we are only using this for highlighting, and don't actually need to separate out the content of the group, we can do \(?:...\), which will save the regex matcher a little time. Inside the group we will need to match an "e" ([eE]), an optional sign ([-+]?), and one or more digits ([0-9]+).
Putting it all together: [-+]?\b[0-9]*\.?[0-9]+\(?:[eE][-+]?[0-9]+\)?\b. Note that I've put the optional sign before the first word boundary, because the "+" and "-" characters create a word boundary.
Comment: To the reader who rushes through this answer, jumping straight to "Putting it all together," note that the answer states at the beginning "[because strings] you must double up on all of your backslashes ... I'm not going to double them up in here." You must apply that correction for this to work!
Answer: First of all, lose the add-hook and the lambda. The font-lock-add-keywords call doesn't need either. If you want this only for python-mode, pass the mode symbol as the first argument instead of nil.
Second, there are two main ways to do that.

Add a grouping construct around the digits. The numbers in the font-lock-keywords forms correspond to the groups, so this would be '(("\\([^a-zA-Z]\\([0-9]+\\)[^a-zA-Z]\\)" 2 font-lock-warning-face prepend). The outer grouping is rather useless here, though, so this can be simplified to '(("[^a-zA-Z]\\([0-9]+\\)[^a-zA-Z]" 1 font-lock-warning-face prepend).
Just use the beginning and end of symbol backslash constructs. Then the regexp looks like this: \_<[0-9]+\_>. We can highlight the whole match here, so there's no need for the group number: '(("\\_<[0-9]+\\_>" . font-lock-warning-face prepend). As a variation, you could use the beginning-of-word and end-of-word constructs, but you probably don't want to highlight numbers adjacent to underscores or whatever other characters, if any, python-mode has in the syntax class symbol.

And lastly, there's probably no need for prepend. The numbers are likely all unhighlighted before this, and if you consider possible interaction with other minor modes like whitespace, you'd better choose append, or just omit this element entirely.
End result:
(font-lock-add-keywords nil '(("\\_<[0-9]+\\_>" . font-lock-warning-face)))

Comment: Note: this doesn't solve the decimal point problem, nor exponential notation, but they shouldn't be too hard to do now.
Comment: Both answers are great, so I'm afraid I've had to accept according to chronological order! Although yours includes its own set of useful information, so many thanks and a +1


Conversion From DB2 to Oracle:

Question: I am working on DB2 to Oracle Conversion, I want to know what is this TABLE keyword means in DB2 or how to convert it in oracle ?? This code is a part of a tabular function.
SELECT   A.A_REQUESTER,
         A.A_TIME,
         A.A_NAME,
         F.LOCAL,
         F.MSGS
FROM STRTOK_SPLIT_IS_TABLES A( A_REQUESTER,
                               A_TIME,
                               A_NAME,
                               A_CODE ),
TABLE( SYSPROC.GET_MSGS(
       INLOCAL,
       A.A_CODES,
( SELECT TOKEN FROM STRTOK_SPLIT_TABLES_USHARE B
  WHERE A.A_REQUESTER = B.REQUESTER
  AND A.A_TIME      = B.ETIME
  AND A.A_NAME       = B.NAME
  AND B.ORDINAL=1 ) )
    ) F;

Comment: Provide sample data, desired results, and an explanation of what the code should be doing.
Comment: Did a Google on `SYSPROC.GET_MSGS` and got https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0054504.html which I'm guessing manipulates/extracts data from XML.
Answer: I'm not familiar with DB2, but if it has the same meaning as Oracle, it is used to "cast" a type object or a function call to a table so it can be referenced in a SQL statement.
The (Oracle) example below joins the type SYS.ODCIVARCHAR2LIST to DUAL. The type SYS.ODCIVARCHAR2LIST is defined as
CREATE OR REPLACE TYPE SYS.ODCIVARCHAR2LIST FORCE AS VARRAY(32767) OF VARCHAR2(4000);

Using the TABLE keyword allows you to reference the type as if it was an actual table.  If you are on Oracle 19, the TABLE keyword is no longer needed.
Query
SELECT *
  FROM DUAL,
       TABLE (sys.odcivarchar2list ('tab_val_1',
                                    'tab_val_2',
                                    'tav_val_3',
                                    'tab_val_4'));

Result
   DUMMY    COLUMN_VALUE
________ _______________
X        tab_val_1
X        tab_val_2
X        tav_val_3
X        tab_val_4

Comment: I know it's late but thanks.

Conversion From DB2 to Oracle:


Bias and Variance, Overfitting and Underfitting

Question: I am trying to understand the concept of bias and variance and their relationship with overfitting and underfitting. Right now my understanding of bias and variance is as follows.(The following argument is not rigorous, so I apologize for that)
Suppose there is a function $f:\mathcal{X}\to\mathbb{R}$, and we are given a training set $\mathcal{D}=\{(x_i,y_i):1\le i\le m\}$, i.e., we know $y_i=f(x_i)$ for $1\le i\le m$, and that $(x_i,y_i)$ in $\mathcal{D}$ are sampled from the same distribution $P(x,y)$. We use the training set $\mathcal{D}$ to obtain a model $\hat{f_{\mathcal{D}}}$.
(a) The bias and variance of the learning algorithm is then the bias and variance of the estimator $\hat{f_{\mathcal{D}}}(\hat{x})$ on an unseen example $\hat{x}$, respectively. Is this correct?
(b) The bias of $\hat{f_{\mathcal{D}}}(\hat{x})$ on an unseen example $\hat{x}$ is defined to be $\mathbb{E}[\hat{f_{\mathcal{D}}}(\hat{x})-f(\hat{x})]$, where the expectation is taken across all possible training sets $\mathcal{D}$. In other words, we repeat the procedure of sampling the training set $\mathcal{D}$ from $P(x,y)$, and then obtaining a function $\hat{f_{\mathcal{D}}}$ for each such $\mathcal{D}$. We then compute the average $\hat{f_{\mathcal{D}}}(\hat{x})-f(\hat{x})$. Is this a correct interpretation of bias? Different $\mathcal{D}$s can give different $\hat{f_{\mathcal{D}}}(\hat{x})$, and the variance of $\hat{f_{\mathcal{D}}}(\hat{x})$ measures the expected deviation of $\hat{f_{\mathcal{D}}}(\hat{x})$'s from the expected value of $\hat{f_{\mathcal{D}}}(\hat{x})$. Am I correct?
(c) I read that as the model capacity increases, the bias decreases and the variance increases. Although I could understand this somewhat intuitively, I don't quite understand this when I think in terms of the definition of bias. If the model capacity increases, then it is prone to over-fitting. So the learned model does worse on the unseen example $\hat{x}$. In other words, $\hat{f_{\mathcal{D}}}(\hat{x})$ is not very close to $f(\hat{x})$ on an unseen example $\hat{x}$. This will be true if we repeat the procedure for different samples of training set $\mathcal{D}$. Then why is the average error, which is the bias $\mathbb{E}[\hat{f_D}(\hat{x})-f(\hat{x})]$, low? Is it because the positive deviations and negative deviations balance each other to give a low bias?
(d) (very important) Can you explain why high capacity means low bias and high variance (and low capacity means high bias and low variance) using part (b)?
Comment: One can also show relations of the form you informally wrote down in a mathematically "clean", rigorous way. At least I know a source for the classification case. One measures "expressiveness" in terms of shattering coefficients and finally by the VC dimension. Then one shows that certain variations of empirical and actual errors do only deviate much of the VC Dimension gets big (i.e. the model is *very* expressive) and by a "uniform" law of large numbers this is sufficient to obtain "consistency" (the learner does the best it can achieve). Then by regularization one also achieves that the
Comment: classifier is "best possible". All this is presented in a not too formal way in https://arxiv.org/pdf/0810.4752.pdf
Answer: As you correctly stated in (a) and (b), bias and variance are expected values evaluated over repeated sampling of a training set. Even if the bias were 0 for a model, any specific fitted model based on a particular training set will over and underestimate the true function at certain values of the domain due to sampling error; however, over the distribution of possible training sets the model is expected to have no systematic errors for any value of the domain (i.e., no bias).
To address (c) and (d), it helps to think of a very simple model:
Let $\mathcal{D} = \{(x_i,y_i)\},\;\rm{where}\;(x_i,y_i)\sim \rm{MultivariateNormal}(\mathbf{0},\mathbf{I})$
This model basically says that the $y_i$ are just iid standard normal random variables, regardless of the value of $x_i$ -- so its just a constant model $f(x)=0$
Now, let's pretend we don't know this. We could model this process using two extreme approaches:

Fit a constant model: $E[y_i] = \mu$
Fit an interpolating polynomial model $E[y_i] = \sum_{j=1}^{n} a_jx_i^{j-1}$

Using your terminology, the first approach is "low capacity" since it has only one free parameter, while the second approach is "high capacity" since it has $n$ parameters and fits every data point.
The first approach is correct, and so will have zero bias. Also, it will have reduced variance since we are fitting a single parameter to $n$ data points.
Contrast this with the second approach -- for any given value $x$, $f(x)$ will exactly  fit the training data. On average, the fit to an arbitrary $x$ not in our dataset will not be high or low when averaged over all possible datasets of size $n$ (even the fit beyond the data will tend to have polynomials that flip from one sense to another with equal frequency). However, because it fits all the noise (since each $y_i$ is an iid standard gaussian) there will be much more variance in the estimate for an arbitrary $x$  compared to the constant model, hence it will have more variance when averaged over all possible training sets.
So, you see how having more degrees of freedom means you are fitting more of the random component in your model (assuming the model is actually not that complex).
Let's change the true model: if we now assume that our true model is actually some linear model, then what we will see is that the constant model will systematically under-estimate in some parts of the domain and over-estimate in others, no matter how much data we collect. Thus, it will have bias for most values of $x$. However, since we are still using $n$ data points to fit a single parameter, the value of $f(x)$ will be less sensitive to particular data points in the training set and hence will still have relatively low variance.
Compare this to fitting, say, a third-degree polynomial model to the data. Here, you may not have much bias (since a linear model is actually contained in a third-degree model) but the extra parameters mean that the actual polynomial will be affected by the data more than a constant model would.
The key here is that in this second case, both models are wrong -- but, the first one trades some bias for less variance while the second has increased variance but less bias. Which one is "better" (in an MSE sense) must be determined using a test dataset or cross-validation.


Alterar a cor da Seleção da Borda com o Mouse

Question: Olá, tenho a seguinte função abaixo na qual eu seleciono (com o mouse) uma determinada coordenada de uma imagem e a salvo. Acontece que quando é uma imagem muito CLARA ou BRANCA eu não consigo ver o espaço que estou selecionando!
Existe alguma forma de mudar a cor da "borda" da Seleção que estou fazendo na imagem?
Vou salvar somente a parte que seleciono a imagem.
procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  if IsDown then
  begin
    Canvas.Pen.Style := psDot;
    Canvas.Pen.Mode := pmNotXor;
    Canvas.Rectangle(OldStartX, OldStartY, OldEndX, OldEndY);
    OldEndX := X;
    OldEndY := Y;
    Canvas.Rectangle(StartX, StartY, X, Y);
  end;
end;

Segue um PRINT explicando exatamente qual BORDA eu quero mudar: http://prntscr.com/9bgj90
Answer: Tem como sim amigo, porem, como a linha da borda é muito fina, é provável que você precisara fazer alguns ajustes.
Adicione essa propriedade abaixo da pmNotXor:
Canvas.Pen.Color := clRed; //ou a cor de sua escolha

Se precisar deixar a borda mais expessa você pode usar:
Canvas.Pen.Width := 2; //ou qualquer tamanho de sua escolha

Mas para a propriedade Width ficar legal, você terá que escolher alguns estilos de linha para ficar legal.
Aguardo o Feedback!
Comment: Perfeito @Júnior Moreira, muito obrigado!


JQuery UI (Draggable) + TouchPunch moving elements when losing/gaining focus

Question: I've just gotten some draggable screens working on an app I'm working on through jqueryui & touchpunch, but on mobile when the screen loses and comes back into focus, the elements used by jqueryui jump all over the place and not sure what's causing it.  It's fine if none of the elements are interacted with before the loss of focus, only after they've been interacted with.
Any help would be appreciated!
<code>$(document).ready(function(){   // Draggable Elements
    var overviewOpen = true;
    var assignmentOpen = false;

    $(function(){   // Job Overview resize
        $('#overviewResize').draggable({
            handle: "#overviewHeader",
            axis: "y",
            revert: true,
            revertDuration: 0,
            start: function(){ $(this).css("transform", "translate(0px, 0px)"); },
            stop: function(){
                if (overviewOpen == false){
                    $('#overviewResize').css("transform", "translate(0px, -" + ($(window).height() - 196) + "px)");
                    $('#overviewJobID').css("display", "flex");
                    overviewOpen = true;
                } else {
                    $('#overviewResize').css("transform", "translate(0px, " + ($(window).height() - 196) + "px)");
                    if (assignmentOpen == true){
                        $('#assignmentResize').css("transform", "translate(0px, 0px)");
                        assignmentOpen = false;
                    }
                    overviewOpen = false;
                }
            }
        });
    });
    $(function(){
        $('#assignmentResize').draggable({
            handle: "#assignmentHeader",
            axis: "y",
            revert: true,
            revertDuration: 0,
            start: function(){ $(this).css("transform", "translate(0px, 0px)"); },
            stop: function(){
                if (assignmentOpen == false){
                    if (overviewOpen == false){
                        $('#overviewResize').css("transform", "translate(0px, 0px)");
                        overviewOpen = true;
                    }
                    $('#assignmentResize').css("transform", "translate(0px, -" + ($(window).height() - 196) + "px)");
                    assignmentOpen = true;
                } else {
                    $('#assignmentResize').css("transform", "translate(0px, " + ($(window).height() - 196) + "px)");
                    assignmentOpen = false;
                }
            }
        });
    });
});
</code>
Answer: For anyone else with this issue, I figured out that although I'm trying to manipulate my elements css transform, jquery ui adds "top" & "left" to the css as well once it's been placed.  My issue was stemming from the fact that when the screen loses focus on mobile, there's a brief window resize that was throwing everything into chaos.  Adding <code>$('#element').css("top", "");</code> to both stop functions for both elements alleviated the problem.
As a side note, this also cleared up all the other weird calculations I had to do to the translate when this was happening.


Shortened Drush option

Question: I am trying to write a shortened Drush option - we want to have an option for both --force as well as -f
I'm searching everywhere and not seeing any documentation, but it seems like something like it is supported based on this page:
https://groups.drupal.org/drush/commands

What I've got so far:
function parsexml_drush_command() {

  $items['parsexml'] = array(
    'description' => 'Parses XML from an XML feed.',
    'aliases' => array('pxml'),
    'arguments' => array(
      'path' => 'Path to the XML file.',
    ),
    'options' => array(
      'force' => 'Flag to force processing of previously processed XML files.',
      'f' => 'Shortened flag to force processing of previously processed XML files.',
    ),
  );

  return $items;
}

But my guess is that that isn't correct.
What is the correct way to have multiple aliases per option? I can only find how to set the alias for a given drush command.
Answer: Sorry, Drush reserves all short (-f) options for use exclusively by Drush core.  You cannot define them in contrib extensions.
See the function drush_get_global_options for an example of how to define options that have attributes; the short option is 'short-form', although this does not work right for non-Core commands.

Shortened Drush option


Using a randomization to compare frequencies in two groups?

Question: I have a dataset of males and females and whether they dispersed (yes = 1). For example:
<code>Male   0
Male   0
Male   0
Male   0
Male   0
Female 0
Female 1
Female 0
</code>
I'm interested in performing a randomization to determine if the frequency of dispersal is different between males and females. However, very few individuals dispersed, so I do not meet the assumptions of a chi-square test. Of 42 males, 0 dispersed. Of 27 females, 4 dispersed.
I understand that I can do a randomization with data for means, but am less clear if I can do this with binomial data?
Also, is there a simple way to do this in R?
Thanks!
Comment: Yes, you can do a randomization test analgous to chi-square test of association.  Have you considered the `simulate.p.values` option in `chisq.test` in R?  But with 0 positive observations in one group and 4 observations on the other group, you have to consider what could be concluded from the results.
Answer: I would recommend the binomial test as the assumptions are less restrictive than the chi-squared test. Search on binom.test function in R.
Comment: I don't think the binomial test would solve the problem, as the question asks about what is essentially a 2 x 2 contingency table.
Answer: I think what you want to do is to compare two proportions. R's prop.test function does that.
Edited after discussion: Apparently this uses an asymptotic approximation that gives a warning for these data, probably because of too small success numbers.
Thinking about this more, Fisher's exact test should do what you want. This is a permutation test for whether two binary variables (male/female and 0/1) are unrelated.
<code>> x <- c(0,4,42,23)
> x<-as.matrix(x)
> dim(x) <- c(2,2)

> fisher.test(x)

    Fisher's Exact Test for Count Data

data:  x
p-value = 0.0203
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.0000000 0.9167391
sample estimates:
odds ratio
         0
</code>
Comment: Is this test appropriate with the small counts in the data?
Comment: The test doesn't assume that counts are large, so it should be fine. I don't think there's any better for this situation.
Comment: The function will give a warning in the case of these data, that the chi-square result may not be accurate. It gives this warning if any n*x/n is < 5. In this case, with one x being 0, obviously it triggers this warning.
Comment: Ah, you're right. This wasn't transparent from the help page.
Comment: [Comments above refer to the `prop.test` function, not the `fisher.test` function.]
Comment: @Sal.Mangiafico: Actually the fisher.test should be pretty similar to chisq.test with simulate.p.value=TRUE as proposed by you in your first comment. In this case fisher.test doesn't use Monte Carlo approximation and seems preferable to me (test statistic and null hypothesis are not quite identical), however I'd be curious if you have something to say on the comparison between the two (in this case results are pretty much identical).
Comment: I don't have have much intelligent to say about the difference between the two.  I suppose the practical limit to using `fisher.test` is the computing power for tables with high counts or large tables.  But `fisher.test` also has a `simulate.p.values` option.  Note that there is also a `chisq_test` function in the `coin` package`.
Comment: simulate.p.values in fisher.test is only relevant for larger than 2*2 tables. For 2*2 tables it will compute precise p-values.


Como faço pra manipular 3 Checkbox no Angular 2?

Question: Tenho 3 Checkbox. A primeira a opção é tem pão, a seguna a opção é tem peixe e a terceira tem sal. Quero usar o Tamplate forms e não reactive forms. Alguém pode me ajudar?

<form #form="ngForm">

        <input name="" type="checkbox">Tem pao
    <input type="checkbox">Tem peixe
    <input type="checkbox" name=""">Tem sal
    <button type="submit" (click)="enviarPrint(form)">Enviar</button>
</form>
Comment: mas de fato o que precisa que ele retorne true ou false para o backend?
Comment: @Willian Na verdade quero retornar os nomes mesmo...Quando clicar em Tem pão, retornar para o banco "Tem pão". Quando for tem peixe, retornar para o Banco "Tem Peixe". Quando for tem sal a mesma coisa. Consegue me ajudar ?
Comment: coloca o value no checkbox axo que resolve... value="tem pão",  se não me engano quando ele ta false ele nao imprime o value... se for true imprime o value. ou coloca antes de enviar no enviarPrint()  this.opcao2 ? 'tem pão' : 'não tem pao;
Answer: Tudo que você precisa está nesta página, o que você precisa é colocar os três valores num array e fazer um *ngFor, ao final você terá um array onde cada índice vai possuir true ou false. O código exemplo do tutorial está aqui.
Update: Para um Template Form (o que não vai fazer sentido porque não tem diferença), basta você percorrer o formulário, verificar se o checkbox está selecionado e incluir no array.
enviarPrint(form: any | FormGroup) {
    this.array = [];
    for (const field in form.controls) {
        const control = form.controls[field];
        if(control.value === true) {
          this.array.push(field);
        }
    }
  // enviar pro back-end
  }

Exemplo no StackBlitz aqui
Comment: Esse seu método está implantando o Reactive Forms e ele comentou que está usando o Template Forms
Comment: Fiz um update na resposta, favor revisar o voto feito. Obrigado pela correção
Answer: Declare uma variável no seu Typescript
checks = [
    { id: 1, name: 'check 1', check:"true" },
    { id: 2, name: 'check 2', check:"false" },
    { id: 3, name: 'check 3', check:"false" },
    { id: 4, name: 'check 4', check:"true" }
  ];

E no seu HTML utilize o *ngFor

    <input type="checkbox" [checked] = "check.check === 'true'" >
    {{check.name}}


Azure AD app Need admin approval error: App needs permission to access resources in your organization that only an admin can grant

Question: We have an Azure AD app used for authenticating to APIs. We use permissions like offline_access, openid, profile, User.Read etc. and have granted admin consent already. This has been working since 1 year without any issues. In this week, we received 4-5 external users complaining about the error:

Need admin approval
App needs permission to access resources in your organization that
only an admin can grant. Please ask an admin to grant permission to
this app before you can use it.

It is not related to a particular external user from a particular organization, some other user from the same organization don't get this error.

This error occurs only for new external users, we haven't yet received any issues from existing external users.

Admin granted admin consent again after reported error but the users still get the same error message.

I went through few other questions with same error. But since the configuration has been working since past year I am bit confused. During this period we have had lot of external users without any issue.
What configuration should I check to resolve this? Or is there any update in Azure AD default settings?
Answer:
Check if the Allow users to consent to apps accessing company data on
their behalf is set to No in Enterprise Application Users settings.
If it set to No then please toggle it to yes . This option lets users
decide by themselves if they want to grant access to a given app to
everyone in their organization.

From Microsoft's official    documentation: If this option is
set to yes, then users may consent    to allow applications which are
not published by Microsoft to access    your organization's data, if
the user also has access to the data.    This also means that the
users will see these apps on their Access    Panels.  If this option
is set to no, then admins must consent to    these applications before
users may use them.

Check if the Allow users to request admin consent to apps they are
unable to consent to is set to No.
If it is set to No then toggle it
to yes as well. If your organization decides that users indeed must
have explicit approval, this option makes it easy for those users to
request approval.
To enable this option, click on User settings (same
as in the previous stem) and then toggle Admin consent requests to
"Yes". Make sure to Save your changes, which may take a few minutes
to propagate.

From Microsoft Documentation: If this option is set to    yes,
then users request admin consent to any app that requires access    to
data they do not have the permission to grant. If this option is
set to no, then users must contact their admin to request to consent
in order to use the apps they need.

Note : If this Setting is done from your APP tenant , Please also check the external users tenant as this needs to be done from their
side as well as while trying to use the app, your app will retrieve
user profile etc. from the users tenant .

Add Priority Matrix as an Enterprise Application (org-wide)
if your
AAD administrator decides that everyone in your organization should
get access to Priority Matrix, they can follow these steps:
From the
"Enterprise Applications" view, click on All Applications
Select +
New Application to set up Priority Matrix with Azure AD
authentication
Search "Priority Matrix" and proceed to configure the
app with AD authentication

Note: If you still face the issue please reach out to Azure support engineer to get assisted support by clicking on (Help+support)
and creating a technical support request as it may need live troubleshooting.
Comment: Thanks! This helped me understand. Users were not set to provide consent. We had to add Graph related permission which was not present when we debugged. After adding the missing permission followed by admin grant solved this issue.
Comment: @SushrutParanjape what was the missing permission? We have hit a similar issue
Comment: @sjgp In our case, we were adding scope Sites.ReadWrite.All in the login URL. But this app permission was missing in the Graph App (Sites.ReadWrite.All was present but someone might have removed this later). So even with admin providing consent, users were getting error. After adding Sites.ReadWrite.All again and providing admin consent, the error resolved for us. So you can check if you are requesting a specific permission but that is not added to the graph. I hope this helps.
Comment: also need admin role for the user, otherwise cannot proceed too
Comment: Why does it prompt for approval when admin has already approved?
Answer: Please note that, Consent phishing attacks are highly emerging these days. So, as an admin, we should think about granting permissions to users consent to other applications into our Office 365. You can refer the blog manage user consent to apps to know the ways to approve the applications that users requested.
Also, please don't get upset about the existing applications that were approved by user without your concern. You can now review the permissions granted to apps in office 365 and take remediations immediately if you find an unnecessary application.


For what values of c is there a straight line that intersects a four-polynomial's graph in four distinct points?

Question:

I can't understand the part of the solution: $\textbf{If and only if}$
It is trivial that if a four-degree polynomial has four real solutions, then $f''(x)=0$ has two real solutions. But the converse has a counterexample($f''(x)=0$ has two real solutions can mean that $f'(x)=0$ has three extreme values. But that doesn't mean $f(x)=0$ has four real solution)
Is there a proof about the opposite side? or is the solution wrong?
*I've searched similar question in the web, and they all say that "if and only if" is trivial
Comment: i think $f$ only can have shapes of v or w. So if there are a straight line cut f at 4 points, f must have shape of w, then we get bedim thing like above.
Answer: You are correct that having three points where $f'(x)=0$ does not guarantee four roots, but having some line intersect four times is less restrictive than having the line $y=0$ intersect four times.  Assume the $x^4$ coefficient is positive, otherwise invert things. If there are two minima you can draw a line between the minima.  The local maximum must be above that line, so you can move it up a bit if necessary and cut the graph in four points.  There must be an inflection point between the local maximum and each local minimum because the curvature changes from down to up somewhere in the segment.  This is a rough proof that two inflections means a line cuts four times.
If a line cuts four times, subtract the line from the polynomial to get a quartic with four roots.  There must be minimum/maximum/minimum and there must be inflections between them.
Comment: What an answer sir! I was improved by your answer. I now realize there is a difference between "Having four intercepts with y=0" and "Line intercepts four times". The latter is equivalent to "Having two inflection points", by your rough proof. (I think that applying the Role's theorem will make the proof more logical. Am I right?)  Anyway, thank you for your kind answer :)
Comment: Yes, you can apply Rolle's theorem to $f'(x)$ to justify an inflection point between two local maxima/minima


Zen subtheme: no sidebar on a given page

Question: The overall layout of the site is composed of a 2 column layout (main content area + right sidebar). I have a /forum section on my site and I would like to have a single plain area for it and its childs.

Adding a forum.tpl page containing no sidebars does the trick?
Another way might be to prevent .sidebar-second being loaded as a
body class for a given URL (mysite.com/forum). Is this a clean way
to do it and above all will it escalade to /forum/subforums ?

I'm using a 7.x-5.x zen subtheme with D7 and Advanced Forum as the forum solution.
Answer: After some tests which involved using arguments in page.tpl and CSS trickery to clean up after, I couldn't manage to have a proper working solution.
Although I would have prefered to find a way to do this at a template level, easiest and quickest solution I finally found, was to use Context module
Basically I created a simple context with a Condition on path option and a Reaction on regions of the concerned theme. Checked the sidebar I wanted to exclude Saved and it was done.
Good thing doing this through the Context module is that, it removed the concerned regions, but most importantly it removed also the corresponding classes from  which were the pain in the butt to begin with.


Adding shortcut to setup project in visual studio 2010

Question: I am using visual studio 2010 and I have a .net desktop app (winform). I want to create a setup for project. I have added a setup wizard project to the solution. Now I want to add a shortcut to Programs menu and desktop. With right click on "User's Program menu" and selecting Add, I have only these options: Folder, File, Project output and Assembly. How can I add shortcuts?
Another question: Is it possible to add .net 4.0 to setup project and install it if necessary?
Thank you in advance.
Comment: possible duplicate of [Visual Studio Deployment Project - Create shortcut to deployed executable](http://stackoverflow.com/questions/3303962/visual-studio-deployment-project-create-shortcut-to-deployed-executable)
Comment: Your deployment project has a 'Detected Dependencies' folder, the .Net framework should be in there.
Comment: .. and it should also be in 'Launch Conditions' (right-click on project, view, launch conditions)
Comment: This worked greate: http://stackoverflow.com/a/4333203/1152549
Answer: if you're looking to add shortcut to your desktop while installing your windows app you should follow these steps

From Solution Explorer click your setup project.
Click File System Editor (on top of Solution Explorer).
When File System Editor has opened, on left tab you can see "File System on Target Machine". Click Application Folder.
Then on the right tab the "Primary output from MyApp (Active)" appears. Right click it and select "Create shortcut to Primary output from MyApp (Active)". You should now see the shortcut appear below the primary output, which is your application executable.
Drag & Drop that shortcut from right tab to left tabs File System on Target Machine - User's Desktop folder.
Now the shortcut to your .exe will appear on the desktop after install.
You can click the shortcut in File System Editor and edit the Name property from Properties grid to change the text that appears on the icon.
Comment: Hello. I followed the steps, but when trying to open the app using the desktop icon, it tries to open the .dll, not the executable. Any thoughts on what am I doing wrong? It's a WPF app with .NET Core. Thanks.
Comment: Nevermind. I just found an answer. Apparently for my issue, I needed to include the application's executable in the Application Folder section, and then create the shortcuts from that. This helped https://www.technical-recipes.com/2011/how-to-create-an-installer-in-microsoft-visual-studio/
Answer: here the explanation to add a shortcut in your project:
http://support.microsoft.com/kb/837220
Comment: Isn't that outdated since VS2008? http://thinksimpleshirin.wordpress.com/2012/02/13/creating-desktop-shortcuts-in-deployment-projects/ is better and has screenshots..
Comment: link only answers tend to move after time.
Answer: Here is a good visual
This explains the entire setup and deployment in vs2010.
A short note from my answer:
(1) File -> New Project -> Other Project Types
   -> Setup and Deployment -> Visual Studio Installer
(2) Add a name to your setup project.
(3)   Right click Application Folder -> Add -> project output
(4) ****Select your respective project's solution "primary output from yours.."****
(5) ****Add the respective 3rd party dlls.**** // Never forget this one.
(6) Right click setup project in solution explorer and BUILD it.
(7) Find the respective setup in debug folder(by default)
You will get the .exe and .msi in the folder.
Comment: Hi @Praveen, After completing installation of window form MSI setup, my raw files(Design and coding) are also showing at installation location. I've developed this application using visual studio 2010. Setup created successfully, but after installation that MSI this problem is happening. Please help me. Thanks in advance.
Answer: In order to include .net framework as part of the installation package, select your installer project from solution explorer, right click -> properties.
In the opened window, press "prerequisites" button. Another window opens and select your desired .Net Framework version and then from the radio buttons choose "Download prerequisites from the same location as my application".


length of trademark symbol in python 2.x

Question: why is
>>> len('™')
>>> 3

in python 2.x?
how can I quickly fix it to be considered as one character (like Python 3.x?)
Answer: Your terminal encoding is set to UTF8. You are counting the bytes in the encoded character:
>>> '™'
'\xe2\x84\xa2'
>>> len('™')
3

Use unicode to count characters instead of bytes:
>>> u'™'
u'\u2122'
>>> len(u'™')
1

or decode from the terminal encoding:
>>> import sys
>>> '™'.decode(sys.stdin.encoding)
u'\u2122'

In Python 3, strings are unicode values, with the Python 2 str type renamed to byte (your input is essentially the same as b'™' in Python 3).
You may want to read up on Python and Unicode:

The Python Unicode HOWTO
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky


Fatal error: Range end index has no valid successor

Question: So i have a problem using the Switch statement, when i used it with a range i get this "Fatal error: Range end index has no valid successor" in the console.
var ArrayBytes : [UInt8] = [48 ,48 ,48]
 var SuperArrayMensaje : Array = [[UInt8]]()
var num7BM : Array = [UInt8]()

    for var Cont27 = 0; Cont27 < 800; Cont27++ {

        ArrayBytesReservaSrt = String(Mensaje7BM[Cont27])

        switch Mensaje7BM[Cont27] {

        case 0...9 :
                     num7BM = Array(ArrayBytesReservaSrt.utf8)
                     ArrayBytes.insert(num7BM[0], atIndex: 2)

        case 10...99 :
                     num7BM = Array(ArrayBytesReservaSrt.utf8)
                     ArrayBytes.insert(num7BM[0], atIndex: 1)
                     ArrayBytes.insert(num7BM[1], atIndex: 2)

        case 100...255 : // --> THE problem is here "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"
                     num7BM = Array(ArrayBytesReservaSrt.utf8)
                     ArrayBytes.insert(num7BM[0], atIndex: 0)
                     ArrayBytes.insert(num7BM[1], atIndex: 1)
                     ArrayBytes.insert(num7BM[2], atIndex: 2)

        default : break

        }

    SuperArrayMensaje.insert(ArrayBytes, atIndex: Cont27)

                ArrayBytes = [48 ,48 ,48]
    }

Comment: Can you give info of `Mensaje7BM`?
Comment: It's not really needed.  The type being switched on is `UInt8`.
Comment: Related: [Lesser than or greater than in Swift switch statement](http://stackoverflow.com/q/31656642/2792531)
Answer: The problem can be reproduced with this MCVE:
let u = 255 as UInt8

switch u {
case 0...9: print("one")
case 10...99: print("two")
case 100...255: print("three")
}

And to a degree, we see the problem if we simply try to create a range variable that would cover this range:
let r = Range<UInt8>(start: 100, end: 256)

This doesn't compile.  First, we must note that the end argument for the Range constructor is not included in the range.
The range 100...255 is equivalent to 100..<256.  If we try to construct that range, we get the compile error:

Integer literal '256' overflows when stored into 'UInt8'

We can't create a range which includes the max value for that integer type.  Problematically, there's no UInt8 value larger than 255.  That's needed because for something to be contained within a range, it must be smaller than the end value of the range.  That is, it must return true when compared with the < operator.  And there's no UInt8 value that can make this statement: 255 < n return true.  Therefore, 255 can never be in a range of type UInt8.
So, we have to find a different approach.
As the programmer, we can know that the range we're trying to create representing all the three digit decimal numbers that fit in UInt8, we could just use the default case here:
let u = 255 as UInt8

switch u {
case 0...9: print("one")
case 10...99: print("two")
default: print("three")
}

This seems the simplest solution.  I like this option best because we don't end up with a default case that we know will never execute.
If we really explicitly want a case that captures all of the values from 100 to UInt8 max, we can also do this:
switch u {
case 0...9: print("one")
case 10...99: print("two")
case 100..<255, 255: print("three")
default: print("how did we end up here?")
}

Or like this:
switch u {
case 0...9: print("one")
case 10...99: print("two")
case 100...255 as ClosedInterval: print("three")
default: print("default")
}

For more reading on the ClosedInterval, see the Apple documentation or Swift doc.


Good vs Bad Trial in Probability

Question: I am watching this video on Probability, around the end there is a problem to be solved:

I can't understand how a summation which extends from 1 to infinity can be equal to  $\frac{1}{1-4/6}$
Comment: https://en.wikipedia.org/wiki/Geometric_series#Formula -- it even shows how to derive it.
Comment: Search Geometric series on internet.
Answer: You know the sum is finite, since it is a probability and so must be between $0$ and $1$.  Let's call it $S$ where $$S=\frac16+\left(\frac46\right)\frac16 +\left(\frac46\right)^2\frac16 +\left(\frac46\right)^3\frac16 +\cdots$$
Multiplying through by $\frac46$ gives $$\frac46 S=\left(\frac46\right)\frac16 +\left(\frac46\right)^2\frac16 +\left(\frac46\right)^3\frac16+\left(\frac46\right)^4\frac16 +\cdots$$
and taking the difference gives $\dfrac26 S=\dfrac16$ i.e. $S=\dfrac12$, as you might intuitively expect from the symmetry in the question.  This is a geometric series
Answer: The series $S = (\frac 46)^0\frac 16 +(\frac 46)^1\frac 16+... = ar^0 +ar^1 + ar^2...$ is a geometric series. You can search Geometric Series on internet to get the answer. In addition, you may get the result for the sum of the first n terms of a geometric series, which is $a \frac {1-r^n}{1-r}$ and also useful in statistics.

Good vs Bad Trial in Probability


Views Load More pagination causes duplication

Question: I am encountering an issue with Views Load More with Waypoints module. My question is more focused on the next contents that are retrieved. Because there are new contents added to the top, the page 2, for example, now contains items from page 1, thereby showing duplicates. Please see explanation below. How can this be addressed?
Comment: Sites like deviantArt does not address this at all, for example. Anyway, this is not Drupal issue, this is general design issue. If you have a solution algorithm and you want Drupal **implementation**, then it's something we could help here.
Comment: Hi Molot, thanks! I initially posted this question in ux.stackexchange.com but was directed to post here instead. I hoped to get ideas on how this can be done with Views, and the Views_Load_More module. An idea is that timestamp of first load is captured and passed in exposed filter to ensure that view results are still the "old" ones. But I am having difficulty in programmatically passing the timestamp to the exposed filter.
Answer: Some suggestions:
1) Do not use the LOAD MORE option in views but use a self generated link with the help of global text in the footer. Then this link is going to a second page and then you have the view in a new fresh window. Hopes this helps.
2) You can try if the behavior of the view is the same without Ajax. Sometimes live is a miracle. if so you know that is a ajax issue and not a views issue.
Answer: You can solve this by using Views Random Seed module.
This may occurred due to any of your SORT CRITERIA which is likely the cause of duplicates. So add Global: Random seed also as one your sort criteria conditions to avoid duplicates.
Answer: In Drupal views we have an advanced section .In that Other options we ll find the Query edit that settings into distinct .This may avoid duplicates
Comment: Issue OP asks about is not about that. It's about entries that were pushed from 1-10 range to 11-20 range after 1-10 was displayed bud before user requested 11-20. It has nothing to do with duplicates in *one* query
Answer: I was able to achieve this by:

Setting a JavaScript variable with the current timestamp (drupal_add_js() in hook_preprocess_page())
Appending this value to my pager anchor through JavaScript


How to differentiate function related to bloom filters?

Question: I am trying to understand a scribe note on choosing the right number of hash functions $k$ for a bloomfilter of size $n$ and $m$ elements. The following is stated:
Suppose we are given the ratio $\frac{m}{n}$ and want to optimize the number $k$. If $$g=\ln(f)=k\ln(1-e^{-kn/m})$$ and we let $p=e^{-kn/m}$. Then the derivative of $g$ is: $$\frac{dg}{dk}=\ln(1-p)+\frac{kn}{m}\cdot\frac{p}{1-p}$$
This confuses me because when I try to differentiate $g$ I get the following: $$\begin{equation} \frac{dg}{dk}=\ln(1-p)+\frac{1}{1-e^{-km/n}} \cdot \frac{e^{-km/n} \cdot m-kn}{m^2} \end{equation}$$
Link to equation (on page 2): http://people.math.gatech.edu/~randall/AlgsF09/bloomfilters.pdf
Comment: You can't derive w.r.t. to an integer, so it is probably assumed that $k\in\mathbb R$ for the derivative. How did you try to differentiate $g$ yourself? If you differentiate $e^{\alpha k}$ with respect to $k$, there is no way that a factor $k$ appears. $\frac{d}{dk} e^{-\alpha k} = -\alpha e^{-\alpha k}$
Comment: I realise that I have made a mistake. I will correct it
Comment: @GoldenRetriever You used the chain rule. So you have to find the derivative of the denominator of $(1-p(k))$ which is $-p^{'}(k)=\frac{n}m\cdot p(k)$ Here you have to use the chain rule again.
Comment: Your term $\frac{1}{1-e^{-kn/m}}(1-e^{-km/n}) $ does not make sense.
Comment: @YvesDaoust right. Corrected now.
Comment: Now $\frac{1}{1-e^{-km/n}} \cdot \frac{e^{-km/n} \cdot m-kn}{m^2} $ does not make sense.
Comment: the point is that I have not done it right. I have not applied the chain rule as Calvin puts it in his answer.
Comment: Bloom filters deserve a capital "B" because it is a certain Mr Bloom that has defined them...
Answer: This is because you also have to differentiate $p$ as it depends on $k$. It goes like this: first note
$$ \frac{d}{dk} p = \frac d{dk} e^{-kn/m} =-\frac{n}{m} e^{-kn/m} =-\frac{n}{m}p$$
Then applying product rule and chain rule,
\begin{align} \frac{dg}{dk} = \frac{d}{dk}(k(\ln(1-p))
&=\ln(1-p) + k\frac{d}{dk}(\ln (1-p))\\
&=\ln(1-p) + k\frac{\frac{d}{dk}(1-p)}{1-p}\\
&=\ln(1-p) + k\frac{0-\frac{dp}{dk}}{1-p}\\
&=\ln(1-p) + k \frac{-\left(-\frac nmp\right)}{1-p}\\
&=\ln(1-p)+\frac{kn}m\cdot\frac{p}{1-p}
\end{align}
Comment: @GoldenRetriever for the first question, yes, sort of, but you could say that $g$ is "actually" $g(k,n,m)$, or maybe you prefer to say $g$ is "actually" $g(p(k))$. Pure mathematics books at undergraduate level and up try to avoid this kind of notation (sorry, I was away and didn't notice the first question)
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/120453/discussion-between-calvin-khor-and-goldenretriever).
Comment: 1. I am not sure what you are doing in the first note? 2. How do I know that I need to differentiate for $k$ as well? I just thought that I should try to find the derivative for everything on the right side of the equation, and then I am good.
Comment: aah okay. So when I use the chain rule I have to differentiate what I pulled down from the exponent as well?
Comment: @GoldenRetriever yes. I added details for point 1, hopefully it is clear
Comment: totally :) the first note is what you are applying at the last chain right?
Comment: @GoldenRetriever yes exactly
Comment: Now, since we have $\frac{dg}{dk}$ could I say that the function $g$ is actually $g(k)$? I.e. the derivative of $g$ with respect to $k$?
Comment: How is that you go from $\frac{d}{dk}e^{-kn/m}$ to $-\frac{n}{m}e^{-kn/m}$. I am confused about where the $k$ goes ?
Comment: @GoldenRetriever the derivative of $e^{\lambda k}$ is $\lambda e^{\lambda k}$?
Comment: alrighty. thanks again.
Comment: I am sorry, but I still don't see how $\frac{d}{k}(-kn/m)=-\frac{n}{m}$. I have tried to do this: $\frac{d}{dk}(-k\cdot \frac{n}{m})=-k\cdot \frac{d}{dm}(\frac{n}{m})-(\frac{n}{m}) = \frac{-kn}{m^
2}+\frac{-n}{m}$
Comment: @GoldenRetriever, $\frac{d}{dk}( Ck) = C$. Here, $C = -\frac{n}{m}$
Comment: So we would do anything more to $C=-n/m$ because there is no $k$ in it?
Comment: @GoldenRetriever this is highly dependent on context. In your case $n,m$ do **not** depend on $k$, so you are done. But e.g. if  $n$ was a function of $k$, then you need to continue  $$ \frac d{dk}{\frac{-n}m k} = \frac{-n}m + k\frac{- \frac{dn}{dk}}m$$
Comment: okay, because I was confused that $C$ didn't become $0$ since $\frac{d}{dk}(\frac{n}{m})=0$
Comment: @GoldenRetriever The $C$ only becomes 0 if you differentiate it. You *can* apply product rule to $Ck$ and then you will have to use this fact:
$$ \frac d{dk} (Ck) = \frac{dC}{dk} k + C \frac{dk}{dk} = 0\times k + C \times 1 = C$$
this result is the same as what I said earlier
Answer: $$g=k\ln(1-e^{-kn/m})$$ and
$$\frac{dg}{dk}=\ln(1-e^{-kn/m})+k\frac{\dfrac nme^{-kn/m}}{1-e^{-kn/m}}=\ln(1-p)+\frac{kn}m\frac{p}{1-p}.$$
I don't see any problem.

You can also work this out as follows:
$$\frac{dp}{dk}=-\frac nm p$$
and
$$\frac{d(k\log(1-p)}{dk}=\log(1-p)-k\frac{\dfrac{dp}{dk}}{1-p}
\\=\log(1-p)+\frac{kn}m\frac{p}{1-p}.$$
Comment: nice. How is that you go from $\frac{d}{dk}e^{-kn/m}$ to $-\frac{n}{m}e^{-kn/m}$. I am confused about where the $k$ goes?
Comment: @GoldenRetriever: come on, that's the derivative of an exponential.
Comment: right. thanks. much appreciated.


How to style a programmatically created page with a template?

Question: I'm struggling with understanding theming pages with templates. I'm stuck with creating a new template for a programmatically created page. I have a module that shows a download page for a file. The page is basically a form where user can click Submit and get their file downloaded. I construct the whole form programmatically in a page callback. But what if I want to style it with a template? I fail to see how to do it. Here is my (simplified) code:
// Implements hook_menu()
function mymodule_menu()
{
    $items = array();
    $items['file/%mymodule_mycustomfile/download'] = array(
    'page callback' => '_mymodule_filedownload',
    'title' => 'Page Title',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    );
    return $items;
}

// Implements autoloader %mymodule_mycustomfile
function mymodule_mycustomfile_load($fid)
{
    return ($fid > 0) ? (object)array('fid' => $fid) : FALSE;
}

// Page callback function
function _mymodule_filedownload($mycustomfile)
{
    return drupal_get_form('_mymodule_filedownload_form', $mycustomfile);
}

// Creates page form
function _mymodule_filedownload_form($form, &$form_state, $mycustomfile)
{
    $form['label'] = array('#type' => 'item', '#markup' => 'File ID');
    $form['fid'] = array('#type' => 'item', '#markup' => $mycustomfile->fid);
    $form['submit'] = array('#type' => 'submit', '#value' => 'Download');
    return $form;
}

// Submit button click handler
function _mymodule_filedownload_form_submit($form, &$form_state)
{
    die('On Submit');
}

You can see that I construct my form fully in _mymodule_filedownload_form(). But I want to have something like file-download.tpl.php for it and put things like Label there. I fail to see how to do it. My problems are:
1) I stumbled upon theme_hook_suggestions and by default Drupal suggests the following template names: page__file, page__file__%, page__file__1, page__file__download. When I created page--file--download.tpl.php and went to /file/1/download, my screen went blank. I do not know how to output my form in this file and I'm afraid I do not even want to restyle the whole page. I only need to style the page content (the form itself) and leave the page alone. Why can't I have file--download.tpl.php if I have node.tpl.php and comment.tpl.php?
2) As a side note, when you execute template_preprocess_page(&$variables) on node pages, you can see the defined $variables['node'] that contains full node object. How is it done? Can I possibly have something like $variables['mycustomfile'] on my file download pages?
Answer: In this case your page is a form, so you need to create a form template this way:
Implement hook_form_alter() in a module or template.php and set the form's #theme property:
function _mymodule_filedownload_form($form, &$form_state, $mycustomfile)
{
    ...
    $form['#theme'] = array('mymodule_filedownload_form');
    ...

}

Then implement new theme:
/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path){
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'mymodule_filedownload_form' => array(
      'render element' => 'form',
      'template' => 'form--mymodule_filedownload_form',
      'path' => $path . '/templates',
    ),
  );
}

And then add form--mymodule_filedownload_form.php template with follow code to render complete form (you can render it also by components):
<?php print drupal_render_children($form) ?>

Comment: thanks. I managed to figure out most of your solution myself, but what I lacked was $form['#theme'] = array('mymodule_filedownload_form'); Now I can use a template.


Finding the maximum order of an element of $U(4) \times U(9) \times U(5)$

Question: I would like to find the maximum order of an element of $U(4) \times U(9) \times U(5)$. I know that $U(4) = U(2^2)$, and $U(9) = U(3^2)$. So I get that $U(4) \times U(9) \times U(5) = U(2^2) \times U(3^2) \times U(5).$
I also know that $U(2^2) \cong \mathbb Z_2 \oplus\mathbb Z$ and $U(3^9) \cong \mathbb Z_6$. So we get that $U(2^2) \times U(3^2) \times U(5) \cong (\mathbb Z_2 \oplus\mathbb Z) \oplus \mathbb Z_6 \oplus \mathbb Z_4$.
Clearly, the maximum order of an element of $U(4) \times U(9) \times U(5)$ is finite. But one of the isomorphism theorems I've applied above tells me that that particular maximum order of an element of $U(4) \times U(9) \times U(5)$ is equal to the maximum order of an element of $(\mathbb Z_2 \oplus\mathbb Z) \oplus \mathbb Z_6 \oplus \mathbb Z_4$, which is, in fact, infinite. I don't get this at all.
$(\mathbb Z_2 \oplus\mathbb Z) \oplus \mathbb Z_6 \oplus \mathbb Z_4$ would have infinitely many elements since $\mathbb Z_2 \oplus\mathbb Z$ has infinitely many elements.
Can someone please explain this to me?
Thanks in advance.
Comment: So we have $\Bbb Z_2×\Bbb Z_4×\Bbb Z_6$.  We should have an element of order $12$.
Comment: $U(2^2)\cong \Bbb Z_2$.
Comment: How come it says in my notes though that for all $k$ greater than or equal to $2$, $U(2^k) \cong \mathbb Z_2 \oplus \mathbb Z_{2^{k-2}}$. In our case, we chose $k$ to be equal to $2$.
Answer: $U(4)\cong\Bbb Z_2$.
We wind up with $\Bbb Z_2×\Bbb Z_6×\Bbb Z_4\cong\Bbb Z_2×(\Bbb Z_2×\Bbb Z_3)×\Bbb Z_4\cong\Bbb Z_2×\Bbb Z_2×(\Bbb Z_3×\Bbb Z_4)\cong\Bbb Z_2×\Bbb Z_2×\Bbb Z_{12}$.
There is thus an element of order twelve.
Comment: But in my notes, it says that for all $k$ greater than or equal to $2$, $U(2^k) \cong \mathbb Z_2 \oplus \mathbb Z_{2^{k-2}}$. In our case, we chose $k$ to be equal to $2$.
Comment: If $k=2$, you get $\Bbb Z_2×\Bbb Z_1\cong\Bbb Z_2$.
Answer: This is an issue of notation.
Remember that $\mathbb{Z}_{n}$ actually means the quotient group $\mathbb{Z} / n\mathbb{Z}$, i.e., the group of integer remainders modulo $n$.
So $\mathbb{Z}_1 \cong \mathbb{Z} / 1\mathbb{Z} \cong \{0\}$, the trivial group. The only possible remainder when dividing by 1 is 0. So $\mathbb{Z}_1 \ncong \mathbb{Z}$! A reasonable mistake to make!


How to use Piano pedals without using the foot?

Question: I have a piano and am disabled -- wheelchair kind of disabled: I can move my feet but not use the pedals. That task is kind of complicated.
I've considered buying some kind of a car hand-control like this, but I'm not sure if it works, and if I want to use the sustain pedal, it means I have to keep holding the controller, leaving only one hand to play music.
Are there tools or ways to solve that problem?
Comment: Apparently the term I was looking for is actually "puff switch". I wasn't talking about a MIDI breath controller. I was thinking you or someone could rig up a sip/puff switch for this. http://orin.com/access/sip_puff/ You probably wouldn't be able to half-pedal or anything like that with a sip/puff, but with enough visits to Home Depot and Radio Shack you could build something that pushes down the damper on puff and lets it up on sip.
Comment: Agreed. I was suggesting something that would have to be custom built. I'm not aware of anything off the shelf. A Yamaha Disklavier as suggested by @alephzero should be a lot easier to make workable using a typical MIDI breath controller (not all of which require a computer). Disklavier + breath controller might be a more expensive solution than others, though.
Comment: I've seen breath controllers to solve problems like this before, but never one specifically for piano. Worth looking into though.
Comment: @ToddWilcox yeah but breath controllers need to be plugged in USB, not an option on acoustic pianos
Comment: @ToddWilcox it has to be DYI tool :) requires to much pressure to push it :D
Comment: This looks like a project for a graduate student!  I'm thinking of the field of ergonomics, maybe.
Comment: How about a pulley attached to your head or shoulders so you could adjust by moving your head/shoulders. Lift your left shoulder for paino and right shoulder for forte.
Comment: I propose a bite-activated pressure sensor rigged to an actuator pushing on the pedal. This sounds like a fun project for an electrical engineering student.
Comment: Are you playing an acoustic or electronic piano?
Comment: @MaxWilliams acoustic
Comment: Just this week I will do a first test with a system that can solve the problem of pianists who are unable to control the damper pedal with a foot.
See: http://www.pianoman.nl/pedal-adaptor-for-the-disabled-pianist.html
I will update that page as soon as I can tell more.
Answer: Can't use feet well, but if you could move a knee to one side, it would be a simple lever attachment to the pedal, maybe from your wheelchair. Look at knee levers that pedal steel players use. You only really need the damper pedal - the 'soft' pedal could be added later, but it's not as vital as the sustain.
Comment: I might mention that the knee lever was the piano damper mechanism that preceded the pedal.  Mozart has some quotes about using it and liking it.  The pedal was introduced in the 1770's.
Comment: +1. And as a bonus, depending on your range of motion, that same mechanism could serve as multiple pedals.  Squeeze your right knee in for one pedal, push it out to the right for another pedal, etc.
Answer: This may not be as "simple" as it first appears, because (apart from the most basic playing technique) the piano pedal action is not just an "on-off switch". You need to control the speed of movement, and not necessarily depress the pedal fully. Also the pedals need quite a lot of force to operate them, which is no problem for normal human feet, but would require some "serious engineering" to do accurately (and safely, reliably, and silently) with an electric motor
Unless you really can't bear to part with the actual gifted piano, you might consider a Yamaha Disklavier, which is a conventional piano plus the mechanics for full MIDI control (of everything, not just the pedals). They aren't cheap, but presumably your existing piano would offset some of the cost. You could then use almost any sort of MIDI controller to operate the pedals - possibly even a set of "digital piano pedals", perhaps mechanically modified to work with the foot movement that you have.
There are plenty of companies who sell kits for the opposite purpose - i.e. to convert an acoustic piano into a source of MIDI data, to record a live performance - but that is not what you want. I don't know of anybody (apart from the Disklavier) selling something that would convert an acoustic piano to be played by MIDI.
Incidentally, even the Disklavier mechanism is quite "wimpy" compared with the old-style pneumatically operated "player pianos" controlled by piano rolls.
This http://www.soundonsound.com/sos/aug00/articles/ballet.htm is the saga of some of the problems recreating an avant-garde piece written for 16 synchronized player pianos (!!!) using a stage full of Disklaviers.
Comment: At least in classical piano playing, you don't bang the pedal to the floor as fast as you can and release it the same way, unless that's what you *intend* to do. If you do that you produce mechanical noise. Lifting the dampers quickly off the strings makes every string in the piano vibrate slightly, and releasing the pedal quickly makes an audible "thump" when the dampers land back again. The pedal drive mechanism on a Diskclavier moves the pedal in 16 incremental steps, each step timed independently by recording what the human player did using his/her feet, not just an "up" and "down" motion.
Comment: Actually, the previous comment is out of date. The current "pro" disklaviers record and reproduce 256 steps of pedal movement not 16, and 1024 steps for the keys.
Comment: How do you mean 'control the speed of movement'?
Comment: @alephzero: Interesting.  I used to sell Yamaha pianos back around 1990, when the unit was a big box that sat beside the piano, and I remember 16 steps of pedal movement too.  I'm not surprised to see that they have improved the sampling granularity to that degree.
Answer: There are instruments like harpsichord or clavichord that seldom (or even never) had pedals similar to the pedals of the modern piano. And the music for these instruments is often played on a piano now.
I suggest to practice without pedals and perfect your skill to replace them by manual action where needed.
Pedals just help to control the duration and volume. Both can be achieved through the manual keyboard as well, while maybe more difficult. You may think about your repertoire but not all even really good pieces absolutely require pedals for playing.
Comment: and this guy agrees https://www.youtube.com/watch?v=XRseYIWteKw
Comment: This is a great point.  I'm primarily an organist, so sometimes I accidentally forget to use the sustain pedal on the piano.  There are quite a few pieces where organ fingerings feel and sound quite natural on a piano.
Answer: I'm not sure if this is any help, but I would probably approach the problem first by suggesting you swap out an acoustic piano for an electronic keyboard. This allows for other controllers to be used in non-standard ways (usually using the MIDI control standard).
You might find that this is quite technical to start on, I'm not sure where you stand with music technology.
You could try a MIDI breath controller (for instance http://www.tecontrol.se/products/usb-midi-breath-controller), to see if you can map blowing into a tube to the sustain control.

With less technical jiggery-pokery you could also use a standard sustain pedal (such as this http://www.guitarguitar.co.uk/keyboards/detail.asp?stock=12052310152332&gclid=CM_038GxtccCFa-WtAoduwkGug). With electronic instruments, the pedal can be a lot more easily re-located, so you could try pressing the pedal with another part of your body (putting it under your arm, or rigging up some way to press it with head movement, perhaps).
I don't know of any way you could achieve either of these solutions with a standard acoustic piano.
Comment: Fair enough, I don't really know what to suggest, then. There may be a technical solution possible, a small processor (Arduino or Rasperry Pi, for instance) to push the pedal with a servo-motor when a button is pushed. But it would be a bit of engineering to make it all work. (If you want to have a try at this, you could ask questions over on the Rasperry Pi stack exchange).
Comment: yeah considered that but the piano was given to me as a gift and I really like it, it's a luxurious item to have in your home :) so prefer to keep it and look for a solution :)
Comment: tim's answer seems the simplest but im seriously considering pi for the fun of it :)
Comment: It would be an interesting project, and possibly one which other people would be interested in. (Disclaimer: I don't have the skills to make that happen)
Comment: @AJFaraday Instead of pushing the pedal itself, it may be easier to install the actuator at the top end of the [pedal rod](http://community.fortunecity.ws/emachines/e11/203/pedals.html).
Comment: @200_success That's a good idea, although it may mean a little more modification of the instrument itself (depends just how open the pedal mechanism is at the top)
Answer: Depending on the repertoire you want to play you might consider playing Mozart's fortepiano. It is not always built with pedals;

sometimes hand stops or knee levers were used instead
  -Wikipedia

The music written for these instruments tends to differ in the way that the 'pedals' are used, they might be held on for longer passages. If music of this period did intrest you, then the fortepiano would be the authentic way to play it.
Answer: Bite-controlled, wireless system with graduated control
Dr. Rüdiger Rupp / Heidelberg University Hospital
A bite-controlled, wireless system allowing for graduated control of the sustain pedal.

A press release from the university was published by ScienceDaily
The press release was also adapted into a UPI article.

This actuator-based system was developed in collaboration with piano manufacturer Steingraeber & Söhne. Contact Steingraeber to find out more. I received a very kind and informative response to my inquiry. You can also try contacting the hospital.
Head-activated wireless controller
CanAssist / University of Victoria

Head-Activated Piano Pedal:...a two-part technology: a mechanical device that sits on the floor and attaches to a piano pedal, and a headband containing a wireless sensor that measures changes in its own position. The sensor wirelessly communicates its position to the device on the floor, activating it to push down or release the pedal.

Based on the description on the CanAssist website, this seems to have been a custom-built system; however, the website includes a page for requesting technology, so perhaps it can be provided to others. (NOTE: As of 14 Nov 2020, I've requested further information from CanAssist and will update with any response.)
There is a YouTube video of the device being used by its recipient.
Steingraeber & Söhne

For more than 20 years, there have been electromagnetic pedal controls for paraplegic pianists – mostly accident victims – that were invented by the renowned Bayreuth piano manufacturer Steingraeber & Söhne and are custom made. (SOURCE)

The company has sought technical solutions to simplify piano playing for wheelchair users and, above all, to provide them with a serviceable alternative to working the pedals with their feet. (Wikipedia)

UPDATE

The electromagnetic system we have here in our showroom, built into a Steingraeber model 130. The right pedal can be activated by leaning into the cushion of the backrest. The left pedal by pushing a button in front of the keys. This system is available and could be built in other pianos, too. (Personal communication with Steingraeber.)

I suggest contacting the company to find out more. I received a very kind and informative response to my inquiry.

pianoman.nl / Michiel van Loon

The system is built into their own instrument and adapted to their specific needs and abilities.
The system consists of a solenoid (electromagnet), a control unit for setting the correct forces and sizes depending on the type and brand of the instrument, a 24 volt DC power supply, and a cable set.

The system can be controlled by a variety of different parts of the body, including arm, knee, mouth, and head.
A demonstration video is posted to YouTube, and additional information can be found on the maker's website.
This is the system referred to in the answer by @Michiel and, presumably, in the comments by user32742.
Head-controlled system (no longer available?)
Winfield Clark (dec.)
The Coalition for Disabled Musicians mentions a head-activated device created by Winfield Clark. However, the website is no longer active, I did not find information about the device on the Wayback Machine version, and the inventor is deceased. I mention it here for completeness and in case an adventurous reader wants to try tracking down a family member.
Answer: If you have variable pedaling you could just permanently tie it down at the sweet spot where there is just a little but of sustain. Just enough to bridge short notes together but not long enough to reverberate for so long that it gets muddy.
Answer: I use this "bluetooth ring" for sustain pedal. Very easy to use. Just one finger up/down is ur new pedal :)
According to the website (https://genkiinstruments.com/products/wave), the Wave Ring, a MIDI controller, can add dynamic effects with the tap of a finger, the click of a button or the wave of your hand.
Answer: I have developed an app called MouthPedal. It allows you to control the sustain pedal in real time using your mouth. You don't need to open your mouth too much. I was amazed to see that it actually works even when I move my head around, so I decided to publish it on the App Store for FREE :) I should mention that it only works with Mac (any DAW like GarageBand) and an iPhone with a FaceID camera. You can use Wi-Fi or a cable to connect it to your Mac. A detailed tutorial is available within the app.
Answer: On acoustical pianos, I don't know exactly how, but there's some projects on adaptations.
But, in synths and digital pianos (with midi) you can assign pedal functions to buttons of the keyboard or external device. It gets a little tricky in coordination, but doable.
Comment: This really doesn't answer the question. It leaves all of the work to the asker and all the information is provided in other answers. The point about assigning pedal functions to buttons is, I believe, unique to your answer. I suggest either leaving it as a comment on another post, or expanding it to show how it's done.
Comment: @Aaron *Welcome to the internet, let me be your guide*


Modal não sobe ao ser chamado pela jquery

Question: Depois de alguns erros, consegui fazer a jquery funcionar. Agora eu preciso chamar o Modal de dentro da jquery no change de uma DropdownList. Abaixo minha jquery.
$(document).ready(function() {
    $('#faturarParaDrop').change(function() {
        var $div = $('#modalPartial'); //exibir a modal
        var idcustomer = $(this).val(); //valor do id da dropdownlist
        $.ajax({
            url: '@Url.Action("GetDados/")' + idcustomer,
            type: 'GET',
            success: function(dados) {
                alert(JSON.stringify(dados));
                var obj = JSON.parse(JSON.stringify(dados));
                alert(obj.Nome); ?
                ? ? ? ? ? ? ? ? ? //Como chamo aqui?
            },
            error: function(erro) {}
        })
    });
});

Na minha View, tenho a View e o Modal que devará ser exibido, veja a View abaixo com o Modal

Editar Fatura Para

@using (Html.BeginForm())
{

Modal Example

                            <button type="button" class="close" data-dismiss="modal">×</button>

Markup!!!

O Markup para o Cliente... é zero(0).

                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        @Html.HiddenFor(m => m.OrderId)

                    Pedido:
                    @ViewBag.Order.OrderId

                    Forma de pagamento:
                    @ViewBag.Order.PaymentMethodSystemName

                    Status:
                    @ViewBag.Order.Status

                    Pedido criado em:
                    @ViewBag.Order.CreatedOn.ToString("dd/MM/yyyy")

                    Faturar para:
                    @Html.DropDownListFor(m => m.CustomerId, new SelectList(Model.Options, "CustomerId", "Description", Model.CustomerId), new { @id = "faturarParaDrop" })

        @Html.ActionLink("Voltar", "GetOrderDetail", "SearchOrders", new { id = Model.OrderId }, new { @class = "btn btn-cinza wd-170" })
        <input type="submit" class="btn btn-verde wd-270 f-right" value="Salvar" onclick="startLoading();" />
        }

Se eu coloco um botão como esse e chamo o Modal, ok, funciona
<button type="button" class="btn btn-info btn-lg" id="myBtn" data-toggle="modal" data-target="#myModal">Open Modal</button>

A pergunta é: Como eu faço para chamar a partir da jquery? Não posso chamar pelo botão, mas sim, pelo change da DropDownList.
Comment: Sua partialView com a modal está completa? Ou você que cortou uma parte dela? content.js é arquivo seu de javascript? Debugou no console pra tentar entender onde exatamente está o problema?
Comment: Vamos por parte, cria uma função para chamar o modal, verifica se está certo e aparecendo o modal. Se tiver chamando certo, chama essa função no change do dropdown para verificar se funciona e atende seu problema.
Comment: Então, estava chamando pelo botão. Esse exemplo eu peguei na W3Schools, mas passar para o change que é que não tô sabendo fazer
Comment: Com esse código, consigo chamar o moda ` Open Modal`
Comment: Se coloco a chamada no botão salvar, ele exibe mas continua sem que eu feche o modal. Como faria para fechar o modal e só continuar após o modal ser fechado?
Comment: Colocando isso no sucesso da jquery eu chamo o modal: `$("#myBtnModal").click();`, mas acho isso gambi
Answer: No seu HTML não encontrei nenhum elemento com id modalPartial. Mas de acordo com o seu exemplo, isso deve funcionar para exibir o modal dentro da jquery no change:
$('#myModal').modal('show');

Caso queira fechar o modal em algum momento depois, use:
$('#myModal').modal('hide');

Comment: Breno, da forma acima não rola. Parece que o modal é chamado, mas não é mostrado e tenho que sair, pois não consigo acessar nada na tela devido ao modal, mas ele não é mostrado


Expected Value for Sum of Squares in Reduced Model

Question: $\newcommand{\ol}[1]{\overline{#1}}\newcommand{\szdp}[1]{\!\left(#1\right)}
\newcommand{\szdb}[1]{\!\left[#1\right]}$I am studying Design and Analysis of Experiments, 2nd Ed., by Dean, Voss, and Draguljic. In the context of a one-way ANOVA, Exercise 3.8 reads as follows:
Problem Statement: For the model in the previous exercise, find an unbiased estimator
for $\sigma^2.$ (Hint: first calculate $E[ssE_0]$ in (3.5.10), p. 42.)
[AK Note]: The model is the reduced model for the one-way ANOVA:
\begin{align*}
Y_{it}&=\mu+\tau+\varepsilon_{it}^0,\quad i=1,\dots,\nu;\quad t=1,\dots,r_i,\\
&\varepsilon_{it}^0\sim N\left(0,\sigma^2\right)\;\text{independent RVs.}
\end{align*}
My Work So Far: We take the hint. Eq. (3.5.10) states:
$$ssE_0=\sum_i\sum_t\szdp{y_{it}-\ol{y}_{\bullet\bullet}}^{2}.$$
We define the sample variance for the $i$th treatment as
$$S_i^2
=\sum_{t=1}^{r_i}\frac{\szdp{Y_{it}-\ol{Y}_{\bullet\bullet}}^{\!2}}{r_i-1}$$
for this model. Then, in the random variable correspondence $SSE_0,$ we have
$$SSE_0
=\sum_i\sum_t\szdp{Y_{it}-\ol{Y}_{\bullet\bullet}}^{\!2}
=\sum_i(r_i-1)S_i^2.$$
We compute $E\szdb{S_i^2}$:
\begin{align*}
E\szdb{S_i^2}
&=E\szdb{\sum_{t=1}^{r_i}\frac{\szdp{Y_{it}-\ol{Y}_{\bullet\bullet}}^{\!2}}
                              {r_i-1}}\\
&=\sum_{t=1}^{r_i}\frac{E\szdb{\szdp{Y_{it}-\ol{Y}_{\bullet\bullet}}^{\!2}}}
                              {r_i-1}\\
&=\sum_{t=1}^{r_i}\frac{E\szdb{\szdp{\mu+\tau+\varepsilon^0_{it}
-\ol{Y}_{\bullet\bullet}}^{\!2}}}
                              {r_i-1}.
\end{align*}
But
\begin{align*}
\ol{Y}_{\bullet\bullet}
&=\frac1n\sum_{i=1}^\nu\sum_{t=1}^{r_i}Y_{it}\\
&=\frac1n\sum_{i=1}^\nu\sum_{t=1}^{r_i}\szdp{\mu+\tau+\varepsilon_{it}^0}\\
&=\mu+\tau+\ol{\varepsilon}_{\bullet\bullet}^0,
\end{align*}
so that
\begin{align*}
E\szdb{S_i^2}
&=\sum_{t=1}^{r_i}\frac{E\szdb{\szdp{\varepsilon^0_{it}
-\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}}
                              {r_i-1}.
\end{align*}
Now then, we have
\begin{align*}
E\szdb{\szdp{\varepsilon_{it}^0-\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}
&=E\szdb{\szdp{\varepsilon_{it}^0}^{\!2}}
-2E\szdb{\varepsilon_{it}^0\ol{\varepsilon}_{\bullet\bullet}^0}
 +E\szdb{\szdp{\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}.
\end{align*}
Recall that, for any random variable $X,$ we have
$$V(X)=E\szdp{X^2}-(E(X))^2,$$
so that
\begin{align*}
E\szdb{\szdp{\varepsilon_{it}^0}^{\!2}}
&=V\szdp{\varepsilon_{it}^0}
+\underbrace{E\szdb{\szdp{\varepsilon_{it}^0}}^2}_{=0}\\
&=\sigma^2,\\
E\szdb{\szdp{\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}
&=V\szdp{\ol{\varepsilon}_{\bullet\bullet}^0}
 +\underbrace{E\szdb{\szdp{\ol{\varepsilon}_{\bullet\bullet}^0}}^2}_{=0}\\
&=V\szdp{\frac1n\sum_{i=1}^\nu\sum_{t=1}^{r_i}\varepsilon_{it}^0}\\
&=\frac{1}{n^2}\sum_{i=1}^\nu\sum_{t=1}^{r_i}V(\varepsilon_{it}^0)\\
&=\frac{\sigma^2}{n},\\
E\szdb{\varepsilon_{js}^0\ol{\varepsilon}_{\bullet\bullet}^0}
&=E\szdb{\varepsilon_{js}^0\frac1n\sum_{i=1}^\nu\sum_{t=1}^{r_i}\varepsilon_{it}^0}\\
&=\frac1n\,
E\szdb{\varepsilon_{js}^0\sum_{i=1}^\nu\sum_{t=1}^{r_i}\varepsilon_{it}^0}\\
&=\frac1n\,
\sum_{i=1}^\nu\sum_{t=1}^{r_i}E\szdb{\varepsilon_{js}^0\varepsilon_{it}^0}.
\end{align*}
In this last expression, if $j\not=i$ or $s\not= t,$ then the first random
variable is independent of the second random variable, the expectation can
be applied to each random variable separately, and the result is zero. It
follows that only when $j=i$ and $s=t$ do we pick up anything non-zero:
\begin{align*}
E\szdb{\varepsilon_{js}^0\ol{\varepsilon}_{\bullet\bullet}^0}
&=\frac1n\,E\szdb{\szdp{\varepsilon_{js}^0}^{\!2}}\\
&=\frac{\sigma^2}{n}.
\end{align*}
Plugging these expressions back into the previous computations reveals that
\begin{align*}
E\szdb{\szdp{\varepsilon_{it}^0-\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}
&=E\szdb{\szdp{\varepsilon_{it}^0}^{\!2}}
-2E\szdb{\varepsilon_{it}^0\ol{\varepsilon}_{\bullet\bullet}^0}
 +E\szdb{\szdp{\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}\\
&=\sigma^2-\frac{2\sigma^2}{n}+\frac{\sigma^2}{n}\\
&=\sigma^2-\frac{\sigma^2}{n}\\
&=\frac{(n-1)\sigma^2}{n}.
\end{align*}
In turn, we plug this back into the previous computations to reveal that
\begin{align*}
E\szdb{S_i^2}
&=\sum_{t=1}^{r_i}\frac{E\szdb{\szdp{\varepsilon^0_{it}
-\ol{\varepsilon}_{\bullet\bullet}^0}^{\!2}}}
                              {r_i-1}\\
&=\sum_{t=1}^{r_i}\frac{(n-1)\sigma^2}{n(r_i-1)}\\
&=\frac{(n-1)\sigma^2}{n}\sum_{t=1}^{r_i}\frac{1}{r_i-1}\\
&=\frac{r_i(n-1)\sigma^2}{n(r_i-1)}.
\end{align*}
Finally, pulling ourselves all the way out of our computations, we have that
\begin{align*}
E\szdb{SSE_0}
&=E\szdb{\sum_i(r_i-1)S_i^2}\\
&=\sum_i(r_i-1)E\szdb{S_i^2}\\
&=\sum_i(r_i-1)\frac{r_i(n-1)\sigma^2}{n(r_i-1)}\\
&=\sum_i\frac{r_i(n-1)\sigma^2}{n}\\
&=(n-1)\sigma^2.
\end{align*}
Hence, an unbiased estimator for $\sigma^2$ is $SSE_0/(n-1),$ as
expected.
My Question: Is this correct? Perhaps more specifically: what justifies moving to the RV version: $ssE_0\to SSE_0?$
Comment: The calculation seems legit at a quick glance. One thing that is bugging me is how $E[ssE_0]$ is possible: isn't $ssE_0$ the _observed_ variable and $SSE_0$ the random variable, that is won't $E[SSE_0]$ be taken?
Comment: I'm not sure I understand your comment when you say "won't $E[SSE_0]$ be taken?" It is true, I believe that $ssE_0$ is the observed value of the sum of squares, whereas $SSE_0$ is the corresponding random variable. And that's the main thrust of my question: why can we just switch from the one to the other?
Comment: What I am saying is that whether it would be right to take expectation of observed value. Say, I have a random variable $X;$ now $EX$ makes sense but does the expectation of observed value of $X,$ say $x, $ i.e. $Ex$ make sense?
Answer: Denote $\alpha_i :=  \tau_i-\bar \tau_{\bullet}.$ Rewrite the One-Way ANOVA model as
\begin{align}Y_{it} &= \mu+\tau_i+\varepsilon_{it}^0\\ &= (\mu+  \bar \tau_{\bullet})+(\tau- \bar \tau_{\bullet})+\varepsilon_{it}\\  &= \mu^\prime + \alpha_i + \varepsilon_{it}\tag 1.\end{align}
It can be shown that
\begin{align}\mathbb E[\textrm{SST}] &= \sum r_i\alpha_i^2 + (v-1)\sigma^2,\tag 2\label 2\\ \mathbb E[\textrm{SSE}]&= (n-v)\sigma^2\tag 3\label 3.\end{align}
Under the null hypothesis, $\forall i, ~\alpha_i = 0;$ so $\eqref 2$ becomes
$$\mathbb E[\textrm{SST}] = (v-1)\sigma^2;\tag 4\label 4$$
adding $\eqref 4$ and $\eqref 3$ yields
\begin{align}\mathbb E[\textrm{SST}+ \textrm{SSE}] &= \mathbb E[\textrm{SSE}_0]\\ &= (n-1)\sigma^2.\tag 5\end{align}
Comment: This is not the reduced model. No doubt the calculations are similar, but I would want to know where, if anywhere, they differ. Also, the "It can be shown that" would need to be shown. Thanks for answering!
Comment: Sure. I wanted to verify the result. Because you already correctly derived it. I merely showed that it was correct. And yes, if you want, I can show $(2), (3). $


JavaScript - Focusout não ativa o AJAX

Question: Olá! estou tendo um problema com JS que é o seguinte:
O evento focusout não está ativando o $.ajax
JS:
$('.focusout_input_budget').focusout(function () {
  var amount = $(this).val(),
      id = $(this).parent('.line-table-products').attr('data-id'),
      nomeprod = $(this).parent('.line-table-products').find('.coll1-line-product-list').html();

  if (amount > 0) {
     $.ajax({
        url : SITE  + 'addbudget',
        type: "POST",
        dataType: "JSON",
        data: { id: id, amount: amount, nomeproduto: nomeproduto },
        async: false,
        success: function (json) {
           json = json;
           if (json['true'] === 'true') {
              $('.icon-inform-budge').html(json['quant']);
              console.log(json['quant']);
              if (json['quant'] == 1) {
                 $('#products-budge-top li').first().remove();
                 var li = "
"+json['nome']+"
";
                 $('#products-budge-top').append(li);
              }
              if (json['quant'] > 1 && json['quant'] <= 5) {
                 $('#products-budge-top li').last().remove();
                 var li = "
"+json['nome']+"
";
                 $('#products-budge-top').append(li);
              }
              if (json['quant'] == 6) {
                 $('#products-budge-top li').last().remove();
                 var li = "
Ver todos os produtos...
";
                 $('#products-budge-top').append(li);
              }
              if(json['quant'] >= 6){
                 $('#products-budge-top li').first().remove();
                 var li = "
"+json['nome']+"
";
                 $('#products-budge-top').append(li);
              }
              var link = SITE + 'carrinho';
              var last = "
Revisar Orçamento
";
              $('#products-budge-top').append(last);

              $(this).html('ADICIONADO COM SUCESSO');
              setTimeout(function(){
                 $('.button-add-product-budget').html('ADICIONAR AO ORÇAMENTO');
              },200);
           } else {
              $(this).html('ERRO AO ADICIONAR');
              setTimeout(function(){
                 $('.button-add-product-budget').html('ADICIONAR AO ORÇAMENTO');
              },2000);            }
        }
     });

  } else {
     $.ajax({
        url : SITE  + 'removebudget',
        type: "POST",
        dataType: "JSON",
        data: { id:id },
        async: false,
        success: function(json){
           json = json;
           if(json == 'true'){
              location.reload();
           }
        }
     });
  }
});

html:

                NOME DO PRODUTO
                UNIDADE
                QUANTIDADE
                ADICIONAR AO MEU ORÇAMENTO

            <?php foreach($produtos as $prod){ ?>
            <li class="line-table-products" data-id="<?php echo $prod->codigo; ?>">
                <span class="coll-line-product coll1-line-product coll1-line-product-list <?php if(check_size_line($prod->nome, 36, 'space') == 'true') echo 'item-large-size-products'; ?>"><?php echo $prod->nome; ?>
                <?php echo $prod->unidade; ?>

                    <img src="<?php echo IMG . 'px.png'; ?>" alt="Icone diminui quantidade" data-operation="subtraction" class="icon-amount-product-budget icon-decrease-product-budget" />
                    <input type="text" name="productqtd" value="<?php echo check_prod_in_budget($prod->codigo); ?>" placeholder="00" class="input-amount-product-budget focusout_input_budget"/>
                    <img src="<?php echo IMG . 'px.png'; ?>" alt="Icone diminui quantidade" data-operation="sum" class="icon-amount-product-budget icon-increase-product-budget" />

                ADICIONAR AO ORÇAMENTO

            <?php } ?>

Alguém poderia me Ajudar?
Comment: Mas o evento usado aí é o `blur`.
Comment: eu já tentei e não funcionou também, ai um colega me disse para usar o evento focusout
Comment: o código funciona até a checagem do "if(amount > 0){" depois ele não funciona mais!
Comment: Podes montar um exemplo com HTML aqui ou no jsFiddle?
Comment: link para o jsFiddle: https://jsfiddle.net/samuelbdesouza/ufetc77b/
Answer: Existe um erro no seu if, algumas '{' estavam em lugares errados, coloque ele dessa forma:
if(amount > 0){
    $.ajax({
        url : SITE  + 'addbudget',
        type: "POST",
        dataType: "JSON",
        data: { id:id, amount:amount, nomeproduto:nomeproduto },
        async: false,
        success: function(json){
            json = json;
            if(json['true'] == 'true'){
                $(this).html('ADICIONADO COM SUCESSO');
            }
            else {
                $(this).html('ERRO AO ADICIONAR');
            }
        }
    });

}

Abaixo um exemplo funcional utlizando o on() do jquery.

jQuery(document).ready(function(){
  jQuery('#teste').on('focusout',function(){
     alert('focusout ativado');
  });
});

<input id="teste">
Comment: Corrigi os erros, mas ainda não está funcionando!
Comment: Poste o código atual e completo inclusive os elementos html
Comment: editei a pergunta adicionando o html e js atual
Comment: Testei seu código no próprio jsfiddle e deu problema na variável SITE, ela não está definida favor verificar, fora isso ao retirar todos os locais que ela está funcionou normal, tente adicionar antes de tudo a 'var SITE = ' ';'
Comment: A variável "url : SITE  + 'addbudget'," está mandando os dados para uma pagina que faz o cadastro dos códigos na sessão e no banco, já testei esse mesmo código com o evento click e funciona normalmente, só com o focusout ou blur que não está funcionando!
Comment: O evento é acionado ? tem como colocar console.log dentro para confirmar. irei fazer um exemplo com out
Comment: Acabei de adicionar um exemplo funcional utlizando on() do jQuery.
Comment: O evento é acionado, mas ele não declarava o $.ajax(), troquei essas linhas:
 var amount = $(this).val(),
      id = $(this).parent('.line-table-products').attr('data-id'), por essas: var amount = $(this).val(),
    id = $(this).attr('data-id'), e adicionei um data-id no input e funcionou
Comment: Parabéns amigo, ainda bem que resolveu, até a próxima.

JavaScript - Focusout não ativa o AJAX


List nodes from a taxonomy based on a field

Question: I'm looking for the most "Drupal" way to create either a view/block (not sure about either) that contains a list with the top level items being the parent taxonomies from a certain vocabulary (4 parents in total), and then nested under each taxonomy, the first 5 products that have a certain field on them set to true.
Essentially a "featured products"-esque block that will have 4 tabs.
Answer: So you need to do the following:
1) Create a view for products

Install Views Field View module
http://drupal.org/project/views_field_view Create a view for 4
products. Make sure it has contextual filter for term id set.
Save it

2) Create a taxonomy view

Create taxonomy view, set display as block, so you could output it in
a block
Add 'taxonomy term parent' filter and make it equal to 0. This way you'll select only parent terms
Select Views Field View in Fields and set it to output a view for products
Save

So now you should have a block which outputs parent taxonomy terms and under each term you have a list of products.
Let me know how it works.
Comment: I have made some progress, I have the view within a view, but all the sub-products for each taxonomy are the same..


Coefficients from power regression in R do not match Excel

Question: I created power regression equations for length vs dry mass in both R and Excel but the coefficients do not match.
I  used Hong Ooi's answer from this link: Power regression in R similar to excel. In that code, they were able to replicate the power equation from Excel using the R code. However, when I tried, I got some very weird coefficients. The Excel equation from the power trendline is much more accurate when tested with random lengths.
Code as follows:
#sample dataset of Lengths and Dry Masses
test <- structure(list(
  Length = c(23, 17, 16, 25, 15, 25, 11, 22, 13, 21, 31),
  DryMass = c(3.009, 1.6, 1, 4.177, 0.992, 6.166, 0.7, 1.73, 0.613, 3.429, 7.896)),
  .Names = c("Length", "DryMass"),
  row.names = c(NA, 11L),
  class = "data.frame")

#log-log regression
lm(formula = log(Length) ~ log(DryMass), data = test)

Coefficients:
 (Intercept)  log(DryMass)
      2.7048        0.3413

This should give me the equation "14.9515*x^0.3413" once I convert the intercept (EXP(2.7048) = 14.9515). I attempted to test it with some random lengths and the predictions are way off.
However, the equation given by Excel is "0.0009*x^2.6291" which, when tested, was very accurate. I would just use the equation from Excel but I need to make 50 more of these and would love to automate it using R.
Answer: You are trying to fit the following model.
library(ggplot2)
ggplot(test, aes(x = log(DryMass), y = log(Length))) +
  theme_bw() +
  geom_point() +
  scale_y_continuous(limits = c(0, 5)) +
  geom_smooth(formula = y ~ x, method = "lm", se = FALSE)

(Intercept) (first coefficient) is where the line crosses y at x=0, I believe. On the image above, this appears to be between 2.5 and 3, so let's say 2.8, which is pretty darn close to 2.7 if you ask me. Maybe Excel is wrong, in which case, I suggest you contact their authors? Or maybe you're doing something in Excel which is not being heard here for which reason it could be said about reproducibility of the said tool.
Answer: Edit:
You switched x and y in R.
mod_linearized <- lm(formula = log(DryMass) ~ log(Length), data = test)

exp(coef(mod_linearized)[1])
# (Intercept)
#0.0008775079

Old answer (which might still be useful):
The back-transformation of the linearized model is not the same as the non-linear model because error terms are different:
Back-transformed linearized model results in multiplicative error:
y = exp(a) * x ^ b * exp(epsilon)
Non-linear model has an additive error:
y = a * x ^ b + epsilon
Basically, the linearization is equivalent to a different weighting of data points (larger values are weighted less). That can actually be desirable (depending on your specific data generating process). But sometimes you want equal weight and then you should fit the non-linear model.
You can do non-linear regression in R:
mod_linearized <- lm(formula = log(Length) ~ log(DryMass), data = test)

exp(coef(mod_linearized)[1])
#(Intercept)
#   14.95152

mod_nonlinear <- nls(Length ~ a * DryMass ^ b, data = test,
                     #use result from linearization as starting values:
                     start = list(a = exp(coef(mod_linearized)[1]),
                                  b = coef(mod_linearized)[2]))

coef(mod_nonlinear)[1]
#      a
#15.2588

Comment: ...This is the correct answer. At first, I didn't know I had to take the exponent of the intercept so I had ignored the negative values and switched the x and y. Was reading some other things and found out how to actually use the coefficients but had forgotten I switched the x and y. Thank you!


Functions for these options (Python)

Question: How can i make use of functions in this case.
what i'm trying to do is when
1-will allow the user to input a number to save
2-will allow the user to reduce the saved number
3- will make the user view the saved number
This is my current code:
print '1. Add \n2. Remove \n3. View'

x = raw_input('ur choice:')

when '1' is entered:
if x == '1':
    print 'you have:'
    add = raw_input('how many do you want to add:')
    print '1. Add \n2. Remove \n3. View'

if '2' is entered:
if x == '2':
    print 'you have:'
    remove = raw_input ('How many do you want to remove:')

    print '1. Add \n2. Remove \n3. View'

and if 3 is entered:
if x == '3':
    print 'Total:'

Comment: What are you trying to achieve by putting this code into functions, you haven't said if it already works or not, please make question clear.
Answer: I don't know what exactly are you expecting, but at least you could move the code into functions:
def add:
    print 'you have:'
    add = raw_input('how many do you want to add:')
    prompt()

def remove:
    print 'you have:'
    remove = raw_input ('How many do you want to remove:')
    prompt()

def total:
    print 'Total:'

def prompt:
    print '1. Add \n2. Remove \n3. View'

x = raw_input('ur choice:')
if x == '1':
    add()
elif x == '2':
    remove()
else:
    total()

Comment: Consider putting the functions in a dictionary to remove the `if: elif:`.
Comment: what i'm trying to do is when 1-will allow the user to input a number to save 2-will allow the user to delete or reduce the saved number 3- will make the user view the saved number

Functions for these options (Python)


Empty string if null

Question: I have this in my code:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?
/M
Comment: Is `CustomerID` the null value, or is the `Customer` itself null? Also, what is the type of `CustomerID`?
Answer: (Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";

One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";

For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";

Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer's parent class (type of cu in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
Answer: (C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()

Here is real-life example from my code:
 private HtmlTableCell CreateTableCell(object cellContents)
 {
     return new HtmlTableCell()
     {
         InnerText = (cellContents ?? "").ToString()
     };
 }

Comment: One of the outcomes of this code is redundant `"".ToString()`, moreover `(myObject ?? "")` will work only if `myObject` was a string in the first place, making `.ToString()` even more unnecessary. I think you meant `myObject?.ToString() ?? ""`.
Comment: @ensisNoctis 1. This was written at the time we had C# 5, which didn't have `?.` operator. For C# 6+, I'd use `?.`. 2. `.ToString()` works on objects just fine.

I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
Comment: Fine with me :)
Answer: It depends of the type of CustomerID.
If CustomerID is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)

If CustomerID is a Nullable<T>, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

This will work because the ToString() method of Nullable<T> returns an empty string if the instance is null (technically if the HasValue property is false).
Answer: SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)

Empty string if null