Is the gaussian function a Nash function on $\mathbb{R}$?

Question: Let me explain the question. Take a gaussian function $f:t\in \mathbb{R} \mapsto \exp(-t^2)$. Does there exist a nontrivial polynomial $P\in \mathbb{R}[X,Y]$ such that
$$
\forall t\in \mathbb{R},\qquad P(t,f(t))=0 ?
$$
(If such a polynomial exists, then the function $f$ is called a Nash function on $\mathbb{R}$)
I know that $t\mapsto \exp (t)$ and $t\mapsto \sin t$ are not Nash functions (on $\mathbb{R}$) but the proofs are based on the periodicity of $\sin$ and the fact that $\exp$ is unbounded. For the gaussian, I don't know if the function is Nash or not. Do you know if it is or not ? And could you provide a proof or a reference ?
Comment: Assuming your argument for $t\mapsto\exp(t)$ uses the superpolynomial growth rate, you should be able to apply the same argument to $t\mapsto \exp(t^2)$.  Then you can pass from $\exp(t^2)$ to $\exp(-t^2) = 1/\exp(t^2)$ by using the [reciprocal polynomial](https://en.wikipedia.org/wiki/Reciprocal_polynomial).
Comment: So, for functions defined on all of $\mathbb R$, "Nash function" is the same as "algebraic function"?
Comment: @GEdgar I don't know... I'm not an expert in that domain...
Answer: I asssume $P(X, Y)$ is not allowed to be the trivial polynomial, i.e., that $P(X, Y) \ne 0$.
Then the answer is "No"; we can see this as follows:
Suppose there were such a polynomial $P(X, Y) \in \Bbb R[X, Y]$; then any such $P(X, Y)$ may be written as
$P(X, Y) = \displaystyle \sum_{n = 0}^N \sum_{i + j = n} p_{ij}X^iY^j, \tag{1}$
where $p_{ij} \in \Bbb R$ and $N$ is the degree of $p(X, Y)$; that is, the greatest of the values $i + j$ over all the terms $p_{ij}X^iY^j$ occurring in $P(X, Y)$.  We write $P(X, Y)$ as the sum of two terms  $r(X)$ and $q(X, Y)$, where
$r(X) = \displaystyle \sum_m p_{m0}X^m  \tag{2}$
and
$q(X, Y) = \displaystyle \sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} X^i Y^j; \tag{3}$
$r(X)$ consists of those terms of $P(X, Y)$ which are of degree $0$ in $Y$; including the constant term $p_{00}$;  all other terms, those of degree one or greater in $Y$, are absorbed into $q(X, Y)$.  We thus have
$P(X, Y) = r(X) + q(X, Y). \tag{4}$
If we now take $X = t$ and $Y = e^{-t^2}$ into (4), we obtain
$P(t, e^{-t^2}) = r(t) + q(t, e^{-t^2}) = \displaystyle \sum_m p_{m0}t^m + \sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} t^i (e^{-t^2})^j, \tag{5}$
so we have by hypothesis
$r(t) + q(t, e^{-t^2}) = \displaystyle \sum_m p_{m0}t^m + \sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} t^i (e^{-t^2})^j = P(t, e^{-t^2}) = 0. \tag{6}$
Now the critical observation to be made at this point is that any term of the form  $p_{ij}t^i (e^{-t^2})^j$, $i \ge 0$, $j \ge 1$, $p_{ij} \in \Bbb R$, obeys
$\lim_{t \to \infty} p_{ij}t^i (e^{-t^2})^j = 0; \tag{7}$
(7) is in fact very easy to see if we consider the expression
$t^{-i}e^{t^2} = t^{-i} \displaystyle \sum_0^\infty \dfrac{(t^2)^n}{n!} = \displaystyle \sum_0^\infty \dfrac{t^{2n - i}}{n!} = \displaystyle\sum_0^{2n < i}\dfrac{t^{2n - i}}{n!} +  \sum_{2n \ge i}^\infty \dfrac{t^{2n - i}}{n!}; \tag{8}$
The first sum on the right of (8) clearly approaches $0$ as $t \to \infty$; as for the second sum, an application of the ratio test to successive terms yields
$\rho_n(t) = \dfrac{\dfrac{t^{2n + 2 - i}}{(n + 1)!}} {\dfrac{t^{2n - i}}{n!}} =   \dfrac{t^2}{n+ 1} > 0. \tag{9}$
We see from (9) that for fixed $t$,
$\lim_{n \to \infty} \rho_n(t) = 0, \tag{10}$
which shows that the series
$s(t) = \displaystyle \sum_{2n \ge i}^\infty \dfrac{t^{2n - i}}{n!} \tag{11}$
converges.  However, the ratio $\rho_n(t)$ may also be used to show that the sum $s(t)$ may take on arbitrarily large values for sufficiently large $t$, e.g., letting $n_0$ be the smallest $n$ such that $2n_0 > i$, we may choose $t$ such that $t^{2n_0 - i} / n_0!$ is as large as we please; since every term of $s(t)$ is positive for $t > 0$, it follows that
$s(t) > \dfrac{t^{2n_0 - i}}{(n_0!)}; \tag{12}$
thus we see that
$\lim_{t \to \infty}s(t) = \infty, \tag{13}$
and from this it follows that
$\lim_{t \to \infty} t^{-i}e^{t^2} = \infty, \tag{14}$
and thus
$\lim_{t \to \infty} t^ie^{-t^2} = 0; \tag{15}$
furthermore, since for $j \ge 1$
$t^i(e^{-t^2})^j = t^ie^{-t^2}(e^{-t^2})^{j - 1} \le t^ie^{-t^2}, \tag{16}$
we find that
$\lim_{t \to \infty}t^i(e^{-t^2})^j = 0 \tag{17}$
as well.  Referring to (6) we see
$\lim_{t \to \infty}q(t) = \lim_{t \to \infty}\sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} t^i (e^{-t^2})^j = 0. \tag{18}$
Now suppose $r(t) \ne 0$; then, writing (6) as
$r(t) = -q(t), \tag{19}$
and letting $t \to \infty$, we see that the right hand side approaches zero whilst the left either approaches the constant $p_{00}$ or $\pm \infty$; this contradiction shows that we must have $r(t) = 0$, i.e., $p_{m0} = 0$ for all $m$.
Having dispensed with the coefficients $p_{m0}$ of $P(X, Y)$, we may divide
$P(t, e^{-t^2}) = q(t, e^{-t^2}) = \displaystyle \sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} t^i (e^{-t^2})^j = 0, \tag{20}$
by $e^{-t^2} \ne 0$, and find
$e^{t^2}P(t, e^{-t^2}) =  \displaystyle \sum_{n = 1}^N \sum_{i + j = n, j \ge 1} p_{ij} t^i (e^{-t^2})^{j -1}$
$ = \displaystyle \sum_m p_{m1}t^m + \sum_{n = 1}^N \sum_{i + j = n, j \ge 2} p_{ij} t^i (e^{-t^2})^{j -1} = 0; \tag{21}$
we may now repeat the above argument to show that the $p_{m1} = 0$, and so on, until all the $p_{ij}$ are exhausted and we have shown that $P(X, Y) = 0$, the forbidden case.
This contradiction demonstrates that $e^{-t^2}$ is not a Nash function.


A Map into the Tangent Bundle Which Can be Restricted to the Tangent Bundle of a Submanifold

Question: $\newcommand{\R}{\mathbf R} \newcommand{\wh}{\widehat} \newcommand{\vp}{\varphi}$
I think the following should be true.

Let $S$ be an embedded $k$-submanifold of a smooth $n$-manifold $M$ and let $f:N\to TM$ be a smooth map defined on a smooth manifold $N$.
  Assume that $f(q)\in di(TS)$ for all $q\in N$, where $i:S\to M$ is the inclusion map.
  Then the unique map $F:N\to TS$ satisfying $f=di\circ F$ is also smooth.

