Ler XML com tag (nodes) iguais

Question: Eu tenho esse xml, e preciso pegar a tag <ns2:InfNfse Id="24030TZYKNKKIPZM4PU7XGAZJ0UA84O6">
Porém no ´xml´ tem várias tags com nomes iguais. Tentei fazer desta forma abaixo:
XmlElement retEnviNFe = xmlResponse.DocumentElement;
XmlNodeList numero = retEnviNFe.SelectNodes("//ns2:Numero", ns);
Numero = numero[4].InnerText;
XmlNodeList codigoVerificacao = retEnviNFe.SelectNodes("//ns2:CodigoVerificacao", ns);
CodigoVerificacao = codigoVerificacao[1].InnerText;
foreach (XmlNodeList node in retEnviNFe.SelectNodes("//ns2:InfNfse", ns))
{
    Id = (node[1].Attributes["Id"].Value);
}

o Número e o Código Verificação eu já pego corretamente, porém preciso pegar o Id de InfNfse, porém possui dois nesse XML de retorno, preciso pegar o segundo, porém na linha foreach (XmlNodeList node in retEnviNFe.SelectNodes("//ns2:InfNfse", ns)) retorna null.
Esse é um xml que eu preciso pegar os dados:
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <ns3:substituirNfseResponse
            xmlns:ns2="http://www.abrasf.org.br/nfse.xsd"
            xmlns:ns3="http://ws.issweb.fiorilli.com.br/"
            xmlns:ns4="http://www.w3.org/2000/09/xmldsig#">
            <ns2:SubstituirNfseResposta>
                <ns2:RetSubstituicao>
                    <ns2:NfseSubstituida>
                        <ns2:CompNfse>
                            <ns2:Nfse versao="2.01">
                                <ns2:InfNfse Id="24029XVB442U6IVDHMJV7C2JMEM26UWH">
                                    <ns2:Numero>14546</ns2:Numero>
                                    <ns2:CodigoVerificacao>0MEID640A</ns2:CodigoVerificacao>
                                    <ns2:DataEmissao>2019-01-04T15:38:17</ns2:DataEmissao>
                                    <ns2:OutrasInformacoes>Val. Aprox. Tributos: Federal (13,45%) R$2,02 Estadual (0,00%) R$0,00 Municipal (10,00%) R$1,50
    Motivo Substituição: Substituição solicitada via Web Service</ns2:OutrasInformacoes>
                                    <ns2:ValoresNfse>
                                        <ns2:BaseCalculo>15.00</ns2:BaseCalculo>
                                        <ns2:Aliquota>2.0</ns2:Aliquota>
                                        <ns2:ValorIss>0.30</ns2:ValorIss>
                                        <ns2:ValorLiquidoNfse>15.00</ns2:ValorLiquidoNfse>
                                    </ns2:ValoresNfse>
                                    <ns2:PrestadorServico>
                                        <ns2:IdentificacaoPrestador>
                                            <ns2:CpfCnpj>
                                                <ns2:Cnpj>01001001000113</ns2:Cnpj>
                                            </ns2:CpfCnpj>
                                            <ns2:InscricaoMunicipal>15000</ns2:InscricaoMunicipal>
                                        </ns2:IdentificacaoPrestador>
                                        <ns2:RazaoSocial>PRESTADOR TESTE</ns2:RazaoSocial>
                                        <ns2:NomeFantasia>EMPRESA TESTE 01</ns2:NomeFantasia>
                                        <ns2:Endereco>
                                            <ns2:Endereco>RUA LOGRADOURO 1</ns2:Endereco>
                                            <ns2:Numero>0</ns2:Numero>
                                            <ns2:Bairro>CENTRO</ns2:Bairro>
                                            <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                            <ns2:Uf>SP</ns2:Uf>
                                            <ns2:CodigoPais>1058</ns2:CodigoPais>
                                            <ns2:Cep>15140000</ns2:Cep>
                                        </ns2:Endereco>
                                        <ns2:Contato>
                                            <ns2:Email>email@example.com</ns2:Email>
                                        </ns2:Contato>
                                    </ns2:PrestadorServico>
                                    <ns2:OrgaoGerador>
                                        <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                        <ns2:Uf>MS</ns2:Uf>
                                    </ns2:OrgaoGerador>
                                    <ns2:DeclaracaoPrestacaoServico>
                                        <ns2:InfDeclaracaoPrestacaoServico>
                                            <ns2:Rps>
                                                <ns2:IdentificacaoRps>
                                                    <ns2:Numero>23</ns2:Numero>
                                                    <ns2:Serie>463</ns2:Serie>
                                                    <ns2:Tipo>1</ns2:Tipo>
                                                </ns2:IdentificacaoRps>
                                                <ns2:DataEmissao>2019-01-04</ns2:DataEmissao>
                                                <ns2:Status>2</ns2:Status>
                                            </ns2:Rps>
                                            <ns2:Competencia>2019-01-04</ns2:Competencia>
                                            <ns2:Servico>
                                                <ns2:Valores>
                                                    <ns2:ValorServicos>15.00</ns2:ValorServicos>
                                                    <ns2:ValorDeducoes>0.00</ns2:ValorDeducoes>
                                                    <ns2:ValorPis>0.00</ns2:ValorPis>
                                                    <ns2:ValorCofins>0.00</ns2:ValorCofins>
                                                    <ns2:ValorInss>0.00</ns2:ValorInss>
                                                    <ns2:ValorIr>0.00</ns2:ValorIr>
                                                    <ns2:ValorCsll>0.00</ns2:ValorCsll>
                                                    <ns2:OutrasRetencoes>0.00</ns2:OutrasRetencoes>
                                                    <ns2:ValorIss>0.30</ns2:ValorIss>
                                                    <ns2:Aliquota>2.0</ns2:Aliquota>
                                                    <ns2:DescontoIncondicionado>0.00</ns2:DescontoIncondicionado>
                                                    <ns2:DescontoCondicionado>0.00</ns2:DescontoCondicionado>
                                                </ns2:Valores>
                                                <ns2:IssRetido>2</ns2:IssRetido>
                                                <ns2:ResponsavelRetencao>1</ns2:ResponsavelRetencao>
                                                <ns2:ItemListaServico>01.05</ns2:ItemListaServico>
                                                <ns2:CodigoTributacaoMunicipio>0000010000005</ns2:CodigoTributacaoMunicipio>
                                                <ns2:Discriminacao>Descricao: teste Qtd: 1 V.Unit.: 15,00 V.Total: 15,00</ns2:Discriminacao>
                                                <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                                <ns2:ExigibilidadeISS>1</ns2:ExigibilidadeISS>
                                                <ns2:MunicipioIncidencia>3504800</ns2:MunicipioIncidencia>
                                            </ns2:Servico>
                                            <ns2:Prestador>
                                                <ns2:CpfCnpj>
                                                    <ns2:Cnpj>01001001000113</ns2:Cnpj>
                                                </ns2:CpfCnpj>
                                                <ns2:InscricaoMunicipal>1.000.10</ns2:InscricaoMunicipal>
                                            </ns2:Prestador>
                                            <ns2:Tomador>
                                                <ns2:IdentificacaoTomador>
                                                    <ns2:CpfCnpj>
                                                        <ns2:Cpf>08297163008</ns2:Cpf>
                                                    </ns2:CpfCnpj>
                                                </ns2:IdentificacaoTomador>
                                                <ns2:RazaoSocial>Teste Mariana</ns2:RazaoSocial>
                                                <ns2:Endereco>
                                                    <ns2:Endereco>RUA JARBAS PIMENTA</ns2:Endereco>
                                                    <ns2:Numero>514</ns2:Numero>
                                                    <ns2:Complemento>complemento cobrancaaeAaO</ns2:Complemento>
                                                    <ns2:Bairro>NOVA ERA</ns2:Bairro>
                                                    <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                                    <ns2:Uf>SP</ns2:Uf>
                                                    <ns2:Cep>37170000</ns2:Cep>
                                                </ns2:Endereco>
                                                <ns2:Contato>
                                                    <ns2:Telefone>3538511836</ns2:Telefone>
                                                    <ns2:Email>firstname.lastname@example.com</ns2:Email>
                                                </ns2:Contato>
                                            </ns2:Tomador>
                                            <ns2:RegimeEspecialTributacao>0</ns2:RegimeEspecialTributacao>
                                            <ns2:OptanteSimplesNacional>2</ns2:OptanteSimplesNacional>
                                            <ns2:IncentivoFiscal>2</ns2:IncentivoFiscal>
                                        </ns2:InfDeclaracaoPrestacaoServico>
                                    </ns2:DeclaracaoPrestacaoServico>
                                </ns2:InfNfse>
                            </ns2:Nfse>
                            <ns2:NfseSubstituicao versao="2.01">
                                <ns2:SubstituicaoNfse>
                                    <ns2:NfseSubstituidora>14547</ns2:NfseSubstituidora>
                                </ns2:SubstituicaoNfse>
                            </ns2:NfseSubstituicao>
                        </ns2:CompNfse>
                    </ns2:NfseSubstituida>
                    <ns2:NfseSubstituidora>
                        <ns2:CompNfse>
                            <ns2:Nfse versao="2.01">
                                <ns2:InfNfse Id="24030TZYKNKKIPZM4PU7XGAZJ0UA84O6">
                                    <ns2:Numero>14547</ns2:Numero>
                                    <ns2:CodigoVerificacao>XJ5K4QNCE</ns2:CodigoVerificacao>
                                    <ns2:DataEmissao>2019-01-04T15:39:16</ns2:DataEmissao>
                                    <ns2:OutrasInformacoes>Val. Aprox. Tributos: Federal (13,45%) R$2,02 Estadual (0,00%) R$0,00 Municipal (10,00%) R$1,50</ns2:OutrasInformacoes>
                                    <ns2:ValoresNfse>
                                        <ns2:BaseCalculo>15.00</ns2:BaseCalculo>
                                        <ns2:Aliquota>2.0</ns2:Aliquota>
                                        <ns2:ValorIss>0.30</ns2:ValorIss>
                                        <ns2:ValorLiquidoNfse>15.00</ns2:ValorLiquidoNfse>
                                    </ns2:ValoresNfse>
                                    <ns2:PrestadorServico>
                                        <ns2:IdentificacaoPrestador>
                                            <ns2:CpfCnpj>
                                                <ns2:Cnpj>01001001000113</ns2:Cnpj>
                                            </ns2:CpfCnpj>
                                            <ns2:InscricaoMunicipal>15000</ns2:InscricaoMunicipal>
                                        </ns2:IdentificacaoPrestador>
                                        <ns2:RazaoSocial>PRESTADOR TESTE</ns2:RazaoSocial>
                                        <ns2:NomeFantasia>EMPRESA TESTE 01</ns2:NomeFantasia>
                                        <ns2:Endereco>
                                            <ns2:Endereco>RUA LOGRADOURO 1</ns2:Endereco>
                                            <ns2:Numero>0</ns2:Numero>
                                            <ns2:Bairro>CENTRO</ns2:Bairro>
                                            <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                            <ns2:Uf>SP</ns2:Uf>
                                            <ns2:CodigoPais>1058</ns2:CodigoPais>
                                            <ns2:Cep>15140000</ns2:Cep>
                                        </ns2:Endereco>
                                        <ns2:Contato>
                                            <ns2:Email>firstname.lastname@example.com</ns2:Email>
                                        </ns2:Contato>
                                    </ns2:PrestadorServico>
                                    <ns2:OrgaoGerador>
                                        <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                        <ns2:Uf>MS</ns2:Uf>
                                    </ns2:OrgaoGerador>
                                    <ns2:DeclaracaoPrestacaoServico>
                                        <ns2:InfDeclaracaoPrestacaoServico>
                                            <ns2:Rps>
                                                <ns2:IdentificacaoRps>
                                                    <ns2:Numero>24</ns2:Numero>
                                                    <ns2:Serie>463</ns2:Serie>
                                                    <ns2:Tipo>1</ns2:Tipo>
                                                </ns2:IdentificacaoRps>
                                                <ns2:DataEmissao>2019-01-04</ns2:DataEmissao>
                                                <ns2:Status>1</ns2:Status>
                                            </ns2:Rps>
                                            <ns2:Competencia>2019-01-04</ns2:Competencia>
                                            <ns2:Servico>
                                                <ns2:Valores>
                                                    <ns2:ValorServicos>15.00</ns2:ValorServicos>
                                                    <ns2:ValorDeducoes>0.00</ns2:ValorDeducoes>
                                                    <ns2:ValorPis>0.00</ns2:ValorPis>
                                                    <ns2:ValorCofins>0.00</ns2:ValorCofins>
                                                    <ns2:ValorInss>0.00</ns2:ValorInss>
                                                    <ns2:ValorIr>0.00</ns2:ValorIr>
                                                    <ns2:ValorCsll>0.00</ns2:ValorCsll>
                                                    <ns2:OutrasRetencoes>0.00</ns2:OutrasRetencoes>
                                                    <ns2:ValorIss>0.30</ns2:ValorIss>
                                                    <ns2:Aliquota>2.0</ns2:Aliquota>
                                                    <ns2:DescontoIncondicionado>0.00</ns2:DescontoIncondicionado>
                                                    <ns2:DescontoCondicionado>0.00</ns2:DescontoCondicionado>
                                                </ns2:Valores>
                                                <ns2:IssRetido>2</ns2:IssRetido>
                                                <ns2:ResponsavelRetencao>1</ns2:ResponsavelRetencao>
                                                <ns2:ItemListaServico>01.05</ns2:ItemListaServico>
                                                <ns2:CodigoTributacaoMunicipio>0000010000005</ns2:CodigoTributacaoMunicipio>
                                                <ns2:Discriminacao>Descricao: teste</ns2:Discriminacao>
                                                <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                                <ns2:ExigibilidadeISS>1</ns2:ExigibilidadeISS>
                                                <ns2:MunicipioIncidencia>3504800</ns2:MunicipioIncidencia>
                                            </ns2:Servico>
                                            <ns2:Prestador>
                                                <ns2:CpfCnpj>
                                                    <ns2:Cnpj>01001001000113</ns2:Cnpj>
                                                </ns2:CpfCnpj>
                                                <ns2:InscricaoMunicipal>1.000.10</ns2:InscricaoMunicipal>
                                            </ns2:Prestador>
                                            <ns2:Tomador>
                                                <ns2:IdentificacaoTomador>
                                                    <ns2:CpfCnpj>
                                                        <ns2:Cpf>08297163008</ns2:Cpf>
                                                    </ns2:CpfCnpj>
                                                </ns2:IdentificacaoTomador>
                                                <ns2:RazaoSocial>Teste Mariana</ns2:RazaoSocial>
                                                <ns2:Endereco>
                                                    <ns2:Endereco>RUA JARBAS PIMENTA</ns2:Endereco>
                                                    <ns2:Numero>514</ns2:Numero>
                                                    <ns2:Complemento>complemento cobrancaaeAaO</ns2:Complemento>
                                                    <ns2:Bairro>NOVA ERA</ns2:Bairro>
                                                    <ns2:CodigoMunicipio>3504800</ns2:CodigoMunicipio>
                                                    <ns2:Uf>SP</ns2:Uf>
                                                    <ns2:Cep>37170000</ns2:Cep>
                                                </ns2:Endereco>
                                                <ns2:Contato/>
                                            </ns2:Tomador>
                                            <ns2:RegimeEspecialTributacao>0</ns2:RegimeEspecialTributacao>
                                            <ns2:OptanteSimplesNacional>2</ns2:OptanteSimplesNacional>
                                            <ns2:IncentivoFiscal>2</ns2:IncentivoFiscal>
                                        </ns2:InfDeclaracaoPrestacaoServico>
                                    </ns2:DeclaracaoPrestacaoServico>
                                </ns2:InfNfse>
                            </ns2:Nfse>
                        </ns2:CompNfse>
                    </ns2:NfseSubstituidora>
                </ns2:RetSubstituicao>
            </ns2:SubstituirNfseResposta>
        </ns3:substituirNfseResponse>
    </soap:Body>
