Additional field data stored outside of the field storage (in a separate table) doesn't load with the rest of the field

Question: I've implemented a custom field that needs to store data outside of the Field Storage mechanism and in a custom DB table. (The field structure is enough to require a second table, but not enough to justify creating a new entity type. It's an image field with tooltips that will be later styled with JS.) I've hooked the necessary functions and I can see that the data is getting saved to the table, but the load hook doesn't get called when the edit screen form is built, nor does it's additional content show up in the passed-in $items array.
Since hook_field_widget_form doesn't get the $entity being edited, I can't manually query the auxiliary table for the data. How do I get the data into $items and onto the form so the user can edit again?
(It also doesn't appear to be calling hook_field_load on the node load either, but I haven't started working on the field formatter yet.)
Answer: hook_field_load is being called, but only once after a cache clear. Either the loaded field or the whole node is cached somewhere. Remember to clear your caches!
I missed the initial load because I had yet to instrument the function with the typical bevy of dpm() and ddebug_backtrace() calls. Also the function itself isn't loading the data back properly, but that's outside the scope of the original question.


Variável global em todas as funções da classe

Question: Normalmente quando quero puxar uma variável que está fora da classe, eu uso global $variavel, porém queria que essa variável fosse acessível em todas as funções da classe, pra não ficar precisando "puxar" em todas as funções, como fazer?
Comment: Você quer deixar de usar `global`, que é bom, e pegar uma variável não global que deve sobreviver durante toda aplicação facilmente dentro de cada função?
Comment: Por que você quer obter uma variável de fora da classe? Os parâmetros servem justamente para passar para os métodos o que eles precisam.
Comment: A classe tem um construtor ?
Comment: A variável deve ser global mesmo, deve durar por toda a aplicação e estar disponível para todas as classes ou ela é uma variável que deve pertencer a uma classe?
Comment: Ia postar comment na outra pergunta, mas como vc deletou, segue aqui uma tabela extensa de primos: http://primes.utm.edu/primes/download.php
Comment: Sim e sim @Zuul
Comment: @Oeslei a variavel é de conexao com db..
Answer: O meu entendimento da pergunta é que é necessário guardar os dados da conexão em uma variável que possa ser acessada de qualquer ponto da aplicação. Uma variável global é uma solução para isto mas de fato não é bom usá-la.
Então a solução é encapsular a variável que não é global em uma função mantendo seu estado de forma estática ou usando uma abordagem considerada mais moderna, mas não necessariamente melhor, encapsulando a variável em uma classe estática.
Note que ser estático é o segredo por que isto dá um tempo de vida para a variável igual ao tempo da aplicação, ou seja, a variável fica disponível o tempo todo exatamente como a variável global fica mas tem a vantagem da variável não ser exposta diretamente criando ambiguidades e conflitos com outras variáveis locais. É melhor ter funções ou classes globais. Mesmo isto pode não ser a solução ideal, alguns criticariam esta solução que é pragmática.
class Conexao {
    private static $conexao = "dados da conexao aqui - classe";
    public static function PegaConexao() {
        return self::$conexao;
    }
}

function conexao(){
    static $conexao = "dados da conexao aqui - funcao";
    return $conexao;
}

class Uso {
    public function AbreBanco1() {
        echo conexao() . "\n";
    }
    public function AbreBanco2() {
        echo Conexao::PegaConexao();
    }
}