Can anybody confirm if this is correct? Here is my argument:
Proof:
Let $p$ be any point in $S$ and $(U, \vp)$ be a slice chart centered at $p$ for $S$ defined on a neighborhood $U$ of $p$ in $M$.
Write $\vp(U)=\wh U$.
Then we know that $\pi\circ \vp\circ i:U\cap S\to \pi(\wh U\cap (\R^k\times \mathbf 0))$ is a smooth chart on $S$ about $p$.
We may assume that $\wh U$ is an open ball.
Therefore, $\pi(\wh U\cap (\R^k\times \mathbf 0))=\pi(\wh U)$.
The corresponding smooth chart $\Theta:T(U\cap S)\to \pi(\wh U)\times \R^k$ on $TS$ is defined as
$$
\Theta(q;\ v)=(\pi(\vp(q)),\ d(\pi\circ \vp\circ i)_qv)=(\pi(\vp(q)),\ d(\pi\circ \vp)_qdi_qv)
$$
for all $(q;\ v)\in T(U\cap S)$.
From this it is easily checked that $\Theta\circ F(q)=(\pi\circ\vp(q),\ \pi\circ d\vp_qf(q))$ and therefore $\Theta\circ F$ is a smooth map.
This shows that $F$ is locally smooth and hence $F$ is smooth.
Answer: Yes it is correct. Here is another proof:
$di:TS\to TM$ is a smooth embedding, so $di(TS)$ is an embedded submanifold of $TM$ (see here for a proof of a more general statement). Hence, since $f(N)\subseteq di(TS)$, $f$ restricts to a smooth map $f:N\to di(TS)$ (by Corollary 5.30 in Lee's Introduction to Smooth Manifolds). Now, compose with the diffeomorphism $di(TS)\to TS$.


Javascript + Ajax não está retornando o esperado

Question: Estou tentando enviar os dados desta página para o servidor, porém o Js não retorna a variável Mensagem...
Link
Conheço pouco de JS e gostaria de saber de alguma forma de chamar a variável assim que o servidor receber os dados.
Comment: Olá Tonielto, inclua a maior quantidade possível e relevante de código a sua pergunta, somente assim podemos te ajudar.
Comment: Tira a função do botão e coloca na tag `form` no evento ``. Se não der certo, faça como o Gerep disse, adicione o código onde está o problema para podermos identificar melhor.
Comment: Kadu, ele só retorna a mensagem pelo console do browser, no caso eu gostaria que a mensagem fosse transmitida através de um pop-up ou que o  a parte de baixo do JS funcionasse.

O código está no link, está hospedado no servidor.
Comment: Dá uma olhada a esta pergunta/resposta: http://pt.stackoverflow.com/q/6626/129 Entretanto podes explicar aqui se queres enviar o nome e mail também via AJAX ou se queres fazer o submit da form?
Comment: O que pretendo é enviar o "Nome" e "e-mail" para o Banco de dados, no código do link isso acontece como pode ver, porém ele não retorna nenhuma mensagem de "Obrigado por se cadastrar"... (Mensagem que está declarada na var Mensagem="..."
Comment: Cara, você tem acesso a URL do site em .aspx ? Seu botão está com `submit`. Troque por `button`, se não ele automaticamente vai redirecionar seu site para ele mesmo e você não vai ver o retorno da função. Agora... o que tem nessa URL em .aspx ? Tentei aqui, mas não deixou acessar...
Answer: Habilite o CORS do lado do servidor...
(http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api)
Se você adicionar um error em seu ajax, vai perceber que ele cai lá.
$.ajax({
    type: "GET",
    url:  strUrl,
    crossDomain: true,
    dataType: 'jsonp',
    beforeSend: function (xhr) {
       xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    },
    success: function(data)
    {
        if (data == "Realizado com sucesso.")
        {
            var Mensagem = "Obrigado por se cadastrar na BILLABONG!";

            $("#divNewsLetterContainer").html("");
            $("#divNewsLetterContainer").append("" + Mensagem + "");
        }
        else
        {
            alert(data);
        }
    },
    error: function(data) {
        alert('Ocorreu um erro, olhe o console');
        console.log(data);
    }
});

Adicione uma action no seu form:
   <form action="javascript:void(0);" id="divNewsLetterContainer" class="newsletter" onsubmit="EnviarNewsLetter();">
        <input type="text" class="fitext" name="nome" id="nome" size="20" value="" placeholder="name" required="">
        <input type="email" name="email" id="email" size="20" value="" placeholder="firstname.lastname@example.com" required="">
        <input type="submit" id="btw-ok" value="assinar" class="btw-ok">
   </form>

Comment: Não tenho acesso para Habilitar o Cors no servidor.

Eu notei que o erro acontece, neste caso especifico, o acesso é limitado quando o assunto é servidor. De forma que estou enviando somente os dados para o banco e gostaria de exibir uma tela em espécie de pop-up para o usuário.
Comment: Então eu te aconselho a usar uma linguagem server-side (asp.net, java, php) para fazer isso. Nesse caso o seu javascript vai chamar uma função no próprio dominio, evitando o cross domain e a linguagem faz a requisição para o servidor externo.
Answer: Me parece que seu problema está nas variáveis:
var strNome = $("#nome").attr("value");
var strEmail = $("#email").attr("value");

Troque por:
var strNome = $("#nome").val();
var strEmail = $("#email").val();

Do jeito que está, eles estão sendo enviadas "vazias", e por isso não retorna nada no Ajax.
Mude também o seu form, adicionando um onsubmit, desta forma:
<form id="divNewsLetterContainer" class="newsletter" onsubmit="return EnviarNewsLetter()">
     <input type="text" class="fitext" name="nome" id="nome" size="20" value="" placeholder="name" required/>
     <input type="email" name="email" id="email" size="20" value="" placeholder="firstname.lastname@example.com" required/>
     <input type="submit" id="btw-ok" value="assinar" class="btw-ok">
</form>

E no script, adicione return false; após o Ajax (isso evita que a página seja recarregada):
$.ajax({
...
});
return false;

Outra coisa... onde tem :
if (data == "Realizado com sucesso."){
...
}

Talvez seja melhor usar:
if (data.indexOf("Realizado com sucesso.") != -1){
...
}

A não ser que o retorno da variável data seja uma string EXATAMENTE igual a "Realizado com sucesso." (sem tags HTML etc).


elasticsearch match all words from document in the search query

Question: We can search for ALL words in a specific document.field like this:
{ "query" : { "match" : { "title": { "query" : "Black Nike Mens", "operator" : "and" } } } }

This will search for the words Black, Nike and Mens in the field title such that only those documents are returned that will have ALL these words in the title field.
But what I am trying to do is a little different.
I want to lookup such that if all the words of the title field of the document are present in my search query then it will return that document.
For e.g.
suppose there is a document with title : "Nike Free Sparq Mens White" in the elasticsearch database
now if I search with a query : "Nike Free Sparq 09 - Mens - White/Black/Varsity Red" then it should return this document, because all the words in the document.title do exist in my query
but if I search with a query : "Nike Free Lebron - Mens - White/Black" then it should NOT return the document because my query has the word Sparq missing
this is a sort of reverse-and-operator search
Is this possible? If yes, then how?
Comment: Though you posted a workaround, I also want to know a cleaner solution.
Comment: Have a look at this link. You'll find your answer there :)

http://stackoverflow.com/questions/26001002/elastic-search-difference-between-term-match-phrase-and-query-string
Comment: thanks for the help @betto86, it did not answer my question but helped me on more related things.
Answer: I finally got it to work but not with a direct method!
This is what I do:

Create a clean list of words from the source query, by:

change to lower case
replacing any special chars and punctuation with space
remove duplicate words

Search using normal match with OR operator for the words joined as a string
Now we will find the best relevant hits in result
We take those hits one by one and do a word to word search in php (or whatever programming language you use)
This word search will check for all the words of a document from the hits we just found, and match them with the words in source query; such that all words from hit document should be present in the source query string

This worked for me well enough!
Unless someone has a direct method from elasticsearch query language.
Answer: The Percolate query should help here. You'd register your documents as queries, making "Nike Free Sparq Mens White" a match query with an AND operator.
Then your query can become a document like one having "Nike Free Sparq 09 - Mens - White/Black/Varsity Red" as content. You should get "Nike Free Sparq Mens White" back, because it matches all terms.
Unfortunately, this won't scale well (e.g. if you have millions of documents, it might get slow).


Erro ao tentar fazer upload de imagem no fire base com flutter

Question: Estou tentando lançar uma imagem no storage do fire base
mas a seguinte mensagem aparece
Unhandled Exception: type 'XFile' is not a subtype of type 'File' in type cast
esse é o codigo:
 IconButton(
              onPressed: () async{
                final File? imgFile = (await ImagePicker().pickImage(source: ImageSource.camera)) as File;
                if(imgFile == null){
                  return;
                }
                else{
                  widget.enviarMensagem(imgFile: imgFile);
                }
              },
              icon: const Icon(Icons.photo_camera),
          ),

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Pela documentação e exemplos apresentados pelo plugin, o retorno é um XFile e não um File (dart:io), consequentemente não é possível fazer a conversão da forma que está fazendo. Se precisa mesmo de um File, pode criá-lo utilizando o atributo XFile.path:
final XFile? imgFile = await ImagePicker().pickImage(source: ImageSource.camera);

// supondo que 'imgFile' não é nulo aqui.
final File file = File(imgFile.path);

Comment: muito obrigado!!


Empilhar Blocos com Bootstrap

Question: Estou fazendo um layout usando bootstrap e me deparei com um problema na hora de empilhar blocos para ser responsivo.
Tenho 5 blocos de alturas diferentes, divididos em 3 colunas:
Ao chegar em certa largura preciso que os blocos se empilhem, mas a altura de cada "camada" é definida pelo maior bloco dela:
Alguém teria uma solução para isso?
Comment: O que deseja seria algo parecido [com essa pergunta](http://pt.stackoverflow.com/q/124234/20615)?
Answer: Sim, tem uma solução, porém para obter o efeito desejado, você terá que usar um plugin chamado masonry.
De um estudada, é bem prático.
http://masonry.desandro.com/

$('.grid').masonry({
  // options...
  itemSelector: '.grid-item',
  columnWidth: 200
});

  ...

Seria mais ou menos assim, as grid item seriam suas li.
Este plugin faz com que de acordo com a resolução da sua tela ele se adapte e deixe de forma responsiva automaticamente.

Empilhar Blocos com Bootstrap


Select não deixa selecionar a opção

Question: Olá, eu tenho uma lista de option de um select e não consigo selecionar um item da lista.
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

export default function ListCompany(props) {

const Label = styled.label"
display: flex;
align-items: center;
padding: .375rem .75rem;
margin-bottom: 0;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
white-space: nowrap;
background-color: #e9ecef;
border: 1px solid #ced4da;
border-radius: .25rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
text-align: center!important;
"

const Select = styled.select"
  display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
position: relative;
flex: 1 1 auto;
width: 1%;
margin-bottom: 0;
 "

const [company, setCompany] = useState([]);

useEffect(async () => {
 const response = await fetch('http://localhost:57248/api/listaempresas');
const data = await response.json();

setCompany(data);
}, []);

return (

    {props.texto}

  <Select className="" id={props.id} required="required" onChange={props.change}>
    <option value={0}>Escolha...</option>
    {company.map(function (empresa) {
      return (<option key={empresa.ax_cod_empresa} value={empresa.ax_cod_empresa}>{empresa.ax_desc_empresa}</option>);
    })
    }
  </Select>

  )
}

Este seria o Select que é renderizado:

Ele deixa eu ver as opções porém não deixa selecionar. Quando eu clico ele volta para o Escolha...
Como solicitado aqui está o resto do código:
<ListCompany
 id="empresa"
 texto="Empresa: "
 change={this.handleCompanyChange}
 errorText={this.state.companyError}
/>

Este é o handleCompanyChange:
handleCompanyChange(e) {
 var g = document.getElementById("empresa");
 var result = g.options[g.selectedIndex].value;
 this.setState({ empresa: result });
}

Comment: Gabriel, sua função onChange tá vindo de um componente acima desse (props.change), então precisa exibir ela pra entender o que tá rolando. E o mais importante ali é que está faltando o Value para o Select que possivelmente deve vir por props tbm.
Comment: Como solicitado, já coloquei os trechos correspondentes a chamada da função e ao change.
Answer: Gabriel, acredito que você poderia fazer de forma diferente usando melhor a api do React. Eu faria o seguinte:
Onde tem sua função handleCompanyChange:
import React, { useState, useEffect } from 'react';
import ListCompany from './ListCompany'
export default function SeuComponente() {
  const [company, setCompany] = useState([]);
  const [value, setValue] = useState(null);

  useEffect(async () => {
    const response = await fetch('http://localhost:57248/api/listaempresas');
    const data = await response.json();
    setCompany(data);
  }, []);

  return (

    {/* Deve ter alguma coisa aqui pra exibir... */}
    <ListCompany
       id="empresa"
       texto="Empresa: "
       change={(e) => setValue(e)}
       value={value}
       companies={company}
       errorText={'sua validação de erro...'}
    />

  );

}

No componente ListCompany ficaria algo assim:
import React from 'react';
import styled from 'styled-components';

// Seus styles devem vir antes de declarar a função para
// evitar renderização das variáveis desnecessariamente.

const SeuEstiloVemAqui = styled.label``; // use 'crase' ao invés de aspas

export default function ListCompany(props) {

return (

    {props.texto}

  <Select
    className=""
    id={props.id}
    required="required"
    onChange={(e) => props.change(e.target.value)}
    value={props.value}
    >
      <option value={0}>Escolha...</option>
        {props.companies.map(empresa => (
          <option
            key={empresa.ax_cod_empresa}
            value={empresa.ax_cod_empresa}
          >
            {empresa.ax_desc_empresa}
          </option>
        ))}
  </Select>

  )
}

Teria só que ver como seu Select recebe os valores. Esse parece ser um Select estilizado de alguma lib e alguns recebem o value como objeto {label: '', value: ''}
Answer: Aqui tem um exemplo de Select que eu utilizo:

 class Teste extends Component {

  state = {
    assunto: "",
  };

 alterar = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

 render() {
  const { ocorrencias } = this.props;
  return (

  <select id="assunto" name="assunto" className="form-control"  onChange={this.alterar}>
                  <option value="0">Selecione...</option>
                  {ocorrencias.assunto.map(assunto => (
                   <option value={assunto.codigo}>{assunto.titulo}</option>
                  ))}
                </select>

 )
}

}

Select não deixa selecionar a opção


Como fazer um deserialize em um Json com C-sharp

Question: Tenho o seguinte código
private void WbRanking_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            RunOnUiThread(() =>
            {
                string json = Encoding.UTF8.GetString(e.Result);
                //lstRanking = JsonConvert.DeserializeObject<List<string>>(json);
                var obj = JsonValue.Parse(json);
                //var obj = JsonConvert.DeserializeObject<List<string>>(json);
                JsonTextReader reader = new JsonTextReader(new StringReader(json));

                ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, obj);

                while (reader.Read())
                {
                    if (reader.Value != null)
                    {
                        //string nome = obj[0];
                        lstRanking.Add("Nome " + obj[0] + "Sobrenome " + obj[1]);
                    }

                    lsvRanking.Adapter = adapter;
                }
            });
        }

Como é possível ver na imagem o var obj está recebendo com sucesso o Json de uma api rest que tenho local. Mas na hora de colocar as informações na listview o sistema me retorna este erro conforme a imagem.
Agradeço desde já!
Answer: normalmente para serializar e deserializar coisas utilizo o Newtonsoft json, nas comparações é mais rápido que o do próprio c# e é bem simples de usar.
Tem no Nuget, que faciliata bastante obter o pacote :D
https://www.newtonsoft.com/json
Não conenheço os metodos que voce esta chamando mas normalmente utilizo assim
using Newtonsoft.Json;
...

public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

void PersonToJsonToPersonExample ()
{
    var person = new Person { Name = "Bob", Birthday = new DateTime (1987, 2, 2) };
    var json = JsonConvert.SerializeObject (person);
    Console.WriteLine ("JSON representation of person: {0}", json);
    var person2 = JsonConvert.DeserializeObject<Person> (json);
    Console.WriteLine ("{0} - {1}", person2.Name, person2.Birthday);
}

Comment: Na verdade eu já estou utilizando mas não está funcionando.
Comment: não sabia direito como colocar aqui atualizei a resposta... hehehe


Sorting a FormGroup in Angular

Question: Aim is to sort the FormGroup contents based on creation date.
This is what I have tried. It is having no effect on the output. Nothing is being sorted. Please point out the fault.
sortByCreationDate()
  {
    for( var i = 0; i < (this.getCheckboxes_FormGroup.length); i++ )
    {
      for( var j = i ; j < (this.getCheckboxes_FormGroup.length); j++ )
      {
        if( Date.parse( this.getCheckboxes_FormGroup.at(i).get('creationDate' ).value)
                        > Date.parse( this.getCheckboxes_FormGroup.at(j).get('creationDate' ).value))
        {
          var objFormGroup1 : FormGroup;
          objFormGroup1 = this.objFormBuilder.group(
                            {
                              checkboxesBlogs: new FormArray([])
                            }
                          )

          objFormGroup1.patchValue( this.getCheckboxes_FormGroup.at(i) )

          this.getCheckboxes_FormGroup.at(i).patchValue( this.getCheckboxes_FormGroup.at(j) )

          this.getCheckboxes_FormGroup.at(j).patchValue( objFormGroup1 )
        }
        else
          console.log("else")
      }
    }
  }

Comment: Please let me know if some other information is required by me.
Comment: You may need to use variable names on the html elements, then grab the elements using ViewChildren. Next, cast ViewChildren to an array. https://angular.io/api/core/ViewChildren
Comment: @MatthewPitts You may have valuable information. Please write a detailed answer.
Answer: I believe this.getCheckboxes_FormGroup is a FormArray collection of FormGroups. Another way to sort your form array is to get a plain js array of objects of your form values as this.getCheckboxes_FormGroup.value. Apply sorting on form values and then loop through sorted collection and update each item in form array again.
const formValues = this.getCheckboxes_FormGroup.value;
formValues.sort(function(a,b){
    return new Date(b.creationDate) - new Date(a.creationDate);
});
for( var i = 0; i < formValues.length ; i++ ){
    this.getCheckboxes_FormGroup.at(i).patchValue(formValues[i])
}

Sorting a FormGroup in Angular


Basis vectors derivation from the position vector in general curvilinear coordinates

Question: In general coordinates, the basis vectors are defined as the derivatives of teh posituon vector:
$$\vec e_i = \frac { {\partial \vec R}} {\partial x^i}$$
Nonetheless, the position vector is given by:
$$\vec R= \sum_i x^i \vec e_i$$
and when we do the derivative we have:
$$\frac{\partial \vec R}{\partial x^n} = \sum_i(\frac{\partial x^i}{\partial x^n} \vec e_i + x^i \frac{\partial \vec e_i}{\partial x^n}) = \vec e_n + \sum_ix^i\frac{\partial \vec e_i}{\partial x^n} $$
Since the term $\sum_ix^i\frac{\partial \vec e_i}{\partial x^n}$ is not null in general, then the question is: where am I messing up?
Comment: $\vec{e}_i$ is being used to denote two different things here; the standard, euclidean basis vectors (which are constant) and the basis vectors associated with the curvilinear coordinates $R$. If might be a good to distinguish these two.
Comment: I would recommend to write

$$
\vec{R} = \sum_i x^i \vec{\epsilon}_i
$$

just so the difference between the Euclidean basis $\epsilon_i$ and the curvilinear vectors $e_i$ is more clear
Comment: Your equation for $\vec R$ as a linear combination of $\vec e_i$ is just wrong in general. Have you tried something like polar coordinates in the plane?
Comment: you deserve congrats for the right usage of  the indexing technique as $x^i$ for coordinates functions and $\vec e_i$ for basis vectors
Comment: OK, I think to have understood my error. The formula I used to express the position vector is valid just in Cartesian coordinates, not in general coordinates. Thanks!
Answer: You should be considering $\vec R=\sum_i R^i\vec e_i$ (instead of $R=\sum_i x^i\vec e_i$) where
each $R^i$ are functions of the euclidean coordinates $x^j$. It is necessary that
the Jacobian matrix $J\vec R=\left[\frac{\partial R^i}{\partial x^j}\right]$ has determinant different from zero in the domain of definition of $R$.
A new basis for the space in these coordinates are
$$\vec \partial_k=\sum_s\frac{\partial R^s}{\partial x^k}\vec e_s,$$
which give you, may be, a non-orthogonal neither non-orthonormal frame of the space.
Comment: yes, that is why you need to use $\vec R=\sum_s R^s\vec e_s$ where we have the dependence $R^s=R^s(x^1,...,x^n)$
Comment: also, it is of common use to symbolize $\vec e_i$ for the canonical basis of the space which is  orthonormal
Comment: As said in the above comments, the issue is simply that the formula $\ vec R = \sum_i x^i \vec e_i$ is not valid in general coordinates but just in cartesian coordinates


Configure Iptables to allow a PHP-app accessing a port-nr

Question: I have a php-application which connects to another app called Solr (database search engine).
I can via this php app add/remove documents (records) from the Solr index.
However, the Solr security is low, and anybody with the right port nr can access Solr and remove documents (records).
I wonder, is it possible to ONLY allow my own php-app to have access to Solr somehow?
Prefferably via Iptables. I am thinking I can only allow my own servers IP to that port, and it would solve my problem, because PHP is a server-side code. But I am not sure.
About the Php-app:
The website is a classifieds website, and when users wants to add or remove classifieds, they do so through a php app, which is this one.
The app has a function which connects to solr and updates the database (index).
I appreciate detailed answers...
Thanks
Answer: You cannot do that with iptables. Your best bet is using something in solr
http://wiki.apache.org/solr/SolrSecurity
Answer: No you can't control what application connects to a specific port, even on the local machine (you can do this with file permissions and Unix domain sockets - but not across a network).
Yes, you should restrict network access onthe SOLR port to a specific white-list. And if there are machines connecting from outside the local LAN, consider using IPSEC or a VPN and restricting access to that.
Alternatively, for remote access you might consider disallowing ALL access to the SOLR port, except for the localhost then running stunnel at both ends and require client certificate validation - and run your own snake oil CA if required.
HTH
C.


Receiving Two Objects in req.body

Question: I am receiving a POST request from an Unity app in x-form-encoded format into my NodeJs web-server .
I use app.use(bodyParser.urlencoded({ extended: true})) , to parse the content . But the req.body returns two objects , problem is that I cannot access the property of an individual property since they are neither wrapped in an array or object .
On console.log(req.body)
I get the following result
{ sessionId: '5ujgp6vwk1pivth4', gameId: '1', level: '0', score: '0' }

{ sessionId: '5ujgp6vwk1pivth4', gameId: '2', level: '0', score: '0' }

I want to know which type of datatype is this and how will I be able to access a particular property , suppose if I do
console.log(req.body.sessionId) , I get
5ujgp6vwk1pivth4

5ujgp6vwk1pivth4

Even if I try to push it into an array I still get the same result .
I am trying to fetch these objects into an array so that it will be easier for me to access them .
The script for the Express routes :
const express = require('express')
const path = require('path')
const hbs = require('hbs')
const bodyParser = require('body-parser')
const viewsRouter = require('./routers/views')
const apiRouter = require('./routers/api')
const cookieParser = require('cookie-parser')
require ('./db/mongoose')

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.use(cookieParser())
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
const viewsPath = path.join(__dirname,'../templates/views')
const partialsPath = path.join(__dirname,'../templates/partials')

hbs.registerPartials(partialsPath)
hbs.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
hbs.registerHelper("math", function(lvalue, operator, rvalue, options) {
lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);

return {
  "+": lvalue + rvalue,
  "-": lvalue - rvalue,
  "*": lvalue * rvalue,
  "/": lvalue / rvalue,
  "%": lvalue % rvalue
  }[operator];
  });