</soap:Envelope>

Necessito das informações de Código Verificação, Número, e o id da tag infNfse, como consigo, no caso eu preciso <ns2:NfseSubstituidora>que é a segunda parte do xml, como conseguir ?
Comment: Já pensas-te em usar linq? Fica mais facil para fazer a query
Comment: Eu já tentei fazer em linq, porém não tive sucesso, como posso obter em linq ?
Answer: Utilizando LINQ:
var xDoc = XDocument.Load(@"C:\temp\xmlnfse.xml");

XNamespace ns3 = "http://ws.issweb.fiorilli.com.br/";
var result = xDoc.Descendants(ns3 + "substituirNfseResponse");
XNamespace ns2 = "http://www.abrasf.org.br/nfse.xsd";

var infProt = from record in result.Descendants(ns2 + "NfseSubstituidora").Descendants(ns2 + "InfNfse")
select new
{
    Id = record.FirstAttribute.Value,
    CodigoVerificacao = record.Elements(ns2 + "CodigoVerificacao").First().Value
};

string id = string.Empty, codigoVerificacao = string.Empty;
foreach (var element in infProt)
{
    id = element.Id;
    codigoVerificacao = element.CodigoVerificacao;
}
Console.WriteLine($"ID: {id} CODIGO VERIFICACAO: {codigoVerificacao}");
Console.ReadKey();

Comment: Deu certinho, inclui para pegar o número, e funcionou. Obrigado.
Comment: Eu consegui entender já, obrigado.
Comment: Pode tirar uma dúvida minha ?
Comment: @marianac_costa Sim, pode perguntar.

Ler XML com tag (nodes) iguais


search only on taxonomy and user autocomplete drupal 7

Question: I would search only on user and taxonomy in autocomplete but not search in content. I try many modules :

Views Autocomplete
Filters  Search Autocomplete
Custom Search
Term Search

But none complete that ! any clues would be good.
Answer: Filters Search Autocomplete works great for that but there a bug with entity Reference

We can achieve this by following these steps:
Add the required node reference field as relationship.
Add a title field in fields and give them the above relationship.
Add the title in combine filters.
It Worked for me :)

read more on drupal.org


Show that the relation $R$ is closed if and only if $R^{-1}$ is closed

Question: Let $S$ and $T$ be Banach spaces and consider a relation, $R\subseteq S\times T$ in their direct sum. We call a relation closed if $R$ is closed as a subset of the direct sum $S\times T$. We define the inverse relation by $$R^{-1}=\{(t,s)\in T\times S:(s,t)\in S\times T\}\subseteq T\times S.$$
I want to show that $R$ is closed if and only if $R^{-1}$ is closed. Here is my attempt:
First of all notice that the map $M:R\rightarrow R^{-1}$ which assigns $(s,t)\mapsto(t,s)$ is a bijection.
To see that it is a surjection, notice that for every $(t,s)\in R^{-1}$ we find $(s,t)\in R$ such that $M((s,t))=(t,s)$.
On the other hand, to show that it is an injection, consider $(s_1,t_2),(s_2,t_2)\in R$ and suppose that $M((s_1,t_1))=M((s_2,t_2))$. Then $$M((s_1,t_1))=M((s_2,t_2))\implies(t_1,s_1)=(t_2,s_2).$$
Suppose, then, that $R$ is closed in $S\times T$. Then, for every $(s,t)\in S\times T$ there is some sequence $((s_n,t_n))_n$ in $R$ such that $\lim_{n\to\infty}((s_n,t_n))_n=(s,t)$, which happens if and only if $\lim_{n\to\infty}s_n=s$ in $S$ and $\lim_{n\to\infty}t_n=t$ in T.
Then, $M((s_n,t_n))=(t_n,s_n)$ for every $n\in\mathbb N$. But then, we know that $\lim_{n\to\infty}t_n=t$ in $T$ and $\lim_{n\to\infty}s_n=s$ in $S$ so that $\lim_{n\to\infty}((t_n,s_n))_n=(t,s)$ in $R^{-1}$. Hence, $R^{-1}$ is closed in $T\times S$.
Here are my questions on the above:

Is what I have written for the injectivity claim correct? I have tried to proceed by considering $a,b\in X$ for which $f(a)=f(b)$ and showing that this implies $a=b$. Above, starting with $a:=(s_1,t_1)$ and $b:=(s_2,t_2)$ and considering their image under $f:= M$, I haven't exactly obtained that $a=b$, and so I am wondering whether what I have done is sufficient, or if I have overlooked anything.
I have used that $\lim_{n\to\infty}((s_n,t_n))_n=(s,t)$ if and only if $\lim_{n\to\infty}s_n=s$ in $S$ and $\lim_{n\to\infty}t_n=t$ in T. Is it possible to explicate the above to show that the map $M$ is continuous (in fact, an isometry) in order to pass to the limit in $M\lim_{n\to\infty}((s_n,t_n))_n=\lim_{n\to\infty}M((s_n,t_n))_n=\lim_{n\to\infty}((t_n,s_n))_n=(t,s)$ in $T\times S$? Is it the case that one uses this fact without explicating it or not?

