Uncaught TypeError: Cannot set property 'innerHTML' of null

Question: O trecho de código abaixo está dando erro pois _elemento está retornando null alguma idéia de como resolver?

class View {

    constructor(seletor) {

        this._elemento = document.querySelector(seletor);
    }

    update(model) {

        this._elemento.innerHTML = this.template(model);
    }

    template(model) {

        throw new Error('Você precisa implementar o método template');
    }
}

class NegociacoesView extends View {

    template(model) {

        return `

                    DATA
                    QUANTIDADE
                    VALOR
                    VOLUME

                ${model.paraArray().map(negociacao =>
                `

                        ${DateConverter.paraTexto(negociacao.data)}
                        ${negociacao.quantidade}
                        ${negociacao.valor}
                        ${negociacao.volume}

                `).join('')}

                    ${model.volumeTotal}

        `
    }
}

class MensagemView extends View {

    template(model) {

        return model.texto
            ? `<p class="alert alert-info">${model.texto}</p>`
            : `<p></p>`;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Negociações</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Negociações

    <form class="form">

            Data
            <input type="date" id="data" class="form-control" required autofocus/>

            Quantidade
            <input type="number" min="1" step="1" id="quantidade" class="form-control" value="1" required/>

            Valor
            <input id="valor" type="number" class="form-control" min="0.01" step="0.01" value="0.0" required />

        <button class="btn btn-primary" type="submit">Incluir</button>
    </form>

        <button id="botao-importa" class="btn btn-primary text-center" type="button">
            Importar Negociações
        </button>
        <button id="botao-apaga" class="btn btn-primary text-center" type="button">
            Apagar
        </button>

Comment: Posta o código onde você tentar usar o método `update`.
Comment: Posta o código em que você cria uma `new View`. E o código HTML que vai junto. Se não for erro no seletor, pode ser que o elemento ainda não exista no momento em que você roda esse código.
Comment: na verdade as views q criei herdam essa class view
Comment: acredito q tudo oque vc precisa pra me ajudar está aqui
Comment: acredito que descobri o erro rsrsrs e ta no html
Answer: Na verdade no meu código o original #mensagemView estava sendo chamado como .mensagemView por isso nao funcionava

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Negociações</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Negociações

    <form class="form">

            Data
            <input type="date" id="data" class="form-control" required autofocus/>

            Quantidade
            <input type="number" min="1" step="1" id="quantidade" class="form-control" value="1" required/>

            Valor
            <input id="valor" type="number" class="form-control" min="0.01" step="0.01" value="0.0" required />

        <button class="btn btn-primary" type="submit">Incluir</button>
    </form>

        <button id="botao-importa" class="btn btn-primary text-center" type="button">
            Importar Negociações
        </button>
        <button id="botao-apaga" class="btn btn-primary text-center" type="button">
            Apagar
        </button>


Lista encadeada em C- adicionar!

Question: Estou com duvida em um exercício e se alguém pudesse me ajudar seria muito bom! Obrigado desde já!
#include <stdio.h>
#include <stdlib.h>

struct Numeros {
    int numero;
    struct Numeros *next;
};

void adicionar (int n, struct Numeros **here) {
    struct Numeros *temporario;

    if((*here)->next == NULL)
       {getch();
       (*here)->numero=n;
       }
       else if(((*here)->next->numero!=n)&&((*here)->next->numero>n))
       {
           temporario=(struct Numeros*)malloc(sizeof(struct Numeros));
           temporario=(*here)->next;
           temporario->numero=n;
           temporario->next=(*here)->next;
           (*here)->next=temporario;
           free(temporario);
           }
}

void remover (int n, struct Numeros **here) {
// 1- Verificar se não existem elementos na lista
// 1.1- sair

// 2- Caso exista elementos, verificar se o atual éo que se deseja remover
// 2.1- atualizar os ponteiros

// 3- Caso não seja o elemento procurado, avançar na lista procurando!
}

void imprimir (struct Numeros *here) {
    printf("[%d]", here->numero);
    if (here->next != NULL)
        {
        imprimir(here->next); // manda imprimir o proximo!
        }
}

 int main (){
struct Numeros *head = NULL;

int flag = 0, numero;
do {
    printf("1) adicionar\n");
    printf("2) remover\n");
    printf("3) imprimir\n");
    printf("0) sair\n");
    printf("Informe uma opcao: ");
    scanf("%d", &flag);

    switch(flag){
        case 0: // sair
            break;
        case 1: // adicionar
            printf("--------------------------------------------\n");
            printf("Informe o valor para ser adicionado: ");
            scanf("%d", &numero);
            adicionar(numero, &head);
            printf("--------------------------------------------\n");
            break;
        case 2: // remover
            printf("--------------------------------------------\n");
            printf("Informe o valor para ser removido: ");
            scanf("%d", &numero);
            remover(numero, &head);
            printf("--------------------------------------------\n");
            break;
        case 3: // imprimir
            printf("--------------------------------------------\n");
            (head != NULL) ? imprimir(head) : printf("Não existem elementos na lista\n");;
            printf("\n");
            printf("--------------------------------------------\n");
            break;
        default:
            printf("Opcao invalida\n");
    }

} while (flag);

free(head);

return 0;
}

Em relação ao
void remover(int n,struct Numeros **here)

não precisam se preocupar pois ainda não comecei a desenvolver e nem a fazer, por isso gostaria de ter a oportunidade de tentar, mas a minha duvida esta no adicionar, já a partir do
if((*here)->next == NULL)

começa a ter falhas no programa. Se alguém puder me explicar o que está errado e o que falta me ajudaria bastante na compreensão. Valeu!!!
Comment: No inicio tens `head = NULL` quando acedes a `(* here)->next` ou seja NULL->next, deve dar seg.fault. Talvez juntat um `if((*here) == NULL)...`
Answer: Tenta usar:
(*(*here)).next == NULL

Em vez de usar:
(*here)->next == NULL

Lista encadeada em C- adicionar!


Can we settle this STD vs SEM debate once and for all?

Question: OK, I AM getting tired of seeing the SEM used simply as a means of reducing the size of error bars.  If the SEM is a measure of the precision of a mean from a sample, then in my mind one cannot generate an SEM from one mean.  One needs many means to estimate the precision of the "population mean"  SO, the only time I ever used the SEM was when I calculated many sample means (each with replicates of course to generate a mean) and then calculated the STD of the average of those means to use in the equation SEM = STD/sqrt of n which in my case was the number of individual sample means.
To me one should show the STD of a representative experiment (itself a somewhat ambiguous and often inaccurate phrase) and dispense with the SEM.  I just see zero utility in its use from a SINGLE sample mean.
Comment: What is your question?
Comment: The SE model is for questions that have answers, not a discussion forum (that's what chat is for). This isn't a question at all, but at best a thesis of sorts, and something of a rant.
Comment: Yup.  Too bad.  Just ignore and move on if you have an issue.
Answer: I assume that with STD you mean standard deviation and with SEM you mean the standard error. The two just measure different things: the standard deviation just measures how much the obervations in your sample are appart from each other. The standard error measures the standard deviation of the sampling distribution of the statistic. The first is purely descriptive, the latter is there to do inference. Both can be valid aims for research. So I don't see why there is a debate: You can use either without problems as long as you make sure that you are showing the things you want to show and your audience understands that.
From your question I suspect that the real problem is that you have trouble understanding how one can estimate the standard error of the sampling distribution from just one sample. The background there is the central limit theorem.
What I often find useful to get an initial idea about the logic is to create a simulation. For example create many draws of size 100 each from a standard normal distribution, compute the mean in each of these and collect those means. They are an estimate of the sampling distribution. Now see if the mean of that sampling distribution is close to the mean in the population (0) and the standard deviation of the sampling distribution (the standard error) is close to $\frac{1}{\sqrt{100}}=0.1$. Here is the output of such a simulation in Stata:
<code>. clear all

. set more off

. set seed 12345

. program define sim
  1.         drop _all
  2.         set obs 100
  3.         gen x = rnormal()
  4.         sum x, meanonly
  5. end

. simulate m=r(mean), reps(10000) nodots : sim

      command:  sim
            m:  r(mean)

. sum m

    Variable |        Obs        Mean    Std. Dev.       Min        Max
-------------+---------------------------------------------------------
           m |     10,000    .0013082      .10061   -.443326   .3668843
</code>
Comment: +1 for spotting the underlying confusion. A bit more commentary connecting the simulation results to SE and SDs in the single sample case might help the OP.
Comment: Sorry, the SEM means nothing to me from a single mean of replicates.  For example, I measure the height of 100 random people from Germany, I generate a mean.  That SINGLE mean can hardly be used to estimate its precision to the entire mean height of the world.  On the other hand, let's say I then do two more experiments (100 people from USA and 100 people from China).  Now I have three means.  The SEM now makes sense here because I have three means in which to estimate the error of the POPmean.
Comment: TO continue….not sure what discipline most readers are in, but I can assure all that in Biology, the SEM is grossly and inaccurately used to define a data set.  SEM does not measure dispersion.  That would be the STD.  In fact, I tell my students NOT to use SEM and to show their data as a scatterplot with the STD,  That means much more to me than SEM, which again,  has little to no meaning to me in biology.  regrets to the math and stat geeks!
Comment: Why are you so negative? I am just trying to help you understand what the logic behind the standard error is. Standard errors and standard deviations both have meaning, even in biology. They just mean different things. It is common to confuse the two, but the solution is not to ban one, but to understand what both mean and use the appropriate measure in each situation.


Formulário continua aberto após this.close()

Question: Eu tenho um formulário de menu principal, que chama o de cadastro de alunos.
Porém o código de saída do formulário de alunos não o fecha, chama o formulário principal mas ele continua aberto de fundo e não posso nem fechá-lo manualmente.
Código para abrir o menu de cadastro:
frmCadAluno oloko = new frmCadAluno();
this.Visible = false;
oloko.ShowDialog();

Código para fechar:
FrmMenuPrincipal oloko = new FrmMenuPrincipal();
oloko.ShowDialog();
this.Close();
this.Dispose();

Comment: "codigo para abrir", qual o form origem? é o menu principal? No "codigo para fechar", tente fechar o form atual antes de abrir o menu principal
Comment: @AugustoVasques
Comment: Pergunta mal feita. Melhore isso aí.
Comment: Você está abrindo o oloko e fechando o this, que seria o form que abriu o oloko, tenta oloko.Close()
Comment: @AugustoVasques eu peço desculpas, primeira vez utilizando o stackoverflow. O meu erro era no showdialog, devia ser apenas show().
Comment: @BrunoMoraes [https://pt.stackoverflow.com/help/asking](https://pt.stackoverflow.com/help/asking)
Answer: O erro era usar showdialog() ao invés de show().
Comment: +1 por ter respondido uma pergunta ininteligível. Mesmo que seja sua.


Probability of drawing exactly 2 balls of a same color from a bin

Question: There is a bin with 1 green ball, 1 red ball, 1 blue ball, and 1 yellow ball.
We draw 4 balls with replacement. What is the probability of drawing exactly 2 of a given color? Order doesn't matter, as long as we have exactly 2 balls drawn of a given color.
My attempt was as follows:
There are $\binom 4 2$ ways to select two "spots" in the 4 output spots. For each of those ways, the probability of having exactly two is $\frac 1 4 \cdot \frac 1 4 \cdot \frac 3 4 \cdot \frac 3 4$. Hence the final probability is just $\binom 4 2 \cdot \frac 1 4 \cdot \frac 1 4 \cdot \frac 3 4 \cdot \frac 3 4$.
Is this right?
Comment: Yes, this looks good.  You could also see this as an instance of the binomial distribution with success probability $\frac 14$.
Answer: Suppose the 'given color' is Red. The probability of Red on any one draw is $1/4.$ Let $X$ be the number of times Red is drawn. Then $X \sim \mathsf{Binom}(n=4, p=1/4).$ We seek $P(X=2) = 0.2109.$
dbinom(2, 4, .25)
[1] 0.2109375

According to this interpretation RRYG, RBRY, and RYRY all meet the condition.
However, if the
condition is that exactly two balls of any color are drawn, then RRYG, GBBY both count. That seems to be a harder problem. This may be a possible interpretation of the title, as it currently stands.
Comment: Sorry, the second list should have been something like `RRYG` and `GBBY`. Fixing the typo.


Korselt's Criterion Proof Doubt

Question: I'm reading this paper, which details the proof of Korselt's Criterion. I have a doubt regarding part ii) of the proof. Namely, when we attempt to show that for all primes $p$ that divide $n$ (which is a Carmichael number, and is consequently square-free), $p-1|n-1.$ Here is what my doubt is:
Since $n$ is square-free, then $p$ and $n/p$ are coprime. Choose a $b \in \mathbb{Z}$ such that $\text{ord}_n (b) = p-1.$ Then by CRT, there exists and $a \in \mathbb{Z}$ such that $a \equiv b \pmod{p}$ and $a \equiv 1 \pmod{n /p}$ and there is a solution for it modulo $n$. Therefore, $(n,a) = 1 \implies a^{n-1} \equiv 1 \pmod{n}.$ However, when Conrad "reduces" this to the form $b^{n-1} \equiv 1 \pmod{p},$ I'm entirely lost. Could someone please explain why this is true? I'm not sure if I'm missing some fundamental fact about modulus or if he's using some lemma I'm unfamiliar with. I would greatly appreciate some assistance.
All the best.
Answer: Well, since $p \mid n$ and $a^{n-1} \equiv 1 \pmod n$ we have also $a^{n-1} \equiv 1 \pmod p$ and since $a \equiv b \pmod p$ we therefore have $b^{n-1} \equiv 1 \pmod p$.

Korselt's Criterion Proof Doubt


Here API -'routing mode' unexpected result

Question: I have a question about the result of the routing api according the 'routing mode'.
Routing mode Fast
I use the following request with the "routingMode=fast" option. I expect a result that is optimized for the travel time (duration).
https://router.hereapi.com/v8/routes?transportMode=car&departureTime=any&return=summary&origin=50.90089918068732,5.916744771297889&destination=50.91922009774642,6.024552765189207&routingMode=fast&apiKey=
The result summary is:
<code>"summary":{"duration":1031,"length":11170,"baseDuration":1031}
</code>
Routing mode Short
Then I use the same request, but with "routingMode=short". I expect a result that is optimized for the travel length.
https://router.hereapi.com/v8/routes?transportMode=car&departureTime=any&return=summary&origin=50.90089918068732,5.916744771297889&destination=50.91922009774642,6.024552765189207&routingMode=short&apiKey=
The result summary is:
<code>"summary":{"duration":1098,"length":10725,"baseDuration":1098}
</code>
This route is shorter than the first request, so far so good.
Routing mode Fast with alternative routes
However, now I back to the "routingMode=fast" and add the option for alternatives to the request (alternatives=1).
https://router.hereapi.com/v8/routes?transportMode=car&departureTime=any&return=summary&alternatives=1&origin=50.90089918068732,5.916744771297889&destination=50.91922009774642,6.024552765189207&routingMode=fast&apiKey=
The response contains two routes as a result. The first is:
<code>"summary":{"duration":1031,"length":11170,"baseDuration":1031}
</code>
(same as the request without alternatives)
The second is:
<code>"summary":{"duration":966,"length":17028,"baseDuration":966}
</code>
The duration of the alternative route is 966 minutes, this is less than the original 1031 minutes. This alternative is the fastest route. Why isn't this the response on the request without alternatives? I would expect that since I use "routingMode=fast" I always receive the fastest route as a first result. Can anyone explain this? I cannot find this in the documentation of the api.
Answer: We changed the name from fastest to fast, since we consider other things along side travel time. Certain situations add penalties which do not show in the ETA. In this case the fastest route goes bit more through FRC5 roads, which are slightly penalized. Plus it uses few slip roads, which also have a penalty on them.

Here API -'routing mode’ unexpected result


Can't find in Lilypond docs - how to place notes in a chord?

Question: How do I tell Lilypond which side of a stem I want individual chord tones on?
With a simple chord in single angle brackets, like <e g b> <e a c>, the note heads all go to the left (default) side of the upwards-extending (default) stem.
With the chord <f g b>, Lilypond puts the F and B on the left, and the G on the right. I'd like the F on the left, and the G and B on the right. But I can't find any reference to any way to control which side they are placed on. I haven't even found a clear reference to which object makes the decision.
Comment: I don't think it can be set in any (easy) way, because there are "stylistic" rules for these situations and Lilypond adheres to these. As far as I know, a note head can appear on the "wrong" side of a stem only if there is another head on the adjacent line/space, and in that case the lower note is on the left. So with stem up, left is the right place to put them, and so the B is put on the left (then F on the left because it is the lower one, and G on the right).
Comment: Easy would be nice, but is beside the point. My understanding is that those rules are implemented SOMEWHERE in Lilypond's internals, and can in almost every case be modified and overridden. i can move the note heads by brute force, but that's not the correct way, and Lilypond's documents explain why. It's just that there are many levels to this, and I'm not confident that "it can't be done" rather than "I didn't find the answer" is correct.
Answer: This solution may be a start. It's a function to offset a note individually. The value 1.2 is the amount needed to shift the note to the other side of the stem.
<code>horOff =
#(define-music-function (parser location x-off music) (number? ly:music?)
         (set! (ly:music-property music 'tweaks)
        (acons 'extra-offset (cons x-off 0)
         (ly:music-property music 'tweaks)))
   music)

\relative c' {
  <f g b>
  <f g \horOff #1.2 b>
}
</code>
I found it here: https://lists.gnu.org/archive/html/lilypond-user/2012-04/msg00134.html
Try other solutions presented in this thread if the one above does not work for you.
Comment: It works as the last thing I do before printing. It is exactly what Lilypond docs tell me not to do - forcibly move graphic objects by fixed measurements. The rest of Lilypond doesn't recognize those tweaks, or rescale them, or accomodate other objects to them. They kind of sort of attempt to address that.

There is a place, somewhere in Lilypond's code, where the note heads are assigned to the right or left of the stem, rather than a pixel location. That is the part of the code I'm seeking access to.


What is the best way to visualize a single numeric variable as a heatmap?

Question: I'm a hobbyist programmer whose friend recently took a business trip overseas.  He's polled our mutual friends for bets on the size of his email inbox when he returns.  I'd like to visualize this as a one-dimensional heatmap where color reflects a kind of density of guesses for that value.  I understand I could create a histogram and find a way to translate its values into color values.  However, the histogram bins would create janky transitions in color.  Is there a way to create an appropriate, continuous function for prettier output?
Answer: Use density and fields::colorbar.plot
<code>require(fields)
plot(1:10, rep(1,10), ylim=c(0,10))
 colorbar.plot( 2, 4, 800*density(rgamma(100, shape=2))$y)
 colorbar.plot( 2, 5, 800*density(rexp(100))$y)
 colorbar.plot( 2, 6, 800*density(rnorm(100))$y)
 colorbar.plot( 2, 7, 800*density(rlnorm(100))$y)
 text(6,4, "Gamma")
 text(6,5, "Exponential")
 text(6,6, "Normal")
 text(6,7, "LogNormal")
</code>
Comment: The rainbow/jet colormap is generally a bad idea. http://www.jwave.vt.edu/~rkriz/Projects/create_color_table/color_07.pdf
Comment: What programming language/system is this?
Comment: This is done in R. I just assumed anyone who wanted a heatmap would be using R or S, since none of the statistical languages I worked with in the past had that facility, but I guess they may have caught up if your expectation was to get a heatmap implemented in another language.


Exercise to determine the subspace of $\mathbb R^4$ that these 4 vectors span

Question: The vectors are $(1, 2, 3, 4)$, $(5, 6, 7, 8)$, $(9, 10, 11, 13)$ and $(15, 18, 21, 25)$.
I know the last vector is the sum of the other three, that are linear independent, so they span a 3-dimensional subspace of $\mathbb R^4$ . My problem is to determine this subspace.
For example, these two $\mathbb R^3$ vectors span a 2-dimensional subspace: $(1, 2, 1), (2, 0, -1)$. It is a plane and I can find the normal vector to it with the cross product of the vectors, being able to write the subspace $U = \{(x, y, z)\in \mathbb{R} | 2x-3y+4z=0\}$.
I was trying to write the subspace of the exercise similar to this of the plane, but was unable to develop the concept of a $\mathbb R^3$ subspace of $\mathbb R^4$.
Comment: It is a three dimensional subspace: the set of all linear combinations of those three lin. ind. vectors. There is hardly anything else to it...
Comment: So, you've seen the cross product in $\Bbb R^3$.  [You can extend the concept to higher dimensions as well](https://en.wikipedia.org/wiki/Cross_product#Multilinear_algebra), but unlike in $\Bbb R^3$ where you just take the product of two vectors, in $\Bbb R^n$ you take the "product" of $n-1$ vectors.  The result will be a vector normal to all of the previous $n-1$.  Other than that, you could write it as the span of the basis vectors (*which always works*) and would probably be easiest to explain.
Comment: But how could I write it like $U=\{ (x, y, z, w) \in \mathbb R | ...\}$?
Comment: @AlexandreTourinho  You need a vector orthogonal to the given vectors. To find one, solve the system $AX=0,$ where $A$ is a matrix whose rows are the given vectors, $X$ is a column vector=solution, and the right side is a column vector $0.$
Answer: Let us find a vector $\;v=(a,b,c,d)\in\Bbb R^4\;$ s.t. $\;v\perp U:=Span\{\,(1,2,3,4), (5,6,7,8), (9,10,11,13)\,\}\;$, and for this it is enough to find the solution to the homogeneous system determined by these three vectors:
$$\begin{pmatrix}1&2&3&4\\5&6&7&8\\9&10&11&13\end{pmatrix}\longrightarrow\begin{pmatrix}1&2&3&4\\0&-4&-8&-12\\0&-8&-16&-23\end{pmatrix}\longrightarrow\begin{pmatrix}1&2&3&4\\0&-4&-8&-12\\0&0&0&1\end{pmatrix} $$
and we thus get that the solution space of dimension $\;1\;$, which is spanned say by $\;(1,-2,1,0)\;$, from which you can write that $\;U=\left(Span\left\{(1,-2,1,0)\right\}\right)^\perp\;$
Another way: Take the vector product of the three lin. ind. vectors in $\;\Bbb R^4\;$ to get an orthogonal vector to them all. Puting $\;\ell\;$ as the fourth dimensional unit vector, we get:
$$\begin{vmatrix}i&j&k&\ell\\1&2&3&4\\5&6&7&8\\9&10&11&13\end{vmatrix}=(-4,8,-4,0)$$
and we get a scalar multiple of the first vector above...but calculating big determinants can be tough


Overriding application root URL creates a page not available

Question: I am following this tutorial and four minutes in he simply runs the application- after I do the same I get "web page not available". I did everything like him and set override application root url, I set the start URL and then set the applicationhost.config like he did:
<binding protocol="http" bindingInformation="*:80:www.onenotedemowebsite.com" />

Of course before I did any of those things, the MVC application worked fine while the binding info was left to localhost.
Can I get any suggestions?
Answer: I suspect you didn't add the url to hosts file like they did in the video.
Open the file: C:\Windows\System32\Drivers\etc\hosts in Notepad(open as administrator).
Add the following line:
127.0.0.1     www.yoururl.com

Save and close the hosts file. Restart the browser and try again.
Comment: That was it, I was wondering where that hosts file was located...
Since I have multiple projects- can I now just put new names here or change this one?
Comment: Add new line for a new site in the hosts file.
Answer: Have you changed your hosts file?

%SYSTEMDRIVE%\Windows\System32\drivers\etc\hosts

You should put a redirection from localhost to the site like this:

127.0.0.1       www.onenotedemowebsite.com

//EDIT: Was to late...


Do all Groups have a representation?

Question: I know that many kind of groups can be represented by matrices; for example: rotation groups can be represented by matrices.  Especially all elements of rotation groups can be represented by orthogonal matrices with determinant positive one. Also Permutation group can be represented by matrices.
But I need to know:

are there any kind of group which can not be represented by matrices?
Or is there any kind of group which does not have a representation?

Can you show me sample?
Comment: As in your other question, I think a few of us is very confused at what you mean by "representing a group", and I think this leads to a mess in the answers and comments below.  In representation theory, a representation of a group is a homomorphism $\rho:G\to GL(V)$ for some vector space $V$, can you confirm this is what you mean?
Comment: [http://en.wikipedia.org/wiki/Regular_representation](http://en.wikipedia.org/wiki/Regular_representation)
Answer: There are infinite groups which cannot be represented by finite-dimensional matrices over any commutative ring. If a group can be represented by matrices in such a way then it is called linear$^{\ast}$. Not all groups are linear.
A group $G$ is residually finite if for every element $g\in G$ there exists a homomorphism $\phi_g: G\rightarrow F_g$ onto a finite group $F_g$ such that $\phi_g(g)$ is non-trivial. Equivalently, for every element $g\in G$ there exists an action of $G$ on a finite object such that the action of $g$ is non-trivial. It is a rather famous result of Malc'ev that finitely generated linear groups are residually finite. This allows you to conjure up non-linear groups almost at will!
Non-Hopfian groups One way of constructing finitely-generated, non-residually finite groups is to construct finitely generated groups which have a surjective endomorphism $G\rightarrow G$ which is not an isomorphism. Such groups are called non-Hopfian, and it is a result of (again) Malc'ev that these groups are non-residually finite. See this Math.SE answer of mine for the proof, and this one for examples of such groups (the main example is the group $\langle a, b; b^{-1}a^2b=a^3\rangle$).
Simple groups A second way of constructing finitely-generated, non-residually finite groups is to construct finitely generated infinite simple groups. Examples of such groups are Thompson's group's $T$ and $V$ (these can be realised as groups acting on the unit interval in very natural ways - see these notes or this answer of mine) and Tarski monster groups.
Higman's group The group $G=\langle a, b, c, d; a^{-1}ba=b^2, b^{-1}cb=c^2, c^{-1}dc=d^2, d^{-1}ad=a^2\rangle$ was the first example of a finitely generated, infinite group with no finite quotients. This clearly implies that $G$ is not residually finite. Higman's paper is a joy to read$^{\dagger}$, and in it he points out that $G$ can easilly be used to construct finitely generated, infinite simple groups (his paper was pre-Thompson's groups, and pre-Tarski monsters) - taking a maximal normal subgroup $N$ of $G$, $G/N$ must be simple!
$^{\ast}$Perhaps this definition really requires field not commutative ring, but everything in this answer works for the more general commutative ring definition.
$^{\dagger}$Higman, Graham (1951), A finitely generated infinite simple group, J.Lon. Math. Soc.
Comment: Btw, I would say that today, the interest of Higman's group is not that it has infinite simple quotients (because as you mention there are many others, more natural than a quotient obtained by finding a non-explicit maximal normal subgroup), but that it's finitely presented with an explicit presentation and has no trivial quotient, and that in addition it is very rich in terms of quotients (it's SQ-universal).
Comment: I agree that the definition of linear is more natural over a commutative ring than a field. Anyway I don't know an example of finitely generated group that would be linear over a commutative ring, but not over a reduced commutative ring (or equivalently over a finite product of fields).
Answer: A representation of a group $G$ is a morphism $\rho:G\rightarrow\text{GL}(V)$ where $V$ is a vector space over a field $K$.
There are always at least the following two representations:

the trivial representation, where $\rho(g)=\text{id}_V$ for all $g\in G$.
the regular representation, where $V$ is the space of $K$-valued functions on $G$ and $\rho(g)\phi(x)=\phi(xg)$ for all $\phi\in V$ and for all $x, g\in G$.

EDIT: Also note that whenever $H$ is normal in $G$ any representation of $G/H$ can be lifted to a representation of $G$ by composing with the quotient homomorphism $G\rightarrow G/H$.
In particular if the quotient $G/H$ is abelian this gives rise to lots of representations of $G$ since abelian groups have many representations, starting with characters (i.e. $1$-dimensional representations)
Comment: So you mean that all kind of groups have a representation? even minimum two representation! right?
Comment: Andrea, is this still valid if $G$ is infinite?
Comment: Of course this is valid also when $G$ is infinite. Mind, though, that in that case $\dim_K(V)$ is also infinite.
Comment: @Andrea see user1729's answer, this is what I meant ...
Comment: @Nicky The difference is that I am assuming the matrices are finite-dimensional but Andrea Mori is not. I have modified the first paragraph of my post to make this clear.
Answer: As you stated, every (finite) permutation group can be represented by matrices (take $G=S_n$ and represent the permutations by permutation matrices (the permutations act naturally on a vector space of dimension $n$ over some field $K$)). Subsequently, every finite group can be embedded in a permutation group (a Theorem of Cayley), since it acts on itself by left (or right) multiplication.
Comment: I need to know which group can not be represented by representation?
Comment: It follows that each finite group has a reresentation. I concluded from your question that you were talking about finite groups.
Comment: what about infinite groups? So you mean that if there is a group which can not be represented by representation, then that group might be infinite groups?!

Do all Groups have a representation?


How do i know if a time is elapsed/expired in php?

Question: Here's the scenario
I would like to know if a date like '2011-03-04' and time like '17:06:00' in a specific TimeZones like 'IST/PDT/CDT' is elapsed by using php?
Is there any function available to check this
<code> $strDate = '2011-03-04 17:06:00';
 $TZ      = 'IST';

 $strDate = '2011-02-01 11:16:30';
 $TZ      = 'CDT';

 $strDate = '2010-08-04 07:20:00';
 $TZ      = 'IST';

 $strDate = '2011-02-27 09:55:00';
 $TZ      = 'PST';
</code>
I've tried/searched all over the net but no joy, please help
Yeah i tried it using DateTime but it doesnt work for me.. My server is in IST TimeZone
<code>$date = new DateTime('2011-03-04 17:06:00');
$date->setTimeZone(new DateTimeZone("PST"));
$newtime = $date->getTimestamp();
$time     = time();
if ($time > $usertime)
    echo 'time passed';
else
    echo 'time NOT passed';
</code>
Thanks to tobyS but it too falied
<code>$elapsedTime = new DateTime(
    '2011-03-04 17:00:00', // I set it to 5PM. Now the time is 5:45 PM here in INDIA
    new DateTimeZone( 'IST' )
);

$elapsedInt = $elapsedTime->diff( new DateTime() );
echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";
</code>
Comment: Did you try [`DateTime::createFromFormat()`](http://www.php.net/manual/en/datetime.createfromformat.php)?
Comment: You must specify the time zone during construction of the DateTime object. Otherwise, it will be created in your servers time zone and the setTimeZone() call will re-calculate the existing time to be shifted into the foreign time zone.
Comment: possible duplicate of [Check if a time in a timezone is elapsed in php?](http://stackoverflow.com/questions/5192065/check-if-a-time-in-a-timezone-is-elapsed-in-php)
Answer: You can create a DateTime object from your time data and use its diff() method against the current time.
Example code:
<code><?php

$elapsedTime = new DateTime(
    '2010-08-04 07:20:00',
    new DateTimeZone( 'IST' )
);

$notElapsedTime = new DateTime(
    '2012-08-04 07:20:00',
    new DateTimeZone( 'IST' )
);

$elapsedInt = $elapsedTime->diff( new DateTime() );

echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";

$notElapsedInt = $notElapsedTime->diff( new DateTime() );

echo ( $notElapsedInt->invert ? 'Future' : 'Past' ) . "\n";

?>
</code>
Comment: @tobyS Thank you, Could you check for this $elapsedTime = new DateTime('2011-03-04 17:20:00', new DateTimeZone( 'IST' )); It returns 'Future' not 'Past'
Comment: Hmm, IST is interpreted as +0200. Is that the correct offset? IST is not listed as a valid time zone name on http://php.net/manual/en/timezones.php. Maybe you can switch to a supported name?
Comment: The time you speficied is converted here to "Fri, 04 Mar 2011 17:20:00 +0200", which is converted to "Fri, 04 Mar 2011 16:20:00 +0100" when I switch to "Europe/Berlin".
Comment: Its there and is called 'Asia/Calcutta'
Answer: PHP doesn't understand those timezones:
<code>$timezone = 'America/New_York';
$date = new DateTime($strDate, new DateTimeZone($timezone));
</code>


HTML to String for Mail Message Body

Question: I am developing a page in asp.net for sending mail to the user.
I need to convert html message body to string message including css styles added to it.
How to convert html format to string format so that i will give as
MailMessage mail=new MailMessage(firstname.lastname@example.com,firstname.lastname@example.com);
mail.Body=strHTMLBody; //the HTML Converted string
mail.IsBodyHtml = true;

Thanks in Advance.
Comment: `mail.IsBodyHtml = false;` ?
Comment: Are you asking how to construct a string that contains all the html and css you want to use as the body of your email?
Comment: *strHTMLBody* is html ? what is going wrong. do you want to send web page like html as a mail body or what.
Comment: yes.how to assign as string so that when the user open his mail it will be rendered as actual html in message body.
Comment: Are you asking how to convert a string with html formatting so that a plain text message is sent?
Answer: Replace mail.IsBodyHtml = true; with mail.IsBodyHtml = false; if I understand you

HTML to String for Mail Message Body


Finite cyclic subgroups of the homeomorphisms of the real numbers

Question: This inquiry was inspired by this post: The automorphism group of the real line with standard topology.
While trying to come up with some interesting examples, I attempted to figure out the finite cyclic subgroups of the homeomorphisms of the reals with their Euclidean topology (under composition). I believe them to be $\{1_\Bbb R\}$ and $\langle(x\mapsto -x)\rangle$ just from intuition, but I haven't been able to show this completely. Here's what I have done:
Suppose $f$ is homeomorphism of $\Bbb R$ with $f^{[n]}=1_\Bbb R$ for some $n$. We have that $f$ is either (strictly) increasing or decreasing. Suppose $f$ is strictly increasing. Let $x\in\Bbb R$. Either $x\leq f(x)$ or $f(x)\leq x$. In the first case, induction shows that $x\leq f(x)\leq f^{[2]}(x)\leq\cdots\leq f^{[n]}(x)=x$ and thus $f(x)=x$. In the latter case, induction shows that $x=f^{[n]}(x)\leq\cdots\leq f^{[2]}(x)\leq f(x)\leq x$ and we have again that $f(x)=x$. Since $x$ was arbitrary, we have that $f=1_\Bbb R$.
Now we only have to deal with a strictly decreasing homeomorphism, but my attempts have been fruitless. Any help would be appreciated.
Comment: The reflection of the real line $R_a : \mathbb R \to \mathbb R$ defined by $R_a(x) = 2a - x$ generates a group of order two, so there are certainly more examples than $1_{\mathbb R}$ and $x \mapsto -x$.
Answer: If $f$ is strictly decreasing, then if $x < y$, $f(x) > f(y)$, and so $f(f(x)) < f(f(y))$. Hence $f^{[2]}$ is strictly increasing, and is a homeomorphism, which means by your previous reasoning the order of $f$ must be $1$ or $2$.
However, it's not true that every involutive (order 2) homeomorphism of $\mathbb{R}$ is $x \mapsto -x$. In fact, if $f:\mathbb{R} \rightarrow \mathbb{R}$ and $Z$ is a cyclic subgroup, then $f^{-1}Zf$ is also a cyclic subgroup, and in your case if $i$ is an involution $f^{-1}if$ is another involution. Concretely, $x \mapsto f^{-1}(-f(x))$ is an order 2 homeomorphism of the real line. Examples are $x \mapsto a - x$ or $x \mapsto (a - x^3)^{1/3}$
So the question is: Are all involutions conjugate to $x \mapsto -x$? I'm not sure now, but I think the answer is yes.
Comment: yes this is true: indeed is $f$ is a nontrivial involution, then $f$ is increasing and has a unique fixed point $x_0$. Define an increasing self-homeo $u$ of the reals as follows: on $[0,\infty[$ it's a homeo onto $[x_0,\infty[$, and on $]-\infty,0]$, it maps $t\le 0$ to $f(u(-t))$. Then $f=usu^{-1}$, where $s(x)=-x$.


In Asp.net, on button click, how to open a download dialog, and then redirect the user to another page?

Question: I have a button. When the user clicks it, I want to trigger a download dialog box, and then redirect the user to another page.
However, I'm having problems getting the download and redirect to run together. Once the download dialog box is shown, execution on the rest of the code seems to end:
Sub DisplayDownloadDialog(ByVal filepath As String)
    Dim filename As String = Path.GetFileName(filepath)
    Response.ContentType = "application/octet-stream"
    Response.AddHeader("Content-Disposition", "attachment; filename=""" & filename & """")
    Response.WriteFile(filepath)
End Sub

I tried to add a refresh to the header, but it still doesn't work. I also tried javascript (but not using window.open...since some browsers block that), but I can't get a redirect to work.
Any ideas? I really appreciate the help.
Answer: Once you call Response.WriteFile(filepath), the response is over and Redirect is not going to work
You may try this:
On button's OnClientClick event, using windows.open() to open a new .aspx page, named like "download.aspx". and in button's postback event, do your redirect.
In the "download.aspx" page, your write your download code.
I think it should work,
Answer: Try the following
Suppose you have three pages like

Content.aspx --> This page will have a download link
Thanks.aspx --> The page to which you want to redirect ie this page will show a thanks note
Download.aspx --> This page will do the actual download function.

Now in Content.aspx
You have a link button/image button/button control called btnDownload
In Page load of Content.aspx you can add the following code in the page load
protected void Page_Load(object sender, EventArgs e)
    {

        btnDownload.Attributes.Add("onclick", "Javascript:GotoDownloadPage();return
        false;");

    }

Add the following script function in the source of Content.aspx

Now in Thanks.aspx
Add the following code in the page load
protected void Page_Load(object sender, EventArgs e)
    {

            if (!IsPostBack)
            {
                ScriptManager.RegisterStartupScript(Page, GetType(), "Redirect",
                "", false);
            }

    }

Add the following script function in the source of Thanks.aspx

Now In Download.aspx
Add the logic for downloading file
Hope this will help you..


Optimize jQuery each loop

Question: I have a very basic search function that sorts through a list of names. There are about 4,000 names so this loop is a bit to slow to keep up as users type. Here is the loop for each new search value:
elements.each(function(i, el){
    var name = $(el).find('button').text();
    name = name.toLowerCase();
    if(name.indexOf(value) >= 0) {
        $(el).show().addClass('visible');
    }
    else {
        $(el).hide().removeClass('visible');
    }
});

How can I optimize this loop so it can keep up with a user typing?
Follow up:
Based on user suggestions, I mapped and stored the data in an array when the text input receives focus. Then, I changed the active search to the below:
Array.prototype.forEach.call(this.cache, function(el, i){
    var name = el.name;
    if(name.indexOf(value) >= 0) {
        el.element.style.display = '';
        el.element.classList.add('visible');
    }
    else {
        el.element.style.display = 'none';
        el.element.classList.remove('visible');
    }
});

I tried to cut off jQuery where I could to better optimize. It seems to be working without any noticeable lag now! Thanks for the great suggestions and discussion.
Comment: Throttle the event so you only loop after the user stops typing for a given amount of time.  Say 350 milliseconds.  Other than that, `$(el)` is repeated three times in the logic.  That's three repetative jQuery object creations (technically two since two are in an if/else, but ya know).
Comment: @freedomn-m my fault, didn't use jQuery since two years... Thought it became better :D Stupid me
Comment: If your buttons are static, pre-process the data and keep it in a HashMap (dictionary) and get smarter about what you display (for instance most of the `.removeClass('visible')` operations are redundant. Also throttle down as @Taplar mentioned
Comment: https://stackoverflow.com/questions/49076520/execute-my-settimeout-function-after-clicking-stops/49076561#49076561  This version was for clicking, but it can be changed for typing.
Comment: Use a `delayed debounce` script on your keyup event handler.  on keypress, set timeout on next keypress clear timeout and set it again, etc.
Comment: When you call `.show` / `.hide` it starts that action immediately - instead, you could run your elements.each with add/remove class and then `$(".visible").show()` `$(":not(.visible)").hide()` to show/hide them all in one go (add another class to find them more easily, eg `var rows = $(".row"); rows.fitler(".visible").show(); rows.filter(":not(.visible)").hide();`)
Comment: Small side note, not intended to derail, but what's up with doing a show().addClass('visible') and hide().removeClass('visible')?  Kinda feels redundant
Comment: @freedomn-m well, native for jQuery which is used by OP. The point is that it is ready to use and there is nothing to invent
Comment: Another option: use `.map` to filter them and then apply the class/hide/show as appropriate.
Comment: Why `map` over `filter`?
Comment: And filter on only the items you have left
Comment: @Taplar no reason, I tend to forget that you can use `filter` with a callback, so I use `.map` with callbacks and `.filter` with selectors
Comment: Gotcha, just thought it was odd since the ability exists there and you're trying to filter things, not transform them, :)
Comment: In this case `.map` would add extra overhead, especially with 4,000 rows.
Comment: Don't touch the dom in your loop. If that means creating an array of data to filter through beforehand, it'd still be better than touching the dom 4k*n times for each keystroke.
Comment: In reply to the comment about the visible class, this is used by another action and doesn't actually affect visibility.
Answer: As mentioned @Taplar, you could delay the error-check.
Not everything has to be real-time, as it could harm the usability.
It's common to check something in a timespan after the the system stops receiving the action, and while user is typing, you could just grey out the status text and once 500ms after user stops typing passes, you execute the check and assign necessary class to the status text.
Here's an example implementation. It won't throw a "error" unless you type "BAD" in the text box.

var timeout;
$("#txt").keydown(function(e){
  $("#status").removeClass("bad").addClass("wait");
  clearInterval(timeout);
  timeout = setTimeout(checkStuff, 500);
});

function checkStuff(){
  var t = $("#txt").val();
  var s = $("#status");
  s.removeClass("wait").html("No errors");
  if(t.indexOf("BAD") > -1) {
    s.addClass("bad").html("Errors detected!");
  }
}
#status{
  color:green;
}
#status.wait{
  color:rgba(150,150,150,1);
}
#status.bad{
  color:red;
}

<input id="txt" placeholder="type plz">

No errors
Comment: This answer doesn't really apply to the question. I already have the keystrokes handled in a manner that was given to me. I just need to speed up this particular action. Thanks, though!
Answer: jQuery is sloooooooooooooooow, if you can do your looping and most of your heavily repeated functionality in vanilla JS, you will save a lot of processing time. Also pre-mapping text is huge, looking up the button element and getting the text value every time is a big waste.

/*
elements.each(function(i, el){
    var name = $(el).find('button').text();
    name = name.toLowerCase();
    if(name.indexOf(value) >= 0) {
        $(el).show().addClass('visible');
    }
    else {
        $(el).hide().removeClass('visible');
    }
});
*/

let elemQueryArr = elements.map(elem => {
  return {
    elem: elem,
    text: elem.querySelector('button').text.toLowerCase()
  }
}), len = elemQueryArr.length

function filterElems(val){
  let i = -1
  while(++i < len){
    let elem = elemQueryArr[i]
    if(elem.text.indexOf(val) > -1) elem.elem.classList.add('visible')
    else elem.elem.classList.remove('visible')
  }
}

Optimize jQuery each loop


How to Change clang-format Rule for a Specific Code Section?

Question: Is it possible to change a clang-format rule for a code section? I know that you can add a comment to disable formatting completely for a section via // clang-format off, but is it also possible to change a specific rule?
enum class Foo {
    // clang-format AlignConsecutiveAssignments: Consecutive
    ABC = 0,
    X   = 1
};

My overall goal is to align the equal signs in an enum, but not in the rest of the code. With AlignConsecutiveAssignments: Consecutive, clang-format aligns variable assignments as well.
Answer: Unfortunately, overriding styles for a section of code isn't possible.
Source
You could try organizing your project to use different .clang-format's, as described here.


How can I fix the "Could not delete temporary file"?

Question: I'm getting below error when run cron:

The specified file could not be deleted, because it is not a valid URI. More information is available in the system log.

Due to TMP files, my site will be crashed, again we will restored site and unable to clean TMP files in my live site.
Answer: Change to another tmp folder destination? Configuration -> file system
I not sure will this help you.
Comment: Thnks for your quick replay @ peifa before i have tried in place of "/tmp" changed another name "/tmp2" etc no use and just i have deleted tmp file from "file_managed" table error gone away but already set cron every 1 hour after run cron tmp files must delete but in my case not work so i'm trying some custom module for against cron for deleting tmp files using hook_cron().


Despacho múltiplo na linguagem Julia

Question: Estou estudando sobre a linguagem Julia e li que o despacho múltiplo permite que as funções sejam despachadas dinamicamente, mas ainda não ficou claro para mim.
Answer: TL; DR
É só uma sobrecarga de funções resolvida em tempo de execução. Se você sabe os tipos dos objetos em tempo de compilação não precisa deste mecanismo (desde que a linguagem permita resolver na compilação).
Detalhando
Primeiro ponto a definir é que esse tipo de mecanismo só funciona em linguagem que possuem alguma forma dinâmica de execução, portanto a decisão sobre a chamada de uma função se dá só nom momento de ser chamada e não no momento da compilação como costuma acontecer em linguagens que tendem resolver tudo mais estaticamente.
As linguagens mais estáticas costumam fazer o despacho se baseando em uma informação que está disponível na compilação, por isso temos polimorfismo ad hoc (ou sobrecarga) ou paramétrico.
Mesmo as linguagens mais estáticas costumam ter algum mecanismo de resolução de despacho de função dinamicamente, o que é conhecido como polimorfismo clássico ou de subtipo. Dependendo do objeto tratado é decidido qual método chamar. Ele usa apenas um critério para tomar a decisão, é o tipo de um argumento (costuma ser o primeiro que pode até ser oculto no código). É um mecanismo relativamente simples e o custo de runtime dele é muito baixo.
O despacho múltiplo usa vários critérios para decidir o que chamar. Ele pode analisar os tipos de vários argumentos, os valores passados ou até outras informações que ajudem na decisão. Ele se assemelha muito com a sobrecarga de funções, mas difere porque a decisão depende do momento da execução, e dá mais flexibilidade.
Ele é uma forma de polimorfismo mais sofisticada.
Algumas linguagens que não possuem este tipo de mecanismo acabam resolvendo no código o que fazer, com ifs ou alguma forma de switch incluindo pattern matching. O multiple dispatch faz isso por conta própria sem precisar desse tipo de código.
Uma solução para resolver em parte essa questão é implementar o Visitor pattern. Alguns casos com geração de código para facilitar.
Existem outras que acabam fazendo mais ou menos o mesmo que um compilador faria internamente no código de linguagens que suportam nativamente esse padrão, tal como acontece em Julia.
Algumas linguagens criam uma forma de você escrever as várias funções com as combinações possíveis de características diferentes dos argumentos.
As linguagens que não fazem isso e você não usa um gerador de código acaba gerando muito boiler plate, e as que fazem são boas facilitadoras para isso, ainda que gere um custo extra de processamento.
Em Julia você pode ter isto:
function collide(me::Circle, other::Rectangle)
function collide(me::Polygon, other::Circle)
function collide(me::Polygon, other::Rectangle)

E aí chama assim:
collide(objeto, outro)

Coloquei no GitHub para referência futura.
O que será chamado depende do tipo dessas duas variáveis no momento da execução, não se sabe de antemão e a decisão será tomada pelo runtime sem você ter que escrever código algum para tomar essa decisão.
Então se objeto for do tipo Circle e outro for do tipo Rectangle será a primeira função a ser chamada. Mas se outro for Circle e não importa qual Polygon seja o objeto, a segunda função será chamada, e finalmente se o outrofor umRectangleeobjeto for qualquer Polygon, exceto um Circle que já tem um match melhor, então a terceira função será chamada. Note que dará erro se ambos forem um Polygon que o outro não seja Circle ou Rectangle.
Existe algo chamado double dispatch que é uma especialização do multiple dispatch para duas características que é diferente do single dispatch que tem apenas uma e é usada mais amplamente. É o que foi usado acima.
Também são chamados de multi-métodos.
Documentação. Wikipedia.

Despacho múltiplo na linguagem Julia


shared_ptr and use_count

Question: In the following code snippet:
shared_ptr<int> p;

{
    p = shared_ptr<int>(new int);
    cout<<p.use_count()<<endl;
}

cout<<p.use_count()<<endl;

The output comes out to be

1
1

I don't understand why the 1st output is 1 -- shouldn't it be 2?
Comment: Why should it be 2?
Comment: @zeropoint that temp object gets destroyed just after `;`
Comment: @Mat: I may be wrong, but i thought that within that scope of braces, the `p` and the temporary object created by rhs shall make up the `use_count()` to `2`
Comment: @Mr.Anubis: Thank you, I thought the temporary's scope to be local and not the statment-scope
Answer: The temporary object's lifetime does not last long enough for the first p.use_count() to return 2. The temporary object is destroyed first, relinquishing its ownership on anything it owned.
Furthermore, since the temporary is an rvalue, the assignment to p will result in a move-assignment, which means the use-count will never be 2 anyway (assuming a quality implementation). Ownership is simply transferred from the temporary to p, never exceeding 1.
Answer:  #include <memory>
 #include <iostream>

 int
 main(int argc, char** argv) {
   std::shared_ptr<int> p(new int);
   std::shared_ptr<int> p2(p);
   std::cout << p.use_count() << std::endl;
   return 0;
 }

output: 2

EXPLANATION/EDIT: In your source, the initial 'p' never held ownership of anything. In the 2nd reference to p, you are assigning to a temporary and basically giving up ownership to 'p'. Most likely, as well, the move constructor is used to satisfy this assignment.
EDIT: This was probably what you were going for?
 #include <memory>
 #include <iostream>

 int
 main(int argc, char** argv) {
   std::shared_ptr<int> p(new int);
   {
       std::shared_ptr<int> p2(p);
       std::cout << p.use_count() << std::endl;
   }
   std::cout << p.use_count() << std::endl;
   return 0;
 }

output: 2
        1

Comment: I agree, but I had doubt with the temporary object created by rhs of statement `p = shared_ptr(new int);` whereas `p` is already an existing `shared_ptr`
Comment: Yes, but see how you are assigning to a temporary? And 'p' never owned anything, so its declaration had no basis for this at all.
Answer: From boost.org:
template<class Y> explicit shared_ptr(Y * p);
Requirements: p must be convertible to T *. Y must be a complete type. The     expression delete p must be well-formed, must not invoke undefined behavior, and     must not throw exceptions.

Effects: Constructs a shared_ptr that owns the pointer p.

Postconditions: use_count() == 1 && get() == p.

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

Exception safety: If an exception is thrown, delete p is called.

Notes: p must be a pointer to an object that was allocated via a C++ new    expression or be 0. The postcondition that use count is 1 holds even if p is 0;    invoking delete on a pointer that has a value of 0 is harmless.

As you can see, it releases the last construct if you construct a new shared_ptr from the new int.

shared_ptr and use_count


Python 2.7: Calling a text file from various locations

Question: So, I'm in the windows environment.

I created the text file with notepad.
I saved it in my documents.
I opened python's idle shell.
I used testFile = open("test.txt","a+")
Typed testFile.read()

Hit enter and the result was '' two single quotes?
Comment: @inspectorG4dget:  A file opened with mode `a+` will still return results when read.  My guess is that he is specifying the incorrect path to the file.  Or specifying no path so that it's trying to open the file from the current directory, not "My Documents".
Comment: open in read mode with 'r'
Comment: ... or ignore the flag altogether, as `'r'` is the default opening flag
Comment: Fair point @StevenRumbalski. I don't usually use `a+`, so that slipped my mind
Comment: On Windows in Idle `os.getcwd()` returns `'C:\\Python27'` (unless you installed Python elsewhere).  That is where Python is trying to find your file.  If you want it to look in "My Documents" you need to provide the path.
Answer: You need to specify the full path to your text file if it is not in your current working directory:
testFile = open("c:/Users/yourusername/My Documents/text.txt")

Answer: testFile = open("test.txt", "rb")
testFile.read()

Comment: javascript
Comment: Why does javascript print c:/user/ma/ etc  together with what it is supposed to print?


How to compute the complexity

Question: 1) If $a(n)=O(n^2)$ and $b(n)=O(n^3)$. Can someone tell me how to compute the computational complexity of
$$ c(n)=\sum_{k=1}^{n}a(k)b(k) $$
What rules apply?
I think it might be $O(n^6)$, but this sounds wrong.
2) What now if we have two sums. Suppose $a(n)=O(n^2)$ and $b(n)=O(1)$ and $c(n)=O(1)$ what would the computational complexity of something like this
$$ d(n)=\sum_{k=0}^{n}\sum_{j=0}^{k}c(n-k)b(k-j)a(j) $$
be? I would really like to know how to compute the computational complexity of such  types of sums. Any pointers would be appreciated.
Comment: @DoctorBatmanGod - Since there is even no code/algorithm in the question I would say that this is the best site for this question
Comment: You might want to consider posting this on [stackoverflow](http://stackoverflow.com/), one of Math.Stackexchange's sister sites that specializes in computer science. While your question isn't off topic, it might elicit a better response there.
Comment: @DoctorBatmanGod There is also cs.stackexchange.com that can help with time complexity of algorithms.
Comment: For the first one the worst case is when $a(n)=\Theta(n^{2}),b(n)=\Theta(n^{3})$.
without loss of generality $a(n)=n^{2},b(n)=n^{3}$. Then bound the
sum you have in terms of $n$. For example each element is $\leq n^{6}$and
since there are $n$ terms a bound is $n\cdot n^{6}=n^{7}$. But with
a more careful analysis you can get this down and get a better upper
bound.
Answer: For your first question, say $a(k)\le Mk^2$, $b(k)\le Nk^3$. Then your sum is $\le MN(1^5+2^5+\cdots+n^5)$. For large $n$, the sum $1^5+2^5+\cdots+n^5$ behaves like $\frac{1}{6}n^6$.  So the $O(n^6)$ is correct.

How to compute the complexity


If $a$ and $c$ are odd primes, $b$ is an integer, and $ax^2+bx+c=0$ has rational roots, prove that one root is independent of $a$, $b$, $c$

Question:
If $a$ and $c$ are odd prime numbers and $ax^2+bx+c=0$ has rational roots, where $b$ belongs to $\Bbb{Z}$. Prove that one root of the equation is independent of $a,b,c$.

For rational roots discriminant should be a perfect sq.
$b^2-4ac=p^2$ (say $p$)
$(b+p)(b-p)=4ac$
I tried to make cases as
$b+p=2a,b-p=2c$(as both should be even) and I can prove it,but what if I took $b+p=2$ and $b-p=2ac$ or say $b+p=2ac$ and $b-p=2$.Is it right?I am confused about its validity and how to proceed?Would you help?
Comment: Siong, you can't prove it because the statement is not true in general, for example, when b=ac+1, we have $ax^2+(ac+1)x+c=0$, $(ax+1)(x+c)=0$$x=-\frac{1}{a} or -c, $ which are dependent on either a or c.
Comment: What do you mean by " independent of $a,b,c$"?
Answer: \begin{align*}
\text{Given}
\quad b^2-4ac=p^2 \space\implies\space p^2+4ac=b^2\\
\quad\text{we have}\qquad A^2+B^2=C^2
\\
\text{which is a Pythagorean triple where}\\
 A=m^2-k^2\quad B=2mk\quad C=m^2+k^2\\
\end{align*}
In this case,
$\quad p=m^2-k^2\\
4ac=B^2=(2mk)^2=4m^2k^2\implies ac=m^2k^2\\
b=m^2+k^2.$
In any Pythagorean triple, $B= 4n\space\implies \space ac\in\mathbb{N^2}.\quad$  The only way this can work is if both of $\quad ac\quad$ are either $1, 2,\space$ or equal odd primes, or squares themselves.
$\textbf{Non Pythagorean solutions:}$
Other solutions have no pattern that "jumps out" as seen in this sample of
$(p,4\times ac,b)\space$ triples.
$$(3 , 4x2 ,1 )\quad
(4 , 4x3 ,2 )\quad
(5 , 4x6 ,1 )\quad
(5 , 4x4 ,3 )\\
(6 , 4x8 ,2 )\quad
(6 , 4x5 ,4 )\quad
(7 , 4x12 ,1 )\quad
(7 , 4x10 ,3 )\\
(7 , 4x6 ,5 )\quad
(8 , 4x15 ,2 )\quad
(8 , 4x12 ,4 )\quad
(8 , 4x7 ,6 )\\
(9 , 4x20 ,1 )\quad
(9 , 4x18 ,3 )\quad
(9 , 4x14 ,5 )\quad
(9 , 4x8 ,7 )\\
(10 , 4x24 ,2 )\quad
(10 , 4x21 ,4 )\quad
(10 , 4x16 ,6 )\quad
(10 , 4x9 ,8 )\\
$$
Comment: "*$ac$ must always be a square*" $\;-\;$ Why?
Comment: @dxiv.  I would have answered sooner but my comport has been in the shop. We accept that $4ac$. must be a square. Four is a square and then ac must be a square if the product is a square.
Comment: The problem does not state that $4ac$ must be a square. If you are introducing that as an additional assumption, you should make that clear in the answer.
Comment: @dxiv   The statement $\quad 2+4ac=b^2\quad$ requires
 $\space 4ac \space $  to be a square because
$\space  4ac=B^2.\quad$
Comment: There is no "$B$" in the original problem, and just because $\,p^2+4ac=b^2\,$ does not require the three terms to form a pythagorean triple. That seems to be an additional assumption that your answer introduces and uses, but it does not follow from OP's question.
Comment: @dxiv
   There  is no "B" but $4ac$ is the equal of $B$ for the Pythagorean theorem. See the first two lines of my answer.
Comment: Again, there is no assumption of a pythagorean triple in the original problem, and you don't explain why you introduced that assumption. Take any $p,b$ of the same  parity, for example, then you can always find some $a,c$ such that $p^2+4ac=b^2$, but this does not imply that $4ac$ must be a perfect square.


Apache certificates for some urls not working

Question: We are having a rather strange problem with a Apache-installation. Here is a short summary:
Currently I'm setting up Apache with https, and server-certificates. This is fairly easy and works straight out of the box - as expected. This is the configuration for this setup:
<code>Listen 443

SSLEngine on

SSLCertificateFile "/progs/apache/ssl/example-site.no.pem"
SSLCertificateKeyFile "/progs/apache/ssl/example-site.no.key"

SSLCACertificateFile "/progs/apache/ssl/ca/example_root.pem"
SSLCADNRequestFile  "/progs/apache/ssl/ca/example_intermediate.pem"

SSLVerifyClient none
SSLVerifyDepth 3

SSLOptions +StdEnvVars +ExportCertData

RequestHeader set ssl-ClientCert-Subject-CN "%{SSL_CLIENT_S_DN}s"

RewriteEngine On
ProxyPreserveHost On
ProxyRequests On
SSLProxyEngine On

...

<LocationMatch /secureStuff/$>
    SSLVerifyClient require
    Order deny,allow
    Allow from All
</LocationMatch>

...

<Proxy balancer://exBalancer>
    Header add Set-Cookie "EX_ROUTE=EB.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
    BalancerMember http://10.0.0.1:7200 route=ee1 retry=300 flushpackets=off keepalive=on
    BalancerMember http://10.0.0.2:7200 route=ee2 retry=300 flushpackets=off keepalive=on status=+H
    ProxySet stickysession=EX_ROUTE scolonpathdelim=Off timeout=10 nofailover=off failonstatus=505 maxattempts=1 lbmethod=bybusyness
    Order deny,allow
    Allow from all
</Proxy>

RewriteCond %{REQUEST_URI} !^/index.html [NC]
RewriteRule ^/(.*)$ balancer://exBalancer/$1 [P,NC]

ProxyPassReverse / balancer://exBalancer/

Header edit Set-Cookie "(.*)" "$1;HttpsOnly"

...
</code>
So - everything works fine and as expected for all of the pages that are not a part of the LocationMatch-directive.
When requesting something that matches the LocationMatch-directive, I'm asked for a certificate (hence the SSLVerifyClient required attribute) - and getting all the correct certificates in my browser that is based on the root/intermediate chain. After choosing a certificate and clicking "OK", this is what pops up in the apache logs:
[ssl:info] [pid 9530:tid 25] [client :43357] AH01998: Connection closed to child 86 with abortive shutdown (
[Thu Oct 11 09:27:36.221876 2012] [ssl:debug] [pid 9530:tid 25] ssl_engine_io.c(1171): (70014)End of file found: [client 10.235.128.55:45846] AH02007: SSL handshake interrupted by system [Hint: Stop button pressed in browser?!]
And this just spams the logs. What is happening here? I can see this configuration working on my local machine, but not on one of our servers. There is no configration differences between the servers, only minor application-wise-changes.
I've tried the following:
1) Removing CA-certificate-checking (works)
2) Adding required CA-certificate for the whole site (works)
3) Adding "SSLVerifyClient optional" does not work
4) ++
Server/Application Information
Local:
-OpenSSL v.1.0.1x
-Apache 2.4.3
-Ubuntu
-mpm: event
-every configuration should be turned on
(failing) server:
-OpenSSL 0.9.8e
-Apache 2.4.2
-SunOS
-mpm: worker
-every configuration should be turned on
Please let me know if more information is needed, I'll provide it instantly.
Brief sum-up:
-Running apache 2.4
-Server certificates works just fine
-Client certificates for some /Locations does not work, fails with errors
PS:
Could it be related with the OpenSSL version and the "Renegotiation" stuff related to TLS/SSLv3?
Answer: It seems like there is a problem with the version of apache compiled for the Sun OS that we are using. This is explained here:
-http://svn.apache.org/viewvc?view=revision&revision=1373439
In addition to this, we just did an upgrade to openssl v1.0.1c that fixed some other issues..
To sum up:
If you use Sun OS and Apache 2.4.0, 2.4.1 or 2.4.2 then you have to upgrade to version 2.4.3, as the issue with SSLCaching is solved there.
Resources:
http://svn.apache.org/viewvc?view=revision&revision=1373439
http://apache-http-server.18135.n6.nabble.com/DO-NOT-REPLY-Bug-53040-New-apache-2-4-1-Solaris-10-ssl-virtual-hosts-dies-after-idle-for-a-while-td4812609.html


What problems do non-normality in predictor variables cause for a multiple regression analysis?

Question: I am talking about a situation in which I have several continuous predictor variables predicting a continuous outcome. One of the predictors has a very non-normal distribution and has some wild outliers.
I intend the generalize the regression model to a wider population. Does the non-normality and/or the presence of outliers preclude my analysis, or cause difficulties in interpretation?
What should I do?
Comment: Regression methods do not make any assumptions about the distribution of the predictor variables. It may help you to read this: [What if residuals are normally distributed, but y is not?](http://stats.stackexchange.com/q/12262/7290)
Answer: This post poses two different questions, but since both are related to a single regressor, lets treat them as one.
Distribution of regressors
Consider the usual multiple linear regression specification
$$y_i = \beta_0 + \beta_1x_{1i} +...+\beta_kx_{ki} + u_i$$
If regressors are stochastic then the distribution of $y_i$ results from the combination of the regressor's distribution and the error distribution. In the special case where all regressors follow a normal distribution, and the error term is also assumed normally distributed too, then we can conclude that the distribution of $y_i$ should also be normal. But this is a very special case. In general, recovering the distribution of $y_i$ is infeasible...
We side-step the matter by considering the distribution of $y_i$ conditional on the regressors. Our inference and conclusions from the model are conditional on the regressors  (not only on the specific sample we have available, but in general on the regressors as random variables and on their joint sigma-algebra).
The stochastic assumptions are stated in terms of this conditionality: the error term has a zero-mean conditional on the regressors, its variance is constant conditional on the regressors. Exact test results are based on the assumption that the error term is distributed normally conditional on the regressors, etc.
All modern treatments of least-squares estimation do that. Maximum likelihood is mostly implemented as conditional maximum likelihood, although we usually don't say it explicitly: when we say "the joint density of the sample" in most cases, the term "joint" refers to the fact that we consider many observations, not to the joint distribution of the dependent variable and the regressors.
Theoretically, perhaps we would want to know the unconditional distribution of the dependent variable, so that we could handle the uncertainty surrounding it without the need to have specific information about its associations/covariance/causal relations with other variables... but if information is available, why not use it? Conditional inference is more focused (and so less uncertain) than unconditional inference but if it is mistaken (misspecification issues), it creates larger inaccuracies... This is the trade-off we have to live with. So don't worry about the non-normality of your regressor, it is not an issue.
Outliers
Outliers on the other hand is an issue. Many statistics (like the sample mean or the sample standard deviation) are not robust to the existence of outliers (while the median and the mean absolute deviation are, comparatively). There is a tendency to just delete outliers from the sample, based on the argument that they do not reflect "usual behavior" and so they are misleading -but not all situations validate such an argument and action.
There is a large literature regarding the issue. For example, look up "Influential Observations Analysis" where various measures have been constructed that go one step further regrading outliers and evaluate what degree of influence has an outlier on the estimation results that we have obtained from the model. I would say such a step is essential before making any decision about whether to delete or smooth outliers, or not, or factoring them in, when interpreting the results, or not.
Comment: The fact that "outliers" can damage regression fits doesn't imply that the modeling process is dependent on distributions for $X$.  I think of high leverage points as being damaging as a consequence of most of our model fitting methods not being robust.  To handle heavy right-tailed variables I often fit restricted cubic splines in the cube root of the predictor.
Comment: @Frank Harrell I don't see where in my answer I say or imply that the modeling process is dependent on the distribution of $\mathbf X$, on the contrary.
Comment: Sorry my comment was in the wrong location.   It was meant for the original poster.
Comment: @Frank Harrell Oh, ok.Why don't you turn it into an answer? It provides specific suggestions, which is good.
Answer: In OLS the distribution of the predictors doesn't matter. Your predictors form a design matrix $X_{ij}$, where $j$ is the predictor, and $i$ is the number of the observation, so the model specification is $Y_i=\sum_jX_{ij}\beta_j+\varepsilon_i$ or $Y=X\beta+\varepsilon$ in vector notation. The only distribution that matters here is of the error term $\varepsilon$.
Outliers is an interesting topic. In OLS we assume that $X$ are known and their distribution does't matter, so the outliers are not a concern at all so long you know the value of $X$.
The outliers in OLS come from the error terms. The distribution of $\varepsilon$ matters in several ways, and the outliers are important.
So, my answer is that distribution and outliers in the predictors is not a problem.
However, by the way you asked the question I can suspect that you have a problem, which you did not formulate accurately. My guess is that you have a situation where $Y$ depends on a true state, which is not observed directly or observed with an error. So that you see the predictors, but they are not true states of the system.
Answer: The distribution of the predictors does not matter at all. This is a quite common misunderstanding. What rather matters is the distribution of the errors in the fitted model (plus other important assumptions). See this blogspot by Andrew Gelman & the discussion in the comments, and also this previous question.
Comment: Outliers in the input space is a major issue in most types of models. So, I do not fully agree with your answer
Comment: The links I provided and the other answers and comments here clearly state that the distribution of X does not matter per se. If you can convincingly argue otherwise, you should post it as an answer.


NoDecodeDelegateForThisImageFormat `TIFF\"' aws lambda

Question: I am trying to use convert from imageMagick to run this command on aws lambda convert -scene 1 test.tiff output.jpg to convert a tiff to image .
But I am getting this errors always
NoDecodeDelegateForThisImageFormat `TIFF\"

Comment: What is your ImageMagick version? Does `convert -version` list tiff for a delegate? If not, then libtiff was not installed. Otherwise try: `convert test.tiff -scene 1 output.jpg`
Answer: I had a similar problem - in my case, TIFF\" was failing because of a trailing quote (")


How do I install on Windows 11?

Question: I wish to install Drupal 9 on Windows 11 using Drush.
Drupal on the cloud solutions (which should be easily accessible from Windows) cost money and not quite what I seek for a local install.
I can install Drupal 9 on WAMP/XAMPP on Windows but I don't want because it doesn't have Drush (and I don't think WSL will help).
I can install Linux, either directly or on a virtual machine, using a distribution like Ubuntu, which I have used over the years, but I encounter several keyboard and mouse issues (slow mouse scrolling, keyboard input problems, etc.) which make hard for me to edit much content.
How do I install Drupal 9 with Drush on Windows 11?
Comment: Start using a Docker-based setup like DDEV: https://ddev.readthedocs.io/en/stable/. Everything will happen in the containers then and you don't have to mess w/ your Windows. Having drush/drush in your composer.json, execute `ddev composer install` once and from then on use `ddev drush updb` etc.
Comment: This is great you have years of experience running Drupal on Ubuntu. In a virtual machine  you have either performance problems with file sharing or keyboard/mouse issues when accessing the Linux desktop via VNC. So install the IDE (VS Code or PHPstorm) on Windows and connect the Linux VM via SSH. See https://code.visualstudio.com/docs/remote/remote-overview
Comment: Hello @4uk4 what is VNC? I use VirtualBox as a machine. Please consider to publish an answer with steps for newbies like myself.
Comment: @leymannx but where do I install this Docker-based setup? On Windows 11 itself? On Docker Desktop?
Comment: VNC is what you are using now, having the keyboard/mouse issues. My advice is to move away from it. Once you have the Linux VM running (as you say you know how to do it and then you can do it without docker), then the only thing you need are the steps described in the VS code link.
Comment: Read the DDEV docs, please. It will enlighten you. DDEV requires Docker (Desktop). You install DDEV and then get a bunch of commands to do stuff inside the DDEV containers.
Comment: Don't use a VirtualBox - use WSL2.
Comment: I am using Ubuntu as VirtualBox machine (for other reasons), but I have never had keyboard/mouse issues. With GNOME, it's necessary to set VirtualBox with 3D acceleration, or it will start to be slow. That's GNOME, though. Using a different DE doesn't create any issue. It's probable you are using VNC; that would cause issues.
Answer: If you're on Windows 11, you should consider using Docker with WSL2.  This will let you use a WSL installation of Ubuntu, which runs in the hypervisor and will give better performance than a virtual machine in VirtualBox, etc.
However, with WSL2 (different from WSL1), filesystem performance will take a huge hit if you manipulate linux files from Windows. To get around this, you can set up Visual Studio Code or PHPStorm in Windows to access your WSL2 environment.  Alternately, you can install the IDE of your choice in WSL2 and run it with wslg support, but this is harder to set up and prone to graphical glitches.
Personally, if you are comfortable with Ubuntu, I would recommend using a docker-based solution inside WSL2 like lando.  Lando provides a nice interface for setting up docker containers and has great support out of the box for Drupal as well as many of the Drupal PaaS.
So the basic flow is:

Install Ubuntu and upgrade it to WSL2 (it will probably be WSL1 by default).
Install docker and lando in WSL2 and set up your drupal site.
Install your IDE (assuming it is VSCode or PHPStorm) in Windows and then connect to WSL.
Enjoy a complete linux environment from Windows with great performance.

All of the software recommended here is open source (except PHPStorm) and freely available.  lando has been around for 10+ years (used to be called Kalabox) and WSL has been around since 2016 and continues to get big upgrades from Microsoft (it's the basis for Windows 11's Android app compatibility), so although it takes time to set this up, you can be reasonably confident that these solutions will continue to be supported well into the future.
Comment: Docker is used in complicated deployment setups, but it can also be used easily for a single site.  You said you wanted a local dev setup, which lando (and other docker-based dev tools like ddev and docksal) provide out of the box.  With these tools, you can install lando and then use the `drupal9` recipe (https://docs.lando.dev/config/recipes.html) to quickly set up the db and webserver in docker automatically. This is very similar to WAMP but it uses docker as the base, which is generally faster than WAMP in a VM due to containers (using lando, you don't have to worry about the details).
Comment: Thank you so much ! I have only one Drupal website to work on. My personal website. Do I still need Docker? Isn't docker a tool for people who wish to start off from a certain Drupal state/mode when building many Drupal sites for customers?
Answer: If you want to install Drupal 9 on windows 11 then follow these steps which are given on drupal.org Step 1: Get the Code
Install the files you need to run Drupal.
Step 2: Install dependencies with composer
If you installed or updated the codebase using git, then install required PHP libraries with composer.
Step 3: Create a database
Create a database for Drupal to use.
Step 4: Configure your installation
Set up the web server and PHP to work together.
Step 5: Run the installer
Run the installation script.
Step 6: Status check
Check the status of your site at Administration > Reports > Status report. Set trusted hosts patterns, create files directories.
Add Composer to an existing site
How to convert an existing Drupal site to a composer-managed project. Step by step guide to adding composer to manually installed site.
Building a Drupal site with Git
How to use Git to manage the source code for a Drupal site
Drupal Quick Start Command
Launch a local demo version of Drupal.
Trusted Host settings
Protecting against HTTP HOST Header attacks
Comment: Welcome to Drupal Answers! Have a look at the help center to find out more about how to write [good answers](https://drupal.stackexchange.com/help/how-to-answer). This answer does not address the question of how to install drush. It is also lacking links to resources, e.g. to drupal.org, and could easily be improved by better formatting.
Answer: I have found the way to install (and upgrade) Drupal 9 and above on Windows 11 extremely cumbersome and not worth the time.
An alternative, for those who need Windows 11 mechanics and keyboard behavior is to hire a shared hosting (which includes SSH and Composer) and install Drupal on that shared hosting while SSHing to this environment from Windows 11.
If working this way, it's probably best to put the website on maintenance mode and disallow: / in robots.txt for development time.
If one takes the path I have suggested, while working form Windows 11 the installation pretty much narrows down to the following steps:
# Configure DNS records
# Configure database (say, with PHPMyAdmin)

cd WEB_APPLICATION_ROOT
composer create-project drupal/recommended-project WEB_APPLICATION_DIR_NAME
cd WEB_APPLICATION_DIR_NAME
composer require drush/drush
vendor/bin/drush site:install

# Configure web_application_root (example.com/web, done from "domains" in Cpanel)
# Install Drupal from web browser

Comment: DDEV, Docksal and Lando are specifically tailored for this and pitched on drupal.org, Acquia, Pantheon, etc.
Comment: Everyone is encouraged to use Docker based solutions, especially for Windows, vs trying to script and install these things directly which is far more complicated with Windows over other operating systems. This also presumes people have some knowledge of hosting a server before they get this far - most don't. `It is a fact of life that this is one way to work with Drupal in Windows 11` - no, this is 'working' with Drupal on a Linux host.
Comment: @Kevin from my experience using Docker is far more complicated than this solution and in practice it's working both on Windows and Linux...

How do I install on Windows 11?


Dynamic array C++, trouble with new Obj[size] creating only 1 Object pointer, not array

Question: I will try to make this direct. And no, I can't use a vector. I have an existing array declared like so in hpp:
Item *itemList[4];

Then, I need to later create a new size of the array of Object pointers.
Here was my resize array function. It does not work because after the set of slot 1, it runs out of slots. This is because Visual Studio sees **tempList as a singular pointer to a singular Object. What am I missing?:
void List::resizeList(int newSiz) {
Item **tempList = new Item *[newSiz];

//Setup tempList
for (int arraySlot = 0; arraySlot < newSiz; ++arraySlot)
    tempList[arraySlot] = NULL;

//Copy List
for (int listSlot = 0; listSlot < numArraySlots; listSlot++) {
    tempList[listSlot] = itemList[listSlot];
}

delete [] itemList; //Delete Original List
*itemList = *tempList; //Set new itemList
}

Adding this screenshot so you can see that Visual Studio thinks that tempList is just a pointer to a singular Item Object Pointer
enter image description here
#ifndef LIST_HPP
#define LIST_HPP

#include "Item.hpp"

class List
{
private:
    Item *itemList[4]; //Array of 4 Item Object Pointers
    int numItemsOnList; //Track number of Items on List
    int numArraySlots; //Track Array Slots available for comparison on addToList
public:
    List(); //Default 4 Objects
    void addToList(string nam, string uni, int numBuy, double uniPrice);
    void delFromList(string itemName); //Using Name for Lookup
    void resizeList(int newSize); //Resize new array
    void printList(); //Print current List
    double calcTotalPrice(); //Calculate Total Price of items on list
    bool itemExists(string);
};

#endif

Comment: Thanks, but did you not read my comment? I cannot use vector. We are not talking about industry standards or best practice here. I need the proper way to do this if this method had to be used.
Comment: The way to create a new dynamic array is to use ``std::vector``. Why are you not using it?
Comment: `itemList2[0] = itemList[0]`, *itemList2* is an **array of Item objects**. *itemList* is an **array of pointers** to Item object.
Comment: Yes thank you. However, my resizeList uses **tempList and newItem*[size]. What is the proper way to create a Dynamic array of pointers to Objects that will mesh with Item *itemList[4]?
Comment: I can't duplicate the problem on my pc. Are you sure `itemList` elements are initialized before you use them? One more thing `delete [] itemList;` you don't need to use `delete` here because this array was not created with `new` operator.
Comment: @bkVnet, Thank you so much! So I should create the new **tempList instead of setting to NULL? Sorry I am not sure how to add in comments as code.

    for (int arraySlot = 0; arraySlot < newSiz; ++arraySlot)tempList[arraySlot] = new Item();
Comment: Its not clear what is not working for you, but i don't think that is the problem since you are creating an array of pointer to Item object there. Try to make sure the contents of `itemList` are valid.You should probable use a debugger and run you code line by line. And what is `numArraySlots` in your second loop?
Comment: why you cannot use a `std::vector` ? c-style arrays can be converted easily to/from vectors, thus even when depending on some c-stylish api I would use vectors. If you are not allowed to use them because it is homework, then it is different of course, however even then I would use vectors :P
Comment: @bkVnet I added a screenshot to my original post. Please take a look. This is what Visual Studio sees tempList as. Whenever I iterate over tempList[arraySlot] it just sets the Item data members of a single item. It does not see a whole array there at all. numArraySlots is a data member that is the size of 4 by default. It is currently int 4. Also, I removed delete as suggested.
Comment: @tobi303 No I cannot use vector otherwise I totally would... This is for a class and this is the last thing I am stuck on after 20 hours of coding.
Comment: I still don't think that is the problem though. its is just showing you the first element that is pointed to by the first pointer in the array. You can set a break point after you initialize the dynamic array, and use the watch window to see the values of each element pointed to by the pointers like `tempList[1]`,`tempList[2]`,etc.. or just use a for loop to display the contents of the elements pointed to by those pointers.
Comment: @bkVnet Ok I will try that. In addition, I have included the List.hpp to show you what all of it is. Item *itemList[4] always works great when adding items. It makes 4 of them and then explodes on resize function.
Comment: BTW try to look carefully at the logic of `resizeList` is trying to accomplish here because the last two statements doesn't make that much sense to me(if it doesn't cause a run time error).
Comment: @bkVnet Yes delete [] itemList was removed since itemList was not dynamically created as new, it was already declared at compile. The very last statement was supposed to copy the tempList over the top of the original data member itemList. Does that make sense?
Answer: itemList is statically created array and you can't resize it at run time. what you may want to do is make it a double pointer Item** itemList, set its initial size at the constructor of your class using new, resize it, and delete its at the destructor of the class when the class is destroyed.
Try this:
List::List()
{
    itemList=new Item*[4];//allocate its initial size in the constructor
}

List::~List()
{
    delete[] itemList;//release the memory at the destructor
}

void List::resizeList(int newSiz) {
  Item **tempList = new Item *[newSiz];

  //Setup tempList
  for (int arraySlot = 0; arraySlot < newSiz; ++arraySlot)
       tempList[arraySlot] = NULL;

  //Copy List
  for (int listSlot = 0; listSlot < numArraySlots; listSlot++)
       tempList[listSlot] = itemList[listSlot];

   delete [] itemList; //Delete Original List
   itemList = tempList; //Set new itemList
}

I hope this helps.
Comment: THANK YOU! That got it. I guess there is some trouble when an array previously declared tries to turn into a dynamic array...


How to host a nodejs app on ECS?

Question: Iam looking to host a nodejs app on ECS. On local dev i use ngrok to expose port 3000 and it seems to work well. Now i would like to host it. Is dockerizing mandatory? What would be the steps to host it on amazon ecs if the app is dockerized?
I would also like to know if hosting on ecs is possible without dockerizing.
Answer: I would suggest you if you want to go this way to start an EB Instance.
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html
And you can deploy your application using CodeShip or use the traditional way in EB where you upload and deploy the code ( I suggest you use CodeShip ).
Another way to do it, and it might end it up being free is Heroku, it's an amazing and easy cloud service where you can deploy your application and build a continuous integration with GitHub, it takes care of everything to you.
This is the walkthrough for Node.Js apps:
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
Dockerizing is not mandatory at all, you can do it if you like, the roadmap to deploy the app won't change.

How to host a nodejs app on ECS?


Duvida Recebimento de parametros (WebService Soap)

Question: Galera, estou com duvida no seguinte cenário:
Tenho essa classe, ela é um webservice (contem o método @WebService):
@WebService(name = "l", targetNamespace = "o")
    public abstract interface Service {

    @WebMethod(operationName = "Cancelar")
    @RequestWrapper(localName = "Cancelar", targetNamespace = "http://www.x.com.br/y/w", className = "br.com.x.y.w.CancelarRequest")
    @ResponseWrapper(localName = "CancelarResponse", targetNamespace = "http://www.x.com.br/y/w", className = "br.com.x.y.w.CancelarResponse")
    public abstract void Cancelar(
            @WebParam(name = "k", targetNamespace = "http://www.x.com.br/y/w", mode = WebParam.Mode.INOUT) Holder<String> paramHolder,
            @WebParam(name = "Result", targetNamespace = "http://www.x.com.br/y/w", mode = WebParam.Mode.OUT) Holder<ResultType> paramHolder1);
    }

Minha duvida é: se essa classe é um webservice porque defini-la como "abstract interface", alias, - oque acontece quando defino uma classe usando "abstract interface". Até hoje só criei classes que usam um ou outro.
Observe que essa classe é a interface remota, ela define os serviços remotos (@Method), porem não os implementa, toda a implementação parece estar na classe ServiceImpl:
public class ServiceImpl implements Service
    @Override
    public void Cancelar(
            Holder<String> k,
            Holder<ResultType> result) {

        CancelarP p = new CancelarP(ctx, k.value);
        CancelarResponseType execute = p.execute();
        ResultType resultType = execute.getResult();
        result.value = resultType;
    }

Na classe ServiceImpl, se quando eu dou um @Override perco a implementação da classe pai, como farei os Marshall do xml recebido via Soap?. Não estou conseguindo compreender como essas classes estão trabalhando em conjunto.
Espero ter conseguido ser claro na elaboração da pergunta, desde ja agradeço.
Answer: Vamos lá.
Quando vc dá um @Override em Cancelar()você não está perdendo a implementação da interface, justamente por não haver nenhuma, sendo ela uma interface.
O que pode ter te levado a acreditar nisso são as anotações que o criador da interface colocou nos parametros do método.
Para a primeira pergunta, irei traduzir uma resposta a uma pergunta identica feita no SO.
Eu sinceramente nunca usei nada que implementasse a anotação @WebServiceentão só posso descrever a parte técnica.
Não há necessidade de colocar abstractem uma interface, por ela já ser abstrata, e adicionando-o não muda em nada.
public abstract interface Interface {
       \___.__/
           |
           '----> Não é necessário...

public void interfacing();
public abstract boolean interfacing(boolean really);
       \___.__/
           |
           '----> nem aqui.
}

Há alguma mudança na implementação de uma p/ outra?

Não, exatamente a mesma coisa. Os métodos continuarão a ser implementados de forma concreta em suas classes filha.
Fonte
Edição: Uma coisa que esqueci de comentar. As anotações dos métodos provavelmente estão ali para que elas sejam manipuladas da forma correta por algum framework. E como estão na interface, não haverá nenhum mal em não coloca-las na classe impl.


SFTP post upload hook

Question: How would I run a script after a file has been successfully uploaded over (a chrooted) SFTP?
I have this working on standard FTP connection using PureFTP
http://linux.die.net/man/8/pure-uploadscript
I'm running Debian Squeeze
Answer: I'd use incron. This uses the kernel's inotify hooks to run arbitrary commands on specified filesystem events.
Answer: I was able to accomplish this with ProFTPd & the mod_exec module.
Comment: Please update your solution. mod_exec link is broken.

SFTP post upload hook


How do I get translated strings into Drupal.locale.strings?

Question: So I'm trying to use the Drupal.t() function in some of my custom Javascript code (in my theme).
How do I get the strings I need populated in the Drupal.locale.strings object? I see some strings in there, but of course the entire database can't be loaded. What's the best way to add to it? I would like to use the PHP t() function so that the strings added can be edited in the Translate interface.
Answer: Drupal handles populating the needing strings into the javascript object. Much like the entire collection of strings isn't loaded on every page, only the needed strings are added to the JavaScript.
I believe this is done by traversing the script files before they are actually added to the page.
So if you add Drupal.t('Some string'); to your JavaScript code, you should be able to translate that in the translate interface.
Comment: Well then it ain't happening. (the traversal of the script for find the Drupal.t() calls). I'm adding the script via the theme's .info file (scripts[] = scripts/script.js). Maybe I have to add via drupal_add_js() ?
Comment: You are correct. I had to trace through to fully get an understanding, but it does indeed happen automagically. In Drupal 7, the function is locale_js_alter() (in locale.module). It uses the full list of Javascript files and parses each one in _locale_parse_js_file(). Be careful to make sure that file_get_contents() can load your JS file with the path provided (i.e. don't start your path with a / if it's in your theme folder). You can use drupal_add_js or the scripts[] setting in your theme's .info file. Of course, make sure to clear caches and translate the string! :)
Answer: Just ran into this same issue today and researched it a bit more. Chris above has a good comment, but it's ultimately incorrect. You do not need to use Drupal.behaviors for it to work.
As noted by JonMcL himself in his last comment, the function _locale_parse_js_file in locale.inc is responsible for the parsing of Drupal.t("somestring") patterns starting from row 1493 (in Drupal 7.22):
preg_match_all('~
[^\w]Drupal\s*\.\s*t\s*                       # match "Drupal.t" with whitespace
\(\s*                                         # match "(" argument list start
(' . LOCALE_JS_STRING . ')\s*                 # capture string argument
(?:,\s*' . LOCALE_JS_OBJECT . '\s*            # optionally capture str args
  (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
?)?                                           # close optional args
[,\)]                                         # match ")" or "," to finish
~sx', $file, $t_matches);

It's just a "dumb" parsing function that doesn't care about semantics and simply finds all instances of Drupal.t("something") in any file it receives.
What could be a common gotcha is that you need to have the whole string in your source code in the Drupal.t("translateme") form, because (obviously) no javascript gets executed when the file is opened through file_get_contents in php. That means you can never do Drupal.t(somevariable) and hope Drupal will catch all string-containing javascript variables that you throw at Drupal.t.
If you want to translate "women" for a chart and give the string a context, the syntax would be:
Drupal.t("women", {}, {context: "charts"}

Also, if you have drush installed, verify your js file is parsed with the command;
drush vget javascript_parsed

Then you can clean your cache with
drush cc all

... and repeat the vget command above to verify the list of already parsed files is empty. This way your file will get reparsed next run (verify that too).
Comment: Thanks for `drush vget javascript_parsed`! A quicker way to force rebuild translations script files is by just removing CSS and JS files using `drush @sitealias cc css-js`.
Answer: Couple gotchas I've run into while implementing multilingual JS in Drupal 7:

First, make sure your JS file is not being included inline. As of Drupal 7.22, Drupal.locale.strings doesn't seem to automatically update itself if you're inlining JavaScript files in Drupal. The translation interface still picked up the string anyway, adding to my confusion.
Second, make sure you're using Drupal.behaviors to attach your JS to the page. Regular JS closures will not trigger Drupal's "magic" parsing of Drupal.t() invocations. This is technically something you should be doing anyway ;)

From there it really is pretty painless. Just use Drupal.t() around text you want translated, clear your cache each time you update the file, and your translators should see the new string in the interface at /admin/config/regional/translate/translate. It's quite nice once you get it working.