app.use(viewsRouter)
app.use(apiRouter)
// For any of the un-handled routes
app.get('*',(req,res)=>{
res.render('error')
})

//Setting up the CORS functionality in Express for Making AJAX calls
app.use(function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

next();

});

app.set('views',viewsPath)
app.set('view engine','hbs')

app.listen(80,()=>{
console.log('Server Started on Port 80')
})

The Route responsible for the particular POST is
apiRouter.post('/api/updateScore/',async(req,res)=>{
console.log(req.body)
})

The client script is :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Text;

public class ScoreSender : MonoBehaviour {

public Authentication authentication;
public  static readonly string scoreUrl = "https://eyenet.pythonanywhere.com/scores/";
public static ScoreSender instance;
public string Address = "127.0.0.1:8000";
// Use this for initialization
void Start () {
    instance = this;
}

// Update is called once per frame
void Update () {

}

public void sendScore(int gameId, int level)
{

}

public void sendScore(string gameId, int level, int score)
{
    string loginURL = Address+ "/api/updateScore/";

    WWWForm form = new WWWForm();
    form.AddField( "sessionId", authentication.session );
    Dictionary<string, string> headers = form.headers;
    byte[] rawData = form.data;

    WWW www = new WWW(loginURL, rawData, headers);

}
    // StartCoroutine(WaitForRequest(www));

public void saveScore(string gameId, int nextlevel, int score)
{

    // get session id
    string sessionCode = authentication.session;

    // get score array
    int noOfGames = PlayerPrefs.GetInt("totalGames",0);

    // get or create score, level, nextlevel arrays
    int gid = int.Parse(gameId);

    //
    int[] scoreArray = PlayerPrefsX.GetIntArray(sessionCode+"scores",0,noOfGames+1);
    int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionCode+"nextLevels",0,noOfGames+1);

    nextLevelsArray[gid] = nextlevel;
    scoreArray[gid] = score;

    PlayerPrefsX.SetIntArray(sessionCode+"scores",scoreArray);
    PlayerPrefsX.SetIntArray(sessionCode+"nextLevels",nextLevelsArray);

    PlayerPrefsX.SetIntArray("gameLevels",nextLevelsArray);
    Debug.Log("saved score and nextLevels offline");
}

//for sending score to the cloud

public void uploadScore()
{
    //testing
    //StartCoroutine(scoreSend(authentication.session,"1",45,34));
    syncScore(authentication.session);

}

//for online sessions only
void syncScore(string sessionId)
{
    Debug.Log("We are syncing the score for this session");

    int noOfGames = PlayerPrefs.GetInt("totalGames",0);
    int[] currentGamePlays = PlayerPrefsX.GetIntArray(sessionId+"currentGamePlays",0,noOfGames);
    int[] scoreArray = PlayerPrefsX.GetIntArray(sessionId+"scores",0,noOfGames+1);
    int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionId+"nextLevels",0,noOfGames+1);

    for(int i=0;i<noOfGames+1;i++)
    {
        if(currentGamePlays[i]==1)  //if the game is played in this session
        {
            StartCoroutine( scoreSend(sessionId,""+i,nextLevelsArray[i],scoreArray[i]));
            Debug.Log("score:"+scoreArray[i]);
            Debug.Log("level:"+nextLevelsArray[i]);
        }
    }
}