My thinking for the claim in 2. here is that $\|M(s,t)\|=\|(t,s)\|=\|(s,t)\|$ for all $(s,t)\in S\times T$.
Answer: I think your proof of bijectivity of $M$ is correct. You could explicate injectivity like this:
$$M((s_1,t_1)) = M((s_2,t_2)) \iff (t_1,s_1) = (t_2,s_2) \iff t_1 = t_2 \; \wedge
 \; s_1 = s_2 \iff (s_1,t_1) = (s_2,t_2).$$
However, I see problems with your proof of closedness of $R^{-1}$.

Suppose, then, that $R$ is closed in $S×T$. Then, for every $(s,t)∈S×T$ there is some sequence $((s_n,t_n))_n$ in $R$ such that $\lim_{n→∞}((s_n,t_n))_n=(s,t)$.

This is actually saying that $R$ is dense in $S \times T$, not closed in $S \times T$.
You could proceed by considering $M$ on the whole space $S \times T$, instead of only on $R$, and showing that $M$ is a homeomorphism (i.e. continuous with continuous inverse). We will show that $M$ is continuous, the case of $M^{-1}$ is analogical.
We need to choose a norm on the product (they are equivalent) - let it be the maximum norm (i.e. $||(s,t)|| = \max \{||s||,||t||\}$).
For that let $(s_n,t_n)_n$ be a sequence in $S \times T$ that converges to a point $(s,t) \in S \times T$. This means that
$$||(s_n,t_n) - (s,t)|| = \max \{||s_n-s||,||t_n-t||\} \rightarrow 0,$$
hence,
$$||s_n - s|| \rightarrow 0; ||t_n-t|| \rightarrow 0.$$
But now
$$||M((s_n,t_n)) - M((s,t))|| = ||(t_n,s_n) - (t,s)|| = \max \{||t_n - t||,||s_n - s||\} \rightarrow 0$$
and $M((s_n,t_n)) \rightarrow M((s,t))$. We showed that $M$ is continuous.
Now, $R^{-1} = M(R)$ is closed as it is a homeomorphic image of a closed set.
I would also like to mention that this statement remains true if $S,T$ are just topological spaces and we endow $S \times T$ and $T \times S$ with the product topology.


Efeito texto ou paragrafo carregando

Question: Ola.
Venho observando em varios sites. Facebook, Dropbox e varios frameworks que usam css e js um efeito que aparece antes do texto ser carregado. Espero que entendam. Obrigado
Answer: Isso é uma técnica utilizada na experiência do usuário. Um ótimo artigo chamado The Illusion of Time (A Ilusão do Tempo) explica muito bem sobre como a percepção humana do tempo pode ser "driblada" utilizando de recursos simples como um gif animado, veja o exemplo do Facebook abaixo.

A construção desse recurso depende de qual framework ou biblioteca que você está utilizando em seu projeto.
O artigo Facebook content placeholder deconstruction (Desconstrução do placeholder de conteúdo do Facebook) demonstra como é feito essa técnica desconstruindo a mesma utilizada pelo Facebook.
Comment: legal +1 esse eu não conhecia ...

Efeito texto ou paragrafo carregando


Spambot creates 4000 orders a day

Question: Our webshop (built in Drupal 7 and Drupal Commerce) gets bullied by a SPAMBOT which creates about 4000 orders a day. These orders are getting registered as created by 'Anonymous' (unchecked) and stay stuck in the 'Shopping Cart'
Apparently, the Spambot creates these orders by adding a product to the shopping cart on the product overview page (a custom built view with all products and for every product item  an Add to cart button).
Under each 'Add to cart' button, there's a hyperlink. We've already attributed a 'NOFOLLOW' link to those hyperlinks, but the issue still persists.
Our initial set-up for the 'add to cart' button for each product on the Product Overview Page was that people could instantly add a product to the shopping cart without first having to visit the product page.
On the other hand, we chose to offer customers the opportunity to pay as a guest. This, as well, to rule out as many stumbling blocks as possible during the ordering process, which may discourage customers.
Does anyone have a possible solution, preferably a solution that does not compromise the user experience (or has as little impact as possible on the UX?).
Answer: Blocking is hard. Honeypot is a good deterrent, but if you allow anonymous users to click links that add products, then having spam orders might be your new reality. Removing useless, old carts is easy.
We use Commerce Cart Expiration on a number of stores. Also, sometimes its preferable to delete orders outright based on some criteria. For that, you can use Commerce Order Cleanup utility module.
Answer: First off you should block the IP off the spam bot to stop all the orders coming through. This can be done in standard Drupal interface in D7.
Then install some or all of these modules. https://www.drupal.org/project/recaptcha is very good and may solve your problems. This is by Google and blocks known threats from your site, which probably include your daily visitor.
In the past I have had great results from using the Botcha module. This also uses a honeypot field to trick the spam bots. This will solve your UX issues as it works in the background and will reduce your spam considerably.
Maybe later, if you are going to create user accounts to your store, verify the users email using a verify, for example with the Email Verify module.
Comment: Honeypot is a worthwhile module to look at, you can add it to product pages: https://www.drupal.org/project/honeypot

Spambot creates 4000 orders a day


JavaFX DatePicker with better typing features