Uso::AbreBanco1(); //chama só para demonstrar
Uso::AbreBanco2(); //chama só para demonstrar

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Como a pergunta não dá detalhes só posso mostrar uma solução genérica mas é fácil adaptar para uso conforme a necessidade específica.
Não precisa ter as duas formas, coloquei as duas para exemplificar, obviamente só um AbreBanco() existiria de fato. E o conteúdo da variável provavelmente será outro.
Comment: Extenso e complexo? Tem certeza? Eu acho o mais mais curto e mais simples. Note que eu mostrei duas formas diferentes para ele escolher. Mas faz o que ele pediu, a sua resposta não faz. A sua não deixa o conteúdo disponível para todas as funções de todas as classes. Na sua o conteúdo morre quando a variável `$a` sai de escopo. As pessoas só votaram na sua porque não entenderam o problema. Depois de ler seu segundo só posso dizer "Amém". Isto é o que se lê em manuais de boas práticas que não ajudam resolver problema algum. Por isto eu os abomino. Ditam regras e não resolvem problemas.
Comment: Seu exemplo é extenso e complexo. Diferente do meu que trata-se de uma resposta mais direta e sem o uso de variáveis privadas estáticas e/ou métodos estáticos.
Comment: Utilize métodos estáticos somente para funções onde não há necessidade de alterar o estado interno de um objeto. Normalmente métodos estáticos são métodos auxiliares, escritos para dar suporte genérico a outros métodos. Um exemplo é um método de ordenação de vetor: ele recebe um vetor como parâmetro e ordena-o, retornando em seguida. Ele pode ser usado em diversos locais, porém não altera o estado interno de nenhum objeto. Logo, ele é um ótimo candidato a se tornar um método estático.
Comment: Mas de qualquer forma note que eu não altero estado interno em nenhum momento, em nenhum dos dois casos. Você faz isto, mas o problema não pedia para fazer isto.
Comment: Não adianta "enfeitar" a resposta quando o objetivo é outro: "`...queria que essa variável fosse acessível em todas as funções **da classe**`". Você foi além. Sua resposta consome mais códigos.
Comment: Leia os comentários, lá ele esclarece e dá mais detalhes de como ele quer. Você pode reclamar que a pergunta originalmente não estava dando todos os detalhes mas ele escolheu a minha resposta como a correta porque ela resolve o problema real dele. É o mesmo caso que tinha acontecido lá na outra pergunta, o JorgeB deu uma resposta que parecia certa mas não estava e aí apareceu o Bacco e deu a resposta certa porque ele entendeu melhor o problema mesmo a pergunta não ajudando muito.
Comment: Ele não respondeu a sua última pergunta. Por tanto, a variável deve pertencer a mesma classe e acessível a todas as funções da mesma, conforme a pergunta.
Comment: http://pt.stackoverflow.com/questions/53794/vari%c3%a1vel-global-em-todas-as-fun%c3%a7%c3%b5es-da-classe/53797?noredirect=1#comment110288_53794 os dois "sim" são para os comentários anteriores, depois que eu percebi, por isso ele não respondeu mais, já estava respondido.
Answer: Criar variável acessível para todas as funções de uma classe:
<?php

    class teste {

        /* construct */
        function __construct($variavel) {

            $this->global_variavel  = $variavel;

        }

        function checando_funcao() {

                echo $this->global_variavel;

        }

        function checando_funcao2() {

                echo $this->global_variavel;

        }

?>

Para executar um teste:
    //Criando uma nova instância

    $variavel = 'Meu texto!';
    $a = new teste($variavel);

    //Executando as duas funções com os mesmos valores de uma única variável "global"
    $a->checando();
    $a->checando_funcao2();

Obs:

Para garantir compatibilidade reversa, se o PHP 5 não conseguir achar uma __construct() para uma determinada classe, ele procurará pela função construtora à moda-antiga, que tenha o mesmo nome da classe. Efetivamente, significa que o único caso que pode gerar problemas de compatibilidade seria se a classe tiver um método chamado __construct() que fosse usado para outra finalidade que não inicializar o objeto.
Comment: A sua resposta estritamente está errada. Mas a pergunta inicialmente não estava muito clara. É o mesmo problema que você reclamou nesse comentário: http://pt.stackoverflow.com/questions/53689/montar-os-par%c3%a2metros-de-um-url-dinamicamente/53692#comment110408_53692 Até por coerência não estou pregando o negativo na sua resposta mas ela está errada para o que o autor quer. Você só teve esses positivos porque as pessoas também não entenderam bem o que a pergunta queria. Então dá para entender que ela não estava bem formulada. O que você vai fazer agora que sabe que ela está errada?
Comment: Mostre-me as fontes, as regras e prove-me que estou errado quanto ao escopo.
Comment: A sua é igual a minha? Não é, a sua faz outra coisa diferente do que foi pedido. A minha foi aceita na hora, a sua ficou disponível por horas e o autor não considerou certa. Só autor pode provar qual está certa e ele fez isto quando aceitou. Só poderia ter duas certas se as duas produzissem o mesmo resultado, mesmo que de maneiras diferentes. A sua produz um resultado diferente do esperado, a sua perde o estado quando sai do escopo, ele não quer isto.
Comment: Acho que o autor deve ter se impressionado com uma resposta feita por uma reputação de 44k+ e disse: "Nossa! Era isso que precisava. Uma fonte confiável."`Talvez!`
Comment: Como você começou menosprezar a inteligência do autor especulando que ele não sabe o que resolve o problema dele, o que até poderia ser o caso se ele já não tivesse demonstrado que consegue se virar bem com uma informação adequada e não precisa ser tutelado, eu percebo que você não vai mudar de ideia após eu mostrar os fatos para você, não posso dizer mais nada. Se a minha estivesse errada eu reconheceria, consertaria ou apagaria, como já fiz outras vezes.
Answer: Para tornar uma variável membro da classe defina o modificador de acesso e depois seu nome
public - é acessivel por todas os métodos da classe e fora dela também.
protected - acessivel apenas dentro da classe e suas derivadas.
private - acessivel apenas detros dos métodos da classe.
class Teste{
   public $variavel = 'esse valor pode ser modificado externamente';

   public function foo(){
     echo $this->variavel;
   }
}


métodos Com retorno Python

Question: estou comecando em Python e tem um erro que nao estou conseguindo resolver.
tenhoesses dois codigos:
Conta.py
class Conta:
def __init__(Self, numero, cpf, nomeTitular, saldo):
    Self.numero = numero
    Self.cpf = cpf
    Self.nomeTitular = nomeTitular
    Self.saldo = saldo

def depositar(self, valor):
    self.valor += valor

def sacar(self, valor):
    self.saldo -= valor

def gerarExtrato(self):
    print(f"Numero{self.numero} \n Cpf: {self.cpf} \n Saldo: {self.saldo}")

def sacar(self,valor):
    if self.saldo < valor:
        return False
    else:
        self.saldo -= valor
        return True

ClassA.py
from Conta import Conta

conta1 = Conta(1, 123, "Joao", 0)
conta2 = Conta(3, 456, "Maria", 0)

conta2.gerarExtrato()

quando executo o "ClassA.py" eu esperava receber os dados de gerarExtrato(), porem acontece esse erro:
C:/Users/Daniel/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Daniel/Desktop/programacao/Faculdade/PYTHON/PythonOO/Tema2/ClassA.py
Traceback (most recent call last):
File "c:\Users\Daniel\Desktop\programacao\Faculdade\PYTHON\PythonOO\Tema2\ClassA.py", line 6, in
conta2.gerarExtrato()
AttributeError: 'Conta' object has no attribute 'gerarExtrato'
PS C:\Users\Daniel\Desktop\programacao>
qual foi o meu erro ?
Grato!
Comment: Não há erros no seu código, verifique se o arquivo foi escrito corretamente, respeitando os espaços e tabs.
Answer: O código está correto. Só certifique-se que os métodos da classe Conta estejam identados no escopo da classe.
class Conta:
    def __init__(Self, numero, cpf, nomeTitular, saldo):
        Self.numero = numero
        Self.cpf = cpf
        Self.nomeTitular = nomeTitular
        Self.saldo = saldo

    def depositar(self, valor):
        self.valor += valor

    def sacar(self, valor):
        self.saldo -= valor

    def gerarExtrato(self):
        print(f"Numero{self.numero} \n Cpf: {self.cpf} \n Saldo: {self.saldo}")

    def sacar(self,valor):
        if self.saldo < valor:
            return False
        else:
            self.saldo -= valor
            return True

Comment: Verifiquei aqui e está sim :/
Comment: está exatamente como na resposta que vc colocou.
Comment: Pra mim aqui a saída está normal. Executando o ClassA.py, tenho este resultado:

Numero3
 Cpf: 456
 Saldo: 0
Comment: será que pode ser algum bug do VScode ?
Comment: Eu executei no VS Code mesmo. Com os dois códigos no mesmo diretório, rodam perfeitamente, sem erro algum.

métodos Com retorno Python


Test of convergence of $\int_{-\infty}^{\infty} \dfrac{x^6+6}{x^8+8}dx$

Question: I am having some trouble with this problem and don't know if I am doing it right:

$$\int_{-\infty}^{\infty} \dfrac{x^6+6}{x^8+8}dx$$

so the steps I have taken so far are, I split it into
$$\int_0^\infty \dfrac{x^6+6}{x^8+8} + \int_{-\infty}^0 \dfrac{x^6+6}{x^8+8}$$
for the second integral I made a change of variable $x = -u$
so it would look the same as the first integral and then use $$ \lim_{x\to \infty} \dfrac{f(x)}{g(x)}$$ where  $g(x) = \dfrac1{x^2}$.
Just wondering if my approach is correct.
Comment: It is *basically* fine. Note that $\frac{1}{x^2}$ misbehaves at $0$, so if you are going to use a limit comparison, you need to split the integral into $0$ to $1$ (fine) and $1$ to $\infty$ (limit comparison). Or else you can do a limit comparison with $\frac{1}{1+x^2}$, exploiting fact $\int_0^\infty \frac{dx}{1+x^2}=\frac{\pi}{2}$.
Comment: thank you to the people who help me edit my post. This is my first time using mathexchange
Comment: @Siddhant Trivedi : Why change from   $g(x) = \frac{1}{x^2}$ to  $g(x) = 1/x^2$ ?
Comment: oh...i forgot it...sorry...
Answer: Your approach is fine, as long as you compare with $1/x^2$ when $|x|\gt1$ and then use the continuity of $\frac{x^6+6}{x^8+8}$ for $|x|\le1$. We can illustrate this with a slightly different comparison function.
First, note that
$$
\lim_{|x|\to\infty}\frac{(x^6+6)(x^2+1)}{x^8+8}=1\tag{1}
$$
Thus, $(1)$ says that there is an $m$ so that if $|x|\ge m$, then $\frac{(x^6+6)(x^2+1)}{x^8+8}\le2$. Since $\frac{(x^6+6)(x^2+1)}{x^8+8}$ is continuous on the compact set $[-m,m]$, it is bounded there. Therefore, there is an $M$ so that
$$
\frac{(x^6+6)(x^2+1)}{x^8+8}\le M\tag{2}
$$
Therefore,
$$
\frac{x^6+6}{x^8+8}\le\frac{M}{1+x^2}\tag{3}
$$
Now, simply use
$$
\int_{-\infty}^\infty\frac{\mathrm{d}x}{1+x^2}=\pi\tag{4}
$$
to show that
$$
\int_{-\infty}^\infty\frac{x^6+6}{x^8+8}\,\mathrm{d}x\tag{5}
$$
converges by comparison.

Although this answer uses contour integration, it does give the value for
$$
\int_{-\infty}^\infty\frac{x^6+6}{x^8+8}\,\mathrm{d}x=\frac{\pi}{8}\csc\left(\frac{\pi}{8}\right)\left(2^{5/8}+3\cdot2^{-5/8}\right)\tag{6}
$$


Get arrival time without departure time

Question: I am trying to get the travel time to a certain destination based on the time of arrival. It is available through Google Maps, But the API seems to force to enter a departure time... which I don't know. I just know the expected time of arrival.
yet...
https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&traffic_model=best_guess&destinations=San+Francisco|Victoria+BC&arrival_time=1505894400&key=MY-KEY
RETURNS:
{
   "destination_addresses" : [],
   "error_message" : "Invalid request. Missing the 'departure_time' parameter.",
   "origin_addresses" : [],
   "rows" : [],
   "status" : "INVALID_REQUEST"
}
Any clue? Thanks
Answer: Remove the &traffic_model=best_guess:
This works for me:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&arrival_time=1505894400&key=MY-KEY

Get arrival time without departure time


Big O-notation for some exponential

Question: Suppose $\mu>0$ and $\lambda <0$ with $\lvert\lambda\rvert >\mu$.
Is it true that
$$
x e^{2\lambda x}=O(e^{-2\mu x}), \textrm{as }x\to\infty?
$$
I am really not sure.
I think, I have to show that there exists some $\varepsilon >0$ and some $X$ such that
$$
xe^{2\lambda x}\leq \varepsilon e^{-2\mu x}\textrm{ for all }x>X.
$$
Comment: Can you show $\lim_{x\to\infty}xe^{\alpha x}=0$ where $\alpha=2(\lambda+\mu)<0$?
Comment: Can you show $\lim_{x\to\infty}xe^{-x}=0$?
Comment: Yes, by L'Hospital
Comment: Yes, also by L'Hospital
Comment: Okay, I see what you mean.. For large x, I get that $xe^{2\lambda x}e^{2\mu x}\leqslant\varepsilon$. So, in fact, I have a stronger statement, namely small-oh, i.e. $xe^{2\lambda x}=o(e^{-2\mu x})$, as $x\to\infty$. Correct?
Answer: Moving everything to the other side we have
$$xe^{2(\lambda+\mu)x}\le\varepsilon$$
However, we know by taking the limit as $x\to\infty$, the LHS tends to $0$, and hence this holds for arbitrarily small $\varepsilon>0$. This not only gives the desired result, but the stronger $xe^{2\lambda}\in o(e^{-2\mu x})$ as $x\to\infty$.

Big O-notation for some exponential


$A,B$ be $n\times n$ semipositive-definite, rank $A=r.$ Find an invertible $P$, such $P^{-1}A(P^{-1})^T=diag(I_r,0)$, $P^T BP=diag(\lambda_i)$

Question: $A,B$ be $n\times n$ semipositive-definite, $\operatorname{rank} A=r$. Find an invertible $P$, such $P^{-1}A(P^{-1})^T=\operatorname{diag}(I_r,0)$, $P^T BP=\operatorname{diag}(\lambda_i)$
Here, $I_r$ is the $r\times r$ identity matrix, $\lambda_i$ are the eigenvalues of $B$, $P^T$ is the transpose of $P$.
Terribly sorry. I only have known that if $A$ is positive definite, then $P^T AP=I_n$, and then $P^T BP$ is also semipositive-definite. Then some orthogonal matrix $Q$ exists, which let $Q^T P^T APQ=I_n$, and $Q^T P^T BPQ=\operatorname{diag}(\lambda_i)$, but $\lambda_i$ is eigenvalue of $P^T BP$!
Comment: closely related:  https://math.stackexchange.com/questions/3868605/diagonalizing-two-real-symmetric-matrices-with-one-sln-mathbbr-transforma/ .
Answer: This is not always possible. Consider the case where $A$ is a positive definite matrix of determinant $\ne1$. Since $P^{-1}A(P^{-1})^T=I$, we have $\det(P)^2=\det(A)\ne1$. This is inconsistent with the condition that $P^TBP=\operatorname{diag}(\lambda_1(B),\ldots,\lambda_n(B))$ when $\det(B)=\prod_i\lambda_i(B)$ is nonzero.
Comment: A correct statement could be : "let $A$ be a positive definite matrix, and $B$ a symmetric matrix. Then there exists an invertible matrix $P$ such that $P^TAP=I_n$ and $P^TBP$ is diagonal".


Comparision of multiple curves in R using linear mixed models

Question: first of all, I am sorry if a similar question already exits, in that case, please direct me to it!
I've got a repeated measurement of a value over 55-time points (720 min) in triplicate for two conditions (faint lines in the plot below). Now, I want to assess whether the mean curves (mean across all three replicates for each timepoint, bold lines in plot below) between the conditions show significantly different trajectories in R.

Example of the data structure is here:
     Timepoint  Time Value     N condition rep   concat_label
       <dbl> <dbl> <dbl> <dbl> <chr>     <chr> <chr>
 1         0     0  269.   157 A         R1    A_R1
 2         0     0  261.   123 B         R1    B_R1
 3         1    10  426.   162 A         R1    A_R1
 4         1    10  290.   126 B         R1    B_R1
 5         2    20  632.   172 A         R1    A_R1
 6         2    20  320.   126 B         R1    B_R1
 7         3    30  753.   178 A         R1    A_R1
 8         3    30  339.   130 B         R1    B_R1
 9         4    40  790.   178 A         R1    A_R1
10         4    40  350.   132 B         R1    B_R1

In order to do so, I applied growth curve analysis and followed this tutorial (http://www.danmirman.org/gca). With that, I tried to derive a linear mixed model using the lme4 package and the lmer function. In my eyes, the model should have the structure:
lmer(Value ~ Time*Condition + (Time | rep)) to take the variability of the replicates into account. In order to get the right repression of the curves, I am fitting the linear model onto a fourth-order polynom using poly(Time, 4)) and can then convert the t-values into p-vals (I need to report a p-val although I know that they are debatable).
Here is an example code to perform the linear mixed model and generate a list of p-values from the t-values.
    model <- lmer(Value ~ poly(Time, 4)*condition +
                  (poly(Time, 4) | rep),
                control = lmerControl(optimizer="bobyqa"),
                data=data, REML=F)

coef(summary(model))

coefs2 <- data.frame(coef(summary(model)))
coefs2$p <- format.pval(2*(1-pnorm(abs(coefs2$t.value))), digits=2)
coefs2

This returns values like:
> coefs2
                                Estimate Std..Error    t.value       p
(Intercept)                     792.4871  35.297235  22.451819 < 2e-16
poly(Timepoint, 4)1            1499.0161  97.490831  15.375971 < 2e-16
poly(Timepoint, 4)2            -664.3474  84.327948  -7.878140 3.3e-15
poly(Timepoint, 4)3             740.4694 112.671814   6.571914 5.0e-11
poly(Timepoint, 4)4            -586.8091  86.774484  -6.762462 1.4e-11
conditionB                     -357.6736   6.163614 -58.029855 < 2e-16
poly(Timepoint, 4)1:conditionB -667.3512 111.967603  -5.960217 2.5e-09
poly(Timepoint, 4)2:conditionB  542.1113 111.967603   4.841680 1.3e-06
poly(Timepoint, 4)3:conditionB -491.2822 111.967603  -4.387718 1.1e-05
poly(Timepoint, 4)4:conditionB  371.6393 111.967603   3.319168   9e-04

which I believe indicate that there is a significant difference in the trajectory of the example lines as indicated in "conditionB" (p < 2e-16). However, I am not sure whether this is the right model. Therefore, could someone give me some insights into whether this is the right model or how I might have to tweak in order to answer my specific question?
In addition to that, in a more advanced scenario, I would ideally like to compare multiple curves (e.g. conditions A vs B vs C vs D) to see which ones are significantly different (like in ANOVA situation but for non-linear data). Does someone have an idea on how to compare multiple curves using linear mixed models or even other types of regression analysis?
Comment: Did you consider a transformation of the dependent variable to obtain something approaching linearity ? The plots looks somewhat like logarithmic growth so you could try an exponential transform..
Comment: @RobertLong thanks for the suggestion! No, I actually haven't tried any transformation approaches yes, I will definitely give this a go!
Comment: If you have an interaction strictly speaking you should interpret that before looking at the main effects although in this case the main effect is obvious. Is there some scientific reason why a quartic needs to be fitted here? I see a more or less linear rise and a more or less linear plateau.
Comment: Thanks for your comment @mdewey! In general, I would definitely interpret before looking at the main effect (e.g. significance) but thought I could leave that out for this question. No, there is no strict reason why I would need to fit a quartic curve here, that is just because I got a higher R2 value (adjusted + unadjusted) with a quartic polynom. Could I combine two linear curves in a linear mixed model as you described?
Comment: Try looking at the thread in [tag:segmented-regression] or on-line for segmented regression and see if they help you.
Answer: I have found this Cross Validated answer useful to "compare nonlinear fits". Here is how I understood the idea.
Let's say you have three groups of observations which are identified by the levels g1,g2, g3 of a factor grp. One model, let's call it M3,  would be built by fitting the same nonlinear model to each of the three groups (i.e. you get "three fits in one"), the other model M0 would be a single fit to the pooled data where you ignore the group membership. Then you check with the anova() function whether M0 and M3 are "significantly different". If yes, then at least one of the curves is "different" from the rest. If not, then "grouping has no effect", M0 is just as good as M3, so any difference between the separately fitted curves "could be due to chance alone", they are not "significantly different".
This procedure uses a somewhat underdocumented feature of R's nls() function that lets you fit "indexed formulae". Basically, if your model is $$y(x) = \mathrm{MyFunc}(x; a, b)$$ where $a,b$ are the parameters, then the "indexed" formula would look like
y ~ MyFunc(x, a[grp], b[grp])

i.e. the parameters are "indexed" by the factor grp representing the groups and the result will be as if nls() had performed three fits on the three data subsets for which grp==g1, grp==g2, grp==g3, respectively.
I have used this trick on an enzyme inhibition dataset that contained Michaelis-Menten kinetics data points for an enzyme. The three groups were labeled "no inhibitor", and "low" and "high" concentrations of a competitive inhibitor. The question was whether the inhibitor has an effect.
I am not sure whether there's an easy way in R to do this with e.g. orthogonal polynomials, but maybe this idea will inspire you to try it out :-)


Is there a Java annotation to generate parameter documentation?

Question: Projects like hadoop have a ton of parameters, but all that documentation is manually generated from xml, rather than coming from the code.
Is there a way of doing something with an annotation that can generate this documentation?
<code>  public static final String MAP_SORT_SPILL_PERCENT = "mapreduce.map.sort.spill.percent";

  <name>mapreduce.map.sort.spill.percent</name>
  <value>0.80</value>
  <description>The soft limit in the serialization buffer. Once reached, a
  thread will begin to spill the contents to disk in the background. Note that
  collection will not block if this threshold is exceeded while a spill is
  already in progress, so spills may be larger than this threshold when it is
  set to less than .5</description>
</code>
Answer: You can use @param javadoc tag to generate parameter information in the code, such as this example from the wikipedia page:
<code>/**
 * Short one line description.
 *
 * @param  variable Description text text text.
 * @return Description text text text.
 */
public int methodName (...) {
    // method body with a return statement
}
</code>
That's how Oracle generates the official doc for Java (example)
Comment: That's a parameter to a function, this is an external parameter to a program.
Comment: same rules apply, right?  You can still put javadoc on your main() method using the @param annotation.  If that's not what you're looking for, can you clarify the question more?


Generators of the symmetric group $S_n$ [transpositions]

Question: It is clear that $S_n$ is generated by the adjacent transpositions, i.e., $S_n$ = $\langle (1,2),(2,3),...,(n-1,n) \rangle $.
So I took this idea by different way. Let me take for example $S_3$.
It is clear that $S_3 = \langle (1,2), (1,2,3)\rangle $
Then, $S_3 = \langle (1,2), (1,3)\rangle =  \langle (2,3), (1,2)\rangle = \langle (1,3), (2,3)\rangle$
Observing each case, $(1,2)$ and following transposition $(1,3)$ sharing common element "$1$". With the same method $(2,3)$ and following tranposition $(1,2)$ sharing the common element "$2$". Likewise $(1,3)$ and $(2,3)$ sharing the common element "$3$"
So I conducted induction that make my self the statement $(*)$
$(*)$ $S_n = \langle (i_1,i_2),(i_2,i_3),(i_3,i_4),...,(i_{n-1},i_n)\rangle $   for $i_k \in \{1,2,3,...,n\} $.
(Here if $k \neq l \Rightarrow i_k \neq i_l $.)
As you've known, the induction itself doesn't not guarantee true at all because it is just guess. So, does the statement $(*)$ always hold? If true would you suggest the proof idea? (If not, what is a counterexample?) Any answer or comment appreciated. thanks.
Comment: That's what I meant. Rename them. By renaming, you map permutations in your group to permutations in $S_n$, in a bijective way. If you prefer, *what* you are permuting doesn't matter, what matters is *how* you are permuting.
Comment: Just rename the $i_k$ to match $i_k=k$. This renaming yields a bijection from $S_n$ to your group. So?
Comment: @Jean-ClaudeArbaut Thanks for your comment. Yes it surely generates $S_n$ following your comments. But my question is more general case including  $i_k \neq k$.
Answer: Your $i_k$ implies a permutation $i = (j \mapsto i_j : j = 1, 2, \ldots, n)$, and you will find that each $i$-adjacent transposition $(i_k, i_{k+1})$ can be written $i(k, k+1)i^{-1}$, therefore your list of generators generate the same as $\langle i,(k,k+1) : k=1,2,\ldots,n-1\rangle$, which is clearly all of $S_n$, since you already observed just having the adjacent transpositions is enough.
To see why $\langle(i_k, i_{k+1}) : k = 1, 2, \ldots, n-1\rangle=\langle i,(k,k+1) : k=1,2,\ldots,n-1\rangle$, observe the following:
One direction of containment is easy (the RHS generates all of $S_n$ and so in particular it generates the LHS), for the other, note that $i$ itself, as a permutation, can be written as a sequence of transpositions $i = \tau_1\tau_2\cdots\tau_\ell$, and so
$$\prod_{j} i\tau_ji^{-1}=i\left(\prod_{j} \tau_j\right)i^{-1}= iii^{-1} = i$$
Thus the LHS can generate $i$ itself, and so it can also recover any transposition $(k, k+1)$
Comment: and to see why $(i_k, i_{k+1}) = i(k,k+1)i^{-1}$, simply verify mechancially that $(i_k, i_{k+1})i = i(k,k+1)$ by splitting into cases
Answer: HINT
If it is $(1 \ i_k)$ and $(2 \ i_j)$  then
$(1 \ 2)=(1\ i_j)...(i_a \ i_b)(i_k\ i_a)(2\ i_k)$


Angular directive/service to convert number into words (need in Angularjs)?

Question: I want to convert number into words. Like 234 in word would be 2 hundred thirty-four. Similarly 1000 will be  one thousand. Similarly 100 means one hundred.
Is there any library for this in angularjs. If then how we will write in angularjs directive/service so that we can use it again..
Comment: http://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
Answer: Create a words filter.

I got the "toWords" algorithm from this blog post: http://ravindersinghdang.blogspot.com/2013/04/convert-numbers-into-words-using.html

var app = angular.module('app',[]);

app.filter('words', function() {
  function isInteger(x) {
        return x % 1 === 0;
    }

  return function(value) {
    if (value && isInteger(value))
      return  toWords(value);

    return value;
  };

});

var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

function toWords(s)
{
    s = s.toString();
    s = s.replace(/[\, ]/g,'');
    if (s != parseFloat(s)) return 'not a number';
    var x = s.indexOf('.');
    if (x == -1) x = s.length;
    if (x > 15) return 'too big';
    var n = s.split('');
    var str = '';
    var sk = 0;
    for (var i=0; i < x; i++)
    {
        if ((x-i)%3==2)
        {
            if (n[i] == '1')
            {
                str += tn[Number(n[i+1])] + ' ';
                i++;
                sk=1;
            }
            else if (n[i]!=0)
            {
                str += tw[n[i]-2] + ' ';
                sk=1;
            }
        }
        else if (n[i]!=0)
        {
            str += dg[n[i]] +' ';
            if ((x-i)%3==0) str += 'hundred ';
            sk=1;
        }

        if ((x-i)%3==1)
        {
            if (sk) str += th[(x-i-1)/3] + ' ';
            sk=0;
        }
    }
    if (x != s.length)
    {
        var y = s.length;
        str += 'point ';
        for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
    }
    return str.replace(/\s+/g,' ');
}

window.toWords = toWords;

  <input type="text" ng-model="name" /> {{name | words}}

Comment: Any reason why you did the `window.toWords = toWords;` instead of just including the function `toWords()` and variables within the filter?
Comment: Thanks for the resource, very helpful
Comment: is it possible with angular2?
Answer: I have done this for Angular 8.
It also works for float/double numbers.


The name 'model' does not exist in current context in ASP.NET Core

Question: I'm trying to develop a website with plugins using ASP.NET Core. I have my main project, asp.net web application which works fine. I have a class library project with controllers which also works fine and views which I have a problem with. When I open *.cshtml file I can see that Razor doesn't work - @using, @model and other directives are not recognized and intellisense doesn't work. When I hover over model I'm given the error from title:

The name 'model' does not exist in current context in ASP.NET Core

I use EmbeddedFileProvider for discovering views and they're marked as Embedded resource. When I run application everything works - views are rendered correctly. My only issue is false-positive errors in Visual Studio. I googled and there similar issues, but mainly for ASP.NET MVC, not Core - like here. I think something is missing in class library configuration, but I'm not sure what exactly.
Comment: Follow this steps: https://stackoverflow.com/a/33764916/6557649 Works for me
Answer: The new csproj file has an "Sdk" attribute at the top level "Project" element. When you create a new Web application, this gets set to the "Web" SDK:
<Project Sdk="Microsoft.NET.Sdk.Web">...</Project>

When you add/create a class library, it defaults to the standard non-web SDK:
<Project Sdk="Microsoft.NET.Sdk">...</Project>

As far as I can tell, the Web SDK imports additional tasks to allow design-time processing of Web resources, such as Razor views. Change the SDK in your plugin library to Web.
Another parameter of a "Web" project is that it outputs an EXE by default, so also add this to your plugin csproj:
<PropertyGroup>
    <OutputType>Library</OutputType>
</PropertyGroup>

Comment: I have same problem, in MVC web site project, which has the sdk directive as you said, however, Model, the model type is not recgonized and underlined as mistakes in all views
Comment: Thanks! Exactly what i was missing when upgrading from old project.json to new VS17 type. My project was Microsoft.Net.Sdk instead of sdk.web


How to find $\int_{\Gamma} \cos z \sin z dz$ where $\Gamma = \pi t + (1-t)i$ for $t \in [0,1]$?

Question: How to find $\int_{\Gamma} \cos z \sin z dz$ where $\Gamma = \pi t + (1-t)i$ for $t \in [0,1]$?
I subbed in to get $$(\pi-i)\int_0^{1} \cos (\pi t + (1-t)i) \sin (\pi t + (1-t)i) dt$$ which I found to be $-\frac{1}{2} \sin^2(i)$ using a substitution of the form $u=\sin (\pi t + (1-t)i)$.
Is the correct?
Answer: Since we have a primitive everywhere
$$\int \cos z\sin z\;dz=\frac12\int2\sin z\cos z\;dz=\frac12\int\sin 2z\;dz=-\frac14\cos 2x+K$$
we then get at once that
$$\int_i^\pi\cos z\sin z\;dz=\left.-\frac14\cos 2z\right|_i^\pi=-\frac14(1-\cos 2i)$$
and observe that (trigonometric identities)
$$\frac14(\cos 2i-1)=\frac14(\cos^2i-\sin^2i-1)=\frac14(1-2\sin^2i-1)=-\frac12\sin^2i$$


How to reconnect a URLSessionWebSocketTask once its cancelled?

Question: I am cancelling or disconnecting an active WebSocket task using the following code
<code>socket.cancel(with: .goingAway, reason: nil)
</code>
Is there any way to reconnect back or should we create a new URLSessionWebSocketTask and resume again ?
Answer: You should create a new URLSessionWebSocketTask and resume again.


Book recommendations: statistical methods in the social sciences for someone who's not afraid of higher math

Question: I would like to learn basic statistical methods for quantitative data analysis in the social sciences. I volunteer for a nonprofit, and I want to take on a quantitative research project analyzing things like demographic and law-enforcement data. The (admittedly rather vague) goal is to learn things from existing raw data that would be useful in informing policy decisions.
I have a Master's in pure math, focus on algebra. I know how to learn independently out of dense textbooks, but I'm quite weak on applied math and statistics.
I think what I want is to give myself the crash course version of an "Intro to Quantitative Research Methods" class taken by sociology PhD students, but leaning more on mathematical sophistication. (I'm not claiming to be any more "sophisticated" than sociology students. I'm guessing that embracing the math side of things helps you learn enough to do basic research, and I want to take advantage of my background.) So I want a book that does not presuppose any knowledge of statistics but also does not shy away from expounding on the theoretical framework when it's helpful.
If it matters, I'll be using R. Yes, I am prepared to invest plenty of time in the learning curve.
Does anyone have suggestions as to resources? Thanks for the help!
P.S. I thought this question might have been asked before, but I couldn't find it. If I've started a duplicate thread then my apologies and I'd be grateful to be directed to the existing question.
Comment: Might I suggest considering learning how to explore data first?  If you learn that, you will already have tools that are more useful and more powerful for learning from data than those used by most people in the social sciences.
Answer: Basic Search on Google
On google you can search about this with #tags like:
R social science
On youtube you will find this free-course for  psychologists.
R for Social Science
Besides, the CRAN have a task view about Statistical methods in Social Science in this link where shows many packages for support this field;
CRAN Task View: Statistics for the Social Sciences
Books
You can get this book "Applied R for the quantitative social scientist
By Rense Nieuwenhuis" in this link
Book
Alternatively, Springer offers a  book that covers recent advances for quantitative researchers with practical examples from social sciences, called "Advances in Social Science Research Using R "
You can buy the book following this link
Book.
Note:I don't know if it will solve your question.
Answer: There has been some similar questions before. This mathoverflow question https://mathoverflow.net/questions/31655/statistics-for-mathematicians   has a lot of good advice. Good advice on math SE:  https://math.stackexchange.com/questions/735075/statistics-primer-for-the-unwary-mathematician
I especially like my answer to Inference for the skeptical (but not math-averse) reader
From the varied advice on this pages, I will highlight:
Young and Smith, "Essentials of Statistical Inference." A more recent book on: Likelihood, pseudolikelihood, saddlepoint approximations, p∗ formula, modified profile likelihoods and more  which should fit you well. Very good.


Given two nonzero 3-vectors $\vec{u}$ and $\vec{v}$ of equal length, does there always exist a 3x3 matrix M such that $\vec{u}=M\vec{v}$ of this form?

Question: I originally wanted to derive a general rotation matrix that can transform a given 3-vector into another specified 3-vector of equal length. In failing to do so, I derived a matrix that contains information about the axis and angle of rotation. I wanted to share my matrix and ask for confirmation that such a matrix can always be found for two equal length nonzero 3-vectors.
Although my matrix is not a rotation matrix, I find my matrix to be valuable for its ease of use, especially in comparison to the standard method, or Rodrigues' rotation formula.
Let $\vec{u} = (x,y,z), \vec{v}=(p,q,r)$ .
Then the relationship between $\vec{u}$ and $\vec{v}$ can be expressed as
$$
\frac{1}{d}
\begin{bmatrix} d\cos\theta & -c\sin\theta & b\sin\theta \\c\sin\theta & d\cos\theta & -a\sin\theta  \\\ -b\sin\theta & a\sin\theta & d\cos\theta\end{bmatrix}
\begin{bmatrix} p  \\\ q \\\ r\end{bmatrix}=\begin{bmatrix} x\\y\\z\end{bmatrix}
$$
where $d=\sqrt{a^2+b^2+c^2}$, $(a,b,c)$ is orthogonal to the plane containing $\vec{u}$ and $\vec{v}$, and $\theta$ is the angle between $\vec{u}$ and $\vec{v}$.
My derivation is as follows:
Let $\vec{v}=(p,q,r)$ be a non-zero 3-vector. Pick a unit vector $\vec{a}=(a,b,c)$ orthogonal to it.
Then $(x,y,z)=\vec{v}\cos(\theta)+\vec{a}$x$\vec{v}\sin(\theta)$
So
$
\begin{bmatrix} p\cos(\theta)  \\\ q\cos(\theta)  \\\ r\cos(\theta)\end{bmatrix}+
\begin{bmatrix} (br-cq)\sin(\theta)  \\\ (cp-ar)\sin(\theta)\\\ (aq-bp)\sin(\theta)\end{bmatrix}=\begin{bmatrix} x\\y\\z\end{bmatrix}
$
I should add that since learning about Rodrigues' rotation formula I now understand how to derive the general rotation matrix that I originally set out to derive.
Comment: @KurtG. It's not homework. I want to derive the general rotation matrix to get from one 3-vector to another 3-vector. I'm doing this for fun and mathematical curiosity. My derivation is simple: define a unit vector t in the direction of v and a unit vector T in the direction of the cross product (a,b,c) x t. tcos(theta)+Tsin(theta) = u/length(u). This expression can then be turned into the 3x3 matrix above by observing that the terms in the expression are linear combinations of the components of v.
Comment: Your thoughts? Hint: $(a,b,c)$ is the cross product of $u$ and $v$.
Comment: @KurtG. I'm aware. Is the matrix correct? If not, what have I done wrong?
Comment: Shall I solve your homework? Show (with whatever technique you are aware of) if / if not that matrix is correct.
Comment: There is one exception- a pair of vectors which some of your formula breaks down.  Hint: what vector has no direction defined for it?  Modifying how the original question is stated should compensate.
Comment: @nickalh you mean where both of the vectors are the zero vector?
Comment: Yes, adding the word "distinct" vectors, u and v should prevent that breaking your formula.  Obviously, if u = 0 = v, then u & v are not distinct.
Comment: @nickalh Assuming my matrix is correct, would it be a less computationally taxing alternative to the "standard method"
R = I + (\sin\theta) K+(1-\cos\theta)K^2 ? Personally, I like my matrix a lot better
Comment: You have rushed to put your "solution" out into the body of the Question and omitted the important context largely supplied by your longish Comment above.  There are important applications for orthogonal matrices $M$, i.e. "general rotation matrix" of determinant $1$, that transform one vector to another (necessarily of equal length).  Please edit the body of your Question to more clearly setup the problem and your interest in it, even if this is "for fun and mathematical curiosity."
Answer: The standard method to find a rotation matrix that rotates a vector $u$ into $v$ is:
Take as rotation

axis $\omega$ the cross product between $u$ and $v\,,$

angle $\theta$ the angle between $u$ and $v\,.$

Form the  cross product matrix $K$ of $\omega\,.$
Write the rotation matrix as
$$
R = I + (\sin\theta) K+(1-\cos\theta)K^2\,.
$$

Your favourite matrix in OP is not a rotation matrix because its determinant
is $\color{red}{\cos\theta}$ which is not always one.

To check if your matrix really maps $\vec{v}$ into $\vec{u}$ let's assume for simplicity that these vectors have length one. The rotation axis
is the cross product $\vec{v}\times\vec{u}\,:$
$$
\begin{pmatrix}a\\b\\c\end{pmatrix}=
\begin{pmatrix}p\\q\\r\end{pmatrix}\times \begin{pmatrix}x\\y\\z\end{pmatrix}=
\begin{pmatrix}qz-ry\\
rx-pz\\
py-qx
\end{pmatrix}
$$
whose length $d$ is $\sin\theta\,.$ Thus, $\frac{\sin\theta}{d}=1\,.$
We also use the scalar product $\vec{v}\cdot\vec{u}\,:$
$$
\cos\theta=xp+yq+zr\,.
$$
Let's call your matrix $M\,.$
Then  $M\vec{v}$ has the first component
\begin{align}\require{cancel}
p\cos\theta-c\,q+b\,r&=xp^2+\cancel{ypq+zpr}+xq^2\cancel{-ypq-zpr}+xr^2\\
&=x(p^2+q^2+r^2)=x\,.
\end{align}
The other components are verified similarly.

Conclusion: Your matrix maps two particular vectors $\vec{v},\vec{u}$ into each other but is neither a rotation nor a reflection. In particular it is not length preserving and not angle preserving.

To figure out what matrix $M$ is we assume w.l.o.g. that $\vec{u},\vec{v}$ are in the $xy$-plane. Then their cross product is
$$
\begin{pmatrix}0\\0\\\sin\theta\end{pmatrix}
$$
and the matrix simplifies to
$$
M=\begin{pmatrix}
\cos\theta &-\sin\theta&0\\
\sin\theta&\cos\theta&0\\
0&0&\color{red}{\cos\theta}\end{pmatrix}\,.
$$
This is obviously a rotation around the $z$-axis by the angle $\theta$ followed (or preceded) by a compression of the $z$-direction by the factor $\color{red}{\cos\theta}\,.$
Comment: Just what I needed. Thanks
Comment: What does my matrix represent, and why does it successfully get me from one vector to the other? Is it a rotation combined with a scaling factor of cos(theta)?
Comment: I am not even sure if that lovely matrix maps $\vec{v}$ to $\vec{u}\,.$ I tried numerical examples without success. Happy to be convinced otherwise. Can you show it by performing the matrix multiplication? Regarding your second question: matrices that preserve Euclidean lengths also preserve Euclidean angles and must either be rotations or reflections. The determinant must be $\pm 1\,.$ Regarding the scaling factor $\cos\theta\,:$ divide by it and see if you get a rotation.
Comment: https://www.wolframalpha.com/input?i2d=true&i=%7B%7Bcos%5C%2840%290.6423%5C%2841%29%2C-Divide%5B4Sqrt%5B20%5D-2Sqrt%5B3%5D%2C29%5D%2CDivide%5B2Sqrt%5B6%5D-3Sqrt%5B20%5D%2C29%5D%7D%2C%7BDivide%5B4Sqrt%5B20%5D-2Sqrt%5B3%5D%2C29%5D%2Ccos%5C%2840%290.6423%5C%2841%29%2C-Divide%5B3Sqrt%5B3%5D-4Sqrt%5B6%5D%2C29%5D%7D%2C%7B-Divide%5B2Sqrt%5B6%5D-3Sqrt%5B20%5D%2C29%5D%2CDivide%5B3Sqrt%5B3%5D-4Sqrt%5B6%5D%2C29%5D%2Ccos%5C%2840%290.6423%5C%2841%29%7D%7D%7B%7BDivide%5BSqrt%5B20%5D%2CSqrt%5B29%5D%5D%7D%2C%7BDivide%5BSqrt%5B3%5D%2CSqrt%5B29%5D%5D%7D%2C%7BDivide%5BSqrt%5B6%5D%2CSqrt%5B29%5D%5D%7D%7D
Comment: Please don't expect me to unravel that.
Comment: It's a successful numerical example. What ambiguity is there?
Comment: Give me two equal length 3-vectors and I'll come back with a verification that the matrix works
Comment: let's test out (p,q,r)=(1,0,0), (a,b,c)=(0,0,1), and theta = 90 degrees. The matrix indeed gives me that (x,y,z) must be (0,1,0)
Comment: I can't imagine why any numerical examples would've failed as long as you were making sure to pick an (a,b,c) that's orthogonal to your chosen (p,q,r)
Comment: We are messing around. The mathematical way to show $M\vec{v}=\vec{u}$ I have outlined in another update of the answer. Please proceed along those lines.
Comment: I'm unsure what to do about the discrepancy, but can I request that we shift the focus to justifying the derivation of my matrix? I didn't pull the matrix out of nowhere; it follows from the geometric construction of u from components of v
Comment: You cannot request that I further check your work. It is time now to do maths. I showed how this works.
Comment: I'll update the post with a full breakdown of my reasoning for the matrix, complete with exact calculations
Comment: @SimonM after flipping the sign of the cross product it is true that $M\vec{v}=\vec{u}$ ***but*** see my ***Conclusion***.
Comment: This conclusion is exactly what I was wondering about. I now think I understand what I was previously failing to. Thanks for elucidating
Comment: You are welcome. We both learned something.
Comment: Did you previously believe that in order for a matrix to map a vector to an equal length vector then the matrix must have determinant +1 or -1? That's what I thought at first
Comment: No. When we have two *particular* vectors the matrix can be more general. Yours is an example. When we require length preserving for *all* vectors it can only be a rotation or reflection. I think I said this a couple of times today.
Comment: If I divide the matrix by (cos(theta))^1/3, then the determinant would be 1. Would this new matrix be a rotation?
Comment: A rotation matrix has to have orthogonal columns and rows. Have you checked that ?
Comment: Just checked. The columns and rows are not orthogonal. I guess it's not a rotation.
Comment: I know this much about how to geometrically interpret the (original, unscaled) matrix: if you multiply a vector v by this matrix and that vector v happens to be orthogonal to (a,b,c), then the matrix will rotate v by an angle of theta about the axis (a,b,c). Aside from that, I'm completely lost. I'm curious as to what the matrix does to vectors that don't just conveniently happen to be orthogonal to (a,b,c)
Comment: So the matrix rotates the vector by an angle of theta about the axis (a,b,c) as well as scales in the (a,b,c) direction. That would explain why all it does to (a,b,c) is scale it by cos(theta).


How to treat variable in logistic regression?

Question: I have a variable I do not know how I should handle my logistic regression.
The variable is the number of registered students each semester.
If I plot it against my binary outcome, I get the following plot:

what kind of explanatory variables should I use? Linear, polynomial, categorical? I feel myself confused when it looks like this and would therefore need some tips.
Comment: Are you showing us the entire sample? Even a linear relationship would be a stretch with just twelve data points, so higher order terms are pretty much out of the question.
Answer: Without any other information, a linear term is the obvious choice, since the number of students registered is on a ratio scale. This may or may not make sense given all the missing context of the purpose of the study, the nature of the outcome, the other variables available, the sample size, etc.


go: array in struct looses its content

Question: The following go code (shared: link) should insert two positions in an order (both order and position are structs:
package main

import "fmt"

type orderPosition struct{
   art string
   qty string
}

type order struct{
   posList []orderPosition
}

func main() {
  o := new(order)
  o.loadPos()
  fmt.Printf("# pos: %d\n",len(o.posList))

}

func (o order) loadPos() {
  o.posList = append(o.posList, orderPosition {art: "art 1", qty: "2 pc"})
  o.posList = append(o.posList, orderPosition {art: "art 2", qty: "7 pc"})
  fmt.Printf("# pos: %d\n",len(o.posList))
}

The output is:
# pos: 2
# pos: 0

The method loadPos fills the positions in the order. But as soon as the method is left the list of positions is lost.
Why is the array loosing its content?
Any help would be greatly appreciated.
Answer: Your loadPos() method is using a value receiver (as opposed to a pointer), meaning that it's operating on a copy of the order object.
So when you call o.loadPos(), go is copying o, and calling loadPos() on that copy.
The solution is to simply change the receiver to a pointer:
func (o *order) loadPos() {

https://play.golang.org/p/PATpBCZLT7
Answer: Extending the Patrick answer, there is more insight in Golang FAQ
Should I define methods on values or pointers?
func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct)  valueMethod()   { } // method on value

First, and most important, does the method need to modify the
  receiver? If it does, the receiver must be a pointer. (Slices and maps
  act as references, so their story is a little more subtle, but for
  instance to change the length of a slice in a method the receiver must
  still be a pointer.) In the examples above, if pointerMethod modifies
  the fields of s, the caller will see those changes, but valueMethod is
  called with a copy of the caller's argument (that's the definition of
  passing a value), so changes it makes will be invisible to the caller.
Second is the consideration of efficiency. If the receiver is large, a
  big struct for instance, it will be much cheaper to use a pointer
  receiver.
Next is consistency. If some of the methods of the type must have
  pointer receivers, the rest should too, so the method set is
  consistent regardless of how the type is used.

For types such as basic types, slices, and small structs, a value
receiver is very cheap so unless the semantics of the method requires
a pointer, a value receiver is efficient and clear.

go: array in struct looses its content


C#: How to pass parameter key/values to a function?

Question: I have a function that takes in a bool, shown below:
public void LoadEndPoints(bool mock)
{

}

I can call this via LoadEndpoints(true) or LoadEndpoints(false), but this can be a bit hard to understand, as you need to know what true/false represents. Is there a way to pass the parameter name and value to a function such as LoadEndPoints(mock = true)?
Comment: I wouldn't call this code "non-readable" although there might be better ways to express the high-level end goal. *The method-level documentation should explain the `mock` parameter.* Perhaps the name could be expanded (e.g. `mockOnly`), but otherwise I think it's generally "ok". There are *many* methods that take `bool` types and it's up to the caller to know how to call the method correctly.
Comment: I don't understand why using "named parameters" would help here.. and there are so many answers relating to such.
Comment: Perhaps: 1) Use discrete method names: `LoadEndPoints/LoadMockedEndPoints` or; 2) Take in a enumeration (or other type) that conveys more meaning: `LoadEndPoints(EndpointMode.MockOnly)` or; 3) Move the configuration to a [class-level] setting: `var epl = new EndPointLoader { Mock = true }; epl.LoadEndPoints()`; etc.
Comment: Yes, I agree, your code should be more readable.
Comment: Side note, how come you are using a variable for mocking? In what context is variable `mock` used, in testing?
Comment: You should comment your code to make that clear. You should use XML comments, which will be represented in the intellisense to ensure you and future developers will understand.
Answer: Yes!
You can specify the parameter names like this:
myObject.LoadEndPoints(mock: true);