public int noOfScores=0;

public void syncOfflineScore(int num,string actualId)
{
    string sessionId = "offlineSession"+num;

    int noOfGames = PlayerPrefs.GetInt("totalGames",0);
    int[] currentGamePlays = PlayerPrefsX.GetIntArray(sessionId+"currentGamePlays",0,noOfGames+1);
    int[] scoreArray = PlayerPrefsX.GetIntArray(sessionId+"scores",0,noOfGames+1);
    int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionId+"nextLevels",0,noOfGames+1);

    for(int i=0;i<noOfGames+1;i++)
    {
        if(currentGamePlays[i]==1)  //if the game is played in this session
        {
            noOfScores++;
        }
    }

    for(int i=0;i<noOfGames+1;i++)
    {
        if(currentGamePlays[i]==1)  //if the game is played in this session
        {
            StartCoroutine( offlineScoreSend(actualId,""+i,nextLevelsArray[i],scoreArray[i]));
            Debug.Log("score:"+scoreArray[i]);
            Debug.Log("level:"+nextLevelsArray[i]);
        }
    }

}

//working fine
IEnumerator scoreSend(string sessionId,string gameId,int nextlevel, int score)
{
    string scoreUrl = authentication.Address+ "/api/updateScore/";

    WWWForm form = new WWWForm();

    form.AddField( "sessionId", sessionId );
    form.AddField( "gameId", gameId );
    form.AddField( "level", nextlevel);
    form.AddField( "score", score);

    Dictionary<string, string> headers = form.headers;
    //Dictionary<string, string> headers = new Dictionary<string, string>();
    //headers.Add("Content-Type", "application/json");
    byte[] rawData = form.data;

    WWW www = new WWW(scoreUrl, rawData, headers);
    WWW data =www;

    yield return data;
    if(data.error!=null)
    {
        Debug.Log (data.error);

        if(data.error == "Cannot connect to destination host")
        {

        }

    }
    else
    {
        Debug.Log(data.text);
        ServerResponse res = JsonUtility.FromJson<ServerResponse>(data.text);
        if(res.status==0)
        {
            Debug.Log("Updated score");

        }
        else
        {
            Debug.Log("Got an error");
        }
    }
}

//test it
IEnumerator offlineScoreSend(string sessionId,string gameId,int nextlevel, int score)
{
    string scoreUrl = authentication.Address+ "/api/updateScore/";

    WWWForm form = new WWWForm();

    form.AddField( "sessionId", sessionId );
    form.AddField( "gameId", gameId );
    form.AddField( "level", nextlevel);
    form.AddField( "score", score);

    Dictionary<string, string> headers = form.headers;
    byte[] rawData = form.data;

    WWW www = new WWW(scoreUrl, rawData, headers);
    WWW data =www;

    yield return data;
    if(data.error!=null)
    {
        Debug.Log (data.error);

        if(data.error == "Cannot connect to destination host")
        {

        }

    }
    else
    {
        Debug.Log(data.text);
        ServerResponse res = JsonUtility.FromJson<ServerResponse>(data.text);
        if(res.status==0)
        {
            Debug.Log("Updated score");
            noOfScores--;
            if(noOfScores==0)
            {
                authentication.syncOfflineSessionsDataComplete();
            }
        }
        else
        {
            Debug.Log("Got an error");
        }
    }
}

}