Question: Let's suppose we have a DatePicker without a date set.
So if the user wants to type a date, he need to type the entire date, including the slashes:
10/11/2014
It would be good if as the user types the numbers, the slashes could be automatically included (typing 10112014 would set the date correctly).
Another thing is, if there is already a date set on the date picker (10/11/2014), and the user wants to type another date (01/11/2014), then he puts the cursor on the beginning of the text and types the date. The result would be something like 01/11/201410/11/2014. It would be better if when typing on the field of the date picker, it went automatically into insert mode, so as the user types the date it overwrites the original date.
Is there a way to do these things?
--- UPDATE---
Thanks to José Pereda, i found the solution. I got his code and changed a bit:
public static void enhanceDatePickers(DatePicker... datePickers) {
for (DatePicker datePicker : datePickers) {
    datePicker.setConverter(new StringConverter<LocalDate>() {

        private final DateTimeFormatter fastFormatter1 = DateTimeFormatter.ofPattern("ddMMuuuu");
        private final DateTimeFormatter fastFormatter2 = DateTimeFormatter.ofPattern("d/M/u");
        private final DateTimeFormatter defaultFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

        @Override
        public String toString(LocalDate object) {
            return object.format(defaultFormatter);
        }

        @Override
        public LocalDate fromString(String string) {
            try{ return LocalDate.parse(string, fastFormatter1); } catch(DateTimeParseException ignored){}
            try{ return LocalDate.parse(string, fastFormatter2); } catch(DateTimeParseException ignored){}
            return LocalDate.parse(string, defaultFormatter);
        }
    });

    TextField textField = datePicker.getEditor();
    textField.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (!"0123456789/".contains(event.getCharacter())) {
            return;
        }
        if ("/".equals(event.getCharacter()) && (textField.getText().isEmpty() || textField.getText().charAt(textField.getCaretPosition()-1)=='/')) {
            //If the users types slash again after it has been added, cancels it.
            System.out.println("Cancelando o bagulho!");
            event.consume();
        }
        textField.selectForward();
        if (!event.getCharacter().equals("/") && textField.getSelectedText().equals("/")) {
            textField.cut();
            textField.selectForward();
        }
        textField.cut();

        Platform.runLater(() -> {
            String textUntilHere = textField.getText(0, textField.getCaretPosition());
            if (textUntilHere.matches("\\d\\d") || textUntilHere.matches("\\d\\d/\\d\\d")) {
                String textAfterHere = "";
                try { textAfterHere = textField.getText(textField.getCaretPosition()+1, textField.getText().length()); } catch (Exception ignored) {}
                int caretPosition = textField.getCaretPosition();
                textField.setText(textUntilHere + "/" + textAfterHere);
                textField.positionCaret(caretPosition+1);
            }
        });
    });
}

}
Then, to "enhance" the DatePicker i just call this method passing all my desired datePicker instances as parameters
Comment: Sure, just call it like this: `enhanceDatePickers(myFirstDatePicker, anotherDatePicker, andSoOn)`. This works because the method uses varargs (`Datepicker... datePickers`) which accepts how much parameters of that type as you wish to pass...
Comment: toString() should handle a null LocalDate (NPE if there isn't a date set)
Comment: Is there any way to reuse this code on multiple fields? or I have to reapeat the same on any field?
Comment: Thanks, this help me a lot and saves me lots of lines of code. I'm starting with JavaFX so I'm a little lost yet.
Answer: Actually, you can do both requests.
The first part is easy, since you can use more than one date converter. Let's say you have a default format "dd/MM/uuuu" and a fast format "ddMMuuuu":
private final DateTimeFormatter fastFormatter = DateTimeFormatter.ofPattern("ddMMuuuu");
private final DateTimeFormatter defaultFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

Then you have to provide your custom converter, keeping the default format for toString() method and modifying fromString() so you can type with any of your formatters:
DatePicker datePicker=new DatePicker();
datePicker.setValue(LocalDate.now());
datePicker.setConverter(new StringConverter<LocalDate>() {

    @Override
    public String toString(LocalDate object) {
        return object.format(defaultFormatter);
    }

    @Override
    public LocalDate fromString(String string) {
        try{
            return LocalDate.parse(string, fastFormatter);
        } catch(DateTimeParseException dtp){}

        return LocalDate.parse(string, defaultFormatter);
    }
});

For the second request (keeping in mind you can type with or without slashes), you can simulate an insert mode by deleting the next character on the editor after you type one valid character.
Assuming you always type the slashes this will do:
datePicker.getEditor().setOnKeyTyped(event -> {
    if (!"0123456789/".contains(event.getCharacter())) {
        return;
    }
    datePicker.getEditor().selectForward();
    datePicker.getEditor().cut();
});

But if you don't type them you need to delete not only the next digit but also the next slash on the editor:
datePicker.getEditor().setOnKeyTyped(event -> {
    if (!"0123456789/".contains(event.getCharacter())) {
        return;
    }
    datePicker.getEditor().selectForward();
    if(!event.getCharacter().equals("/") &&
       datePicker.getEditor().getSelectedText().equals("/")){
        datePicker.getEditor().cut();
        datePicker.getEditor().selectForward();
    }
    datePicker.getEditor().cut();
});

Note this will be valid either if you use slashes or not. Also notice you will have to type the 0 leading digit when necessary.
Comment: Unfortunately there is no `datePicker.getEditor().getSelection().clear()` or alike. A more cumbersome way could be `datePicker.getEditor().replaceText(datePicker.getEditor().getSelection(), "")`.
Comment: Very good! I changed it a little bit to fit my needs, gonna update my question with my code.
Comment: Thanks for posting back your solution.
Comment: Why use cut() (to clipboard)?
Comment: To remove just the current selection
Comment: I mean, was it just a convenient shortcut, or is there no other good way for doing this?  It's kinda like using the clipboard as a dumping ground - might annoy users.


Duvida com listas dinamicas

Question: No caso necessito gerar 5 numeros aleatorios, e inseri-los em uma lista dinamica, venho tentando, mas o maximo que consigo é gera-los e exibi-los
segue codigo:
<code>#include <iostream>
#include <cstdlib>//Biblioteca responsavel por numeros aleatorios
#include <ctime>//Biblioteca responsavel por numeros aleatorios
#include <list>//Biblioteca responsavel por criar listas

#define PCT 5
using namespace std;

typedef struct Album{
    int figura;
    Album *prox;
/*  list<int> album;
    int tam;

    tam=681;

    for(int i=tam; i>0; i--){
    album.push_front(i);
    }
    cout<<"Album da copa 2018 - total "<<album.size()<<" figurinhas"<<endl<<endl;

    tam=album.size();
    for(int i=0; i < tam; i++){
        cout<<album.front()<<endl;
        album.pop_front();
    }*/
};
    Album *inicio = NULL;
    Album *fim = NULL;
    Album *aux;
    Album *anterior;

void Pacote(){
    system("cls");

    srand((unsigned)time(0)); //para gerar numeros aleatorios reais.
    for (int i=0; i<PCT; i++){
        int maior = 681;
        int menor = 1;
        int Figurinha = rand()%(maior-menor+1) + menor;
        cout << Figurinha << endl;  }
        //Valida();

    Album *novo = new Album();
    cin>>novo->figura;
        if (inicio==NULL){
            inicio = novo;
            novo->prox=NULL;
        }
        else{
            anterior=NULL;
            aux=inicio;
            while (aux != NULL && novo -> figura > aux->figura){
                anterior = aux;
                aux = aux->prox;
            }
            if (anterior==NULL){
                novo->prox=inicio;
                inicio=novo;
            }
            else if (aux==NULL){
                fim->prox=novo;
                fim = novo;
                fim->prox=NULL;
            }
            else{
                anterior->prox=novo;
                novo->prox=aux;
            }

        }
}

/*void Valida(int Figurinha, list<int> album){
    if (Figurinha ){

    }*/

void Menu(){
    int x=0;
    system("color F0");
    do{
        cout<<"==========ALBUM DA COPA========="<<endl;
        cout<<"1 - Inserir novas figurinhas"<<endl;
        cout<<"2 - Exibir album"<<endl;

        cout<<endl<<endl<<"Selecione uma das opcoes acima :"<<endl;
        cin>>x;

        switch (x){
            case 1:
                Pacote();
                break;
            case 2:
                Album();
                break;
        }
    }while (x!=5);
}

int main(int argc, char** argv) {
    Menu();
    return 0;
}
</code>
Answer: Você pode fazer como abaixo:
<code>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <utility>
#include <list>

int main() {
    std::srand(std::time(nullptr));
    int quantidade = 5;
    int cap = 682;
    std::list<int> lista;
    float rand_number;
    for(int i=0; i<quantidade; ++i) {
        rand_number = rand()%cap;
        lista.push_front(std::move(rand_number));
    }
    for (const int& l : lista)
        std::cout << l << ' ';
    std::cout << '\n';
    return 0;
}
</code>

Duvida com listas dinamicas


how to say every point of $D_n$ is an isolated point?

Question: Let $f$ be any real function. Show that $f$ has at most countably many jump discontinuities (discontinuities of the first kind).
The proof outline is Let $E$ be the domain of $f$.
For brevity, let $f_+(a)$ denote $\lim_{x→a+} f(x)$ and let $f_-(a)$ denote $\lim_{x→a-} f(x)$.
For each positive integer $n,$ define $D_n = \{a ∈ E : |f_+(a) − f_-(a)| ≥ 1/n\}$.
How to show that every point of $D_n$ is an isolated point. The hint is [Otherwise, a one-sided limit fails to exist.]
I don't know how to say every point of $D_n$ is an isolated point?
Answer: I am writing a long answer. I am not proceedig in the way as has been hinted at. If we consider the hint, the answer might be much shorter.
Let us assume that $D_n$ is infinite. Otherwise every element should be isolated. Suppose an element $a$ of $D_n$ is not isolated. What does it mean? Given any $\delta>0$, the neighbourhood $(a-\delta, a+\delta)$ contains infinitely many points of $D_n$. Without loss of generality let us assume that given any $\delta>0$,  $(a-\delta, a) \cap E$ has infinitely many elements of $D_n$. Then it is possible to construct a sequence $x_k$ in $D_n$ converging to $a$ such that $x_k < a$. Fix $\epsilon < \frac{1}{4n}$. Then it is possible to find $\delta$ such that whenever $x\in A = (a-\delta, a) \cap E$,
$$|f(x)-f_-(a)| < \epsilon.$$
Choose an $x \in A$ and $x\in D_n$. Both $f_-(x)$ and $f_+(x)$ exist. Further it is possible to choose $\delta_1$ such that $x+\delta_1 < a$, $a-\delta < x- \delta_1$ and
$$|f(y)-f_-(x)| < \epsilon, \quad \forall y\in (x-\delta_1, x) \cap E$$
and
$$|f(y)-f_+(x)| < \epsilon, \quad \forall y\in (x, x+\delta_1) \cap E.$$
Let $y_1\in (x-\delta_1, x)\cap E$ and $y_2 \in (x, x+\delta_1)\cap E$. Then by our construction,
$$|f_-(x) - f_+(x)| = |f_-(x) - f(y_1) -f_-(a)+f(y_1) +f_-(a) - f(y_2) - f_+(x) + f(y_2)| \leq 4\epsilon < \frac {1}{n}.$$
So what we proved is that, if some element of $D_n$ is not isolated, then it is possible to have an element $x$ in $D_n$ such that $|f_-(x)  - f_+(x)| < \frac{1}{n}$.
Answer:
How to show that every point of $D_n$ is an isolated point.

Suppose, to the contrary, that $a\in D_n$ has the property that $(a, a+\varepsilon)$ intersects $D_n$ for every $\varepsilon>0$.
This assumption means that $|f(b)-f_+(a)|>1/3n$ for at least one $b\in(a,a+\varepsilon)$ -- namely a point close enough to one of the sides of the jump of size $\ge 1/n$ we're assuming exists in $(a,a+\varepsilon)$.
Can you go the rest of the way now?
Comment: where does 1/3n come from?
Comment: @Mariana: I'm jumping over a few intermediate arguments here. The basic point is that if $a$ is _not_ isolated, then either $(a,a+\varepsilon)$ contains points in $D_n$ for every $\varepsilon$, or $(a-\varepsilon,a)$ does. (I'm then sketching the argument that would follow in the first of two cases). To wit: if neither of these are true then there must be $(a-\varepsilon_1,a)$ and $(a,a+\varepsilon_2)$ that are both disjoint from $D_n$ -- but that would mean exactly that $a$ is isolated because it's the only point in $D_n\cap(a-\varepsilon_1, a+\varepsilon_2)$.
Comment: @Mariana: $1/3n$ is a number I pulled out of a hat -- the only thing important about it is that it is strictly smaller than half of the jump height.
Comment: I don't know what does your f(b) mean.
Answer: Suppose $x\in \overline {D_n\setminus \{x\} }$. Then WLOG let $(y_j)_{j\in \Bbb N}$ be a strictly increasing sequence of members of $D_n$ converging to $x$. For $j\ge 2$ there exists $u_j\in (y_{j-1},y_j)$ and $v_j\in (y_j,y_{j+1})$ such that $|f(u_j)-f(v_j)|>1/2n$ because $y_j\in D_n.$
Then $x\not\in D_n$
because $f_-(x)$ does not exist
because otherwise $f_-(x)=\lim_{j\to\infty}f(v_j)\ge 1/2n+\lim_{j\to\infty}f(u_j)=1/2n+f_-(x).$
Remark: If $x\in \overline {D_n\setminus \{x\} }$ there is  a strictly increasing or strictly decreasing sequence in $D_n$ converging to $x$. Here, "WLOG" ("without loss of generality") is mathspeak for "the other case is handled in the same manner and I assume this is obvious so do it yourself."


ActiveStorage: How to validate content of file?

Question: I would like to read the content of a file that is to be uploaded in a custom validation. Is it possible?
So far, I've seen that it's possible to perform some validations on the file's metadata (extention, size...) but not on it's content. I've also seen this question that's a bit similar, even though I don't want to modify the file. I just want to read it in a custom validation.
Answer: It seems like you can access the file being uploaded and simply read it in the validation.
For Example
class User < ApplicationRecord
  has_one_attached :resume

  validate :resume_contents

  private
    def resume_contents
      return unless record.send(attribute).attached? && !record.attachment_changes['resume'].blank?
      file = record.attachment_changes['resume'].attachable
      if file.is_a?(ActionDispatch::Http::UploadedFile) && file.read =~ /bad content/i
        errors.add(:resume, :invalid, message: 'cannot contain bad content')
      end
    end
end

For a more in depth implementation you could refer to the active_storage_validations gem:

File Access
File Reading
Comment: Correct me if I'm wrong but If `self.resume.is_a?(ActionDispatch::Http::UploadedFile)` returns `true`, it means that the file has already been uploaded. Since the file upload happens when the record is inserted, it's not possible to access the uploaded file is about to be created (in a validation).
If I tried to read the unread record, I get the following error:
```eval error: undefined method `read' for #<ActiveStorage::Attached::One:0x00000001170f0178```
Comment: @DavidB. updated based on a further code dive through the gem. While I have no where to actually validate this I would like to answer the questions you posed. "*If self.resume.is_a?(ActionDispatch::Http::UploadedFile) returns true, it means that the file has already been uploaded"* this is incorrect. The file has been uploaded via a form (e.g. multipart form data) this doe not mean it  has been uploaded to your data repository (i.e. S3)...
Comment: *"it's not possible to access the uploaded file is about to be created (in a validation)"* this is incorrect. The file data must be sent to the server so that it can even be uploaded so this information does exist on the server side and can be validated


stream list into a set

Question: I am looking to refactor how I have used a stream in some of my code.  The first example is how I currently have done it.  The second example is what im trying to make it look like.
Set<String> results = new HashSet<String>();

someDao.findByType(type)
            .stream()
            .forEach(t-> result.add(t.getSomeMethodValue()) );

Could it look something like this?  If so how do I make it do it?
Set<String> results = someDao.findByType(type)
            .stream()
            .collect(  /*  ?? no sure what to put here  */ );

Comment: You need to map the Stream elements before collecting them into the Set. `someDao.findByType(type)
            .stream().map(TheClass::getValue).collect(toSet());`
Answer: Use Collectors.toSet :
Set<String> results = someDao.findByType(type)
        .stream()
        .map(ClassName::getValue)
        .collect(Collectors.toSet());