Further Reading

Named and Optional Arguments (C# Programming Guide)

Another way to improve readability of your code would be to use an enum, like this:
public enum LoadOption
{
    Normal,
    Mock
}

public void LoadEndPoints(LoadOption option)
{
    ...
}

Then the call would look a bit like this:
myObject.LoadEndPoints(LoadOption.Mock);

Comment: @MustafaEkici OP specifically asked know how to make the code more readable by specifying the parameter name as well instead of just the parameter. The way I read the question this is *exactly* what OP is asking for. That said, *aquaraga*'s answer is good too.
Comment: @MustafaEkici What do you mean? I've showed how it can be done and linked to detailed references. *aquaraga*'s answer listed the same solution.
Comment: its different not same.. check your refrence example, there is weight and height right? they are already defined. so think that i call that method with parameter 30 (parameter means Age or can be everything) so how you get that name (Age) in the function?
Comment: @MustafaEkici and what would a parameter named 'age' do? Why would you expect to be able to pass any parameter with any name to any function that doesn't define what that parameter is or does? I'm sorry, but I fail to see why that would be a criticism of this technique.
Answer: You could use 'Named arguments', a C# 4.0 feature; and thus call: myObject.LoadEndPoints(mock : true);
If readability is indeed your prime concern, you could even expose two explicit methods, and internally reuse the logic - something similar to:
    public void LoadEndPointsWithoutMock()
    {
        LoadEndPoints(false);
    }
    public void LoadEndPointsByMocking()
    {
        LoadEndPoints(true);
    }
    private void LoadEndPoints(bool mock)
    {

    }

Also, I wouldn't say that LoadEndPointsWithoutMock, etc. are great method names. Ideally, the names should have something to do with the domain.
Answer: You can use a KeyValuePair:
   KeyValuePair kvp = new KeyValuePair(BoolType, BoolValue)

Comment: What would a call to the method look like, using `KeyValuePair`?
Comment: The other answers are better, but LoadEndpoints would take a KeyValuePair instead of a bool
Answer: Yes, you can do it with the following syntax in c#:
myObject.LoadEndPoints(mock : true);

And in VB:
myObject.LoadEndPoints(mock := true)

Answer: Use named parameters. Have a look at this Named and Optional Arguments


Time-weighted Pearson correlation

Question: I'm trying to calculate time-weighted Pearson correlation as described in https://www.aaai.org/ocs/index.php/FLAIRS/FLAIRS14/paper/viewFile/7817/7840    The coefficient is given by
$$
\rho_t(X,Y) = \left ( \frac{1-r}{1-r^N} \right ) \sum_{i=0}^{N} r^{i-1} \frac{(x_{-i} - \mu_X)(y_{-i} - \mu_Y)}{\sigma_X\sigma_Y},
$$
where $N+1$   is the number of observations,  $t=0,1,...,N$   indicates time period when the coefficient is calculated  ($t = N$ in my case, i.e. I'm calculating the correlation based on full sample),  $\sigma_X$, $\mu_X$, $x_{-i}$   denote standard deviation, expectation, and the   $i$th  latest observation in $X$  respectively, $r$  is the decay constant, equal to a real number less than 1.
My problem is that  $\rho_t(X,X) \neq 1$  when calculating it based on the formula above. Below is an example of how I calculate it in R.
<code>set.seed(314)
N <- 1000
x <- cumsum(rnorm(N+1)) # random walk

cor(x, x) # Pearson correlation
# Result is 1

r <- 0.998
sigma <- sd(x)
mu <- mean(x)

(1 - r)/(1 - r^N) * sum( r^(0:N-1) * (x - mu)^2/sigma^2 ) # rho_t(x, x)
# Result is 1.171462
</code>
Please correct me if I have a bug in my code or suggest how I should modify the formula if it contains a mistake (my gut feeling says that the normalization might be wrong).
Comment: (+1) That paper's claims about the mathematical properties of $\rho_t$ are untrue.  If you would like a formula in which $\rho_t$ is assured of lying between $-1$ and $1$, *and actually equals those values* when there's perfect correlation, then you also need to compute weighted versions of  $\sigma_X$ and $\sigma_Y$ using the same weights.  (It hardly makes sense to use *unweighted* estimates of standard deviations for a *weighted* estimate of correlation in the first place.) You might even want to use weighted estimates of the means $\mu_X$ and $\mu_Y$.
Comment: Please post your comment as an answer and I'll accept it.
Answer: Answered in comments by whuber, copied here:
That paper's claims about the mathematical properties of $\rho_t$ are untrue. If you would like a formula in which $\rho_t$ is assured of lying between −1 and 1, and actually equals those values when there's perfect correlation, then you also need to compute weighted versions of $\sigma_X$ and $\sigma_Y$ using the same weights. (It hardly makes sense to use unweighted estimates of standard deviations for a weighted estimate of correlation in the first place.) You might even want to use weighted estimates of the means $\mu_X$ and $\mu_Y$.

Time-weighted Pearson correlation


Programmatically printing from field_collection array

Question: Is there any simple way to print a certain number of elements from a field collection?
Say I have an array of 8 elements and want to just print 4 at the top of a page; then, print the other 4 at the bottom.
Right now I'm attempting it in the node.tpl I am theming.
<code>print render($content['field_my_elements_of_whatever']);
</code>
Answer: You can use Entity View Modes to solve the first part.
Install/enable the module, then configure some new view modes for field collections.
Then, goto the Field Collections config, and do the Manage Display for your collections.  Configure the new view mode(s).
Now, goto the Manage Display for your nodes.  Click the settings gear for the field collection field, and choose your view mode.
That should set you up for your second part, which is rendering out a field twice.  There are several ways to do this, like this and this.  You would just need to make sure your duplicated field uses your other view mode.
Comment: Amazingly helpful info. Got a working test using all this. Thanks a ton!


Exposed view filter is not rendered properly

Question: I have a view with a filter "Has taxonomy term", this filter is an exposed filter and is set to be a "Dropdown" and "Show Hierarchy"
The vocabulary has parents and children term (hierarchical).
The filter works fine but the html tags of the select dropdown are incorrect. The parent terms should be wrapped in  instead of  (see image 2)
Can I override this?

I trying to do it with hook_form_alter() but I see that the construction of the select itself is done by drupal_map_assoc() function. Then I see no way to do it? Can I put the value for '#options' in other way?
<code><?php
  $form['undergraduate']['school_country'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(t('UK'), t('Other'))),
    '#title' => t('In what country is your college or university located?'),
  );
?>
</code>
Comment: This is how it is meant to look/work. It does not provide  functionality. I had to do this once and did it with custom code in a form_alter
Comment: ok, I just need that the user can't select a parent item, and indent to the right a little bit the children items. I will try to use form alter
Comment: You could check if it is the top level (maybe by checking if it doesn't have a - at the start), and then add the attribute disabled (disabled="disabled")
Comment: You could also use this module: http://drupal.org/project/term_reference_tree. It has on option to only allow selection of the lowest term in the hierarchy. I used it on a site recently and it worked well.
Answer: You could check if it is the top level (maybe by checking if it doesn't have a - at the start), and then add the attribute disabled (disabled="disabled")
You could also use this module: drupal.org/project/term_reference_tree. It has on option to only allow selection of the lowest term in the hierarchy. I used it on a site recently and it worked well.
Comment: thanks, I didn't know the term_reference_tree module.


Is there a way to factor out the middle tensor product?

Question: Given a state $(|1\rangle \otimes |0\rangle \otimes |1\rangle) + (|0\rangle \otimes |0\rangle \otimes |1\rangle)$, is it possible to factorise out the $|0\rangle$ in the middle of both of them?
Alternatively written as $|101\rangle + |001\rangle$ for convenience.
For a state such as the following it is possible to factorise out:
$|101\rangle + |100\rangle = |1\rangle (|01\rangle + |00\rangle)$
as shown above. Is there any way to factorise out the middle tensor in such a form?
Answer: $(|1\rangle \otimes |0\rangle \otimes |1\rangle) + (|0\rangle \otimes |0\rangle \otimes |1\rangle)$ is clearly a product state. It's tricky to find good notation to denote this and I don't think there's an established standard way. Here's one option:
Let $\sigma_{ij}$ be an automorphism that flips the $i$th and $j$th position of a tensor product $\bigotimes_{k=1}^n V$. Then
$$(|1\rangle \otimes |0\rangle \otimes |1\rangle) + (|0\rangle \otimes |0\rangle \otimes |1\rangle) = \sigma_{12} \Big( \ |0\rangle \ \otimes \ \big( |1\rangle \otimes |1\rangle + |0\rangle \otimes |1\rangle \big) \ \Big) $$
Comment: I guess this is sort of a factorization but I think the better answer is to say that it's not. It's closely related to asking if we can factor out $B$ if we have $ABC + A'BC'$.
Comment: I don't know about that. At least in physics applications, to ability to factor a vector in a tensor product space like this is quite important. In that sense, it seems incidental that it happens in a 'middle' position, versus an end position. Another difference with your proposed analogy also is that each of the kets $|0\rangle$ and $|1\rangle$ belong to the same vector space, while it is not clear that $A,A'$ and $B$ and $C, C'$ don't belong to different homomorphism spaces.
Comment: That's a good point, especially for numerical quantum mechanics. All sorts of tricks are used there. I guess the best answer is to say "it can't be *elementarily* factored, but with permutations it can be."
Answer: If you consider the definition of tensor product by universal property, which is unavoidably equal to one you have in mind, then you have two natural isomorphisms $V\otimes W\cong W\otimes V$ and $(V_1\otimes V_2)\otimes V_3\cong V_1\otimes (V_2\otimes V_3).$ This implies that you can simply say that the position on which we write particular factor of tensor is just a matter of convinience. I bet you start with three qubits. The order of them depends on you. If someone fix some order, then these isomorphisms tells you that you can make a permutation. But after you done a permutation and you want put these cubits in some gate then you also have to change the order in this gate (in imput and output). The point is that the tensor product gives you a flexibility in making permutations, in sucha a way, that if you permute the tensors and perumute the gates (i.e. imputs and outputs) then result will be the same. Which in fact is all we care about.


avoiding download htaccess

Question: I'm trying to develop a book reader online. The problem is that I save the pages as jpg or pdf and then I want to get the file using flash but I do not want this files as direct download, so I want to avoid download jpg and png but not js or swf. I tried to use this in my htaccess but does not work because does not allow to get the js files. Any error?
<code># secure htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>
Options All -Indexes
RewriteEngine On
#RewriteCond %{HTTP_REFERER} !^http://(.+\.)?domain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?server/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(js|swf)$ - [F]
<Files ~ "^.(htaccess|htpasswd)$">
deny from all
</Files>
Options Indexes
order deny,allow
</code>
Answer: You can't do that if you want your swf to read them.
Comment: Is it impossible to deleiver by IP???
Comment: you can use a socket, but its much more complex.
Answer: Any reason you can't use the same Files directive that denies access to the .htaccess and .htpasswd files to also deny access to jpg and png?
Comment: When you deny access to images, then also browsers won't be able to display them on the website
Comment: I believe that was the whole point. He wants the Flash application to provide them instead.
Comment: How will the Flash application download them if Apache won't serve them?
Comment: Good point. I was thinking of Flash combined with a serverside app. It's possible to make a crude PHP/CGI script that will communicate with the Flash app only.
Answer: The only real way to allow your flash application to get at some content and not let other user agents is to use a protocol other than HTTP. For example, if data security is important (just as an example), you could encrypt the data on the server and have the flash application decrypt it when it receives it.
The "protocol" doesn't need to be anything fancy. It could even be as simple as a base-64 encoding on the server-side that the flash-side decodes. The principal behind it though, of using something other than just http, is the only real way to protect it from generic browsers.

avoiding download htaccess


Postfix - how to send maximally 5 emails in 2 minutes

Question: I try to set Postfix through the anvil command so that can be sent altogether maximally 5 emails in 2 minutes, seemingly this is not possible as can be sent emails without any limitation. Maybe I have not found the right settings for the master.cf file regarding to the options smtpd and anvil or similar. Many Greetings
main.cf:
<code>anvil_rate_time_unit = 120s
smtpd_client_connection_count_limit = 1
smtpd_client_connection_rate_limit = 1
smtpd_client_recipient_rate_limit = 5
smtpd_client_message_rate_limit = 5
</code>
master.cf:
<code># service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
#submission inet n       -       -       -       -       smtpd
#smtps     inet  n       -       -       -       -       smtpd
#628       inet  n       -       -       -       -       qmqpd
pickup    unix  n       -       -       60      1       pickup
cleanup   unix  n       -       -       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
relay     unix  -       -       -       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
</code>
Answer: iirc, all these settings apply per remote server (or domain) that it's connecting to, so 5 messages per 120s per remote mailserver or domain.
Comment: Thanks, but how exactly must the file look then? Many Greetings
Comment: I don't think it is even possible to do what you want.
Answer: One approach you could examine is queue-only mode:

Configure Postfix in queue-only mode.
Configure the queue runner to run every 30 seconds.
Configure Postfix to send only one message per queue run.

This would give a maximum of 4 messages every two minutes.
Another approach would be to configure Postfix to rely via a server.  Configure the relay server with the reception limits you need.   You should be able to configure Postfix to relay only for the one host.
Either of these solutions can result in your mail server's queue to grow out of control.


Setting up subdomains on localhost

Question: I have been trying to set up a subdomain on my local development environment, dev.localhost.  I'm using Ubuntu 11.10 and Apache2.  So far, I've edited my host file to include the line 127.0.0.1 dev.localhost.  I've created a file called axis in /etc/apache2/sites-available which looks like this:
<VirtualHost *:80>
    DocumentRoot /var/www/Axis/trunk
    ServerName dev.localhost
    ServerAlias *.localhost

    <Directory /var/www/Axis/trunk/>
            Options Indexes FollowSymLinks MultiViews +Includes
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>
</VirtualHost>

I then enabled the site with sudo a2ensite axis. I encountered a no host named error and added the line ServerName localhost to my default file in sites-available.  I also encountered an error that had something to do with NameVirtualHost, which I solved by adding NameVirtualHost *:80 to httpd.conf and also commenting it out in ports.conf.
Now, when I navigate to dev.localhost I get the SAME webpage as I would if I navigated to localhost.  In other words, both localhost and dev.localhost point to /var/www but I want dev.localhost to point to /var/www/Axis/trunk.
Any idea where I'm going wrong?  Thanks
EDIT: output from apache2ctl -S
ulimit: 88: error setting limit (Operation not permitted)
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   is a NameVirtualHost
     default server localhost (/etc/apache2/sites-enabled/000-default:1)
     port 80 namevhost localhost (/etc/apache2/sites-enabled/000-default:1)
     port 80 namevhost dev.localhost (/etc/apache2/sites-enabled/axis:1)
Syntax OK

Comment: What was the error?  Can you edit your question to include the output from `apache2ctl -S`?
Comment: There is no error, it just doesn't route to the expected folder.  I posted the results of `apache2ctl -S`
Answer: You need to set your /etc/hostsor C:\Windows\system32\drivers\etc\hosts(as administrator) to reflect the "subdomain". So add 127.0.0.1  dev.localhostto either file (depending on your platform).
However it might be that "localhost" as is is somewhat special in terms of a domain name resolution as it might not work as a domain. So instead you can put something like mylan.localas server name and dev.mylan.local as subdomain. (you can basically use everything you want there)
And in the end, don't forget to reload Apache with apache2ctl restart as it needs to reload its config.
Comment: It appears that `localhost` was indeed the problem.  `dev.local` works exactly as expected

Setting up subdomains on localhost


Prime in $\mathbb{Z}[i]$

Question: I'd need a help with an exercise. I am trying to show that $(1-i)$ is a prime (or principal equivalently) ideal in $\mathbb{Z}[i]$. For doing this, I have not worked on the norms yet so I can't use those to prove it.
Thanks for your help!
Comment: My first instinct would be to try showing that $\mathbb{Z}[i]/(1-i)$ is an integral domain.
Answer: Suppose $(a+bi)(c+di)=1-i$, with $a,b,c,d\in\mathbb Z$, so that $ac-bd=1$ and $bc+ad=-1$. Squaring those last two equations, and adding the results,
$$
(ac-bd)^2+(bc+ad)^2=(-1)^2+1
$$
$$
(ac)^2+(bd)^2+(bc)^2+(ad)^2=(a^2+b^2)(c^2+d^2)=2
$$
Since $2$ is prime in $\mathbb Z$, and both $a^2+b^2,c^2+d^2\in\mathbb Z$, without loss of generality, $a^2+b^2=1$. The only solution to this over the integers is $a=\pm1$ and $b=0$, or $a=0$ and $b=\pm1$. Either way, $a+bi$ is a unit in $\mathbb Z[i]$.
Answer: Define
$$\phi: \Bbb Z[i]\to\Bbb Z_2:=\Bbb Z/2\Bbb Z\;\;,\;\;\;\phi(a+bi):=a^2+b^2\pmod 2$$
Check $\;\phi\;$ is a ring homomorphism (Careful! It seems like it is not, but it actually is).
Now, let us find
$$\ker\phi=\left\{\;a+bi\in\Bbb Z[i]\;\;:\;\;a^2=b^2\pmod 2\;\right\}=\left\{\;a+bi\in\Bbb Z[i]\;:\;\;a=b\pmod2\;\right\}=$$
$$=\left\{\;a+bi\in\Bbb Z\;:\;\exists\,r,s\in\Bbb Z\;\;s.t.\;\;a=r+s\,,\,\,b=-r+s\;\right\}=$$
$$=\left\{\;a+bi\in\Bbb Z[i]\;:\;a+bi=(r+si)(1-i)\;\right\}=\langle\;1-i\;\rangle$$
Comment: While true, that's sort of an odd way to present the homomorphism: the more usual way is to specify the image of $i$ and let everything else follow from that.
Comment: @Hurkyl Perhaps, yet the OP stated he hasn't even worked with norms yet, so perhaps he'll be able to understand this better.

Prime in $\mathbb{Z}[i]$


Resolving promises without passing through variables

Question: I am learning about using promises and am trying to use functional programming to achieve code modularity. My issue is that as I progress through the then() chain that I am passing parameters through intermediary then() calls for later functions to use.
This feels unnecessary and I think I am missing the forest for the trees.
function getSession(user, pass) {
    return new Promise((resolve) => {
        // do something with user and pass
        resolve(session)
    })
}

function getAccount(session) {
    return new Promise((resolve) => {
        // do something with session - pass through session
        resolve([session, account])
    })
}

function doThing(session, account) {
    return new Promise((resolve) => {
        // do something with account - pass through session
        resolve([session, thing])
    })
}

function doOtherThing(session, thing) {
    return new Promise((resolve) => {
        // do something with session and thing
        resolve(otherThing)
    })
}

let example = getSession(user, pass).then(getAccount).then(doThing).then(doOtherThing)

So for example, doThing() is passed session and account but only does something to account. However, since doOtherThing() requires session, I pass through the session instance so it can be used by that function.
So to eliminate passing through these extra variables I want to do something like
function getAccount(session) {
    return new Promise((resolve) => {
        // do something with session
        resolve(account)
    })
}

function doThing(account) {
    return new Promise((resolve) => {
        // do something with account
        resolve(thing)
    })
}

let session = getSession(user, pass)
let thing = getSession(user, pass).then(getAccount).then(doThing)
let example = doOtherThing(session, thing)

As you can see, most of these functions return a promise so I can improve code modularity by chaining elsewhere. As such the session and thing variables are assigned promises.
However in this case, I just want to resolve both promises in session and thing to then be used in doOtherThing(session, thing)
I tried something like
let session = getSession(user, pass).resolve()
let thing = getSession(user, pass).then(getAccount).then(doThing).resolve()

and
let example = doOtherThing(session.resolve(), thing.resolve())

but I get resolve is not a function as an error.
Also I know
let session = getSession(user, pass)
let thing = getSession(user, pass).then(getAccount).doThing(account)
let example = doOtherThing(session, thing)

doesn't make sense since the promises in both variables need to be resolved before passing them to doOtherThing() but I am drawing a blank as to how to do this - so this is more pseudo code showing that I don't want to pass through session
I have looked at this question but I don't think I am trying to do the same thing.
Comment: You may be interested in this: [How to chain promise and share prior results](https://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises/28714863#28714863).
Comment: this could be helpful : https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain
Comment: If you `example` is a function that takes `[user,pass]` and returns `otherThing` then you can hard code the functions that convert `[user,pass] => session => thing => [session,thing] => otherThing` and use closure but what if the functions themselves are passed or defined as an array of functions? You can map over them and use a utility called thread, an example can be found [here](https://stackoverflow.com/a/48677470/1641941)
Answer: Ok, so I figured out a way - not sure if it is the cleanest, but it removes passing through variables
let session = getSession(user, pass)
let thing = session.then(getAccount).doThing(account)

Promise.all([session, thing])
    .then((promises => {
        [session, thing] = promises

        return doOtherThing(session, thing)
    }))
    .then(otherThing => { console.log(otherThing) })

Comment: this line may give you error in strict mode as undeclared var `[session, thing] = promises`
Answer: Does this look cleaner?
let session = getSession(user, pass)
let thing = session.then(getAccount).doThing(account)

Promise.all([
  session,
  thing
]).then(data => {
  return doOtherThing(...data)
}).then(anyOtherThing => {
  console.log(anyOtherThing)
}).catch(console.log);

Answer: After looking at another answer, it seems the cleanest and most readable way to do this is using async
function getAccount(session) {
    return new Promise((resolve) => {
        // do something with session
        resolve(account)
    })
}

function doThing(account) {
    return new Promise((resolve) => {
        // do something with account
        resolve(thing)
    })
}

const main = async () => {
    let session = await getSession(user, pass)
    let account = await getAccount(session)
    let thing = await doThing(account)
    let otherThing = await doOtherThing(session, account)

    return(otherthing)
}

let otherThingResult = main()

This allows the promises to be executed in a familiar synchronous code style and gives a number of advantages;

Variables do not need to be passed through 'chained promises'
meaning the results from these resolved promises can be single
variables rather than an array containing the desired variable and
the passed through variables
Which in turn allows 'chained' promise function parameters to accept
individual variables rather than using destructuring of arrays increasing
reusability of code
The use of Promise.all() in other areas of code now hints more at its
original functionality of executing an array of unrelated promises
asynchronously
Code indentation remains low and readability greatly improves


Como pegar a url gerado ao acessar o link de foto do instagram usando /media/?size=l no final

Question: Estou tentando pegar a url que é exibida(trocada) ao acessar um link como por exemplo no instagram https://www.instagram.com/p/B9MjyquAfkE/media/?size=l, o link gerado após o clique, vem da api do instagram, e como esse mesmo link gerado tem tempo de expiração, não tem como usar ele por muito tempo. Existe alguma maneira via php, para pega-lo sem mostrar a página em si do link?
Tentei usar o curl, mas não consegui o resultado.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '"'.$dadosItemInstagram['imagem'].'"');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

O array $dadosItemInstagram['imagem'], é o que contém o link. Andei lendo bastante antes de vir aqui, e pelo que entendi o instagram apartir de uma autorização da conta da acesso a api deles, pra por exemplo exibir imagens ou vídeos nos sites, só que o link tem uma certa duração então estou preso nessa parte, a solução que encontrei foi adicionar o /media/?size=l , no final do link, então sei se é a melhor também.
Answer: O que acontece é que esse link é redirecionado pra outra url, então você precisa que o CURL aceite redirecionamento. Você consegue fazer isso setando a opção CURLOPT_FOLLOWLOCATION:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Comment: Funcionou muito bem, mas só consegui reproduzir colocando um link em `curl_setopt($ch, CURLOPT_URL, "(um_link_aqui)");`  , se eu colocar uma variável que contem o link ele não da certo, não sei se é possível também, tem essa possibilidade?
Comment: É  possível também retornar somente a url redirecionada?
Comment: Sim, isso já está sendo feito com a função `curl_getinfo`: `$urlRedirecionada = $info['url'];`


String translations not working after setting language in page preprocess function

Question: I am using the domains module (D6) with multiple domains on a 1 site, and we have multiple languages on 1 domain. (We have to have this set up with no other option). Internationalization string translations is enabled and the translated strings in the t() function are in the database.
The domian language setting overrides the node language setting which causes the string translations not to work when having multiple languages on 1 domain.
I have overridden the domain language setting with the node language setting in the theme template_preprocess_page() function and works well but I think it happens too late in the process as the string translations still don't work.
What do I need to do to get the string translations to work?
function phptemplate_preprocess_page(&$vars, $hook) {
  global $language;

  // Reset Language to Page Node Level
  // Get the list of languages
  $languages = language_list();

  // Set up the new language code
  $new_lang_code = $vars['node']->language;

  // Make sure the required language object is actually set
  if (isset($languages[$new_lang_code])) {

    // Overwrite the global language object
    $language = $languages[$new_lang_code];
  }
  var_dump($language) // $language = node language setting
}

Answer: I have got this working now by moving the code into the preprocess_node() function instead.

function phptemplate_preprocess_node(&$vars, $hook) {
  global $language;
  $languages = language_list();
  $new_lang_code = $vars['node']->language;
 if (isset($languages[$new_lang_code])) {
  $language = $languages[$new_lang_code];
 }
}


Show that $M_t$ is a Standard Brownian Motion

Question: Let $M=(M_t)_{t\geq0}$ with $$M_t=\int_0^{\log\sqrt{1+2t}}e^s\text{d}B_s$$
where $(B_t)_{t\geq0}$ is a Standard Brownian Motion.
Show that $M$ is also a Standard Brownian Motion and compute $\mathbb{E}[\int_0^tM^6_s\text{d}M_s]$ and $\mathbb{E}[\left(\int_0^tM_s\text{d}M_s\right)^3]$.
Can we use Levy's Characterization Theorem?
Comment: Indeed, the task is to prove that $(M_t)_{t\geqslant0}$ and $(M_t^2-t)_{t\geqslant0}$ are both martingales starting from $0$.
Comment: The problem is that I don't know what to do with the term $\log\sqrt{1+2t}$ in the upper limit of the integral.
Comment: Yes. Thus, you need to know $\mathrm dM_t$ where $M_t=K_{A(t)}$ for some (deterministic) increasing $t\mapsto A(t)$ and some (martingale) process $(K_t)_{t\geqslant0}$. Any idea?
Comment: Well, I guess that would be $\text{d}M_t=\sqrt{1+2t}\text{d}B_{\sqrt{1+2t}}$. Then why is $M_t$ a martingale?
Comment: No it is not. Please first find a formula in the more general setting I indicated (with a purpose, believe it or not) and only then apply this formula to your setting.
Comment: OK, $K_t=\int_0^te^s\text{d}B_s$ is a martingale since $\mathbb{E}[\int_0^te^{2s}\text{d}s]<\infty$.

Also, $A(t)=\sqrt{1+2t}$ is increasing.
Comment: I don't know how to find $\text{d}M_t=\text{d}(K_{A(t)})$. I've think of using Ito's formula but with no success. The problem remains $A(t)$
Answer: From the exchanges in the comments, one reaches the conclusion that $M_t=K_{A(t)}$ with
$$
K_t=\int_0^t\mathrm e^s\mathrm dB_s,\qquad
A(t)=\log\sqrt{1+2t}.
$$
Since $(K_t)_{t\geqslant0}$ is a martingale and the (deterministic) function $A$ is nondecreasing, this is enough to show that $(M_t)_{t\geqslant0}$ is a martingale. Furthermore, for every $0\leqslant s\leqslant t$, by Itô's isometry,
the identity $$
(M_t-M_s)^2=\left(\int_{A(s)}^{A(t)}\mathrm e^u\mathrm dB_u\right)^2
$$
implies that
$$
\mathbb E((M_t-M_s)^2)=\mathbb E\left(\int_{A(s)}^{A(t)}\mathrm e^{2u}\mathrm du\right)=\frac{\mathrm e^{2A(t)}-\mathrm e^{2A(s)}}2.
$$
The function $A$ is tuned such that $\mathbb E((M_t-M_s)^2)=t-s$ hence $(M_t)_{t\geqslant0}$ is a Brownian motion. More generally, for every nonzero function $a$, $(M^a_t)_{t\geqslant0}$ is a Brownian motion, where
$$
M^a_t=\int_0^{A^{-1}(t)}a(s)\mathrm dB_s,\qquad A(t)=\int_0^{t}a(s)^2\mathrm ds.
$$
The two expectatons to be computed are direct since one can replace $(M_t)_{t\geqslant0}$ by  $(B_t)_{t\geqslant0}$ without changing the result. For example,
$$
X_t=\int_0^tB_t^6\mathrm dB_t
$$
is an odd functional of $(B_s)_{0\leqslant s\leqslant t}$, hence $\mathbb E(X_t)=0$. Likewise,
$$
Y_t=\int_0^tB_s\mathrm dB_s
$$
is a centered gaussian random variable hence $\mathbb E(Y_t^3)=0$.
On time-changed Brownian motions, see this.
Edit: Since $A$ is invertible and continuous, the sigma-algebras $\mathcal F_t^B=\sigma(B_s;s\leqslant t)$ and $\mathcal F_t^M=\sigma(M_s;s\leqslant t)$ are such that $\mathcal F^M_t=\mathcal F^B_{A(t)}$. For every $s\leqslant t$, $M_t=M_s+\Delta$ where
$$
\Delta=\int_{A(s)}^{A(t)}\mathrm e^u\mathrm dB_u.
$$
The increments of $(B_u)_{u\geqslant A(s)}$ are independent of $\mathcal F^B_{A(s)}$ hence $\mathbb E(\Delta\mid\mathcal F^B_{A(s)})=0$, which shows that $\mathbb E(M_t\mid\mathcal F^M_s)=M_s$. Hence $(M_t)_{t\geqslant0}$ is a martingale.
Comment: I tried to show that $K_{A(t)}$ is a martingale using the definition but I failed. Could you give me a hint please?
Comment: See Edit. $ $ $ $
Comment: Let $X_t=\int_0^te^s\text{d}B_s$. Observe that if we set:$$\tau_t=\inf\{s>0\ |\ \left_s>t\}$$,
then, by the Dambis/Dubins - Schwartz Theorem, $X_{\tau_t}$ is a standard Brownian Motion and $X_t=B_{_t}$ for all $t\geq0$.
In this case, $\tau_t=\inf\{s>0\ |\ s>\log(\sqrt{1+2t})\}$.
Comment: Could you please give more details of why $\mathcal{F}^M_t = \mathcal{F}_{A(t)}^B$? Moreover, where do you use that $K$ is a martingale? Thanks in advance.


Simultaneous equation

Question: Solve that
$x-y=a  ,  2x^2+y^2=9$ and let solution set $(x,y) = (\alpha,\beta)$
Find the maximum value of $|\alpha + \beta|$
where $a$ is a real number
Answer: Hint: $x-y=a \implies x = y+a$. Plug this into your second equation to find the solution set.
Comment: So I try it and that absolute value has form $\frac {-a \pm \sqrt{27-a^2}}3$. Next what should I do? and I'm sorry I omitted that we can't use differentiation
Comment: @user128766 Those are not the solutions. See [WolframAlpha](http://www.wolframalpha.com/input/?i=2%28y%2Ba%29%5E2%2By%5E2-9%3D0). $y=\frac{-2a\pm \sqrt{27-2a^2}}{3}$
Comment: There should be only 2 solutions. Manual calculation of $|\alpha+\beta|$ should reveal which one is maximal.
Comment: So what is the maximum value? It must be 1 or 2 or 3 or 4.

Simultaneous equation


Ubuntu - * at the end of filename?

Question: In Ubuntu 10.10, showing a file listing using ll will occasionally show files with a * appended to the name of the file.  What does this star mean?
Answer: It means the file is executable and you have ll aliased to ls -F, ls --classify or ls --indicator-style=classify (among other possible options). You can use the command alias ll to see what the alias is and change it persistently by editing your ~/.bashrc file (or other file) where it's defined.
Other indicators:

/ - directory
@ - symbolic links
| - fifos
= - sockets
> - doors

each depending on OS/filesystem support.
Answer: It means the file is executable.

Ubuntu - * at the end of filename?


Não estou conseguindo percorrer duas listas, alguém consegue me ajudar?

Question: O que eu quero é achar as raízes de um polinômio. Com isso, eu criei uma lista com os coeficientes do polinômio e outra lista com os candidatos a serem raízes. Preciso testar todos eles e encontrar as raízes. Porém não esta dando certo.
Pegando um polinômio para exemplificação: x² - 5x + 6
p = [6, -5, 1] #coef. do polinômio
candidatos = [-1, 1, -2, 2, -3, +3, -6, +6]

r = []

resultado = 0

i = 0

while i < len(candidatos) + 1:

    for coef in p:

        resultado = resultado * k[a] + coef   #Briot Ruffini

        if resultado == 0:
            r.append(k[a])

    i = i + 1

print(r)

Answer: Quem seria k e quem seria a no seu código ?
Fiz um pequeno código, espero que ajude, não usei algoritmo de Briot-Rufinni, coloquei 1/3 e 1/2, que são as raízes desse polinômio para fazer um teste. Use a bibliteca math para calcular a potencia.
from math import pow

p = [6, -5, 1] #coef. do polinômio
candidatos = [-1, 1, -2, 2, -3, +3, -6, +6, 1/3, 1/2]

r = list()
exponte = len(p) - 1 #pega o tamanho de p, no caso 3 e tira 1, obetendo o grau do polinomio

for i in candidatos:  #testa cada um dos candidatos
    resultado = 0 #armazenar o resultado

    for j in p: #intera dentro do polimonio com o canditato
        resultado += j*pow(i, exponte) #com o exponte você faz 6*(i)^2 e vai somando
        exponte -= 1 #na segunda interação o expoente que era 2 passa a ser 1

    if resultado == 0: #se o resultado for 0 entra nesse if
        r.append(i)

    resultado = 0 #zera o resultado para repetir o processo

print(r)

Comment: no lugar de k[a] considere candidatos[i]
Comment: Interessante seu código, mas não posso usar a bibliioteca math mas agradeço a ajuda!
Answer: Quebrei um pouco a cabeça e implementei esse briot-rufini
p = [6, -5, 1] #coef. do polinômio
candidatos = [1, -2, 2, -3, +3, -6, +6, 1/3, 1/2]

raiz = list()
aux = 0

for i in candidatos:
    for j in p:
        r = j + aux
        aux = r*i
    if r == 0:
        raiz.append(i)

    r = 0
    aux = 0

print(raiz)

Comment: Muito obrigado, ficou bem simples de entender!


What does it mean for a study to be over-powered?

Question: What does it mean for a study to be over-powered?
My impression is that it means that your sample sizes are so large that you have the power to detect  minuscule effect sizes. These effect sizes are perhaps so small that they are more likely to result from slight biases in the sampling process than a (not necessarily direct) causal connection between the variables.
Is this the correct intuition? If so, I don't see what the big deal is, as long as the results are interpreted in that light and you manually check and see whether the estimated effect size is large enough to be "meaningful" or not.
Am I missing something? Is there a better recommendation as to what to do in this scenario?
Comment: Sounds exactly like my intuitive understanding of this term.
Comment: It is not, because slight biases in the sampling process get reduced with larger sample sizes (law of large numbers). In terms of confidence intervals, the effect size gets closer to 0 in proportion to the shortening of the tails of the confidence intervals. The example above holds for a trial where there is truly no difference in the population
Answer: I think that your interpretation is incorrect.
You say "These effect sizes are perhaps so small as are more likely result from slight biases in the sampling process than a (not necessarily direct) causal connection between the variables" which seems to imply that the P value in an 'over-powered' study is not the same sort of thing as a P value from a 'properly' powered study. That is wrong. In both cases the P value is the probability of obtaining data as extreme as those observed, or more extreme, if the null hypothesis is true.
If you prefer the Neyman-Pearson approach, the rate of false positive errors obtained from  the 'over-powered' study is the same as that of a 'properly' powered study if the same alpha value is used for both.
The difference in interpretation that is needed is that there is a different relationship between statistical significance and scientific significance for over-powered studies. In effect, the over-powered study will give a large probability of obtaining significance even though the effect is, as you say, miniscule, and therefore of questionable importance.
As long as results from an 'over-powered' study are appropriately interpreted (and confidence intervals for the effect size help such an interpretation) there is no statistical problem with an 'over-powered' study. In that light, the only criteria by which a study can actually be over-powered  are the ethical and resource allocation issues raised in other answers.
Comment: Thanks, this is very informative. I understand that the p-value definition doesn't change. Certainly from a statistical standpoint, the rate of type I errors does not increase.
Comment: By definition, we are fixing the type I error rate in setting the p-value threshold. However, it seems like the difference between "statistical" and "practical" significance is the issue here. When the sample size is able to detect differences much finer than the expected effect size, a difference that is correctly statistically distinct is not practically meaningful (and from the perspective of the "end-user" this is effectively a "false positive" even if it's not a statistical one). However, as you say this starts to get outside the realm of statistics.
Comment: i.e. i think i agree - "the difference in interpretation that is needed is that there is a different relationship between statistical significance and scientific significance"
Answer: In medical research trials may be unethical if they recruit too many patients. For example if the goal is to decide which treatment is better it's not ethical any more to treat patients with the worse treatment after it was established to be inferior. Increasing the sample size would, of course, give you a more accurate estimate of the effect size, but you may have to stop well before the effects of factors like "slight biases in the sampling process" appear.
It may also be unethical to spend public money of sufficiently confirmed research.
Answer: Everything you've said makes sense (although I don't know what "big deal" you're referring to), and I esp. like your point about effect sizes as opposed to statistical significance.  One other consideration is that some studies require the allocation of scarce resources to obtain the participation of each case, and so one wouldn't want to overdo it.
Comment: Sorry, "big deal" is too much of an editorial comment. The question of whether it's a "bigger deal" than I'm making it out to be is basically a question of whether there are additional considerations of which I may be ignorant.
Answer: My experience comes from A/B experiments online, where the issue is usually underpowered studies or measuring the wrong things. But it seems to me an overpowered study produces narrower confidence intervals than comparable studies, lower p-values, and possibly different variance. I imagine this can make it harder to compare similar studies. For example, if I repeated an overpowered study using proper power, my p-value would be higher even if I exactly replicated the effect. Increased sample size can even out variability or introduce variability if there are outliers which might have a higher chance of showing up in a larger sample.
Also, my simulations show that effects other than the ones you are interested in might become significant with a larger sample. So, while the p-value correctly tells you the probability that your results are real, they could be real for reasons other than what you think e.g., a combination of chance, some transient effect you didn't control for, and perhaps some other smaller effect you introduced without realizing it. If the study is just a bit overpowered, the risk of this is low. The problem is often it's hard to know the adequate power e.g., if the baseline metrics and minimum target effect are guesses or turn out different than expected.
I've also come across an article that argues that too large of a sample can make a goodness-of-fit test too sensitive to inconsequential deviations, leading to potentially counter-intuitive results.
That said, I believe it best to err on the side of high rather than low power.