Comment: @num8er Thanks for the help, it really is two independent post requests being sent by the client due to which the route handler are running twice , I was just being confused with the way it printed on console.log(), it was actually the route handler running twice , due to which the req.body was also being logged twice .
Comment: What you get if you do `console.log(req)` share that please
Comment: 1. Your unity app sends 2 requests separately, to prove it use morgan https://www.npmjs.com/package/morgan#expressconnect  2. `req.body` is an object and `req.body.sessionId` is a string. 3. if `req.body` would be an array it would put square brackets around these 2 objects. 4. to understand what is req.body contents: `console.log(typeof req.body); console.log(req.body); console.log(typeof req.body.sessionId); console.log(req.body.sessionId);`
Comment: Is it not an object of objects and therefore you could use `Object.entries` to iterate?
Comment: @muasif80 The data is too lrge to comment, I have shared it on pastebin , please have a look at it
[link](https://pastebin.com/wFcxuUHN)
Comment: Any chance you've accidentally installed the handler for that route (/api/updateScore/) twice? That would explain you seeing two things printed out every time you use console.log().
Answer: Unfortunately, what is happening is different than what you think is happening, and there isn't enough information here to figure out what is actually going on.  You say that req.body is returning two objects, but that they are not wrapped in an array or another object, which is fundamentally impossible.
Given the information available, my best guess is that the bodyParser is working exactly as it should, but that whatever client application you are using to send requests is sending two requests where you think it's only sending one, so when you log it you are seeing two objects and assuming they came from a single call to console.log which doesn't appear to be the case.
To confirm that, I would probably stick something like this into the bottom of the file, and then use this to log instead of using console.log directly.  This will demonstrate that it's two different log entries coming from two different invocations of the route.
let counter = 0;
function logWithCounter( ...msg ) {
  console.log( counter++, ...msg );
}

Comment: After running the above snippet I get :

0 { sessionId: '5ujgph9ck1pkbz9a', gameId: '1', level: '0', score: '0' }

0 { sessionId: '5ujgph9ck1pkbz9a', gameId: '2', level: '0', score: '0' }

The counter does not increment
Comment: But the counter does get logged twice, which shows that it's definitely two different calls and not that you somehow have two different objects in the body, but like I said there isn't enough information to tell what is actually going on.  If you post the code you are having trouble with you may get a better response.
Comment: Thanks @Jason Kohles  Everything works perfectly fine it's just that there are two POST requests to the same route handler and the route handler executes twice which produces the two console logs, I was just confused with the way it appeared due to the console.log() , my bad .

Receiving Two Objects in req.body


Will MSE-based estimator generate symmetric residuals if the error has got symmetric support (not distribution)?

Question: This question is more specific than :my old question
Take follow regression model:
$y=f(x)+e$
Where $e\sim D$ with a such symmetric support $A=(-a,a)$, not symmetric distribution. Now given a data set $\{x_i,y_i\}_{i=1}^{N}$ and a estimator $g(.,\mathbf{\beta})$ to $f$.
Will I always get symmetric residuals if:
$\beta=argmin_{\beta}(\sum_{i=1}^{N}(g(x_i,\beta)-y_i)^2)$
I've simulated a regression problem where $y=x^2+e$ with $e$ having the follow distribution:
$f(e)=\frac{1}{exp(1)-exp(-1)}exp(e) I(e)_{\{-1,1\}}$
That is not symmetric at all:

But using random forest with MSE impurity to train $\{x_i,y_i\}_{i=1}^{N}$ I got these residuals:

Where are clearly symmetric. I think it'll always happen but I'm not able to proof it.
Answer: STILL NO
I have a similar argument as I gave in your previous question. Let's do the same model but with an error term that is an asymmetric beta distribution that is shifted to have support on $[-0.5, 0.5]$. I then take this a step further and multiply by a scaling factor to expand the support to $[-50, 50]$. I encourage readers to play with the a, b, and m values to see what happens.
set.seed(2021)
N <- 10000
a <- 1
b <- 3
m <- 100
x <- seq(0, 10, 10/(N - 1))
e <- rbeta(N, a, b) - 0.5 # subtract 0.5 so support is [-0.5, 0.5], not [0, 1]
e <- m * e # Multiply by m to stretch or compress the support to [-m/2, m/2]
y <- x + e
plot(x, y)
L <- lm(y ~ x)
par(mfrow = c(2, 1))
hist(resid(L))
hist(e)
par(mfrow = c(1, 1))

The empirical range of my e values is $-49.99677$ to $45.6901$, so the support looks pretty symmetric about $0$ (which we expect from the construction). However, neither the residuals nor the error term are symmetric, as the histograms below show.
Comment: Please see the hist of your genereted error this hasn't got symmetric interval that is $f(e)$ doesn't have non-null probability in whole interval $(-a,a)$. It seems there is $(-50,-10-ish)$ as support density on it, I'd argue your sample is little sized to stand for but that's not. Look through $length(e[e>-10])/N$ you will get in your hands a null probability when that should get you a positive probability beacause the sup would must be at $(-50,50)$.
Comment: The residuals might not have an error term with symmetric support, but the error term does.
Comment: The error should have symmetric support but that doesn't happen. Please see the error's histogram (not residuals) and be careful using qqplot to evaluate symmetry it actually does normality
Comment: I actually think the example I gave last night works (maybe not, but I think so), but it might have been too extreme to demonstrate what I wanted to show. The new simulation should be quite emphatic.
Comment: Ok I think it worked enough xD, thank you.


Aumentar fonte da lista na Validação de Dados

Question: Olá, tenho um campo da minha planilha que tem uma lista pela validação de dados, gostaria de saber como faço pra aumentar essa fonte, deixando ela mais visível.
OBS: Sem o esquema do zoom.
Essa é a lista:
Comment: Zoom - http://www.contextures.com/xlDataVal08.html#Larger

Combobox, seria algo assim: `With Worksheets("Sheet1").OLEObjects("ComboBox1")
   .Object.Font.Size = 16
End With`
Comment: Aqui um modelo completo: http://www.contextures.com/xlDataVal10.html
Comment: Estava publicando uma resposta quando atualizou... sem zoom acho difícil. A não ser que use um _combobox_
Comment: Eu esqueci de acrescentar desculpa, como seria com combobox?
Answer: Leandro infelizmente, você não pode alterar o tamanho ou o estilo da fonte em uma lista suspensa criada usando a validação de dados.
Você pode estilizar o texto em uma caixa de combinação, no entanto você pode utilizar uma caixa de combinação do controle ActiveX alterando as propriedades 'Font' e 'ListFillRange' você alcançará o desejado.


Is every self-homeomorphism homotopic to a diffeomorphism?

Question: Given a smooth manifold $M$, is every homeomorphism $M \to M$ homotopic to a diffeomorphism?
Hirsch's "Differential Topology" has a proof that every $C^1$ diffeomorphism of smooth manifolds is homotopic to a $C^\infty$ one, but as far as I can tell, says nothing about the case of $C^0$ automorphisms.
If false in general, is the above claim true in dimensions at most $3$? (If somehow false because of exotic smooth structures - is it true for topological manifolds supporting only one smooth structure?)
Comment: Maybe I'm being silly here. I don't understand how your parenthetical argument works, and if it works, I don't understand how it doesn't already imply what you want. Given a smooth manifold $M$ whose underlying topological manifold has more than one smooth structure, I can write down a self-homeomorphism of $M$ which exchanges two of these smooth structures. This self-homeomorphism certainly cannot itself be a diffeomorphism of $M$. (Why) does this imply that this self-homeomorphism cannot be homotopic to a diffeomorphism of $M$?
Comment: @QiaochuYuan I somehow convinced myself swapping the letters changed the situation. (Of course some of these various diffeomorphisms can be homotopic - there are only two homotopy classes of self-homeomorphisms of $S^7$ and 28 diffeomorphism types of $S^7$s. My aim with the letter swapping was to avoid this situation. I've edited the question to remove the parenthetical.
Comment: That's the definition of what it means for the same topological manifold to support more than one smooth structure.
Comment: @QiaochuYuan You say "I can write down a self-homeomorphism of $M$ which exchanges these smooth structures". In retrospect, this is not obvious to me. Why's it true?
Comment: That theorem in Hirsch's text is much stronger than what you quote.  Hirsch proves a $C^1$ diffeo is isotopic to a $C^\infty$ diffeo, not just homotopic (a strange relation on diffeomorphisms).  Are you sure this is the question you really want to ask?
Comment: I'm aware that it's stronger, @RyanBudney. I was asking the weaker question because I didn't expect the stronger condition to be true. Based on the answers posted below it seems that (outside of $n=4$) the two questions - homotopic or isotopic - are equivalent. I haven't read the note I cite carefully, though. (I'm aware it's a somewhat unnatural question.)
Comment: @RyanBudney The theorem in Hirsch's book I found proves that the set of $C^\infty$ diffeomorphisms  between smooth manifolds $M,N$ is dense in $G^1_S(M,N)$, the space of $C^1$ diffeomorphisms between $M$ and $N$ endowed with the strong topology. Why does it then follow that any $C^1$ diffeomorphism is then isotopic to a $C^\infty$ diffeomorphism? I didn't find any other theorems that seemed more relevant in Hirsch's text.
Comment: @MatthewKvalheim What you need is exercises 3 and 4 in that chapter. First, because the space of smooth functions is locally path-connected, there's a small homotopy between $f$ and a nearby smooth diffeomorphism $g$. Now apply a fiberwise, relative version of the smoothing machinery to $M \times I \to M$, which in this case would say 'if $E \to X$ is a fiber bundle, and $E \to Y$ is a map, $C^1$ on fibers, then it can be approximated by a $C^1$ map, $C^1$ close to the original maps on each fiber; and if it was $C^1$ on a given closed subset, we may assume the approximation...
Comment: ...leaves the map fixed on that subset.' Then we have a $C^1$ map $M \times I \to M$, $C^1$ close on the fibers to the original $f_t$ (which, because the set of diffeomorphisms is open and we demanded the homotopy small, are all $C^1$ diffeomorphisms), leaving $f_0$ and $f_1$ fixed. That's precisely what an isotopy is.
Comment: @MikeMiller thanks a lot for the help. As far as I can tell, everything seems to work if the domain and codomain weren't the same either (i.e. $f:M\to N$, $M \not = N$), right?
Comment: @MatthewKvalheim Yup, that works fine, and you could also do this sort of thing for embeddings, immersions, etc. I can't actually find this fiberwise version in Hirsch which surprises me, but I do promise it is a straightforward extension of what he does.
Answer: In dimensions 2 and 3 every homeomorphism is isotopic to a diffeomorphism (this should be in Moise's book "Geometric topology in dimensions 2 and 3", it also follows from Kirby and Siebenmann's work). In dimension 4 there are self-homeomorphisms of simply-connected smooth compact manifolds which are not homotopic to diffeomorphisms. This follows e.g. from invariance of the $\pm$ canonical class of smooth algebraic surfaces under diffeomorphisms, while, by Freedman's work, any automorphism of the intersection form is induced by a homeomorphism.
Edit. One more useful thing: The group of homeomorphisms of a topological manifold is locally contractible (with respect to the $C^0$ topology), this is a theorem by Chernavskii (1969). Thus, if you can approximate a homeomorphism by diffeomorphisms, they will be isotopic (for sufficiently close approximation).
Comment: Thank you for the Chernavskii reference. I'd been looking for something similar but had been unable to find it.
Comment: @MikeMiller: See http://www.encyclopediaofmath.org/index.php/Homeomorphism_group, written by Chernavskii himself!
Answer: In many dimensions, exotic spheres are counterexamples.
For example, the group of $7$ spheres is diffeomorphic to $\mathbb{Z}_{28}$.  Pick any element $\Sigma$ which doesn't not have order $2$, for example, a generator.

There is an orientation reversing homeomorphism $f:\Sigma\rightarrow \Sigma$ (so $f$ has degree $-1$), but there is no such orientation reversing diffeomorphism.

Since the degree is a homotopy invariant, this provides examples of what you want.
Proof:  Since $\Sigma$ is homeomorphic to $S^7$ and $S^7$ admits an orientation reversing homeomorphism, so does $\Sigma$.  Now, in the group of exotic spheres, the inverse element is the same sphere with orientation reversed.  Hence, if $\Sigma$ admits an orientation reversing diffeomorphism, then $\Sigma = -\Sigma \in \mathbb{Z}_{28}$, that is, the order of $\Sigma$ in $\mathbb{Z}_{28}$ is either $1$ or $2$.
$$ $$
Of course, this proof carries over to any dimension for which the group of exotic spheres contains an element not of order $2$.  This has to occur if the order of the group is not a power of $2$, so, according to the chart on wikipedia, there are examples in dimension $7, 10, 11, 13, 15, 19, 20$.  See also the OEIS sequence to find more examples.
Comment: While this answer uses exotic structures, I'm not sure I'd label your claim as "somehow false because of exotic smooth structures".  The exotic structure is just used to get a hold of the manifold to begin with.
Answer: First, note that a homeomorphism $f$ of compact smooth manifolds is homotopic to a diffeomorphism if and only if one can approximate $f$ arbitrarily well by diffeomorphisms.
For $n \leq 3$, this paper of Munkres claims as a corollary that a homeomorphism $f: M \to N$ of smooth manifolds may be approximated arbitrarily well by a diffeomorphism. This settles my question here. There is a  harder question of whether or not every homeomorphism is isotopic to a diffeomorphism. The consensus on this MathOverflow question and answers seem to be that it's true for $n=2$, though I haven't checked the stated references. Ian Agol's answer there sounds like it's true for $n=3$, but I'm not sure.
This note of Stefan Müller gives a proof that for $n \geq 5$, a homeomorphism of compact $n$-manifolds can be approximated arbitrarily well by diffeomorphisms if and only if the same homeomorphism is isotopic to a diffeomorphism.
Every related question in $n=4$ seems to be wide open.
Comment: @MatthewKvalheim The space of homeomorphisms is locally path-connected, as in studiosus's answer.
Comment: "First, note that a homeomorphism $f$ of compact smooth manifolds is homotopic to a diffeomorphism if and only if one can approximate $f$ arbitrarily well by diffeomorphisms."

I might be missing something obvious. Why is this true?


Proving that there can be no set of all ordered pairs.

Question: I have to prove that there is no set which contains all ordered pairs $\langle a,b\rangle$. in set theory, $\langle a,b\rangle$ is defined as $\{\{a\},\{a,b\}\}$.
My proof:
Say $S$ is the set with all ordered pairs. Then $S=A\times B$, where $A$ contains all the first coordinates and $B$ contains all the second coordinates. However, there has to be a set that is not contained within $A$, as there can be no set of all sets. Let that set be $r$. Then $\langle r,c\rangle\notin S$, where $c$ is any set of your choice.
Is the proof correct?
Comment: @Asaf: Pretty much any kind of ordered pair has a "set of all ordered pairs" in NF, but the sets of all Quine pairs and of all Kuratowski pairs have different cardinalities. I mention this because it's weird, and because I'm prone to pointlessly spouting NF trivia.
Comment: What type(s) of thing are $a$ and $b$?
Comment: @Eric: Sets, of course.
Comment: ZF?  ZFC?  New Foundations?
Comment: Since the axiom of choice has nothing to do with it; and I believe that in $\sf NF$ the collection of all ordered pairs is indeed a set; my guess that one of the first two.
Comment: @EricTowers- ZF
Comment: @AsafKaragila:  This matches my expectations, but I'm not going to tell the student what set theory he's using.
Comment: What argument has been used (somewhere else) to show that there is no universal set (i.e., a set containing all sets)?
Answer: No. Take $R_1=\{(1,a),(2,b)\}$.Then $R_1$ cannot be written as $A \times B$. So a set of ordered pair may not be written as cartesian product.
Below I give two proofs independent of perticular definition, say Kuratowski or Weiner or Hausdroff or short def etc.\
Proof1: Let $A$ be a set.Let us construct $B=\{(x,y)$$\in$ $A$$\mid$ $(x,y)$$\notin x$$\}$. We claim $(B,1)\notin A$.\  If possible let $(B,1)\in A$. Then by construction of $B$, $(B,1)\in B$ iff $(B,1)\in A$ and  $(B,1)\notin B$. Since we assume $(B,1)\in A$, $(B,1)\in B$ iff $(B,1)\notin B$. So our assumption $(B,1)\in A$ is false. Since $A$ is arbitary, the proof follows. \ Proof2: Let $A$ be the set of all ordered pairs. Since $A$ is a set of ordered pairs, $A$ is relation. Let $B=dom A$.Then $B$ is set$($Since $B\subseteq \bigcup \bigcup A$, by subset axiom, $B$ exists $)$ . There is set $C\notin B$, since there is no set of all sets. Fortiori $(C,1)\notin A$. This contradicts our assumtion. Hence such $A$ does not exists.
Answer: Here's how I would do it.
Let $V$ denote the meta-set of all entities, and $P$ denote the meta-set of all ordered pairs. Furthermore, let $\pi_0 : P \rightarrow V$ denote the unique meta-function with defining property
$$\pi_0(a,b) = a.$$
Now assume for a contradiction that $P$ can be internalized as a set. Then by replacement, since the domain of $\pi_0$ is a set, we have that $\pi_0[P]$ is also a set.
Exercise 0. Verify that $\pi_0[P]$ is a universal set. i.e. $\pi_0[P] = V.$
Exercise 1. Recall the axiom schema of separation implies that a universal set cannot exist, via Russell's paradox.
Comment: why "meta-set" instead of the standard "class"?
Comment: @AndresCaicedo, no particular reason. Feel free to edit with more standard terminology if you wish.
Answer: No.  The proof you have written says:  If the set of all ordered pairs is constructed as a cartesian product, then the first member of that product is a set we have all agreed doesn't exist.  So, that's (only) one possible way of constructing the set of all ordered pairs rejected.  Now we just have to adapt this for every possible way of constructing the set of all ordered pairs.
Alternatively, we can show that the assumption that the set of all ordered pairs exists leads to a contraduction no matter how it was constructed.
Let $P$ be the set of all ordered pairs of sets.  Let $f(\langle a,b \rangle) = a$ be the function that picks out the first member of a pair.  Then $F = \{f(x) \mid x \in P\}$ is a set.  It contains all of the first members of the pairs in the set of all ordered pairs of sets.  It therefore is a set containing all sets.  Since no such set exists, $F$ does not exist, so either $f$ is not a valid function of $P$ does not exist.
Do you believe that $f$ is a valid function?  If so, then $P$ does not exist.
Comment: I think there is only one way to construct such a set of ordered sets. Let us suppose $A$ is not the set of all sets. Then there is one set $x\notin A$. Hence, $\langle x,x\rangle$ does not exist, where $c$ is any element.
Comment: I meant $\langle x,c\rangle$
Comment: @algebraically_speaking:  How do you know that $P$ can't be the union of perfectly good sets?  Or the intersection of perfectly good sets?  Or that $P$ isn't the subset of some other set specified by a membership predicate?  There are many ways to make a set.  You'd have to eliminate every possible alternative.
Answer: If you're assuming Kuratowski pairs, then there's a very easy reductio. We know that for any $a,b$ we can form both $\langle a,b\rangle$ and $\langle b,a \rangle$, so every set would appear in some ordered pair. If $\mathsf{Pair}$ is our hypothetical set of all ordered pairs, then the axiom of Union says we can form $\bigcup\bigcup\mathsf{Pair}$. This would be $V$, which is impossible in ZF.
Answer: I think basically your approach is valid, but you could skip $A$ and $B$ and just consider the hypotheticall set $S$. Then by the axiom of union theres a set $U$, the union over the set $S$. Now if you know that universal set doesn't exist you have a contradiction since $U$ is just that.
Answer: The proof sketch has a significant gap — it does not attempt to justify writing $S = A \times B$ for sets $A$ and $B$.
Any attempt to justify this step will likely uncover a more direct proof of the theorem in the process.
Comment: It's not just a significant gap, it's a mistake that a set of ordered pairs is of the form $A\times B$. Just look at $\{(n,n)\mid n\in\Bbb N\}$.


independent t-test alternatives for unequal sample size

Question: I tried implementing an independent t-test (alpha = 0.05) using excel for male(n=20) and female(n=25) scores. However, excel doesn't allow it. Are there alternative tests for comparing the two samples??
Comment: I hope I will not sound arrogant, but don't use excel for data analysis. In the windows on the bottom of the page you may code your t-test and execute it, and it does allow different sample sizes. https://www.rdocumentation.org/packages/stats/versions/3.6.1/topics/t.test
Comment: I was going to respond "You don't need a different test, you need different software." There are many threads on this site about free statistical software.  Just this week, I was working with a colleague who was using Excel for statistical analysis.  I got her to try Jamovi.  Result: an email that said only, "I love Jamovi.  Thank you."
Comment: Unequal sample-size two sample t-test works in Excel.
Comment: The alternatives are 1) use other statistical package you are familiar with (again, t-test will work for unequal sample sizes in most of them), 2) write to Microsoft a report that they should fix excel, 3) learn basic R syntax (it will take around 5 minutes to code your vectors and perform a test)
Comment: I think there is a possibility that you are trying to do a _paired_ t test, which does require equal numbers of observations for the two groups. Whatever software you use, you need to be sure you know the difference between a paired t test and a t test for independent samples.
Comment: sorry but i'm not familiar with R
Answer: I will show you how to do a two-sample t test using R. In my illustration,
there are 10 males and 15 females. Notice that the syntax for entering
data requires a c at the beginning of a list.
male = c(55, 57, 53, 52, 53,  54, 55, 52, 54, 56)
female = c(54, 52, 51, 55, 53,  53, 52, 51, 54, 52,  50, 53, 52, 54, 53)