stream list into a set


What function does an E major chord serve in the key of C major?

Question: E or E7 chords seem to work very well in the key of C, particularly at the end of a line/verse before a powerful chorus for instance.
As one example I end a verse on Am - E... hang on the E then jump into a chorus line F - C - G - Am.
Clearly Em is the minor 3rd chord but musically, what is E or E7 and why do they work so well?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/115254/discussion-on-question-by-mr-boy-what-function-does-an-e-major-chord-serve-in-t).
Answer: It's a secondary dominant. As such, it can be used to move to its own tonic, in this case, A minor. Other secondary dominants in key C are B7, leading to Em, and A7, leading to Dm. Both the Dm and Em are diatonic chords in key C.
There are also C7, which is non-diatonic, to lead to F, and D7, leading to the dominant G. So, the dominant of the dominant, or V/V.
Your E moving to F could be called a deceptive cadence - not going where expected.
It seems that secondary dominants don't have to go directly to their 'tonics', but they often do.
Comment: You know how a leading note works. it's as close to the target tonic as it can get. Gives that feeling of 'we know what come next'. The E chord (rather than E7) has the same effect when moving to F. Every note is a sort of 'leading note' moving one semitone up to its equivalent position in chord F. But its *function* is sec. dom.
Comment: Interesting. In my case I hang on E, then jump into a chorus line F - C - G - Am
Comment: Actually, dominant chords really only lead over to a third which may be the low or high third of the target chord. As such, an E major chord does not care whether it leads over to an F major or an A minor chord, they both include the A-C minor third to which the G#-B leads over. E7 can also lead over to the A-C# major third (from the G#-D tritone), which is part of F# minor and A major. So, an E7 can target any of F major, F# minor, A minor, A major.
Answer: As mentioned in (the original version of) Tim's answer, it's indeed a secondary dominant, but I'd like to add that the resolution E7 to F is a specific resolution called deceptive resolution, and it occurs a lot, in almost any style of music. Note that F major and A minor share two out of three chord tones, so it's not so surprising that this type of resolution also works. A different, less used type of deceptive resolution in C major is the cadence G7 to Am.
Answer: E (or E7) is the dominant of the relative minor of C major.   Therefore very much 'home territory'.   Not diatonic, but pretty darn close!
And E leads well to F because all three notes move up by a semitone.  Like leading notes do.
I have a theory of 'honorary diatonic' chords that include (in C major context) E and E7, B♭, C7 and Fm (when used in the cliche 'Saints' C, C7, F, Fm, G7, C ending sequence). Maybe also any secondary dominant that doesn't progress to an established modulation and any ♭5 substitution for one.   My 'honorary diatonics' are chromatic chords that DON'T lose their contact with the home tonality.   They don't need to be described in relation to some supposed change of key centre, or as a 'borrowing'. E7 - F doesn't have to be explained away as a frustrated cadence to A minor, it can have a legitimate identity as III7 - IV in C major.
Once we admit that a B♭ or E7 chord 'belongs' in C major and doesn't have to be described as related or 'borrowed' from some other key, analysis gets much simpler!
Comment: Music theory terms are already pretty badly overloaded with context-dependent meanings, so I can't agree on the honorary diatonic thing. :) I do understand your annoyance with so quickly talking about modulations as an explanation of just about any chromatic note, but  borrowed chords undeniably do modify the harmonic feeling and sense of which notes fit that feeling and which don't. "Modal mixture" isn't a bad word. We take another related mode and mix parts of it into the current one, creating some kind of a hybrid. Which is usually soon morphed back to the original one.
Answer: As mentioned before, E or E7 in the key of C usually acts as a secondary dominant. It's the dominant of both A major and A minor chords. It's often used in progression like E-A-D-G-C (perhaps with some sevenths or minors instead of major chords here.) The other important case is E-a; in this case, it's the dominant of the relative minor. Moving between a key and its relative minor is very common. Check out "Delilah" by Tom Jones. (In reverse, one could have a Folia Progression based on A minor so one would get a-E-a-G-C-G-a-E-a.)
In a Cycle of Fifths (a.k.a. Circle of Fifths) progression in a major key, the viiº chord is often omitted so one gets (in C major), C-F-E-a-d-G, skipping the tritone progression and the diminished chord. As an aside, in a minor key (c-minor) the whole Cycle of Fifths is commonly used as the diminished chord occurs in a "nice" place: c-f-Bb-Eb-Ab-dº-G-c.
Answer: One thing to add to the secondary dominant/deceptive resolution thing is this: a dominant is a harmonically stable chord to end a phrase on (exluding the final ending.)
If the structure of the section is something like...
| ...Am E :||: F | C G | Am...
It may make more sense to describe the part before the double bar repeat a kind of incomplete, half cadence ending. After the repeat C G | Am... would seem more of a deceptive progression. If the E and F belong to separate sections, it doesn't make much sense identifying a deceptive cadence/progression there, because they are separated.
I put a double bar repeat in that example just to make clear I'm indicating separate song sections. You may not actually have repeats or sections like that in your song.
Comment: FYI in my example it is only the last line of the verse that hangs on E, before we make a jump into an enthusiastic chorus. Guess we'd say the E is building tension
Comment: 'A dominant is a harmonically stable chord to end a phrase on'. If you mean the song coud end there, I have to disagree. The point of dominants is that they feel like they're pushing towards the tonic, therefore, can't really be stable. What did I miss?
Comment: @Tim, I made an edit to account for the final ending. Otherwise the idea is half _cadence_. The aren't final, but they still mark endings, are points of rest.


What is the lowered supertonic note called, especially in Phrygian and Locrian modes?

Question: I know most scales/modes like Ionian (major), Dorian, Lydian, Mixolydian and Aeolian (natural minor) have a major second note called the supertonic, but some scales/modes like Phrygian and Locrian have minor seconds above tonic making me wonder if there is a specific name for a lowered supertonic note.
Answer: It's still called the supertonic. It might be called the "flatted supertonic" if being discussed in relation to another mode.
"Supertonic" refers to the second note of a diatonic scale, independent of the interval between it and the tonic.
Answer: In the spirit of the accepted answer of Other than scale-degree 7, do other scale degrees have names for their altered forms?, one may choose to refer to this as the hypo-supertonic, but I've never heard that term used, and would frankly advise against it.
Colloquially, plenty of musicians refer to this as "flat 2" or "the Phrygian 2" (the latter of which also applies to the Neapolitan chord, ♭II).
I've also heard "upper leading tone" used to refer to anything a half step above a pitch of resolution. Thus in minor ♭6 could be an "upper leading tone" to scale-degree 5, and I've heard this lowered 2 described as an upper leading tone to 1.


How to dynamically change connection string ASP.NET

Question: I'm developing an application that relies on ASP.NET C# for the back-end. I'm trying to change the connection string on the controller depending on what's coming from the request.
Example:
POST 1: access to server 10.126.0.1 db: db_manager
POST 2: access to server 10.126.0.2 db: bd2_manager
The ip and db are supposed to be input to the request and change it accordingly.
I'm currently defining the connection string in the Startup.cs (ConfigureServices method) file like this:
 string connectionString = Configuration.GetConnectionString("connection");

            services.AddSingleton<INHibernateSessionFactory>(provider => new NHibernateSessionFactory(connectionString));
            services.AddScoped(provider => provider.GetRequiredService<INHibernateSessionFactory>().OpenSession());
            services.AddScoped<IDataContext, DataContext>();

I'd like to know how can I define and change the connectionString dynamically for the duration of the request, instead of statically in the startup.
Answer: You can't change the settings based on the http request in ConfigureServices. Instead you should implement an abstract factory. A full response with example you may find here:
How to configure services based on request in ASP.NET Core
Comment: Thanks for your help!


Understanding the terms in motion of a particle along a parametric curve

Question: OK so I'm doing motion of a particle along a parametric curve we call $R(t)$. We have acceleration in terms of a unit normal vector and unit tangent vector. Acceleration at a point is given by
$\vec{a} = \frac{d^2s}{dt^2}\vec{T}+\left(\frac{ds}{dt}\right)^2\cdot\frac{d\phi}{ds}\cdot\vec{N}$
Where $\vec{T}$ and $\vec{N}$ are the unit Tangent and normal vectors. My doubts are as follows :

I can understand $\frac{ds}{dt}$ but not $\frac{d^2s}{dt^2}$. How do I visualize it?
I know $\frac{d\phi}{ds}$ is the rate of change of $\phi$ with respect to arc length. But how do I perceive that?
Finally we have $\vec{T}=\cos\phi\hat{\imath} + \sin\phi\hat{\jmath}$ and we say $\frac{d\vec{T}}{d\phi}$ is $\vec{N}$. But we can write it also as $\vec{T}=\frac{dx}{dt}\hat{\imath}+\frac{dy}{dt}\hat{\jmath}$. Now suppose I want to differentiate this with respect to ϕ then what? Also how do I visualize this because there are so many terms like $\frac{d}{d\phi}(\frac{dx}{dt})$.
Comment: Write in TeX please
Comment: I've changed as much as I could have
Answer: $\newcommand{\Vec}[1]{\mathbf{#1}}$To address your first two questions, let's assume your curve is regular, i.e., that the velocity $R'$ is nowhere-vanishing. Writing
$$
R'(t) = \|R'(t)\|\, \frac{R'(t)}{\|R'(t)\|} = v(t) \Vec{T}(t)
$$
uniquely expresses the velocity vector as a magnitude (the speed $v(t) = \frac{ds}{dt}$) and a direction (the unit vector $\Vec{T}(t)$).
Differentiating again, using the product rule, gives
$$
R''(t) = v'(t) \Vec{T}(t) + v(t) \Vec{T}'(t).
\tag{*}
$$
The first summand is obviously parallel to the velocity. The second is orthogonal to the velocity: differentiating $\Vec{T}(t) \cdot \Vec{T}(t) = 1$ gives $\Vec{T}(t) \cdot \Vec{T}'(t) = 0$.
In words, (*) decomposes the acceleration into tangential and normal components. Respectively, these terms correspond to the change in speed $v'(t) = \frac{d^{2}s}{dt^{2}}$ (along the direction of motion) and the change in direction. (If $\Vec{T}'(t_{0}) \neq 0$, there is a unique circle lying in the plane through $R(t_{0})$ and spanned by $\Vec{T}(t_{0})$ and $\Vec{T}'(t_{0})$ that agrees with $R(t)$ to second order. If this circle has radius $r$, it turns out that $v(t_{0}) \|\Vec{T}'(t_{0})\| = \frac{v(t_{0})^{2}}{r}$, a well-known formula for centripetal acceleration.)
All of the preceding carries through for arbitrary regular curves, not just plane curves.
As for the third item, for a Euclidean plane curve the unit vector $\Vec{T}$ may be written as $(\cos\phi) \Vec{i} + (\sin\phi) \Vec{j}$, in which case
$$
\frac{d\Vec{T}}{d\phi} = (-\sin\phi) \Vec{i} + (\cos\phi) \Vec{j}
$$
is orthogonal to $\Vec{T}$. (This usage of Leibniz notation is likely to cause grief, as you've already noticed, though it expresses a simple idea: When a unit vector rotates, its "rate of change with respect to angle" is an orthogonal unit vector.)
The formula $\Vec{T}(t) = \frac{dx}{dt}\, \Vec{i} + \frac{dy}{dt}\, \Vec{j}$ is not correct unless the curve happens to have unit speed.
Comment: 1)Thank you for your answer. My main question is how do I physically view d²s/dt²
Comment: Also how do u find and view dϕ/ds?.. Also please answer the last part of my question meaning d/dϕ((dx/dt)) or d/dϕ((dy/dt))
Answer: If you are driving a car along a windy road, $d^2s/dt^2$ is the acceleration you feel in the direction of motion of the car. The numerical value of this acceleration is proportional to the numerical value of the forward push of force you feel from the car seat behind you, if your foot is pressed hard on the accelerator pedal creating a positive value of $d^2s/dt^2$, or the backward pull of force you feel from the seat belt across your chest, if your foot is on the brake creating a negative value of $d^2s/dt^24.
If the car is maintaining constant speed, and so $ds^2/dt^2=0$, and hence the car is not accelerating in the forward direction at all, you are feeling no push at all from your seat nor pull from your seat belt. You will, of course, feel a push to one side or another depending on the direction of curvature of the road, and that push represents a force which is proportional to the perpendicular component of the acceleration.
For another example, race car drivers learn the concept of "accelerating through a curve", which means keeping your foot on the pedal and speeding up as you go around a curve (do not try this on your friendly neighborhood streets; and, frankly, I do not know why they learn this concept, but so I am told from friends who took racing courses). When you accelerate through a curve in this manner, you will feel a combination of pushing from the seat behind you ($d^2s/dt^2$, which is the tangential component of acceleration) and pull to the side opposite the curve (which is the normal component of acceleration). The resultant force will then be a diagonal push from behind and one side.
ADDED: You also ask about the normal component of acceleration, which is $\bigl(\frac{ds}{dt}\bigr)^2 d\phi/ds$. You can easily compute $d\phi/ds$ along a circle of radius $r$: the total angle equals $2\pi$, and the total length equals the circumference equals $2\pi r$, so $d\phi/ds = \frac{1}{r}$. Physically this means that as you drive a car around in a circle, the normal component of acceleration is inversely proportional to the radius, hence you feel a pull to the side (in the direction away from the inside of the circle) which is inversely proportional to the radius.
We know this intuitively: when driving around tight curves (small $r$, large $1/r$) we feel a lot of centrifugal force and our bodies are pulled hard to the side; driving around shallow curves (large $r$, small $1/r$) we barely feel the centrifugal force at all.
Answer: If you take a multi-flash photograph of a falling object which starts from rest with a high flash rate (like a stroboscope say 100 per sec) on the same photographic plate of a camera, then the  separation between images of the object is observed to increase with each image. This is because speed $ds/dt$ is increasing. However acceleration of gravity ensures next such $ \dfrac{d^{2}s}{dt^2}$ to be constant.Consult any text book of physics.
$d\phi/ds$ is curvature, reciprocal of the radius of curving. It is a measure of how sharply the path is bending.
The third is obtained during differentiation procedure, has no big physical meaning.


Symfony doctrine convert from db to Entity comments are missing

Question: I'm using this official tutorial to generate entityies from database, all works well except db column comments they are totally missing.
When i run this mapping import command in xml i see column comment
php bin/console doctrine:mapping:import --force AcmeBlogBundle xml

right after running
php bin/console doctrine:mapping:convert annotation ./src

when i open Entity/SomeTable.php some_column (which had comment in database) dose not have options={"comment":"some comment"} in annotation
So do i miss some option for convert command or it is bug of doctrine/symfony and is there a solution for this ?
Note: i have tested this with both symfony2 and symfony3 issue is same
Answer: Currently there is no option that will convert your comments and add it to the entity class. The Entity geneartion can be seen in the DoctrineBundle of Symfony in the class Doctrine\ORM\Tools\EntityGenerator this class says it all:

Generic class used to generate PHP5 entity classes from ClassMetadataInfo instances.

So in easy words the mapping you create in xml is then read as ClassMetadataInfo and the EntityGenerator generates the entity class from that ClassMetadataInfo. If you want you can try to add an implementation for the comment or propose a PR or bug in the symfony git repository.
See generateFieldMappingPropertyDocBlock method of the Doctrine\ORM\Tools\EntityGenerator class and see if you can manage to understand the code and add your comment from there.
Answer: Based on @SimeonKolev answer i was able to implement simple fix for this issue in doctrine/orm/lib/Doctrine/ORM/Tools/EntityGenerator.php to have options={"comment"=".."} filled in each Entity
Solution was add in EntityGenerator.php method generateFieldMappingPropertyDocBlock before if (isset($fieldMapping['unsigned']) ... condition near to ~1652 line
if( isset($fieldMapping['options']) && is_array($fieldMapping['options'])
    && isset($fieldMapping['options']['comment']) ){

    $column[] = 'options={"comment"="'.$fieldMapping['options']['comment'].'"}';
}

Comment: Very nice, see if you can manage to propose a PR against the doctrine bundle repo.


Jquery não funciona com o  carregado com Ajax

Question: A função jQuery funciona normalmente mas ao incluir o input ajax o jQuery não funciona para o input que foi incluído!
Tenho a função:
$('.alerta').on('input', function() {
    alert('Olá mundo!');
})

Tenho o input número 1 funcionando com a função acima:

    Número 1:

    <input class="alerta" type="text" name="x"/>

Tenho o ajax que inclui o input número 2 na classe="div", mas esse não funciona com a função do jQuery.
<?php
echo 'Número 2:

<input class="alerta" type="text" name="y"/>

';
?>

Comment: Obrigado ficou bem melhor é que sou novo aqui e estou aprendendo ainda a formatar os textos
Answer: Tentou colocar assim?
$('body').on('click', '#botao', function (e) {
   alert('teste');
});

Comment: Obrigado Marcel! Funcionou
    $('body').on('input', '.alerta', function (e) {
           alert('Olá mundo!');
    });


Leitura na mesma linha

Question: Tenho uma struct para definir o tipo DATA.
typedef struct data {
    int ano, mes, dia;
}DATA;

DATA nasc;

Agora, passo a ler essas informações a partir da entrada do usuário.
printf("Digite sua data de nascimento");
scanf("%d", &nasc.dia);
printf("/");
scanf("%d", &nasc.mes);
printf("/");
scanf("%d", &nasc.ano);

Gostaria de fazer isso de uma maneira melhor. Lendo as três entradas na mesma linha e imprimindo o caracter / depois de cada entrada.
Como posso fazer isso?? Como continuar na mesma linha depois de um input??
Answer: Basta fazer da seguinte forma:
scanf("%d/%d/%d", &nasc.dia, &nasc.mes, &nasc.ano);

Lembrando que o usuário precisará escrever a data utilizando as barras.
Exemplo funcional no ideone
Comment: Isso ajuda bastante! Mas ainda gostaria de saber se tem como inserir as barras entre as entradas... por uma questão de interface.
Answer: Em ambiente Windows, você poderia tentar algo do tipo:

#include &ltstdio.h>
#include &ltconio.h>
#include &ltstring.h>

typedef struct data {
   int ano, mes, dia;
}DATA;

int aux(char str[]){

   int my_number;
   str[0] = getche();
   str[1] = getche();
   my_number = atoi(str);
   return my_number;
}

int main(){

   DATA nasc;

   char str[3];
   str[2] = '\0';

   printf("Digite sua data de nascimento.\n");
   printf("  /  /\r");
   nasc.dia = aux(str);
   printf("\r%.2d/  /\b\b\b", nasc.dia);
   nasc.mes = aux(str);
   printf("\r%.2d/%.2d/", nasc.dia, nasc.mes);
   nasc.ano = aux(str);

   printf("\n\n%.2d/%.2d/%.2d", nasc.dia, nasc.mes, nasc.ano);
}

No Linux, as coisas são um pouco mais complicadas já que é necessário implementar um função correspondente à getche().
Caso haja interesse deixo um link para uma discussão sobre o tema: stackoverflow.com/questions/3276546/how-to-implement-getch-function-of-c-in-linux

Leitura na mesma linha


The same dynamic indication repeated?

Question: Why is the f  dynamic indication repeated in the last two bars displayed below if a dynamic instruction should last until a different indication occurs?
Also, in the same picture, should the notes between the sforzando indications be played as ff  (the last dynamic specified before sf )?
Thanks for your help!
Comment: Please provide composer, name of piece, and publisher.  This information may well affect choice of interpretation.
Comment: The fragment is from Beethoven's 9th Symphony. The print screen is from a score found on free-scores.com
Comment: In that case, knowing how much Beethoven likes dynamics, I wonder whether those should have been "sf" and the printer goofed up
Comment: @CarlWitthoft - that seems a likely idea.
Answer: At least in the classical period, the normal practice (with no explicit notation) was that different beats in the bar were accented differently.
Repeating the "f" on every beat says "ignore the fact that the first beat in the bar is normally louder than the second beat in 2/4 time, and play them both at the same dynamic level".
Comment: I see. Thanks for the insight! If I'm not mistaken, in this context, "sempre f" would serve the same purpose, right?
Answer: Sforzando only applies to the notes immediately above it, so the notes in between should not be played sforzando.
RE: the repeated forte, this is not necessary. Once forte, the layers must continue to play forte until told otherwise. My guess is that the composer wanted to remind the players to do this every few notes.
Answer: The composer wants the staccato notes to be emphasised. But they have a staccato dot over them. They need '>' over as well. There's no room. So he has to put 'f' instead.
Comment: That's not the composer's fault - unless he's really lazy.  I have plenty of sheet music with multiple markings over the notes.  Further,   marking a dynamic is assuredly not an indicator of emphasis.
Comment: @CarlWitthoft - a comment with examples would be so much more helpful to me (and other readers). I don't see music with multiple markings over the same dots. If 'f' doesn't mean emphasise those particular notes, what is it there for?
Comment: 'cello music is rife with examples of notes that have a bowing mark over a  amphasis (>)  mark over  a  staccato or tenuto mark.
Comment: @CarlWitthoft - cello music probably represents way less than 10% of music generally, probably less than 5%. It may be your world, but. it's a small world compared to the whole music world. Please do not let this give you the propensity to consider that all music revolves around the 'cello, because it obviously does not, comparing it to the rest of the musical world. That apart, bowing marks will not appear in most of sheet music. Haven''t seen much in horn stuff, or guitar or piano stuff, for example...Rife it may be, but there is a whole different world out there.

The same dynamic indication repeated?


What is the length of [BC]?

Question: Let A , B and C be 3 points of a circle (c)
P is the intersection of two tangents of the circle in points B and C
Let (AB)//(CP) and AB=3 and BP=4
What is the length of BC
Can someone give hint !
Im blocked , the problem is that i don't know to start my proof
I see that BPC is triangle such that CP=BP
We suppose that ABPC is quadrilater parallelogram
Comment: This is not geometric topology.
Comment: @BalarkaSen you are right
Comment: What do you mean about the last sentence? Is it a given or your finding. A rough sketch shew that XBPC is a parallelogram where X is on BA extended and is 4 units from B.
Answer:
It is not difficult to show that XBPC is a parallelogram. In fact, it is a rhombus because $PB = BX = 4.$
$\alpha = \beta$ (tangent properties)
$\beta = \gamma$ (alternate angles)
$\beta = \delta$ (angles in alternate segment)
$∴ \triangle PBC \sim \triangle CBA$
$∴ \dfrac {PB}{BC} = \dfrac {BC}{BA}$
That is,   $\dfrac {4}{BC} = \dfrac {BC}{3}$
Result follows.
Comment: I haven't finished my edit. Why the down-vote?

What is the length of [BC]?


How can I extrapolate the mean from data ranges, assuming normal distribution?

Question: I have the following summary of data point values:
Under 600: 38%
601-800: 51%
Over 801: 11%
Assuming a normal distribution of values, how can I calculate the mean?
Note: it doesn't have to be precise, just a rough estimation to the nearest 10 would be sufficient.
Many thanks!
Comment: This reads like a routine textbook exercise ... is this an exercise for some class?
Comment: Since this seems like homework, here's a hint.  The median is the same as the mean in a normal distribution.
Comment: No the reason I am asking this question is that I have access to some room rental data from a lettings website and while they don't show the average room price they do show room prices ranges (as listed in the question). So assuming normal distribution (which isn't a correct assumption but workable given the context) I wanted to know what formula I can use to calculate the mean. If there's some other way in which I am meant to ask the question please let me know.
Answer: Interesting question... I'd start with a standard normal table like this one. The only real info you have is the place on the distribution of the numbers 600 and 800. They lie at CDF values of 38% and 89% respectively. The corresponding z scores are -0.31, and 1.23. So that means that the values 600 and 800 are 1.54 SD apart from each other. Since they are 200 apart from each other in score, the SD must be 200/1.54 ~= 130. To get from a z-score of -0.31 to the z-score of zero (the mean), you must add 0.31 SDs, or ~ 40. So the mean is 40 above 600, or 640.
Hope that helps!


$\sum_{i=0}^{k} \binom{m}{i}\binom{n}{k-i} =\binom{m+n}{k}$

Question: I'm trying to show that the equality
$$\sum_{i=0}^{k} \binom{m}{i}\binom{n}{k-i} =\binom{m+n}{k}$$
Is true.
I know it is since there is a good combinatorical argument for it. If we have a group of $m$ men and $n$ women, and we need to choose $k$ then we know its equal to $\binom{m+n}{k}$, but we can also say that we  choose $0$ men and $k$ women, or we can choose $1$ man and $k-1$ women, or we can choose $2$ men and $k-2$ women, etc.
So in theory they should be equal, but I can't work the math behind it.
A hint in the right direction would be appreciated
Comment: 'So in theory they should be equal, but I can't work the math behind it.' .. not sure what you are asking.
Comment: I'm asking for a formal mathematical proof for this equality. Not a combinatorical proof where we count the same thing in 2 ways like i did.
Comment: Another combinatorial argument, if one does not like men or women. The left-hand side is the coefficient of $x^k$ in $(1+x)^m(1+x)^n$.
Comment: Pretty sure it is a duplicate.
Answer: Consider the identity $$(1+x)^m(1+x)^n=(1+x)^{m+n}$$
Develop the LHS using the binomial identity for $(1+x)^m$ and $(1+x)^n$ and do the same with the RHS using the binomial identity for $(1+x)^{m+n}$ and then identify the coefficients of the term of degree $k$ on each side. It is exactly what you are trying to prove.


Uncertainty-minimizing stratified sampling strategy

Question: Suppose there is a school, and I want to know what proportion of students like the color red better than green, or vice versa (suppose there is no "other" option, just a binary variable). The school is 70% female and 30% male for some reason.
The assumption is that females have some (unknown) probability of preferring red, and males have a different, unknown probability of preferring red.
I have time to ask 100 people which color they prefer.
After I ask 100 people, I will estimate the overall proportion of red-likers by estimating female-proportion-of-red-likers and male-proportion-of-red-likers and weighting these two according to the prevalence of females and males.
How many females should I ask, and how many males, to minimize the uncertainty of my resulting estimate?
(An ideal answer would connect this to a larger theory for the case of N strata each of which has an independently drawn unknown Bernoulli parameter. Bonus points if it extends to a Bayesian setting where the prior is non-uniform)
Answer: We call them population partition A and B which is more neutral than male/female while staying equivalent.
Say there is a proportion $f$ of subset A in the population, a probability $p_A$ for that category of having the trait considered, resp. $f_B$ and $p_B$ for the subset B. We are trying to estimate:
$$P = f p_A + f_B p_B$$
Out of the $N$ sample we do, we sample a proportion $\alpha_A$ of population $A$ and $\alpha_B$ of popoulation $B$. An stratified estimator of $P$ is:
$$\hat{P} = f_a \sum_{i=1}^{\alpha_A N}{I_i^A} + f_B p_B \sum_{i=1}^{\alpha_B N}{I_i^B}$$
To minimize the estimation uncertainty, we need to minimise its variance, which is:
$$N^2 Var(\hat{P}) = f_a^2 \frac{1}{\alpha_A^2} p_A (1-p_A) + f_B^2 \frac{1}{\alpha_B} p_B (1-p_B)$$
using our sampling proportion $\alpha = \alpha_A = 1-\alpha_b \in [0,1]$.
The optimal proportion to sample is therefore:
$$\alpha = \arg \min_{\alpha \in [0,1]}  \frac{1}{\alpha^2} f_a^2 p_A (1-p_A) +\frac{1}{(1-\alpha)^2}  f_B^2 p_B (1-p_B)$$
Therefore, we need the value of $p_A$ and $p_B$ (or estimates thereof) to determine (or estimate) the optimal sampling proportion $\alpha$.


How to control page margin when printing HTML document?

Question: I'm printing a long HTML document and i want to set the margin between the pages in the CSS file.
Unfortunately, the padding/margin only take effect in the first page (padding-top) and the last page (padding-bottom).
Any way to set the margin between pages?
Comment: The @page declaration was in an inner css file in Angluar 2. moving it to the higher styles.css solved it.
Answer: It's not margin between pages but page margin. It's controlled by a specific CSS media @page:
@page {
    margin: 1cm;
}

Please refer to linked specs for all the details (especially about how @page combines with, for example,  margins).
Note that with pseudo-selectors you can control the aspect of :left, :right and :first pages (just to mention few common use cases).
Comment: Safari does not support it, Chrome does (tested on Windows), Details: http://caniuse.com/#search=%40page Note: please vote to fix this issue in WebKit (links on caniuse), I'd really love to have `@page` supported in my  wkhtmlpdf docs!!! ;)
Comment: both chrome and safari on OS X ignore this property. What is the browser support for @page margin?


c# - Erro ao tentar fazer o Replace de uma string

Question: Boas Pessoal,
Estou com o seguinte problema:
Ao tentar fazer o replace de uma string (de um Literal Control), utilizando o código a seguir apresentado, o valor da mesma não é alterado.
 MyControl.Text.Replace("id=\"KP\"", "id=\"KPC\"");

No entanto, se eu tentar alterar só o value do id (como mostra o código seguinte), funciona na perfeição.
 MyControl.Text.Replace("KP", "KPC");

P.S: tenho que utilizar o id no replace, porque o texto do literal contêm mais do que uma vez a referência ao valor do id.
[EDIT] - Deixo aqui um excerto do literal para melhor compreensão (é repetitivo)

    BK-001

Comment: Pelo que entendi você está tentando dar replace em (id="KP-01"), mas o seu código considera (id="KP"). Creio que esse pode ser o erro.
Comment: Acho que ele não está a "gostar" da "\" no texto. Experimente assim: `MyControl.Text.Replace(@"id=""KP""", @"id=""KPC""");`
Comment: Vou simular aqui e se der certo posto como resposta
Comment: Criei um pequeno exemplo e tudo funcionou corretamente, não percebo o porquê de não lhe estar a funcionar. Colocou o código assim, correto? `MyControl.Text = MyControl.Text.Replace("id=\"KP\"", "id=\"KPC\"");`
Comment: @JoãoMartins exatamente assim, não consigo perceber o erro...
Comment: @JoãoMartins fiz uma edição e pus um excerto do `literal`
Comment: @JoãoMartins eu acho que já experimentei todas as possibilidades menos aquela que será a solução xD, já experimentei essa também e nada (apesar de ser uma boa proposta). Eu, também, já cheguei à conclusão que a "\" será o problema, mas como não a posso remover  (dado corresponder a um caminho), não sei muito bem por onde me guiar.
Comment: Possível duplicata de [Replace com \ não funciona](https://pt.stackoverflow.com/questions/260390/replace-com-n%c3%a3o-funciona)
Comment: @ramaral não acho que seja duplicado, até porque o código `MyControl.Text.Replace(@"id=""KP""", @"id=""KPC""");` também não funciona. Há aqui algo que não bate certo...
Comment: @ramaral, posso estar enganado, mas eu acho que não é duplicado, até porque se eu substituir a barra por duas, ele também vai substituir as dos elementos (`a` e `li`)
Comment: @AdrianoMaia tem a certeza que o texto `id=\"KP\"` existe exatamente dessa forma no `MyControl.Text`?
Comment: @JoãoMartins sim, também já verifiquei isso no Debug
Comment: @FilipeAndréFloriani, não xD. Eu só quero substituir a parte `KP` por `KPC`
Comment: Então tire a última "
Answer: Segue abaixo solução:
string teste = System.IO.File.ReadAllText("c:\\arquivo.txt");