summary(male);  length(male);  sd(male)
summary(female); length(female);  sd(female)

Now some summary statistics. Notice that the sample mean for males is
slightly larger than the sample mean for females. A t test will
determine whether this small difference is statistically significant.
summary(male);  length(male);  sd(male)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   52.0    53.0    54.0    54.1    55.0    57.0
[1] 10        # sample size
[1] 1.66333   # sample SD
summary(female); length(female);  sd(female)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   50.0    52.0    53.0    52.6    53.5    55.0
[1] 15
[1] 1.352247

Here is a pooled 2-sample t test. The formula can be found in
almost any elementary statistics text. You can verify results using
a calculator. Notice the use of the 'parameter' var.eq=T in the
statement that performs the test. Notice that the number of degrees of freedom df is 10 + 15 - 2 = 23.
t.test(male, female, var.eq = T)

        Two Sample t-test

data:  male and female
t = 2.4796, df = 23, p-value = 0.02091
alternative hypothesis:
   true difference in means is not equal to 0
95 percent confidence interval:
 0.248604 2.751396
sample estimates:
mean of x mean of y
     54.1      52.6

Unless you have prior knowledge that the two populations have the
same variance, it is best to do a Welch two-sample t test. You may
be able to find the formula for this test in an elementary statistics
text or by searching the Internet. This tests uses a more complicated
formula for the degrees of freedom (in order to adjust for the possibility
the population variances may not be equal). That formula is a little
messy (but not impossible) to compute on a calculator.
Following good
statistical practice, R uses the Welch version of the two-sample t test
unless instructed to do otherwise. When sample sizes are unequal the
pooled T statistic and the Welch T statistic are a little different.
t.test(male, female)

        Welch Two Sample t-test

data:  male and female
t = 2.376, df = 16.606, p-value = 0.02983
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
 0.1656084 2.8343916
sample estimates:
mean of x mean of y
     54.1      52.6

For my fake data, both versions of the two-sample t test reject
(5% level) the null hypothesis that population means are equal.
Notice that the P-value is smaller than 0.05 in the output for
each test.
So the difference 54.1 - 52.6 = 1.5 between the two sample means
is statistically significant. Whether such a difference is of
practical importance is another matter.
Note: When Excel was first released years ago, there were some
serious difficulties with its implementation of many statistical
procedures. Reports in statistical journals have indicated that the
most serious difficulties have been fixed. My guess is you can
get nearly the same results shown in R above if you use Excel
correctly with the same data. However, I agree with the Comments
that you may benefit in the long run if you learn to use R instead
of Excel. There are many alternative statistical software
packages, but R is excellent software, available free of charge,
and easy to install.
There are many help pages for using R on the Internet.


MIME type issue in JavaScript

Question: I am working in a Web site. My  is like below.

    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">

But I am getting error The resource from "https://github.com/pchen66/panolens.js/blob/master/build/panolens.min.js" was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff).

Why I am seeing this error ?
Comment: Because github does not want you linking to the files.... It is set to a different content type.
Answer:
use rawgit.com instead of github.com

    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">

MIME type issue in JavaScript


How to create a "navicon" effect

Question: I would to create a "navicon menu", like in this article.
It seems to be a standard for mobile and responsive sites.
Is there some module that do this?
Comment: I think you're talking about what my team calls a hamburger menu. It's really just a convention for having a special menu display below a certain breakpoint. Any theme or module that supports media queries supports it.
Comment: Can you explain what navicon is? Or should we read the whole article?
Comment: The "navicon" is a wayu to render a menu in mobile devices. Generally a menu is renderd as an icon that, if I click on it, it expands and show menu links: http://media.smashingmagazine.com/wp-content/uploads/2012/08/IMG_1990.jpg (the icon on the right)
Comment: I was googling for this by the term Sandwich.
Answer: The Superfish module does that. It integrates the Superfish jQuery script into Drupal. It has two responsive menu options for small screens; either rendering it has an accordion or a drop-down. I strongly recommend using the Dev version as it is 'production ready' and has multiple improvements over the older release.

How to create a "navicon" effect


if $\limsup a_{n+1}/a_n = L < 1$, then $\sum a_n$ converges

Question: I must demonstrate that, $\forall \{a_n\}$ define in $\mathbb{R}^{+}$, if
$$\limsup_{n \to \infty} \frac{a_{n+1}}{a_n} = L < 1 \implies \sum a_n \text{ converges}$$
I know by the ratio test that if the limit is lower than $1$, the series will converges but what about the the superior limit?
Thanks for your help.
Comment: Pick a meaningful title. Titles let people know quickly if they are able to help you. A title like this either wastes people's time (those who can't help but clicked through anyway) and loses people who might help (they simply ignore it and move along.) Help people help you.
Answer: By the definition of $\limsup$ there's for each $\epsilon>0$ an $N$ such that $a_{n+1}/a_n < L+\epsilon$ whenever $n>N$. From this follows that $a_n < a_N(L+\epsilon)$. Choosing $\epsilon<1-L$ will make $a_n$ limited by a geometric series.
It's also bounded below by $0$.
Answer: We have $L < M < 1$ only if there is some $N \geq 1$ such that
$$
\frac{a_{n+1}}{a_{n}} < M
$$
for all $n \geq N$,
and
only if for all $p \geq 1$ we have
$$
a_{N+p} < a_{N}M^{p}
$$
by induction.
But $\sum_{p \geq 1}M^{p}$ converges;
so by comparison test
$\sum_{p \geq 1}a_{N+p}$ converges.
Comment: Why $M^p$? Where came the exposant?
Comment: It can be shown (try!) that If $L = \limsup_{n \to \infty}a_{n+1}/a_{n}$, then for every $\varepsilon > 0$ there is some $N \geq 1$ such that $a_{n+1}/a_{n} < L+ \varepsilon$ for all $n \geq N$.
Comment: Use induction to solve your problem!


Working demo of state management in Polymer 2.x using Mixins

Question: Here, I'm trying to build a working demo to implement the code contained in this blog article written by @CaptainCodeman — Managing State in Polymer 2.0 - Beyond Parent / Child Binding
Share state between separated DOM elements without Redux.
I'm getting the following errors.

run.plnkr.co/:5 GET https://cdn.rawgit.com/download/polymer-cdn/2.0.0/lib/webcomponentsjs/webcomponents-lite.min.js
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/my-options.html 500 ()
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/shared-styles.html 500 ()
my-view2.html:26
Uncaught ReferenceError:
MyOptionsMixin is not defined at my-view2.html:26

Does anyone have a working demo of this?
my-options.html
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-checkbox/paper-checkbox.html">

<dom-module id="my-options">
  <template>

Options

      <paper-checkbox checked="{{ options.subscribe }}">Send Notifications</paper-checkbox>

  </template>

</dom-module>

my-view2.html
<link rel="import" href="../bower_components/polymer/polymer-element.html">

<link rel="import" href="my-options.html">
<link rel="import" href="shared-styles.html">

<dom-module id="my-view2">
  <template>

2

View Two

Ea duis bonorum nec, falli paulo aliquid ei eum.

Id nam odio natum malorum, tibique copiosae expetenda mel ea.Detracto suavitate repudiandae no eum. Id adhuc minim soluta nam.Id nam odio natum malorum, tibique copiosae expetenda mel ea.

Send notifications option is: [[ options.subscribe ]]

  </template>

</dom-module>