teste = teste.Replace("id=\"KP", "id=\"KPC");

Observação: O arquivo .txt continha seu HTML.
Comment: é isso mesmo. Muito obrigado :).
Comment: Que bom que foi resolvido! :]


Posting a form in MVC3

Question: I have a page which load data from multiple partial views. One of the partial view has few links. say 3. Every time user clicks on the link I reload the page with a data related to clicked link. The form looks like this.
@model TestPostback.Models.HomeModel
@{
    ViewBag.Title = "Index";
}

Index

<form id="testform" method="post" action="@Url.Action("Index","Home")" runat="server">

                         This is a test page

</form>

Test Expand

Controller Code :-
 public ActionResult Index(string selectedValue)
        {
            return View();
        }

        public JsonResult GridData(string sidx, string sord, int page, int rows)
        {
            int totalPages = 1; // we'll implement later
            int pageSize = rows;
            int totalRecords = 3; // implement later

            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = new[]{
                    new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
                    new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
                    new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
                }
            };
            return Json(jsonData);
        }

Here is what I am trying to do.
When i click on Link "This is a Test Page", it calls the controller with some value but it does not load my grid. I want that value because i want to load a grid with different value based on user clicks. what are the changes I have to make for this to work?
please advice.
Comment: are you loading via ajax? code here doesnt show and since you have just one form here and no grids shown I have to imagine so? more details please : )
Answer: I'd recommend following the PRG (post redirect get) pattern: so after the post, you redirect to whichever action method is suitable (in this case the one that displays all the jqGrids). With MVC this can be achieved using a RedirectResult or the RedirectToAction method available on Controller.
Comment: This wont work because I have to load few other partial views with data/text from database. So I want to do is return a view which loads all the data in my partial views and also then call those controller methods which loads my Grid Data.
Answer: Are you serializing your data when you get it back (ie serializeGridData)
Are you loading by JSON?
If so, check out
Setting the content-type of requests performed by jQuery jqGrid
Comment: I have updated my question. Can you please review it and let me know what should i do to make that work?

Posting a form in MVC3


In a cloud environment, should we alert on high CPU utilisation or high load avarage?

Question: What is the best practice for monitoring the system, should the CPU alerts be based on the regular CPU usage or load average?
I'm wondering what approach is being used in big cloud environments.
Answer: Reaching 100% CPU utilisation is not what should trigger an alert, remaining at 100% CPU utilisation might be something to worry about.
Sharp spikes are usually good
Load fluctuates but your system does not reach the limit of available resources and doesn't experience continuous resource starvation.
When the CPU load spikes sometimes reach 100% your system is correctly sized, when they never reach 100% your system might be (somewhat) oversized.
Nothing to worry about.
A flat line is usually bad
When your CPU load remains at 100% CPU utilisation  for a long time, your system does not have all the resources it needs.
You may need to scale up, or scale out more. Intervention and sending a pager alert might be appropriate.
On other end of the spectrum,  when your CPU load remains at 0% CPU utilisation  consistently, either your system may be terribly oversized and you might want to downsize, or something else is wrong (and missed by your monitoring). You probably don't want a pager alert after hours but should still follow up during business hours if that is a long term trend.
Comment: Great answer. Only thing I would add is to add alerts for what is important to your application. If response time is important, alert on that regardless of CPU utilization. In our application high CPU utilization results in increased response times. Alerting on response time usually triggers before the CPU alerts.


Evento Padrao Exit na tecla ESC

Question: Atualmente no meu sistema utilizo o evento KeyPress para identificar a tecla Esc e assim fechar o meu form, porém tenho um sistema bem grande com mais de 50 formulários e ainda mais sendo desenvolvidos:
Minha duvida é: Existe alguma forma padrão para setar a tecla Esc como exit do form?
Comment: Crie um form padrão que contenha essa funcionalidade e todas as outras que forem necessárias e herde todos os outros forms desse.
Comment: @LeoLonghi Não, se você fizer com que o nome deste form (da classe) seja `Form`, isso vai valer pros que já foram criados também.
Comment: No caso isto seria viável somente para os novos forms correto?
Comment: @Bacco Alguma forma de desfazer isto?
Comment: @LeoLonghi sim, só clicar em "restaurar" abaixo dela. Mas foi só uma sugestão, veja como acha melhor. Nao tem problema ter deletado, foi só uma idéia.
Answer: Sim, existem várias maneiras de fazer isso. Minha dica pra você é criar um form simples com todos os comportamentos padrões para os forms do sistema e sempre que criar um form novo, fazer com que este novo herde o form padrão.
public class FormPadrao : Form
{
    /* Outros métodos */

    private void form_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            this.Close();
        }
    }
}

E o uso ficaria assim
public FormCadastro : FormPadrao { }

Se você precisa disso para todos os forms, incluindo os que já existem pode simplesmente criar uma classe chamada Form. Perceba que todos os forms atuais já herdam de uma classe chamada Form, então, a partir do momento que você definir uma classe com este nome, os forms atuais irão herdar o form que foi criado dentro do seu projeto.
Então, o Form padrão ficaria assim
public class Form : System.Windows.Forms.Form { }

Comment: Obrigado, era isto que eu precisava! :)

Evento Padrao Exit na tecla ESC


Como listar as variáveis dentro de uma tabela em Lua?

Question: Por exemplo:
minion = {
   hp = 1000,
   x = 10,
   y = 25
}

Existe alguma função que eu possa saber quantas variáveis existem dentro desta tabela?
Answer: Já há uma resposta para o tamanho. Para percorrer os elementos:
minion = {
    hp = 1000,
    x = 10,
    y = 25 }

for i, v in pairs(minion) do
    print(i, "=>", v)
end

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Can I use my own template for a view mode?

Question: I'm creating a cusom module that loads a node  through a view_builder. However, none of the available view_mode display the elements like I'd like them to be, so I'm about to create my own view mode. However, I have parsed quite a few tutorials about view_builders, but none talked about using a custom template (or I missed it)
So, is it possible to use your own template, and how do you do so?
Thank you in advance
Answer: The standard way to do this is to create a template in your theme, you can use node--nodetype--viewmode.html.twig . (two dashes between each part).
To use it in your custom module, you'd have to use hook_theme_registry_alter to change the path that it looks in for that theme hook.
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['node__nodetype__viewmode']['path'] = drupal_get_path('module', 'mymodule') . '/templates/';
}

I don't really see the value of moving it into a custom module though.  It's a standard to keep custom templates in the theme.
Comment: This is a specific need, the project I work on is so big that putting in in the theme directory slows everything down. However thank you for your answer, I got to try it and it worked pretty well!
Answer: When calling the view method, the second argument is the name of a view mode:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilderInterface.php/function/EntityViewBuilderInterface%3A%3Aview/8.2.x
Pass in the machine name of the view mode you want to use.
Example:
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$output = $view_builder->view($node, 'my_view_mode');

Comment: I don't understand what that means, but if you create a new View Mode under Admin > Structure > Display Modes, configure the node display with that view mode, you can certainly then define a `node--node_type--view_mode.html.twig` template. Thats basically using your 'own' template. From here, you can preprocess and add variables or whatever you want and output them in that twig template.
Comment: Yes, that's what I did, but my question is more about if I can use my own template as a `view_mode`
Comment: Oh, okay, do you know if I can put this `node--node_type-view_mode.html.twig` anywhere?
Comment: I've never tried it from the module level, but you can try and see what happens.


prove the convexity of zero one loss multiple a convex function

Question: I am now working on a problem To prove the convexity of a zero-one loss multiple with a convex function, and it looks like this: $$L(s) = s^2 \times \boldsymbol 1(s\leq 0);$$ when proving this convexity, is it ok to assume this $\boldsymbol 1(s\leq 0)$ a constant?
if it is not ok to treat 1(s<=0) as constant, how would we prove the convexity then?
Comment: For me, I always find it helpful to start by typing the definition of convexity.
Comment: Welcome to the site! Unfortunately, it's not a rigorous proof if you assume that term is constant. For me, I always find it helpful to start by typing the definition of convexity.
Answer: Note that
$$
L'(s)=
\begin{cases}
2s&,s \leq0
\\
0 &,s>0
\end{cases}
$$
What do you know about a differentiable function whose derivative is monotonically increasing?
Comment: Emm does that mean when s<=0, it is decreasing, and s>0 it doesn't change
Comment: @icc $L'$ is monotonically *in*creasing on $\mathbb{R}_{\leq0}$ since  $L'(s_1)=2s_1\leq2s_2=L'(s_2)$ for all  $s_1,s_2\in \mathbb{R}_{\leq0},s_1\leq s_2$. Consider, e.g., $s_1=-2,s_2=-1$. We also have: $L'(s_1)=0\leq0=L'(s_2)$ for all  $s_1,s_2\in \mathbb{R}_{>0},s_1\leq s_2$, so $L'$ is also monotonically increasing on $\mathbb{R}_{>0}$.
Comment: @icc Can you find a characterization of convexity that uses the first derivative of a function (and a property I just derived for $L'$) on the [respective Wikipedia page](https://en.wikipedia.org/wiki/Convex_function#Properties)?
Answer: This $\boldsymbol 1(s\leq 0)$, is not a constant.  It has the value
$$\boldsymbol 1(s\leq 0) =\begin{cases} 1 & \text{if $s\leq0$} \\ 0 & \text{if $s>0$}\end{cases}$$
and the product
$$s^2 \times \boldsymbol 1(s\leq 0) =\begin{cases} s^2 & \text{if $s\leq0$} \\ 0& \text{if $s>0$}\end{cases}$$
Comment: Then how would you prove the convexity in this case, I tried a lot of ways but they just don't work
Comment: @icc use the [conditions](https://en.m.wikipedia.org/wiki/Convex_function#Definition) in the definition of convexity, or the [properties](https://en.m.wikipedia.org/wiki/Convex_function#Properties). The answer from starmerkur used the property *"A twice differentiable function of one variable is convex on an interval if and only if its second derivative is non-negative there"*
Comment: Thanks a lot, But I tried to use conditions for a lot of ways, but I find I can't do this.
Comment: How would you proof it when $L(s) = s^2$? Can you proof that for any point $t$ between $s_1$ and $s_2$ you have that $$L(t) < \frac{t-s_1}{s_2-s_1}L(s_1) + \frac{s_2-t}{s_2-s_1} L(s_2)$$
Comment: Yes I can prove that, what about the next step, thanks very much
Comment: @SextusEmpiricus I noticed that $L$ is not twice differentiable, but we can with a criterion that uses the first derivative (which I hinted at and would like the OP to find out, f.i. on the Wikipedia page you linked to).
Comment: @icc now you do the same when only half the function is $s^2$ and the other half is zero.
Comment: @icc here you might use that the function is a constant, so the right side is convex because it is a constant. The left side because it is twice differentiable and has positive second drivative. And then show that when you stick them together that it remains convex as a whole by showing that the line pieces are always above the function.
Comment: Making a diagram would be helpful.