Edit: Working Demo (accepted answer forked and edited)
Comment: AFAIK, at present, [this blog article](https://www.captaincodeman.com/2017/07/06/managing-state-in-polymer-20-beyond-parent-child-binding) and [this working demo](https://plnkr.co/edit/P55mSoApzVz7UhHRu6j6?p=preview) represent the best practice for state management in Polymer. It seems more popular than [tur-nr/polymer-redux](https://github.com/tur-nr/polymer-redux). Can anyone confirm or deny this?
Answer: working plunker

run.plnkr.co/:5 GET https://cdn.rawgit.com/download/polymer-cdn/2.0.0/lib/webcomponentsjs/webcomponents-lite.min.js

Your

run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/my-options.html 500 ()
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/shared-styles.html 500 ()

my-view2.html sets <base href> to polygit.org, and then tries to import my-options.html and shared-styles.html, both of which only exist in the Plunker sandbox:

<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer-element.html">

<link rel="import" href="my-options.html">
<link rel="import" href="shared-styles.html">

The only file imported here that needs to come from polygit.org is polymer-element.html, so you could remove the <base> tag and move the URL prefix to that import:
<link rel="import" href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/polymer/polymer-element.html">

my-view2.html:26 Uncaught ReferenceError:
  MyOptionsMixin is not defined at my-view2.html:26

my-view2 does not declare/instantiate my-options, so the script that defines MyOptionsMixin is never executed. You could resolve this simply by declaring it in my-view2's template:
 <dom-module id="my-view2">
    <template>
      <my-options></my-options>
    </template>
    ...
 </dom-module>


Estimating quantiles using quantile regression

Question: I understand that quantile regression estimates the conditional quantile of some measured variable (call the variable $y$), but can you use quantile regression to estimate an unconditional quantile of a distribution? For example, if I had 100 data points
$$y_1,...,y_{100}\sim N(\mu, \sigma^2)$$
then I could use some method to try to estimate the true quantile of the distribution, i.e., $q = \mu + z_\alpha\sigma$. But if I don't have any covariate information, can I still use quantile regression to estimate some quantile of interest from my data $y$?
Answer: Why not try it and see?
<code>set.seed(1234)
library(quantreg)

x <- rnorm(1000)
m1 <- rq(x~1, c(0.1, 0.5, 0.9))
m1                            #-1.2121   -0.03965, 1.33418
quantile(x, c(0.1, 0.5, 0.9)) #-1.21322  -0.03979   1.3344
</code>
Interestingly, the estimates from quantile regression are not exactly the actual quantiles, although they are very close. I don't know why.
I also tried some other distributions, and some were a little less close than the one above.
Comment: Note that the `quantile` function  has nine methods of performing the calculation. This can be changed using the `type` argument.
Comment: @JohnSmith [Of possible interest](https://stats.stackexchange.com/q/46434/247274)
Comment: Do you know how to get the quantreg function to give a confidence interval on the quantile estimate?
Comment: You can use boot.rq to get CIs.
Comment: Thanks. Might you be able to provide a simple example?
Comment: There doesn't seem to be a SIMPLE way to do it.  You can use:

m2 <- rq(x~1, c(0.5))
summary(m2, se = "boot", bs = "xy")
Comment: the summary function gives the SE for the coefficients.   boot.rq itself gives two matrices; maybe there is a good way to make them useful, but it isn't apparent to me.
Answer: YES
This is just a quantile regression on an intercept and nothing else. The theory is similar to how OLS linear regression on just an intercept gives the mean.
Minimizing the sum of squared deviations gives the mean, and minimizing the sum of quantile loss values gives the quantile.
Comment: thanks for confirming my suspicions. I know it's an estimate, but do you actually recover the true form of the quantile of the distribution using quantile regression in this case? For example, if I knew the true quantile of my distribution was $q=\mu+z_\alpha\sigma$, does the quantile estimate lead to that equation?
Comment: @JohnSmith No, you are not guaranteed to get the true value when you estimate from data.
Comment: Sorry, I need to learn to better state my questions. What I meant by recover the true form, is whether or not solving analytically the formula for the quantile regression gives you back the closed form solution for the quantile of the distribution of interest. So no data here but just maths. I'm attempting now to put pencil to paper by math skills is admittedly not that great


AWS CDK vs AWS Amplify

Question: I have a doubt in my mind regarding AWS Amplify and CDK.
In Amplify if we can create new environments and publish them to their respective buckets? Why do we need CDK?
Any use case that would make CDK a better fit?
Answer: CDK let you deploy (quite) any type of Stack that you have to manually do with cloudformation. Using cdk, you are going to create a CloudFormation stack more quicly and in a more secure way.
An example in JAVA, in order to create a new Table, you can use the following code instead of deal with YAML configuration:
 private Table CreateMasterDataTable(String TABLE_NAME) {
    return Table.Builder.create(this, TABLE_NAME + "_MasterDataTable")
            .tableName(TABLE_NAME.concat("_gvr-bic-masterdata"))
            .partitionKey(Attribute.builder().type(AttributeType.STRING).name("siteId").build())
            .removalPolicy(RemovalPolicy.RETAIN)
            .stream(StreamViewType.NEW_AND_OLD_IMAGES)
            .readCapacity(5)
            .writeCapacity(5)
            .build();
}

In order to create a new Lambda (provided an alredy existent JAR), you can use the following code instead of deal with YAML configuration:
private Function CreateSiteAggregationNowFunction() {
    Map<String, String> env = new HashMap<>();
    env.put(Constants.LAMBDA_KEY_ENV, API_NAME);
    return Function.Builder.create(this, API_NAME + "_SiteAggregationNow")
            .code(Code.fromAsset(Constants.LAMBDA_PATH_SITE_NOW))
            .handler("it.fabricalab.gvr.bic.DeviceLoader::handleRequest")
            .timeout(Duration.seconds(30))
            .environment(env)
            .functionName(API_NAME.concat("_SiteAggregationNow"))
            .runtime(Runtime.JAVA_8)
            .retryAttempts(Constants.LAMBDA_RETRY_FALLBACK)
            .memorySize(512)
            .build();
}

Than, in order to create the policy for let the lambda read from the table:
final Table masterDataTable = CreateMasterDataTable(API_NAME);
final Function siteAggregationNow = CreateSiteAggregationNowFunction();

masterDataTable .grantReadData(siteAggregationNow);

With these few lines, you have crated a CloudFormation stack with a DynamoDB table (that use stream) and a Lambda that read from this table.
Answer: Amplify is ok for deploying static sites, with a simple database and Cognito integration, but it is not good for managing a large number of environments or more complicated stacks.  CDK is much better for managing complex infrastructure deployment. This is an example of how you can deploy static sites with CDK.
https://github.com/davidsteed/awscdkstaticsite.  It improves on what can be done with Amplify by dealing with security headers and certificate generation.
Answer: You will find out that you will need to write and edit a lot of CloudFormation templates for a production app. That gets very painful very fast.
Amplify should emit CDK code, that would give us the best of both worlds.
I used Amplify a lot initially as it could bootstrap you quickly, but since discovering CDK, CDK is the tool I use the most.

AWS CDK vs AWS Amplify


XSS - is it dangerous that innerText string can be HTML elements: script, div etc?

Question: I'm working on the client side of a reviews web site.
the user can insert in the review description, any text including html element text (like : ), and style it with the basic text styles: italic, bold etc...
I wanted to test cross site scripting. so i played with it a little,  and when using italic the elements get rendered as the innerText of the html element.
The innerText in the HTML looked like this:

I didn't saw the alert get executed, though.
can the user write text that will become valid HTML with it's events invoked ?
if so, how ?
Comment: Note: For your img pen-test it should be ``. `onload` wouldn't fire here even on insecure setup.
Answer: What you're seeing in the elements/DOM tab is misleading you a bit. If you've used innerText (or more appropriately textContent, usually) to set the text of an element, it doesn't have tags in it. It has characters. Those characters can form tags from a display perspective, but they aren't tags and the browser doesn't treat them that way.
One way to see this is to see the HTML for them:

const target = document.getElementById("target");
target.textContent =
    `


Issue with GeckoFX Web Browser 33

Question: I have a WinFrom project in VS 2013 which I embedded GeckoFX webbrowser control to display web page inside the form. The GeckoFX Web Browser and XULRunner I am using is 33.0.
When I call GeckoWebBrowser.Navigavte(url), it works fine and displays the web page I am requesting. However, when I call geckoWebBrowser1.Refresh(), the WebBrowser control does not refresh the page. I also tested GoBack and GoForward functions, it all works fine.
Can anyone help me with this refresh issue?
Thanks
Jing
Comment: Try `geckoWebBrowser1.Reload();`. Or you can also use `geckoWebBrowser1.Navigate(geckoWebBrowser1.Url.AbsoluteUri);`.
Answer: I have a WinForm project in VS 2014 with GeckoFX. @IT Captain's solution is the correct answer. When I use Reload() it works while Refresh() doesn't.

Issue with GeckoFX Web Browser 33


libgdx remove bullet from bullet array

Question: im creating a 2d game. i have an array of a bullet class which i use to create my bullets. i also have another array this consisting sprites which move around the screen this being rendered every 3 to 4 seconds.
Problem:
when the bullet and other sprite meet at the same location the bullet should be removed or deleted and never comeback.
please help me...
code for rendering bullet:
bullet.java:
import com.badlogic.gdx.math.Vector2;

public class Bullet{

public Vector2 bulletLocation = new Vector2(0, 0);
public Vector2 bulletVelocity = new Vector2(0, 0);

public Bullet(Vector2 sentLocation, Vector2 sentVelocity) {
    bulletLocation = new Vector2(sentLocation.x, sentLocation.y);
    bulletVelocity = new Vector2(sentVelocity.x, sentVelocity.y);
}

public void Update() {
    bulletLocation.x += bulletVelocity.x;
    bulletLocation.y += bulletVelocity.y;
}
}

main class:
ArrayList<Bullet> bulletManager = new ArrayList<Bullet>();
Array<Other> OthersManager = new Array<Other>();
Bullet currentbullet;
Other currentOthers;

render();
int other = 0;
while (other < OthersManager.size) {
currentOthers = OthersManager.get(other);
        if (currentOthers.OtherLocation.x > guy.getX()) {
            currentOthers.OtherVelocity.x = -2f;
        }
        if (currentOthers.OtherLocation.x < guy.getX()) {
            currentOthers.OtherVelocity.x = 2f;
        }
        currentOthers.Update();
        others.setPosition(currentOthers.OtherLocation.x,currentOthers.OtherLocation.y);
        others.draw(batch);
        other++;
    }

    int counter = 0;
    while (counter < bulletManager.size()) {
        currentbullet = bulletManager.get(counter);
        currentbullet.Update();
        shoot.setPosition(currentbullet.bulletLocation.x,currentbullet.bulletLocation.y);
        if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
            bulletManager.remove(currentbullet);
        }
        shoot.draw(batch);
        counter++;
    }

Comment: Have you written any code for collision?
Comment: yeah. sorry i didnt show it. check my code again I've added it
Answer: It seems that the problem is in this block of code:
    if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
        bulletManager.remove(currentbullet);
    }

I would suggest you to use epsilonEquals method from Vector2 class to check whether your currentOthers.OtherLocation matches currentbullet.bulletLocation:
    if(currentOthers.OtherLocation.epsilonEquals(currentbullet.bulletLocation)){
        bulletManager.remove(currentbullet);
    }

Moreover you can use epsilonEquals with float epsilon:
documentation

libgdx remove bullet from bullet array


.NET System Type to SqlDbType

Question: I was looking for a smart conversion between .Net System.Type and SqlDbType. What I found it was the following idea:
private static SqlDbType TypeToSqlDbType(Type t)
{
    String name = t.Name;
    SqlDbType val = SqlDbType.VarChar; // default value
    try
    {
        if (name.Contains("16") || name.Contains("32") || name.Contains("64"))
            {
                name = name.Substring(0, name.Length - 2);
            }
            val = (SqlDbType)Enum.Parse(typeof(SqlDbType), name, true);
        }
        catch (Exception)
        {
            // add error handling to suit your taste
        }

        return val;
    }

The code above is not really nice and is a code smell, which is why I wrote the following, naïve, not smart, but useful function, based on https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx:
   public static SqlDbType ConvertiTipo(Type giveType)
    {
       var typeMap = new Dictionary<Type, SqlDbType>();

        typeMap[typeof(string)] = SqlDbType.NVarChar;
        typeMap[typeof(char[])] = SqlDbType.NVarChar;
        typeMap[typeof(int)] = SqlDbType.Int;
        typeMap[typeof(Int32)] = SqlDbType.Int;
        typeMap[typeof(Int16)] = SqlDbType.SmallInt;
        typeMap[typeof(Int64)] = SqlDbType.BigInt;
        typeMap[typeof(Byte[])] = SqlDbType.VarBinary;
        typeMap[typeof(Boolean)] = SqlDbType.Bit;
        typeMap[typeof(DateTime)] = SqlDbType.DateTime2;
        typeMap[typeof(DateTimeOffset)] = SqlDbType.DateTimeOffset;
        typeMap[typeof(Decimal)] = SqlDbType.Decimal;
        typeMap[typeof(Double)] = SqlDbType.Float;
        typeMap[typeof(Decimal)] = SqlDbType.Money;
        typeMap[typeof(Byte)] = SqlDbType.TinyInt;
        typeMap[typeof(TimeSpan)] = SqlDbType.Time;

        return typeMap[(giveType)];
     }

Does someone have idea of how to get the same result in a cleaner, better and nice way?
Comment: Making dictionary conversion is OK. Done *once* in a life time. :) (less there is a change)
Answer: Your approach is a good start, but populating that dictionary should only be done once, as Ian says in a comment.
There is a GIST here that is based on the same idea, although it doesn't convert between the same sets of types: https://gist.github.com/abrahamjp/858392
Caveat
I have a working example below, but you need to be aware that this approach does have a few problems. For example:

For a string, how do you pick the correct one between Char, NChar, VarChar, NVarChar, Text or NText (or even Xml, maybe)?
And for blobs like byte[], should you use Binary, VarBinary or Image?
For decimal, float and double, should you go for Decimal, Float, Money, SmallMoney or Real?
For a DateTime, do you need DateTime2, DateTimeOffset, DateTime, or SmallDateTime?
Are you using Nullable types, like int?? Those should most likely give the same SqlDbType as the underlying type.

Also, just providing a Type tells you nothing of other constraints, like field size and precision. Making the right decision is also about how the data is used in your application and how it is stored in the database.
The best thing to do is really to let an ORM do this for you.
Code
public static class SqlHelper
{
    private static Dictionary<Type, SqlDbType> typeMap;

    // Create and populate the dictionary in the static constructor
    static SqlHelper()
    {
        typeMap = new Dictionary<Type, SqlDbType>();

        typeMap[typeof(string)]         = SqlDbType.NVarChar;
        typeMap[typeof(char[])]         = SqlDbType.NVarChar;
        typeMap[typeof(byte)]           = SqlDbType.TinyInt;
        typeMap[typeof(short)]          = SqlDbType.SmallInt;
        typeMap[typeof(int)]            = SqlDbType.Int;
        typeMap[typeof(long)]           = SqlDbType.BigInt;
        typeMap[typeof(byte[])]         = SqlDbType.Image;
        typeMap[typeof(bool)]           = SqlDbType.Bit;
        typeMap[typeof(DateTime)]       = SqlDbType.DateTime2;
        typeMap[typeof(DateTimeOffset)] = SqlDbType.DateTimeOffset;
        typeMap[typeof(decimal)]        = SqlDbType.Money;
        typeMap[typeof(float)]          = SqlDbType.Real;
        typeMap[typeof(double)]         = SqlDbType.Float;
        typeMap[typeof(TimeSpan)]       = SqlDbType.Time;
        /* ... and so on ... */
    }

    // Non-generic argument-based method
    public static SqlDbType GetDbType(Type giveType)
    {
        // Allow nullable types to be handled
        giveType = Nullable.GetUnderlyingType(giveType) ?? giveType;

        if (typeMap.ContainsKey(giveType))
        {
            return typeMap[giveType];
        }

        throw new ArgumentException($"{giveType.FullName} is not a supported .NET class");
    }

    // Generic version
    public static SqlDbType GetDbType<T>()
    {
        return GetDbType(typeof(T));
    }
}

And this is how you would use it:
var sqlDbType = SqlHelper.GetDbType<string>();
// or:
var sqlDbType = SqlHelper.GetDbType(typeof(DateTime?));
// or:
var sqlDbType = SqlHelper.GetDbType(property.PropertyType);

Comment: Looks good! I would only add a check to see if the type exists (`ContainsKey`) in the dictionary and if not throw a `NotSupportedException` (or custom exception) with your own detailed message instead of the default `KeyNotFoundException`. This might make for easier troubleshooting later if a non supported type is ever passed in.
Comment: Thanks for the tip. I have edited the answer to throw an `ArgumentException`, as the `NotSupportedException` is not meant for this type of thing.
Answer: It appears that this sort of lookup table is already available, albeit not in System.Data (or .Object or .Type) but rather in System.Web.
Project -> Add Reference -> System.Web -> OK
Then https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx also says

When setting command parameters, the SqlDbType and DbType are linked.
  Therefore, setting the DbType changes the SqlDbType to a supporting
  SqlDbType.

So, this should theoretically work;)
using Microsoft.SqlServer.Server; // SqlDataRecord and SqlMetaData
using System;
using System.Collections; // IEnumerator and IEnumerable
using System.Collections.Generic; // general IEnumerable and IEnumerator
using System.Data; // DataTable and SqlDataType
using System.Data.SqlClient; // SqlConnection, SqlCommand, and SqlParameter
using System.Web.UI.WebControls; // for Parameters.Convert... functions

private static SqlDbType TypeToSqlDbType(Type t) {
    DbType dbtc = Parameters.ConvertTypeCodeToDbType(t.GetTypeCodeImpl());
    SqlParameter sp = new SqlParameter();
    // DbParameter dp = new DbParameter();
    // dp.DbType = dbtc;
    sp.DbType = dbtc;
    return sp.SqlDbType;
}

Comment: Thank you this is perfect information for what I needed!
Answer: My office mate gave me the idea to try a property of SqlParameter:
Func<Object, SqlDbType> getSqlType = val => new SqlParameter("Test", val).SqlDbType;
Func<Type, SqlDbType> getSqlType2 = type => new SqlParameter("Test", type.IsValueType?Activator.CreateInstance(type):null).SqlDbType;

//returns nvarchar...
Object obj = "valueToTest";
getSqlType(obj).Dump();
getSqlType2(typeof(String)).Dump();

//returns int...
obj = 4;
getSqlType(obj).Dump();
getSqlType2(typeof(Int32)).Dump();

//returns bigint...
obj = Int64.MaxValue;
getSqlType(obj).Dump();
getSqlType2(typeof(Int64)).Dump();

https://dotnetfiddle.net/8heM4H
Comment: In what way?  I casted some of the literals (ie (int?)4) and it seems to work - still returns int as the sql data type.  Remember this is getting the equivalent data type in sql.  Unlike .net where you really have two types, nullability is inherint in the data type and then is denied via contraint.
Comment: Note that this doesn't handle nullable types.
Answer: Edit: I was thinking about and this works for System.Data.SqlTypes types. I'll leave it here just in case it helps someone in the future.
I do something like this:
object objDbValue = DbReader.GetValue(columnIndex);
Type sqlType = DbReader.GetFieldType(columnIndex);
Type clrType = null;

if (sqlType.Name.StartsWith("Sql"))
{
    var objClrValue = objDbValue.GetType()
                                .GetProperty("Value")
                                .GetValue(objDbValue, null);
    clrType = objClrValue.GetType();
}

Because every SqlDbType has a .Value property which is the actual underlying CLR type I use reflection to get it. It's too bad SqlDbType doesn't have some interface that would hold this .Value property and reflection wouldn't be needed.
It's not perfect but you don't have to manually create, maintain or populate  a dictionary. You can just look up a type in an existing dict, and if it doesn't exist use the upper method to add the mapping automatically.
Pretty much auto-generated.
Also takes care of any new types that SQL Server might receive in the future.
Comment: Looks like [SqlDbType](https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx) is an enumeration so I am not sure how that holds additional information about a CLR Type. Also for creating queries it would not work, only for translating results from a query to the correct CLR type.
Comment: "Edited: Not sure where the comment I was replying to went." ah, you're right, for the other direction i don't have a better answer than a pre-populated dictionary. Although usually the use case is from sql type to clr type because one sql type can map to multiple clr types.
Comment: Sorry, I deleted my comment right away because I wanted to rethink a little. My initial comment was *"Doesn't this go the opposite direction?"*. Now I'm more with @Igor, as the desired `SqlDbType` is an enumeration.
Comment: you're right, I was constantly thinking of System.Data.SqlTypes namespace. https://msdn.microsoft.com/en-us/library/system.data.sqltypes(v=vs.110).aspx my bad.

.NET System Type to SqlDbType


Turn off AppEngine (Java) sessions for certain requests

Question: We're using sessions in our GAE/J application. Over the weekend, we had a large spike in our datastore writes that appears to have been caused by a large number of _ah_SESSION entities being created (about 100-200 every minute). Near as we can tell, there was a rogue task queue creating them because they stopped when we purged the queue. The task was part of a mapper process we run hourly.
We don't need sessions in that hourly mapper (or indeed in any of our task queues or cron jobs or many other requests). Is there a way to disable creating a session for selected URLs?
Answer: Unfortunately that can not be done.
This is particularly nasty when you have a non-browser clients (devices via REST or mapreduce jobs) where every request generates a new _ah_SESSION entity in the database.
The only way to avoid this is to write your own session handler: e.g. a servlet filter that sets/checks cookies and set it so that it ignores certain paths.
EDIT:
I just realized that there could be another way: make sure your client (mapreduce job) sets a dummy cookie with a proper name. GAE uses cookies named ACSID in production and dev_appserver_login on dev server. Just use always the same cookie value, so all requests will be treated as one user/session.
There will still be overhead of looking-up/saving session objects, but at least it will not create countless _ah_SESSION entities.
Comment: Thanks Peter. We'll go with a custom handler.


What would cause a duplicate session key?

Question: I occationally recieve the following error resulting in failure of several pieces of code later in the pipeline.
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY-Cu6Y9OkPd1qJuonzHQw2' for key 1:
   UPDATE {sessions}
   SET sid=:db_update_placeholder_0, ssid=:db_update_placeholder_1
   WHERE (ssid = :db_condition_placeholder_0) ;
Array (
   [:db_update_placeholder_0] => QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY
   [:db_update_placeholder_1] => Cu6Y9OkPd1qJuonzHQw2JI67BDvO85pqp50SBsXE1ZU
   [:db_condition_placeholder_0] => fMabX3y84Ngm-HcGF8MomLvLp1kmceLRIwniv_dSj_M )
in drupal_session_regenerate() (line 393 of /var/aegir/platforms/demandmetric/includes/session.inc).

I am using custom code that rougly looks like this:
drupal_session_start();
_$SESSION[''] = bunch of generated info.
Authorize linkedin
create user
$form_state['uid'] = $account->uid;
user_login_submit(array(), $form_state);
Update profile from linkedin info.

The error occurs on the user login submit part.
I suspect that drupal_session_start is causing the issue but I don't understand sessions well enough to debug this. The issue occurs 1 in about 30 users. I added the session start because the session info on line 2 doesn't get set without it.
Other suspects are memcache (very unlikely) and secure pages.
Anyone know about session that can enlighten me to how to track this issue down?
Comment: I think you should possibly be calling drupal_session_regenerate rather than drupal_start_session, as that seems a better match for your purpose, as far as I can tell. https://api.drupal.org/api/drupal/includes%21session.inc/function/drupal_session_regenerate/7
Comment: Alfred, regenerate seems to work in place of start. I pushed that change to see if I will get another occurrence of the duplicate session thing. If someone explain to me how these functions are different better than the documentation on api.drupal.org it would be appreciated.
Comment: Can you elaborate what the `user_login_submit(array(), $form_state);` does?  Are you doing this to fake a login?  And, if so, is there a reason you need the session before you do this?
Comment: `user_login_submit(array(), $form_state)` is not to fake a login. It actually performs a login. It's the way drupal core does a login through code so I just nabbed the snippet form there. The session is needed to validate the user when they come back from being authorized by linkedin. Not actually related to the login.
Comment: Too soon to say for sure but it appears regenerate in place of start is the right answer. Alfred if you post an answer I'll be able to give it to you.
Answer: Check your sites/default/settings.php file, if you have $conf[https] = TRUE; then removing it will fix the error.
Removing it also won't affect any security issues as long as your server/domain is configured properly. You can also check the Enabling HTTP Secure page from Drupal.
Answer: Just leave out drupal_session_start();. You simple can assigning stuff to $_SESSION (even for anonymous users). The data will be still present after a login. For an example of how this works, I'd suggest examining the shopping cart module of Drupal Commerce.
Note that this does not work when logging out for obvious reasons (session is destroyed on logout).
Comment: Unfortunately this is not true in practice. I added the session start because the session was not getting set up correctly. I defined several session variables and they were all blank when accessing them later in the same function. The session start fixed that. I'll peak at drupal commerce and see how they do it though. that's a good idea.