How does an alphabet size relate to the Kraft-McMillan Inequality?

Question: I'm trying to figure out how the alphabet size m relates to the McMillan Inequality.
I'm using Norman L Bigg's equation which is $\sum_{i=1}^M \frac{ni}{b^i}$$=\frac{n_1}{b^1}, \frac{n_2}{b^2}, . . . , \frac{n_M}{b^M}$
With this, I'm trying to answer this question: Let us say that a code is complete if it is PF and K = 1. Show that if
there is a complete b-ary code for an alphabet of size m, then b - 1 must
divide m - 1.
I have an answer but I don't think it's right due to the alphabet size.
To note M is just an integer while m is the alphabet size.
My method was to do $ni=m$ therefore $. . .+\frac{m-1}{(b-1)^{m-1}}+\frac{m}{(b-1)^m} = 1$ Using the end part of the equation.
After rearranging I get, $b(m-1)+1=(b-1)^m$ and by taking out a factor of $b-1$ on the right hand side I can get $m-1=(b-1)*[\frac{(b-1)^{m-1}}{b}-\frac{1}{b(b-1)}]$
I'm trying to figure if my method is correct, thanks.
Answer: That should be
$$K=\sum_{i=1}^M\frac{n_i}{b^i}=\frac{n_1}b+\frac{n_2}{b^2}+\ldots+\frac{n_M}{b^M}\;,$$
where $b$ is the size of the output alphabet, and $n_i$ is the number of code words of length $i$ for $i=1,\ldots,M$. (Thus, we might as well assume that $M$ is the maximum length of a code word.) It appears that $m$ is the size of the input alphabet, so $m=\sum_{i=1}^Mn_i$. Thus, you're trying to show that if $K=1$, $b-1$ divides $m-1=n_1+\ldots+n_M-1$.
If $$\sum_{i=1}^M\frac{n_i}{b^i}=1\;,$$ then we can multiply through by $b^M$ to get $$\sum_{i=1}^Mb^{M-i}n_i=b^M\;,$$
or if you prefer,
$$b^{M-1}n_1+b^{M-2}n_2+\ldots+bn_{M-1}+n_M=b^M\;.$$
Thus,
$$b^{M-1}n_1+b^{M-2}n_2+\ldots+bn_{M-1}+n_M\equiv b^M\!\!\!\pmod{b-1}\;.\tag{1}$$
Now use the fact that $b\equiv1\pmod{b-1}$, so that $b^k\equiv1\pmod{b-1}$ for $k\ge 0$, and eliminate all instances of $b$ from $(1)$ to get the desired result.
Comment: I followed through most of that but I don't understand where the $(mod b-1)$ comes from? Could you please elaborate on that point.
Comment: Also, could you explain what you mean by eliminating all instances of $b$? If I were to do that, would I not just get $m$ on one side?
Comment: @Rawrified: You're trying to prove that $b-1$ divides $m-1$; this is equivalent to saying that $m-1\equiv0\pmod{b-1}$, or that $m\equiv1\pmod{b-1}$. Use the fact that $b\equiv1\pmod{b-1}$ show that $(1)$ reduces to $m\equiv1\pmod{b-1}$, and you have exactly the result that you want.


Smoothest function which passes through given points?

Question: I am trying to interpolate/extrapolate on the basis of a known collection of (finitely many) points. I'm wondering if there is a way to formalize this intuitive notion: find a 'smoothest' function which passes through each of the points. Of course in general the function would not have a nice form.
The idea is similar to that of Bézier curves (and would be closer still, if I used a parametric curve rather than a function) and essentially opposite to the Lagrange interpolating polynomial, where fitting more than a few points usually produces wild oscillations.
Any idea how to make an idea like this work?
Comment: Why don't you just construct the following function: Let $f$ be a Lagrange interpolating polynomial for $x\in [x_1,x_n]$ (say that $(x_1,y_1),...,(x_n,y_n); x_i< x_j \forall \, i\neq j$ are the points you want to interpolate through) and extend  $f$ through $(-\infty,x_1), (x_n, +\infty)$ with some kind of bump function? That should make your function 'nice' enough (not crazy growth before [after] $x_1$ $[x_n]$).
Comment: Just use spline interpolation, for example with the cubic Hermite spline? https://en.wikipedia.org/wiki/Spline_interpolation
Answer: There are many ways to define "smooth", and only you know which definition fits your needs. But, anyway, here are a few things to think about.
The typical mathematical definition of "smooth" says something about how many continuous derivatives the function has. But these sorts of definitions bear little relationship to the intuitive notion of "smoothness" of a curve. Polynomial curves are $C^\infty$, but, as you noted, if they are constructed by Lagrange interpolation, they often wiggle all over the place, and no-one (except a mathematician) would call them "smooth". Also, any statement about continuity of derivatives is dependent on the parameterization of the curve, whereas smoothness is usually considered to be a purely geometric property that is independent of parameterization.
There are numerous techniques for improving curve smoothness by minimizing some "energy" function. The idea is that the curve is analogous to a thin beam, which will try its best to assume a smooth shape by "relaxing" its internal energy. As the other answer pointed out, cubic splines are based on one such energy minimization idea. In fact, before mathematicians started studying them, "splines" were thin strips of wood used to define smooth shapes for ship hulls and aircraft fuselages. One reference is here, but you can find many others by searching for the term "minimum energy spline".
Another idea, common in product design, is that a curve is "smooth" if its curvature varies in some very simple way. Nice-looking curves either have monotone curvature, or a curvature function that has a single maximum. So, from this point of view, the smoothest curves are straight lines and circular arcs. Conic section curves are also popular in design, since their curvature functions are simple and predictable.
Carlo Sequin and his students have studied "MVC" curves (minimum variation of curvature). See the list of papers here, and especially Henry Moreton's thesis.
A curve whose curvature is a linear function of arclength is an Euler spiral. There is a nice thesis by Raphael Levien that discusses these types of curves and related topics.
Answer: Interpolation and extrapolation are two very different games.
For interpolation, the natural cubic spline minimizes the $L^2$ norm of the second derivative among all $C^2$ functions passing through the given points. This can be interpreted as the least possible amount of wiggling in between, e.g., maximal "smoothness" of some sort (though the spline is only $C^2$ smooth, not $C^3$). My blog post has a few pictures and the description of the algorithm (of course it's also in many other places).
Since the natural cubic spline has zero second derivative at the endpoints, it can be $C^2$-smoothly extended by half-lines.
However, when doing extrapolation, one typically does not attempt to precisely reproduce the given points: I don't think that the half-line extension of the cubic spline is particularly meaningful. The main goal of extrapolation to find some pattern underlying the data, rather than reproduce every detail of it. The process goes by the name of curve fitting, and involves choosing a model to which parameters can be fit with the least squares method.
Comment: Yes, this unusual "must match the data" feature does make my problem unusual -- that's probably why I couldn't find much about it. Thanks for the answer. :)
Comment: Maybe you could clarify what you expect of the extrapolation? One, pretty arbitrary, thing to do is to interpolate by a spline and extrapolate by least squares; then glue these two functions by a partition of unity. The result will be extrapolation on large scale, but will still pass through the given points.
Comment: Really it's more about finding bounds on how good a fit can be, more than using it as a prediction as such.
Comment: Okay, but then it's not really extrapolating.


Adicionar o mesmo produto em varias categorias

Question: Boas
E o seguinte eu tenho uma tabela categorias e outra tabela produtos neste momento ao criar o produto seleciono a categoria a que ele pertence por selectbox só que agora tenho a necessidade de associar um produtos a varias categorias gostava de saber qual pode ser a melhor forma de associar o mesmo produto a varias categorias.
CREATE TABLE IF NOT EXISTS `estabelecimentos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_mae` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`titulo` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`slug` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`link_facebook` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`link_mapa` text COLLATE utf8_unicode_ci NOT NULL,
`distritos` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`concelhos` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`morada` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`contacto` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`int_preco` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`link_site` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`introducao` text COLLATE utf8_unicode_ci NOT NULL,
`servicos` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`descricao` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`keywords` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`keywords_pesquisa` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`google_verification` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`activo` tinyint(1) NOT NULL,
`pos` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=198 ;

Comment: bancos de dados é MyISAM
Comment: É possível fazer com `MyISAM` também, mas ficaria vinculado a um "Model" no PHP. Em bancos de dados mais relacionais (como `innoDB`) você usaria o `1:N` (one-to-many), mas também poderia usar many-to-many seria algo como: https://netbeans.org/images_www/articles/73/javaee/ecommerce/data-model/many-to-many.png
Comment: Então será melhor converter a base de dados para innoDB e melhor ?
Comment: Ok então como poderia fazer por um model em php mantendo a mesma estrutura que tenho no banco acima
Comment: Eu já tenho backoffice e front-end neste momento eu faço o insert mas só para uma categoria por meio de selectbox queria e implementar para mais que uma categoria
Comment: Sim César, entendo, realmente eu quis lhe dizer que você precisaria de uma tabela com as categorias e uma com os produtos, o back-end (que é diferente de backoffice) e o front-end (que é html, javascript) seria exemplos de como fazer o processo.
Comment: Consegue me ajudar a criar isso preciso mesmo de fazer esse sistema
Comment: Boa noite César, realmente é um sistema que demanda um certo tempo para desenvolver e ainda formular isto como uma boa resposta. Não é que eu não queira, é que no momento eu não irei conseguir fazer algo realmente funcional em pouco tempo. Mas prometo ver se arrumo um tempo e se sou realmente capaz de criar algo útil :)
Comment: Uma solução que estava a pensar era inserir um array com as categorias na coluna do artigo
Answer: Uma solução é usar uma entidade fraca para tal, supondo o modelo
categorias
----------
categoria_id
categoria_nome

produtos
---------
produtos_id
produtos_nome

categorias_produtos
--------------------
categorias_produtos_id
produto_id
categoria_id

Sendo que ficaria
categorias 1 -------- * categorias_produtos * ---------- 1 produtos

Comment: A minha estrutura dos produtos coloquei acima no tópico em que o campo id_mae e onde leva o nome da categoria actualmente esta assim queria uma forma de não ter de mudar muito a estrutura
Comment: A resposta de Adir e a boa resposta. O que vc tem como problema e comum: produtos, fornecedores mais um fornecedor pode vender mas de um produto e vc pode comprar o mesmo produto em varias fornecedores. A solução e ter uma terceira tabela que faz o link entre fornecedor e produtos (e vice-versa). O seu problema e que vc fiz a tabela antes de pensar sobre isso. Agora, infelizmente, acho que precisa mudar a estrutura.
Comment: Mas dessa forma insiro a categoria_id num array seprado por virgulas ?


Not able to get the title of Page using geb when it has multiple div elements and no ID

Question: Below is my html, from where I am trying to get the text of header. I tried multiple ways to select it but not succeeded in it. Could you please help me to get the element so that I can get the text.

                Case-10006336-2015
                 |
                Case details

Title of the frame is "Case-10006336-2015" and tried to locate the element by using below various ways however not able to succeed in it.

labelSelectedCase { $("div", class: contains("angular-css ng-panel ng-panel-boxed")).$("div", class: contains("ng-panel-hdr")).$("h2",class: contains("ng-binding") ) }
labelSelectedCase { $("div.angular-css ng-panel ng-panel-boxed div.ng-panel-hdr").find("h2", class: contains("ng-binding")) }

and several others but not able to locate this element.
Could you please help me to get this element so that I can get the text and assert it.
Thanks in advance.

Answer: Either of these should work -

labelSelectedCase { $("h2.ng-binding")}
labelSelectedCase { $("span.sch-tek").parent()}

I'm not sure Content defined like you have in 1) is even valid so that could explain why $(x).$(y).$(z) doesn't work, and I'm pretty sure 2) goes astray at the second and third classes of the first div, maybe you have to chain the classes if you want to select on multiple classes like this -
labelSelectedCase { $("div.angular-css.ng-panel.ng-panel-boxed div.ng-panel-hdr").find("h2", class: contains("ng-binding")) }

Good luck,
Deon.


Cubase: find and remove very short notes

Question: In Cubase, how can I find and remove very short notes, notes of a just a millisecond or two in duration?
However carefully I fret my guitar, its MIDI system will still occasionally send very short notes caused by either fret buzz or pickup inaccuracy. These are often too small too see unless zoomed in such that a single beat fills the screen.
Answer: One of the most powerful, yet least-used, features of Cubase is the Logical Editor.
This is one of a myriad tasks it's very good at.
Set up your input parameters as -
Type is Note. Add a new line with the + button, set Length is less than [I used an arbitrary 20 ticks here]
The Action target you can leave at default, we're not using it.
To the right of the Function label at the bottom, set to Select [this is for testing] & hit Apply.
Check it picked all the right notes.
Flip the Function to delete & hit Apply again.

A lot of the built-in functionality actually accesses this set of functions under the hood. I just realised there's a UI specifically done for this task. It's the same deal just in a simpler interface.
Delete Notes…

Do spend some time with the Logical Editor, though - it is massively powerful. You can save presets & give them key commands too.
I used to just about live in this editor in the late 90s, when I was editing Midi for a living.
I used to know the 'berg guys quite well - we'd meet up in Frankfurt or Hamburg every so often & we'd spend many a happy hour at trade shows or in the pub hammering out solutions to complex Midi organisation problems.
The Logical Editor was the result of one such meeting. Our editors had quite specific needs that the general public really wouldn't think of, so we pushed for this type of structure so we could get down 'n dirty with low-level Midi data.
When they came back with this, it was even better than we'd hoped. They then, as above, pushed some of the easier ideas out to separate more punter-friendly GUI interfaces, relying on the same underlying engine. Brilliant work.
Comment: Unfortunately, the full power of the Logical Editor is only available in the most expensive Cubase Pro edition. (It's the _only_ feature I miss in the much cheaper Cubase Artist, which is reduced to a few not-very-useful presets.)
Comment: @gidds - Ah, I didn't realise that. I've only ever had whatever the top-end product was called at the time, even though I finally stopped updating after Cubase 8. idk what number they're up to now. Can we check it does have the simpler interface version?


Verificar resposta correta

Question: Boa tarde,
Estou fazendo um form de perguntas e respostas simples. Gostaria de saber como faço para caso a resposta seja a errada, mostre a alternativa correta no alert.

$(document).ready(function() {

  $("input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      alert("Errado");
    }
  });

});

Primeira pergunta de teste:

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1

<input name="r" type="radio" class="ace" value="S"> Resposta certa

<input name="r" type="radio" class="ace" value="N"> Resposta errada 2

<input name="r" type="radio" class="ace" value="N"> Resposta errada 3
Answer: Os textos, que são as respostas, vem a seguir do elemento, então em DOM você pode usar o nextSibling (em jQuery na API tem o .next(), mas não é a mesma coisa), então ficaria algo como:
 $('[name="r"][value="S"]').get(0).nextSibling.textContent;

Desta forma você irá pegar o texto a seguir do elemento desejado (no caso o elemento com a resposta correta), exemplo:

$(document).ready(function() {

  $("input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      var resposta = $('[name="r"][value="S"]').get(0).nextSibling.textContent;
      alert("Errado, a resposta correta seria: " + resposta);
    }
  });

});

Primeira pergunta de teste:

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1

<input name="r" type="radio" class="ace" value="S"> Resposta certa

<input name="r" type="radio" class="ace" value="N"> Resposta errada 2

<input name="r" type="radio" class="ace" value="N"> Resposta errada 3

No entanto você pode simplificar e até evitar acidentes criando elementos para separar as respostas ao invés de usar
, desta forma você poderá ter várias perguntas na mesma página, exemplo:

$(document).ready(function() {

  $(".resposta input[type='radio']").click(function() {
    var marcado = this.value;

    if (marcado == "S") {
      alert("Correto");
    } else {
      console.log($(this).parents('.pergunta').find('[name="r"][value="S"]').parent().get(0))
      var resposta = $(this).parents('.pergunta').find('[name="r"][value="S"]').parent().text().trim();
      alert("Errado, a resposta correta seria: " + resposta);
    }
  });

});

Primeira pergunta de teste:

         <input name="r" type="radio" class="ace" value="N"> Resposta errada 1

         <input name="r" type="radio" class="ace" value="S"> Resposta certa

        <input name="r" type="radio" class="ace" value="N"> Resposta errada 2

        <input name="r" type="radio" class="ace" value="N"> Resposta errada 3

Segunda pergunta de teste:

         <input name="r" type="radio" class="ace" value="N"> Pedro Álvares Cabral

         <input name="r" type="radio" class="ace" value="S"> Graham Bell

        <input name="r" type="radio" class="ace" value="N"> George Washington

        <input name="r" type="radio" class="ace" value="N"> Thomas Edison

Comment: Porque esta aparecendo esses caracteres? https://prnt.sc/p8c8mn
Comment: @Tiago aqui não apareceu nenhum caractere assim, teste no botão EXECUTAR acima, os dois exemplos (o segundo é melhor) ... esses caracteres parece um outro problema fora deste script, se você tiver como colocar online para eu testar ou enviar o arquivo facilitaria para identificar, mas repito, o problema não é no script da resposta, é em outro lugar.
Answer: Cara é só colocar dentro da condição para mesmo clicando no errado ele marcar o certo. Então se marcar a errada ele da o alerte e faz um :checked no input com name="r" value="S" tipo assim $('[name="r"][value="S"]').prop("checked", true);. Dessa forma vc assegura que apenas o input com value="S" pertencente ao radio-group de name="r" vai ser marcado (Obrigado @AndersonCarlosWoss pela observação)

$(document).ready(function() {

    $("input[type='radio']").click(function() {
        var marcado = this.value;

        if (marcado == "S") {
            alert("Correto");
        } else {
            alert("Errado");
            $('[name="r"][value="S"]').prop("checked", true);
        }
    });

});
[value="S"]:checked {
    transform:scale(2);
}

Primeira pergunta de teste:

<input name="r" type="radio" class="ace" value="N"> Resposta errada 1

<input name="r" type="radio" class="ace" value="S"> Resposta certa

<input name="r" type="radio" class="ace" value="N"> Resposta errada 2

<input name="r" type="radio" class="ace" value="N"> Resposta errada 3
Comment: Mas não é marcar a resposta correta se ele marcar a errada. Somente aparecer no **alert** o texto correspondente a resposta correta.
Comment: @GuilhermeNascimento eu está lendo ela agora mesmo rss, realmente a forma como vc estruturou o HTML ajuda muito a controlar as coisas. Isso deve acontecer bastante quando "designer" faz o HTML, e depois passa para o Dev. fazer o código haha
Comment: Ao invés de `$('[value="S"]')` é melhor fazer `$('[name="r"][value="S"]')` para garantir que pegará a opção correta da mesma pergunta (alterando `r` dinamicamente conforme a pergunta), isso considerando que poderão existir múltiplas perguntas na página. E tenho dizer que é esquisito ter 4 radios com o mesmo `value` :x
Comment: @AndersonCarlosWoss muito bem observado, até fiz um edit na resposta ;)
Comment: @Tiago nesse caso eu só saberi te responder se o texto seguido do Radio estivesse dentro de uma tag, tipo se estivesse assim:  Resposta certa
 eu conseguira pegar. No entento, parece que a resposta do Guilherme vai te atender nesse ponto.
Comment: @hugocsl apesar do nextSibling atender inicialmente o segundo exemplo de minha resposta mostra como fazer se precisar de multiplas perguntas na mesma página.
Answer: Primeiro, preciso dizer que o seu HTML não fez muito sentido e parece ser mal planejado. Você tem uma lista que não está como lista; você possui 5 opções de resposta para cada pergunta, mas na verdade tem apenas 2, pois o que é considerado será o value do elemento input[type=radio]. Isto é, o texto "associado" ao input não fará diferença para a semântica. Quando você quer associar um texto ao campo, deverá utilizar o label.
Deveria ser algo assim:

Enunciado da pergunta

      <input id="opcao-1" type="radio" name="respostas-1" value="1" data-correta="N">
      Opção 1 errada

      <input id="opcao-2" type="radio" name="respostas-1" value="2" data-correta="N">
      Opção 2 errada

      <input id="opcao-3" type="radio" name="respostas-1" value="3" data-correta="S">
      Opção 3 errada

      <input id="opcao-4" type="radio" name="respostas-1" value="4" data-correta="N">
      Opção 4 errada

      <input id="opcao-5" type="radio" name="respostas-1" value="5" data-correta="N">
      Opção 5 errada

Veja que o value das opções é um valor que identifica aquela opção. Neste exemplo eu utilizei os valores de 1 a 5 representando os ids das opções, mas poderia ser qualquer valor que identifique aquela opção naquela pergunta. O controle de qual opção é a correta foi passada para o atributo data-correta.
Assim, com o JavaScript, ficaria:

$("input[type=radio]").on("change", function() {
  if (this.dataset.correta === 'N') {
    // Exibe a resposta correta:
    alert($(`input[name="${this.name}"][data-correta="S"] + label`).text());
  }
});

<fieldset id="pergunta-1">

Enunciado da pergunta

      <input id="opcao-1" type="radio" name="respostas-1" value="1" data-correta="N">
      Opção 1 errada

      <input id="opcao-2" type="radio" name="respostas-1" value="2" data-correta="N">
      Opção 2 errada

      <input id="opcao-3" type="radio" name="respostas-1" value="3" data-correta="S">
      Opção 3 correta

      <input id="opcao-4" type="radio" name="respostas-1" value="4" data-correta="N">
      Opção 4 errada

      <input id="opcao-5" type="radio" name="respostas-1" value="5" data-correta="N">
      Opção 5 errada

</fieldset>

Onde input[name="${this.name}"][data-correta="S"] buscará a resposta correta para aquela pergunta e o + label seleciona o label associado ao input, exibindo o seu texto. Outra opção seria selecionar o label a partir do valor do for através do id da opção correta.
Como as perguntas possuirão um grupo de respostas que serão independentes das opções das outras perguntas, é conveniente utilizar o <fieldset> para agrupar os elementos semanticamente relacionados dentro do formulário.
Comment: @hugocsl e inclusive seria interessante colocar cada pergunta dentro de um `fieldset` para definir a independência entre elas, mesmo pertencendo ao mesmo `form`.
Comment: Dataset + label .... muito elegante! Só faltou colocar dentro de um fieldset haha. E olha isso que massa, das antigas.... https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/radiogroup
Answer: Fiz um modelo em JavaScript Puro, sei que não pediu :)
Tem outros jeitos de fazer mais este também é bem prático e bem simples.
    var ace = window.document.getElementsByName('r');

    ace[0].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })
    ace[1],
    ace[2].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })
    ace[3].addEventListener('click', function (){
        if(ace != 'S'){alert('Resposta Errada')}
        return ace[1].checked = true;
    })

e se você não quiser que marque o botão correto é só apagar os return ace[1].checked = true; e caso queria dar um alert('Resposta correta') é só por assim :
ace[1].addEventListener('click', function (){
        if(ace != 'N'){alert('Resposta Correta')}

    })

Verificar resposta correta


Determining the confidence interval for a non-normal distribution

Question: I have a set of data I ran on a simulation using R with a population size (N) of 1000, sample mean of 64.93, and a standard deviation of 27.61.  The distribution is positively skewed and a Wilks-Shapiro test done in JMP shows that the data is not normally distributed.  I need the confidence intervals of this data to be able to test some experimental data I have.
I have learned that using the boot.ci() function in R can give me confidence intervals using bootstrapping.
As shown in http://www.statmethods.net/advstats/bootstrapping.html, the boot function requires:
bootobject <- boot(data= , statistic= , R=), where data is the data of interest, statistic is a function that produces the statistic to be bootstrapped, and R is the number of times to do it.
My data is simply a vector of 1000 samples.  I am not sure what statistic I should do.  All the examples I have read online require two data sets to make a correlation statistic or a linear regression statistic.
The data can be downloaded from: http://ktdllc.com/data/simp2.csv
Any help on this issue would be greatly appreciated.
Comment: What exactly do you want confidence intervals for? For the estimate of the mean of your data? What do you want to be able to test about 'some experimental data you have'?
Comment: Normal theory-based confidence intervals (e.g., using the $t$ distribution) are symmetric.  When the data are very asymmetric so should be the confidence interval.  The confidence interval based on $t$ may have the right coverage overall but be wrong in both tails.  I would use the bootstrap in any case, which also works if the data happened to be Gaussian (normal).
Comment: I don't think you necessarily need to try a bootstrap confidence interval. Tests of Normality will say the data come from a non-Normal distribution often when your CI method is robust to that assumption. You have a large sample size, meaning a CI based on the t distribution will be fairly unaffected by any non-Normality.
Comment: @Firefeather is quite right.  A subtler problem is that comparing experimental data to confidence intervals is usually not valid; at best, it may be valid but is inferior to more standard comparisons of the experimental data to the simulation.  In effect, you *do* have two data sets: the experimental results and the simulated results.
Comment: I am testing for copy number differences of genes in an organism. I have experimental data where I take a single organism from a sample when it enters exponential population growth phase and put it into new media. I do a single cell each transfer to reduce any chance of selection occurring.  I quantified the DNA at the start of the experiment. Then again after 6 months (~200 generations).
Comment: I did a simulation that matched my experiment and the model for what controls the copy number of the genes between cell division. I want to find the confidence intervals of my simulation so that I can use them to determine if my experimental data fall within or outside my confidence intervals.  I have 2 simulations that show a positively skewed distribution that the Wilks-Shapiro shows is non-normal.  I also have 2 simulations that are normally distributed.  If comparing the confidence intervals of my experimental data to my simulation data is not valid enough, what do you suggest I do instead
Comment: Before I try to answer this question, I'd like to know what your random variable is so that I could determine whether a more suitable distribution could be used so that you could avoid the bootstrap all together. I'd also like to know if you've tried transformations of your data to see if it becomes more normal, such as a log transform (careful, doesn't work if you have zeroes!) or some other transform. Thanks.
Answer: If you want to just do a simple bootstrap of a median CI then all you need is a median function that accepts indices.
med <- function(y, indices) median(y[indices])

Then you can just...
b <- boot(dat, med, 1000)
boot.ci(b)

(you might want to plot(b) to examine your boostrap)
But in your case, assuming your simple exponential model described the data well, I would just be tempted to let the entire simulation speak for itself in a figure. Plot your data distribution and overlay your simulation. If you use density curves your simulation can have a much higher N than the data.
densDat <- density(dat)
plot(densDat)
densSim <- density(sim)
lines(densSim, col = 'red')

(You might want to adjust the bw argument in density to smooth the curve.)


Is this textbook wrong about scaling eigenvectors?

Question:
This doesn't seem right. The eigenvalue of $s\boldsymbol{v}$ should be $s \lambda$ right? Or no?
Comment: No.$ A(sv) = s(Av) = s(\lambda v) =\lambda(sv)$.
Comment: If you scale the *matrix* by $s$, then you do scale all of its eigenvalues.
Answer: No: by linearity of matrix multiplication,
$$ A(sv) = sAv = s\lambda v = \lambda(sv), $$
so $sv$ still has eigenvalue $\lambda$.
Answer: Well, when you multiply $sv$ by $A$, you will get $sv\lambda$.
I see where you are coming from with the eigenvalue being $s\lambda$, but $sv\lambda$ is only $\lambda$ times $sv$, so the eigenvalue is still $\lambda$.


c++ return type has pointer with type of current class

Question: Sorry for the bad question formulation, could not find a better way to shortly describe my problem:
I have a class A with a pure virtual method that returns an object of type B.
Class B has a member variable wich is a pointer to an object of class A.
Is there a way to achieve this?
Example:
class A {
public:
  B mymethod() const = 0;
}

struct B {
  std::shared_ptr mypointer;
}

If I include the files in each other the compiler tells me that one is not declared in this scope. How can I avoid this?
Comment: Lots of circular dependency questions on SO
Answer: std::shared_ptr was designed to replace raw pointers - so in order to provide compatible semantics, it also can be used without a full type definition.

Implementation notes
In a typical implementation, std::shared_ptr holds only two pointers:

the stored pointer (one returned by get())
a pointer to control block

So, forward declaration is enough:
A.h:
#include "B.h"

class A
{
public:
  B mymethod() const = 0; //returns by value, so full definition of B is required (*)
};

B.h:
class A; //Forward declare A

struct B
{
  std::shared_ptr mypointer;
};

(*) In fact, in your case such include may not be required, since it's only a declaration of function returning B. As long as you separate declarations (.h) and actual body (.cpp) or simply forward-declare functions prototypes, headers for particular types should be only included by source files, that use them.
Comment: A shouldn't need the full definition of B to simply *declare* a function that returns it. A simple declaration should be enough.
Comment: As long as it's separated from actual body - yes. I made an update, thanks for noting.


Cisco 877 as PPPoA/PPPoE bridge (no routing) - how to make it listen to IP for management?

Question: I have a Cisco 877 configured to bridge ADSL with PPPoA to PPPoE on Vlan1. This works fine, but in this mode the only way I can configure the Cisco is via the serial console. I'd like to have the Cisco also listen on an IP address so I can telnet/ssh into it. I think the right way to go about this would be via bridge irb, but I'm not sure exactly how (or if that's even the right direction). IOS is 12.4T and my current config (cut down to essentials) is:
no ip routing
no ip cef
!
!
interface ATM0
 no ip address
 no ip route-cache
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5snap
 !
 dsl operating-mode auto
 bridge-group 1
!
!
interface Vlan1
 no ip address
 no ip route-cache
 bridge-group 1

Just setting an IP address on Vlan1 didn't have the desired effect, but surely this must be possible somehow (the Draytek Vigor 120 even does it by default).
Answer: You have to create a BVI interface and give the desired IP address to it. Don't forget to add:
bridge 1 protocol ieee
bridge 1 route ip

note:
before create BVI interface you must use this command:
bridge irb

Comment: Here's the whole working config I ended up with: https://sdfjkl.org/blog/cisco-877-as-adsl-modem/


Javascript para exibir Divs aleatoriamente (Com textos ou imagens)

Question: Estou desenvolvendo uma página e preciso exibir alguns textos e imagens de forma aleatória numa determinada parte da página.
Eu encontrei aqui no fórum (Exibir texto aleatoriamente) um código que quase faz o que eu preciso.
Segue o código:

$(document.body).ready(function(){
    textos = ['Texto exemplo', 'Texto 2', 'Aleatório', 'Exemplo para o usuário', 'Texto 5'];
    $('#textos').text(textos[0]);
    setInterval(function() {
        var indexTexto = Math.floor(Math.random() * textos.length); //Pegará um número aleatório entre 0 e a quantidade de textos;
        $('#textos').text(textos[indexTexto]); //Definirá o texto de acordo com o índice sorteado
    },
    1000); //1 segundo
});

Mas eu preciso que ao invés de exibir os textos que estão dentro do código, exiba algumas Divs chamando-as por suas respectivas IDs, que têm textos e imagens.
Tenho conhecimento básico em HTML e nenhum conhecimento em Javascript.
Se alguém puder me ajudar, ficarei grato.
Answer: Primeiro posicione as divs no lugar onde quer que o conteúdo seja mostrado mas com a style="display:none;"

image

texto

image

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
  //O numero máximo é excluído getRandomInt(0,100) pode mostrar de 0 até 99
}

$(document.body).ready(function(){
    var id_das_divs = ['div-1','div-2','div-3'];

    setInterval(function() {
      var indice_rand = getRandomInt( 0, id_das_divs.length );
      var div_para_mostrar = id_das_divs[indice_rand];

      // a lista de divs tem 3 items mas o índice começa no zero
      // id_das_divs[0] = div-1
      // id_das_divs[1] = div-2
      // id_das_divs[2] = div-3

      // Ah melhor esconder os divs antigos antes
      id_das_divs.forEach(function(item_da_lista) {
        $("#"+ item_da_lista ).hide();
      });
      // mostrar a nova imagem/texto
      $("#"+ div_para_mostrar ).show();
    },
    1000); //1 segundo
});

Comment: Seu código funcionou perfeitamente. Exatamente como eu preciso.

Colocando o seu código em prática, me surgiu questão. Caso uma pessoa esteja lendo algo que está dentro da Div e no meio da leitura, puf, o texto muda ou aparece uma imagem, a pessoa ficará no mínimo insatisfeita com a situação.

Minha dúvida é: Tem como adicionar um botão com a opção retroceder e um outro botão com a opção pausar?

Mas olha, de qualquer forma, você me ajudou imensamente. Seu código vai me ajudar muito. Muito obrigado! Abraço.
Comment: Outra situação que ocorreu, foi que eu mudei o tempo de exibição para 1 minuto. Mas o problema é que quando carrega ou recarrega a página, leva um minuto para ser exibida a primeira Div. Tem como mudar isso? Obrigado.


How could you notate a measure where you have "cut-off" triplets?

Question: So, let's say you have a measure of 3/4. Like the following:

Then you have a triplet in the next measure, like this:

How would I "cut off" the last quarter rest from that triplet? I was thinking to create a measure of 2/3, or two "third notes" aka triplets. Is there a better way to do this?
Comment: @OldBrixtonian Because the note grouping used is characteristic for 6/8 rather than 3/4, and because the rhythm would be rather natural in 6/8, and syncopated in 3/4. Of course there is nothing wrong with using syncopation, and such short-hand notation of syncopated rhythm can be sometimes used, given OP is asking about time signatures and notation, it looks like something they may want to double check.
Comment: Is the first measure 3/4 with syncopation, or is it 6/8?
Comment: We discussed these time signatures recently. Here, if it's any help: https://music.stackexchange.com/questions/101870/can-any-score-writer-do-irrational-time-signatures
Comment: Your idea is right ZipCreator, but it would be 2/6, not 2/3. You'd use 3 on the bottom if it were *half*-note triplets, but 6 for quarter-note triplets (and 12 for eighth-note triplets). Alternatively, you can do a tempo modulation.
Comment: Just to make sure I understand what you want.  You have music that is going at, say, 80 quarter notes per minute, and somewhere in the middle you want a measure with 2 quarter notes at 120 quarter notes per minute.
Comment: @user1079505 It says 3/4. And it looks like 3/4. Why do you think it might not be?
Comment: I don't understand how, in 3/4 time, there can be a triplet worth exactly what a standard 3/4 bar contains. If you mean two equal notes to fill that bar, 6/8 would be a simple answer.
Comment: @user1079505 You say the note-grouping used is characteristic of 6/8 rather than 3/4. It isn't. How ELSE can you write it in 3/4?!
Comment: There is no such thing as a "third note,"  "irrational meters" cultists notwithstanding.
Answer: The simplest solution is given by the Wikipedia Irrational Meters entry. You would just write it as two half-notes, which, given the 2/3 time signature, would be understood as two "thirds-of-a-whole-note".

for example, one beat in 4⁄5 is written as a normal quarter note, four quarter notes complete the bar, but the whole bar lasts only 4⁄5 of a reference whole note, and a beat 1⁄5 of one (or 4⁄5 of a normal quarter note).

Another possibility, from Wikipedia's Tuplet:Notation entry would be to notate the tuplet using a [3:2] ratio indication, meaning "three of this type of note comprises two beats", but you'd only have two notes present within the tuplet.
Comment: What I meant was that the time signature should be 2/6. Then it's two quarter-note triplets like the OP wanted.
Comment: Right, that's the OP's mistake: 3rd notes would be half note triplets, sixth notes are quarter note triplets.
Comment: @PatMuchmore OP indicates 2/3 time but used a quarter-note triplet as his example. So am I understanding correctly that two quarter notes would give 2/6 and two half notes would give 2/3?
Comment: Do you still want to retain '2/3' in the 1st para?
Comment: @Tim Yes, unless my post is incorrect. My intention is to err on the side of the OP meaning "2/3" and that the quarter-note triplet was just to get across the idea of what was being sought.
Answer: Thinking "out of the box", if you can allow yourself to change the first measure time signature, you may consider:
X: 1
K: Bb
M: 9/8
L: 1/16
V:Vc clef=bass
C,3D,3 E,3(D,3 D,3) C,3 | [M: 2/4]  C4B,4 |]

or
X: 1
K: Bb
M: 9/8
L: 1/16
V:Vc clef=bass
C,3D,3E,3 D,6 C,3 | [M: 2/4]  C4B,4 |]

This of course depends on the rest of the composition. The dotted eights might be annoying to read, but might be easier than irrational meters.
Comment: Really is easier to read and play if you stick with  3/4 - 2/4 time and add a written instruction as to the change in meter (bpm)
Answer: I think this is what you're trying to do:
Comment: Bad notation!  No biscuit!    Notes (post + head + flag) do not accept the concept of a nonbinary base unit
Comment: :-) As a matter of fact Carl, I myself find this *particular* example less appealing, but only 'cos the notes are a bit er... uninformative. I can't see any advantage of the 2/6 bar over a 3/8 one with two dotted quavers, except that the two bars together would then amount to one 9/8 bar. Nonetheless, that's how I personally - not knowing the context - would write it, but I'd add the magic word **riten.** extended by a horizontal line over the two notes, just to stop it sounding like 9/8 and being in any way foot-tappable. *Might* even add a **giusto** over the following bar. There. Biscuit?


Prove an orthogonal reflection is of the form $T(u) = u - 2 \langle u,v\rangle v$

Question:
Let $V$ be an inner product space of dimension $n$. A linear transformation $T : V \to V$ is called an orthogonal reflection if there exists a $(n−1)$-dimensional subspace $W$ such that $T (w) = w$ for $w \in W$, and there exists a vector $v$ orthogonal to $W$ such that $T (v) = −v$. Show that given this $v$, and assuming $v$ is scaled so $||v||= 1$, then $T$ must be given by the formula $T(u) = u - 2 \langle u,v\rangle v$.

Can I have some guidance for this problem? I feel like I'm lacking the tools to solve this, as it's over a general inner product space. I have however verified that $T(v)$ and $T(w)$ give the right outputs
Comment: Hint: If the equation holds for $u=v$ and for $u \in W$ then it holds for all $u$.
Comment: @KaviRamaMurthy Why is that true?
Answer: Hint: Once you know what $T(v)$ is and what $T(w)$ is for $w \in W$, you can deduce what $T(u)$ must be for every $u$ in $V$. Indeed, every $u$ can be written in the form $kv + w$ for some $k \in \Bbb C$ and $w \in W$, so it follows that
$$
T(u) = T(kv + w) = kT(v) + T(w).
$$
Comment: Ohhhhhh, it finally clicked. Thank you!
Comment: I know that $T(v) = -v$ and $T(w) = w$, but how does that relate to what $T(u)$ is?
Comment: @beginner As I wrote in my answer: if $u = kv + w$, then $T(u) = kT(v) + T(w) = -kv + w$.
Comment: Ohhh, how does that relate then to $T(u) = u - 2 \langle u,v\rangle v$?
Comment: Using the formula $T(u) = u-2\langle u,v\rangle v$, you now only need to state/show 3 things. 1: $T$ is a linear transformation, 2: $T(v) = -v$, and 3: $T(w) = w$ for any $w \in W$.
Comment: Sorry I'm still a bit confused. I've already verified those three things, I'm just having trouble relating it to $T(u) = -kv + w$. Am I trying to figure out what $k$ is?
Comment: Not quite. You have two maps that satisfy these 3 properties. However, you can use these properties to get a formula for $T(u)$. It follows that two maps with these properties must be the same linear map, which is what we wanted to show.
Comment: @beginner For what it's worth, $k = \langle u,v \rangle$. As we've established, however, that information is not necessary to reach the conclusion we're after.
Comment: So because these two maps have the same output on $w,v$ they're the same map?
Comment: Yes. Because these two *linear* maps have the same output on $w,v$ *for every $w \in W$*, they're the same map.


Como preencher dados contidos em input no BOOTSTRAP POPOVER

Question: Pessoal possuo um código com um modal que contém um Bootstrap popover e gostaria que nesse balão de informações, contenha os dados desses inputs.
Atualmente já consigo pegar os dados das variáveis do php e passar para o javascript e quando o modal é aberto consigo visualizar esses dados nos campos.
No popover não consigo fazer o mesmo.
Segue o código:
$(function () { $(".glyphicon-search").click(function () {

    var id_codigo = $(this).data('codigo');
    var id_nome = $(this).data('nome');
    var id_endereco = $(this).data('endereco');

    $(".modal-body #id_codigo").val(id_codigo);
    $(".modal-body #id_nome").val(id_nome);
    $(".modal-body #id_endereco").val(id_endereco);
    })
    })

    $(document).ready(function(){
    $('[data-toggle="popover"]').popover({html: true});
 });

HTML

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <?php
    $codigo = 1;
    $nome = "Zé";
    $endereco = "Rua";
    ?>

    <button type="button" class="btn btn-primary" data-toggle='modal' data-target='#Alt'
    data-codigo='$codigo'
    data-situacao='$nome'
    data-distribuidora='$endereco'
    >MODAL</button>

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

    <input readonly id='id_codigo' type='text'>

    <input readonly id='id_nome' type='text'>

    <input readonly id='id_endereco' type='text'>

    <button
    id='id_button' type="button" class="btn btn-info" data-position="top-left" title="Contato"
    data-toggle="popover"
    data-placement="down" data-content="Nome: <input readonly id='id_nome' style='Border:0' type='text'>

Endereço:<input readonly readonly id='id_nome' style='Border:0' type='text'>

Contato:<input readonly readonly id='id_endereco' style='Border:0' type='text'>">Contato</button>

Answer: $('#idpopover').popover({
    trigger: 'manual',
    placement: 'right',
    content: function() {
       var message = "A tua menssagem que seria o id da variabel"+ id_codigo;
         return message;
    }
});

Espero ter ajudado!
Answer: Você tem que usar os eventos da modal e do popover:
Da modal: shown.bs.modal (quando a modal fica visível)
Do popover: shown.bs.popover (quando o popover fica visível)
Utilizando uma função separada que será chamada pelos dois eventos acima, basta você passar para ela o botão que abriu a modal, de onde serão tiradas as informações dos data-*.
Só que você está duplicando as ids #id_codigo, #id_nome etc., além do que você colocou os nomes dos data-* diferentes:
data-codigo='$codigo'
data-situacao='$nome'
data-distribuidora='$endereco'

E no popover e na modal colocou data-nome e data-endereco.
Para corrigir isso, troque os id's por class e ajuste os nomes dos data-* (como fiz no exemplo abaixo):

$(function () {

   function contatos(e){

      e = $(e);
      var id_codigo = e.data('codigo');
      var id_nome = e.data('situacao');
      var id_endereco = e.data('distribuidora');

      $(".id_codigo").val(id_codigo);
      $(".id_nome").val(id_nome);
      $(".id_endereco").val(id_endereco);

   }

   $('#Alt').on('shown.bs.modal', function(e){
      // passa o botão que abriu a modal
      e = e.relatedTarget;
      contatos(e);
   });

   $('[data-toggle="popover"]')
   .popover({html: true})
   .on('shown.bs.popover', function(){
      // busca o botão que abriu a modal pelo atributo data-target
      var e = $("[data-target='#"+ $(this).closest(".modal").attr("id")+"']");
      contatos(e);
   });

});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

   <button type="button" class="btn btn-primary" data-toggle='modal' data-target='#Alt'
   data-codigo='1'
   data-situacao='Zé'
   data-distribuidora='Rua'
   >MODAL</button>

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

<input readonly class='id_codigo' type='text'>

<input readonly class='id_nome' type='text'>

<input readonly class='id_endereco' type='text'>

<button
id='id_button' type="button" class="btn btn-info" data-position="top-left" title="Contato"
data-toggle="popover"
data-placement="down" data-content="Nome: <input readonly class='id_nome' style='Border:0' type='text'>

Endereço:<input readonly readonly class='id_endereco' style='Border:0' type='text'>

Contato:<input readonly readonly class='id_codigo' style='Border:0' type='text'>">Contato</button>

Answer: Vou deixar mais uma alternativa, vc pode utilizar o método content da função popover e utilizar template strings para inserir os campos dentro do método content, aí é só utilizar expressões passando os valores que pegou do Php:

$(function () {
  $(".btn-primary").on('click', function () {

    var id_codigo = $(this).data('codigo');
    var id_nome = $(this).data('nome');
    var id_endereco = $(this).data('endereco');

    $(".modal-body #id_codigo").val('1');
    $(".modal-body #id_nome").val('Zé');
    $(".modal-body #id_endereco").val('Rua');
  })
})
// apenas para exemplo
let valor1 = 'Bla bla';
let valor2 = 'Testes';
let valor3 = 'Outro Teste';

$(document).ready(function(){
  $('[data-toggle="popover"]').popover({
    html: true,
    content: function() {
      return `Nome: <input id='id_nome' readonly style='Border:0' type='text' value='${valor1}'>

Endereço: <input id='id_endereco' readonly style='Border:0' type='text' value='${valor2}'>

Contato: <input id='id_codigo' readonly style='Border:0;' value='${valor3}' type='text'>`
     }
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<?php
$codigo = 1;
$nome = "Zé";
$endereco = "Rua";
?>

<button type="button" class="btn btn-primary" data-toggle='modal' data-target='#Alt'
data-codigo='$codigo'
data-situacao='$nome'
data-distribuidora='$endereco'
>MODAL</button>

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

<input readonly id='id_codigo' type='text'>

<input readonly id='id_nome' type='text'>

<input readonly id='id_endereco' type='text'>

<button
id='id_button' type="button" class="btn btn-info" data-position="top-left" title="Contato"
data-toggle="popover"
data-placement="down">Contato</button>

Comment: Opa. Ótimo estou quase lá. Eu gostaria que essas variáveis " let valor1" tivessem o mesmo valor do id que estão contidos nos inputs. Como faço?
Comment: Do mesmo jeito que está populando os inputs do modal pode popular o popover, só que os valores tem que estarem dentro de variáveis tipo `let id_nome =  valordoPHP` e no input do popover vc coloca ${id_nome}.


Compound interest derivation of $e$

Question: I'm reviewing stats and probability, including Poisson processes, and I came across:
$$e=\displaystyle \lim_{n\rightarrow \infty} \left(1+\frac{1}{n}\right)^n$$
I'd like to understand this more fully, but so far I'm struggling. I guess what I'm trying to understand is how you prove that it converges. Can anyone point me toward (or provide) a good explanation of this?
Comment: This is a common definition of e. What definition are you using?
Comment: Sorry for my lack of latex markup skills. The link points to a wikipedia image of this limit properly notated.
Comment: There is more than one way to prove this statement. What exactly are you struggling with?
Answer: Historically this is the definition of the number $e$. One can show that the sequence
$$\left( 1+\frac{1}{n}\right)^n$$
is increasing and bounded, and thus convergent. We define the limit to be $e$ and then it follows from this limit that $(e^x)'=e^x$.
Here is the proof of it:
Let $a_n= \left( 1+\frac{1}{n}\right)^n$ and $b_n=\left( 1+\frac{1}{n}\right)^{n+1}$. Then clearly $a_n \leq b_n$.
Then
$$\frac{a_{n+1}}{a_{n}}=\frac{\left( 1+\frac{1}{n+1}\right)^{n+1}}{\left( 1+\frac{1}{n}\right)^{n}}=\frac{n^n(n+2)^{n+1}}{(n+1)^{2n+1}}=\left( \frac{n(n+2)}{(n+1)^{2}}\right)^{n+1}\frac{n+1}{n}$$
By Bernoulli inequality
$$\left(1-\frac{1}{(n+1)^2} \right)^{n+1}\frac{n+1}{n} \geq \left(1-\frac{n+1}{(n+1)^2}\right)\frac{n+1}{n} = 1  $$
This shows that $a_n$ is increasing. Similarly $b_n$ is decreasing.
Thus $a_n$ is increasing and bounded by $b_1$, and hence convergent.
Now I will show that its limit is exactly $e$.
Let $l$ be its limit. Then
$$\ln(l) = \lim_n \frac{\ln(1+\frac{1}{n})-\ln 1}{\frac{1}{n}}=\ln'(1)=1$$
Comment: Most textbooks use the last argument to show this limit, but it only works for the wrong reason. We assume that the exponential is differentiable (because it "intuitively" is) and moreover that there is one exponential whose tangent at $(0,1)$ has slope exactly 1 (in other words, we use that $\ln(x)$ is continuous at $x=1$ to define $e$ and $\ln(x)$)..
It is exactly this limit which makes all these work.... And using directly those arguments, the argument really reduces to "because this limit is $e$, it follows that this limit is $e$".
There are actually simpler correct ways of defining $e$ but they all need a deep understanding of Analysis (like viz Taylor  Series or using FTC: $\frac{1}{x}$ has an antiderivative).
Comment: Just a quick note on the comment, there is no need to assume that the exponential is differentiable. Simply define the exponential function $\exp(x) = \sum_{i=0}^{\infty}$ and all the usual properties of $\exp(x)$ and $\ln(x)$ follow quite easily, with no need for the FTC. This is particuarly nice because most of the interesting properties of $\exp$ and $\ln$ are differentiable properties rather than integral properties, and they all follow almost immediately from these definitions.
Comment: @TomOldfield I mentioned that in my last paragraph, but all those definitions use Theorems not covered in an introductory calculus class, at least in North America. ;) And some of them are relatively strong results in Analysis...  Moreover, with this approach you define $e=\sum_{n=0}^\infty \frac{1}{n!}=\lim_n \left( 1+\frac{1}{n}\right)^n$, so is not really a new definition, you just prove the existence of the above limit in a different way....
Comment: @TomOldfield And, to clarify, how would you introduce the exponential this to way to a student if Power series and sequences are NOT part of the material studied in the class?
Comment: Trying to follow the proof, I'm stuck at: $$\frac{\left( 1+\frac{1}{n}\right)^{n}}{\left( 1+\frac{1}{n+1}\right)^{n+1}}=\frac{(n+1)^{2n}}{n^n(n+2)^n}\frac{n+1}{n+2}$$  Can you explain this step?
Comment: Oh wait, wait, I think I got it :)
Comment: @N.S. I think any serious introductory analysis course must include series as well as sequences. In which case the definition of $\exp(x) = \sum_{i=0}^{\infty}\frac{x^n}{n!}$ would be totally valid, since it is a series for each $x$ and can be shown to converge for each $x$ without knowing anything about power series, by the ratio test for example. You would need to know about power series to show that it is a differentiable (and continuous) function, but I don't know how you'd do that at all from your definition.
Comment: Still working through this, I'm getting a slightly different, $$\frac{a_n}{a_{n+1}}=\frac{(n+1)^{2n}}{n^n(n+2)^n}\frac{n+1}{n+2}=\left(1+ \frac{1}{n^2+2n} \right)^{n}\frac{n+1}{n+2}$$ so by the Bernoulli inequality,  $$\frac{a_n}{a_{n+1}} \geq (1+\frac{n}{n^2+2n})\frac{n+1}{n+2} =(1+\frac{1}{n+2})(1-\frac{1}{n+2})$$ I'm not sure how to prove that's > or = to 1, but even if you can, doesn't that mean that $$\frac{a_n}{a_{n+1}} \geq 1 \Leftrightarrow a_n \geq a_{n+1}$$ and thus $a_n$ is decreasing?
Comment: @ivan You are right, actually there were couple mistakes in the line above (powers didn't match).. Not that reasoning should be right... I also made that part easier to read... To get the right inequality I should had of course calculated $\frac{a_{n+1}}{a_n}$
Comment: And to prove that $b_n$ is decreasing, which is needed to conclude that $a_n$ is bounded, you do the same but this time you need to calculate $\frac{b_n}{b_{n+1}}$ :)
Comment: @N.S. Thanks for helping me out with this- I really appreciate it! I'm taking another look at it...
Comment: @ivan Sorry for the previous mistake, now I am pretty sure it is right. You can probably prove the part about $b_n$ by yourself, if you need help let me know :)
Comment: I took a stab at $b_n$ and managed to proove that $\frac{b_n}{b_{n+1}} \geq 1 + \frac{1}{n\left(n+2\right)^2}$, so $b_n \geq b_{n+1} + \frac{b_{n+1}}{n\left(n+2\right)^2}$ and since $n \geq 0$, $b_n \geq b_{n+1}$, so $b_n$ is decreasing. I *think* this is right :)  I'm not sure I see how this proves $a_n$ is bounded though.
Comment: Actually, I think I see it now: $a_n \leq b_n < b_1$
Comment: @ivan yup that's how you see the last part.
Comment: I think you cant use $\ln(x)$ without $e$. So your answer is circular at that point.
Comment: @MrYouMath one can easily avoid this, I only use the $\ln$ to emphasize that this is the right limit. If one wants to prove that the limit is $e$ without formally using the argument, one can proceed as follows: Call this limit $a$ and show first that $$\lim_n \left( 1+\frac{x}{n} \right)^n=a^x$$ for all $x$ rational. Then conclude from here that this equality holds for all real $x$. Finally, using this one can show that $(a^x)'=a^x$.
Answer: It's not too hard to prove, but it does rely on a few things. (In particular the validity of the taylor expansion of $\ln$ around 1 and that $\exp$ is continuous.)
Consider in general the sequence $n\ln(1+x/n)$ which is defined for all $x$, positive or negative provided $n$ is large enough. (In fact the proof that follows can also be modified slightly to work for complex $x$). Using the power series representation $\ln(1+y) = \sum_{i=1}^\infty (-1)^{i+1}\frac{x^i}{i}$ we get
$$n\ln(1+\frac{x}{n}) = x + \sum_{i=2}^\infty(-1)^{i+1}\frac{x^i}{in^{i-1}}$$
The absolute values of the terms in the series on the right hand side are bounded above by a geometric series (for n large enough) whose summation tends to 0 as $n$ tends to infinity. Hence
$$\lim_{n\rightarrow \infty} n\ln(1+\frac{x}{n}) = x$$
And so using the fact that $\exp(x)$ is a continuous function:
$$\lim_{n\rightarrow \infty}\bigg(1+\frac{x}{n}\bigg)^n = \exp\bigg(\lim_{n\rightarrow \infty}n\ln(1+\frac{x}{n})\bigg) = \exp(x)$$
In particular, set $x = 1$ to get the result you ask for.
Comment: BTW: Taylor series are not needed $\lim_{n\rightarrow \infty} n\ln(1+\frac{x}{n}) = x$ follows immediately from the definition of the derivative of $\ln(x)$ at $1$...
Comment: @N.S. We define the function $\exp(x)$ to be the power series $\sum_{n=0}^{\infty} \frac{x^n}{n}$, and $e = \exp(1)$ There is no problem with this definition and allows us to work with both $\exp$ and $\ln$ without the FTC.

To derive the limit, it depends on your definition of $\ln(x)$. You can define it as in integral of $\frac{1}{x}$ in which case your method works, or as the inverse of $\exp(x)$ in which case mine does.
Comment: The problem with this type of approach, while it is easy to understand by students, is this: what is your definition of $e$? :)
Comment: Yes, you are right there is no problem with this definition, but this is not how most of our undergrad textbooks define $e$. The limit you calculate is actually equivalent to the fact that your definition of the exponential makes sense (i.e. it is an exponential function)...  BTW: using the binomial expansion you can prove directly that $\lim_n (1+\frac{1}{n})^n=\sum_{n=0}^\infty \frac{1}{n!}$.
Comment: @N.S. I wouldn't know, this is how I had $e$ defined to me as an undergraduate. Personally I would view the real test of a function as being exponential as having the property $f(x+y)=f(X)f(y)$. Yes, this definition can be derived from the other, and that just goes to show that it doesn't really matter which one you use, as long as you can use it easily! I guess everyone should just pick their favourite :)
Comment: Yes that's how I learned exponential too, but it is typically introduced this way to math students which really can understand the subtilities involved in this definitions.... But the issue is that you cannot pick favorites, you need to pick the one you can truly understand. Power series and sequences are typically not covered in introductory Calculus classes (in NA), so, which definition should such a class use? Also, I learned the $e$ this way in undergrad too, but I covered sequences in highschool (but not power series).. I could still learn $e$ in highschool... And not ....
Comment: ... and not because it was my favorite, but because ot was the only approach which could use the little knowledge I have... It is probably the reason I always think about $e$ this way, but I like it because it uses much less Analysis that the exponential approach, which I agree, in many ways is more natural (if you think in terms of exponential functions not numbers)....
Answer: I have removed the more precise, but more confusing, justifications of $(1)$ and $(2)$. In this answer, I show that
$$
\left(1+\frac1{n+1}\right)^{n+1}\ge\left(1+\frac1n\right)^n\tag{1}
$$
and
$$
\left(1+\frac1{n+1}\right)^{n+2}\le\left(1+\frac1n\right)^{n+1}\tag{2}
$$
Therefore, $(1)$ says that $\left(1+\frac1n\right)^n$ is an increasing sequence and $(2)$ says that $\left(1+\frac1n\right)^{n+1}$ is a decreasing sequence. Since $\left(1+\frac1n\right)^n\le\left(1+\frac1n\right)^{n+1}$ the increasing sequence is bounded above and the decreasing sequence is bounded below; thus, they both converge.
Since $\lim\limits_{n\to\infty}\frac{\left(1+\frac1n\right)^{n+1}}{\left(1+\frac1n\right)^n}=\lim\limits_{n\to\infty}\left(1+\frac1n\right)=1$. They both converge to the same limit. This is called $e$.
$$
e=\lim_{n\to\infty}\left(1+\frac1n\right)^n\tag{3}
$$
Answer: A great elementary proof is on Rudin's Principles of Mathematical Analysis page 64 Theorem 3.31.

PS: Sorry I don't know how to stretch it, maybe you can download the pic and enlarge.
Comment: Please write it down here for us who don't have that book at hand.
Answer: I want to put this as an answer rather than a comment so that people can find it easily:
https://en.wikipedia.org/wiki/Characterizations_of_the_exponential_function#Equivalence_of_characterizations_1_and_2
^ Wikipedia has the cleanest approach I can find. i.e. It doesn't pull anything out of the blue, and it doesn't sit on top of other advanced results.
I'm not going to replicate the working; I am confident it will not change for the worse.
EDIT: I just noticed it cites its source as Rudin, theorem 3.31, p. 63–5, so it is the same as the picture posted in another answer!

Compound interest derivation of $e$


Learn to finger march in f by Daniel Turk

Question: I am trying to learn to finger 'March in f' by Daniel Turk, but it's driving me nuts how to do it.
It's in  'Essential piano repertoire', selected and edited by  Keith Snell  (preparatory level, page 7). Any tips would be helpful and nice.
Comment: You are going to have to be more specific. What specific problems are you having? Read about [ask] a good question.
Comment: I see in the image that someone has written finger numbers above the notes. When you try to use those finger numbers to play the piece, what goes wrong? It seems to me that using those fingers should make it fairly easy to play, so you'll have to explain what is going wrong when you use the fingers specified.
Comment: If you have questions about the fingering in a specific part of that piece (e.g. a certain bar), you could upload an image of that sequence. (or maybe write out the which notes to play in each hand)
Comment: Well, nobody can help if they can't see the music. But this isn't a copyright issue anyway, since showing a fragment of the music for learning purposes should fall under fair use. You still need to be more specific. "It's driving me nuts how to do it": then you must have tried some things and particular things are not working. What?
Comment: but that is a copy write issue though
Comment: as for the problem i have no clue how to finger the piece, i am a beginner in piano etc. thanks for the answers.
Comment: @DarrenSharrocks Regarding the copyright: do not poste the whole piece.  And you have a teacher?
Comment: https://www.facebook.com/photo.php?fbid=10157276505328332&set=a.241478948331.181278.750728331&type=3 it here Daniel Turk march in f, i do know how to post it on here, best wishes
Comment: no teachers are too expensive
Comment: i have no clue what i  am doing so just guessing, and it just confuses me, there i no video i can reference from so i cannot use them.  so its a bit convoluted. i use other people's  views on it as a reference and build from there etc.
Comment: Are you saying you don't know how finger numbers work?
Comment: yes what are correct fingers, do the positions move etc, bit confusing
Answer: The little numbers above the notes are meant to indicate which finger to use to play each note. For example, in the image in your question, there is a 3 above the first note, and then hand-written there are the numbers 4, 3, 2, 1 above the notes of the descending part at the end of the first measure.
The fingers of both your right and left hands have the following numbers:

Thumb
"Index" or "Pointer" finger
Middle finger
"Ring" finger
"Pinky" finger

So that means for the right hand part in the picture, you play the first two notes with your middle finger, then use your ring finger to play the third note, middle for the fourth note, index finger for the fifth note, and thumb for the sixth note (the last note of the measure).
Notice that you don't have to move your hand at all to play the notes with the fingers as written. Usually finger numbers are chosen and written in to allow for the minimum of hand movement, especially for beginner pieces like this one.
Comment: @DarrenSharrocks There is no one "correct" fingering for any piece. You have to figure out which fingering works best for your hands. I would finger the piece in the image exactly as written. I'm very confused because in your comments you indicated you didn't know how finger numbers work, but apparently you do know how they work. So I have no idea what you're actually asking at this point.
Comment: i  added the notes, how ever i d o not know if they are correct, if a more advance piano person can comment  that would be nice etc
Comment: Well put it this way. I know we have ten fingers on our hands, but there is lots of cross overs and position moves in piano playing, and they catch a beginner like me unawares very easily. There is a advance  way of doing this piece, in which the player would know how to plot the correct fingers.  so when i place the fingers on the piano, i have no clue if its correct and if i am not careful i could go in the wrong direction  and mess up. Case in point the one below it
 is March in G i got the fingering from a video on  u tube. I am not able do this for march in  F so i i am left in a loop
Comment: @DarrenSharrocks The fingering is already written in for March in F in the picture. I thought you said you were the one who wrote in the fingering. When you play those notes using those fingers, what problem do you have?
Comment: In my low experience  of  notations on piano pieces i believe and am sure i am incorrect. so i am asking a more advance person who knows the piano and music notation, am i on the right lines and what would they do for fingering in regards to the piece.
Comment: @DarrenSharrocks Do you think, the answer from Todd Wilcox was helpful to you, or did you know all this already? If it was not helpful, what exactly do you expect in an answer? Btw, it is normal to mix up things in the beginning - play more slowly if that happens.
Comment: @DarrenSharrocks This site is about discussing objective answers to questions, so we can tell you how fingering works and what the finger numbers mean, but we don't discuss our opinions of specific fingerings. I've already said that I would finger the piece in question the same way it is written in the image, so I don't know what more you want in terms of a more advanced person. I've been playing piano for almost 40 years. Only one person can tell you if a specific fingering works right for you, and that's you.
Comment: look i am a beginner so i do not how to finger a piece of music. If you say you play the piano for over 40 years that is would of been obvious, instead of going into the relm of paranoia about what my supposed motives are. i asked the question how does one finger this piece of music, the right answer would of been i do not know what is best for you but i would do it this way  or that, end of  just they do on u tube.
Comment: @DarrenSharrocks Actually my answer is "finger it the way the written finger numbers say to finger it". I still don't understand why that's not an acceptable answer for you. I'm not paranoid, just confused by your comments. Each of them seems to be asking the same question over and over again even though I feel like I've already answered it. My real advice is you need a teacher. Some things can't be learned from the internet. Piano is one of them.


The man with two boys

Question: I have recently seen a probability question which says
"i am asking randomly the persons I met if they are having two chidren and one of them is a boy who was born on tuesday. At last I met one whose answer is yes. What is the probability that the other child is also a boy. Assume equal probability to either gender and equal probability to be born on each day of the week"
I could actually solve it to 2/21. Did I do it right or can some one help me solve it?
Comment: [Duplicate of this question](http://math.stackexchange.com/q/4400/264).
Answer: This is going to get a bit long for a comment.
Suppose you are asking three questions in sequence:
1 Do you have exactly two children?
If the answer is yes, you include the person on your sample, and ask
2 Do you have a child who is a boy born on a Tuesday?
If the answer is yes, the person continues in the sample - call this $BT$ and you ask
3 Are both of your children boys?
Say the yes answers to this are $BB$, you are looking for $\frac {BB}{BT}$
Note that (given reasonable assumptions) one fourteenth of all children are tuesday-born boys. However, at stage 2, there will be $0$ or $1$ or $2$ Tuesday-born boys in the family. Case $0$ is discarded, and the other two are not equally likely.
Taking the day and the sex into account, there are 14 possibilities for each child - 196 altogether. In one of these, both are Tuesday-boys. There are 26 more possibilities containing a Tuesday-boy, making 27 in all (the $2$ case takes two of the expected 28) - twelve of which have two boys (two of the fourteen having been taken into account already), and fourteen (as expected) with a boy and a girl.
Counting, one sees the proportion with two boys is $\frac {13}{27}$.
I noted this, because it was not explained in the answers to the closely related question Zev Chonoles linked.

The man with two boys


How to discretise continuous attributes while implementing the ID3 algorithm?

Question: I am trying to implement the ID3 algorithm on a data set. However, all attributes are continuous and can have values between 1-10. I found that we have to specify the bin intervals for discretization but couldn't understand how to do this exactly.
Can some one explain on how to do this? The data set I am using is Breast Cancer Data from Wisconsin hospitals.
Comment: What is the "ID3 algorithm"? If it requires you to discretize continuous variables, it may be better to use some other method. Certainly there are classification tree methods (from your tag) that do not require binning.
Answer: ID3 is an algorithm for building a decision tree classifier based on maximizing information gain at each level of splitting across all available attributes. It's a precursor to the C4.5 algorithm.
With this data, the task is to correctly classify each instance as either benign or malignant. Since each attribute takes on whole integer values in the range 1-10, strictly speaking the values aren't continuous in that they can't take decimal values. For each integer value of each attribute, you'll need to calculate which split provides the most homogenous grouping of instances at each level of splitting. This is done by calculating the information gain for each possible split and selecting the greatest (ID3 is known as a greedy algorithm).
You can do this by hand, but it's obviously better to run the algorithm in a tool such as Weka or R.  If you're creating your own implementation, then you'll need to test each possible split and select the one with the greatest information gain, assuming you don't already have a homogenous group (in which case you'd assign the class attribute and change the node to a leaf).
Answer: Even though the original magnitudes might be continuous, the data is already discretized into discrete levels, so I do not see why you should do that.
Still, a popular method to discretize is to use kmeans, as explained here. k-means is a particular case of dictionary learning. The idea is that you express data in a more compact representation by finding a set of vectors that allow to reconstruct data while still minimizing the distortion introduced.
Notice that you perform k-means on each dimension. A detailed analysis of the distortion introduced in each variable is given in the classic paper "Least Squares Quantization in PCM" by Stuart Lloyd.


What periodic functions have to do with rational numbers?

Question: I would like to understand why is the answer of this question letter d.
Question:
The solution φ(t) = (x (t) , y(t), z(t), w(t)) of the system of equations:
x' =y, y' = - x, z' =w, w' =-(k^2)*z, that satisfies φ(0) = (1,0,0,1) is periodic.
So, is correct to say:
a) k is a whole number
b) k = 0
c) k > 0
d) k is a rational number different of zero
e) k is not a rational number
Answer: The solution of this system is made of functions with two distinct periods: $2\pi$ and $2k\pi$. For the solution to be globally periodic, $k$ must be rational, let $\dfrac pq$, so that after $q$ period for the second, you have seen $p$ periods of the first.

In other words, rational numbers have to do with periodic functions in that the respective periods must be commensurable.
Comment: still dont get it :(
Why they get 2 periods?
I think I lack information. Can u explain to someone not so good in hard math?
I solve the equations to t, tried to change for t + p(period), but i cant understand why have to be Rational.
Comment: @FELINTONETO: solve the equations, they are easy.


JQuery - Each com multiplos arrays

Question: Preciso fazer um each com vários items, exemplo:
Como posso fazer isso ?
O "item" já gera o resultado do array "data.id_site" mas preciso de um novo array junto, o "item2" que gera o resultado do array "data.name".
Seria algo como:
$.each(data.id_site, data.name, function(i, item, item2) {
    $(".lado").append("
" + item2 + "
");
});

Comment: Podes explicar melhor a pergunta? Podes dar um exemplo do que tem o `data` e do resultado que esperas obter?
Comment: alterei a pergunta, preciso de um each com mais de 1 array, é isso!
Comment: Queres então algo como `$(".lado").append("" + name + "");` é isso?
Comment: Sim!!!!!!!!!!!!!
Answer: Supondo que ambos data. e data.name têm o mesmo numero de elementos, podes iterar um deles como estás a fazer e usar o indice para ir buscar o que queres ao outro array. Assim:
$.each(data.id_site, function(i, item) {
    $(".lado").append("
" + data.name[i] + "
");
});

Porém para não estar a chamar sempre o .append() é melhor fazer assim:
var divs = data.id_site.map(function(id, i){
    return "
" + data.name[i] + "
"
}).join('');
$(".lado").append(divs);

Comment: era isso mesmo, vlw!

JQuery - Each com multiplos arrays


Quantitative rule for reporting mean (SD) vs. Median (IQR)?

Question: I see this question as more a matter of opinion and specific to the quantity or interest and what information you seek, however I thought some might have a pragmatic rule.
Essentially, I am writing a personal R script for generating descriptive tables to streamline my reports (like createTableOne, Stargazer etc.).
I wanted to write in a general rule for when the table should report mean (SD) or median (25th, 75th percentile) for numeric variables. Right now I have to specify for the function what I want, which is okay but I wanted to see if I could get fancier with it.
I was thinking about maybe some rule like so: if mean/median > 1.5 or <0.5 than report median (IQR).
Answer: A general rule of thumb for reporting mean or median as the defining measure of central tendency is a function of skewness. In a normally distributed distribution (with skew more or less between -1 and 1), the mean is the best measure of central tendency. With positively and negatively skewed distributions, however, median might be a better measure of central tendency. For the purposes of writing a function() (or a script, as you call it) to make your workflow more efficient, this rule of thumb might work for you. Altogether though, there is no overarching rule in this matter. Finally, I would argue for always reporting the mean over the median as it is the best measure of all participants' scores.
Comment: @KevinM, it depends on the type of variable in question. LoS is time to event data. It cannot be normally distributed. It is typically very skewed & often rather irregular (eg, not fitting any of the 'named' survival time distributions well). It is typical (& appropriate) to use medians & quartiles for such data. This example illustrates that "there is no [nor could be any] overarching rule in this matter", as Jay states.
Comment: Appreciate the point, I will consider abs(skewness(x))>=1 as a rule. I do think mean is generally better, but median/mode is often done conventionally for certain variables in my field (i.e. length of hospital stay).


SystemError:  returned a result with an error set

Question: I'm trying to upgrade from:
SWIG 2.0.11 and Python 2.7.12 to
SWIG 3.0.12 and Python 3.6,
but I get the following exception when I run the tests on any iterator (automatically generated using %template):
SystemError: <built-in function xxx_iterator> returned a result with an error set

For example, even the simplest iteration fails:
Traceback (most recent call last):
File "testRender.py", line 459, in testRender
    for v in vertices:
File "ncore.py", line 90833, in __iter__
    return self.iterator()
File "ncore.py", line 90830, in iterator
    return _ncore.Vertices_iterator(self)
SystemError: <built-in function Vertices_iterator> returned a result with an error set

Any ideas?
Again, this was all working great with SWIG 2.0.11 and Python 2.7.12....
Edit: Adding simpler example:
It could be ANY %template-generated iterator, so, for example, this template, defined in the .i file:
%template(Ints) std::list<int>;

will fail when using this simple code:
intsList = ncore.Ints()
intsList.append(1)
intsList.append(2)
for i in intsList:
    print(i)

with a message similar to this:
Traceback (most recent call last):
File "testRender.py", line 459, in testRender
    for i in intsList:
File "ncore.py", line 90833, in __iter__
    return self.iterator()
File "ncore.py", line 90830, in iterator
    return _ncore.Ints_iterator(self)
SystemError: <built-in function Ints_iterator> returned a result with an error set

Comment: without knowing the source code for `Vertices_iterator` it's impossible to give any help.
Comment: If you want me to be able to look at this you need a real minimal complete example that I can get running in my own debugger. I ignored it before because there isn't one and even with a bounty I still can't help. The traceback shows at least 459 lines of Python you've not shown in your "simple test case" that could be related and goodness knows how much else in the rest of ncore C and Python generated code. If you really want an answer you need to isolate it to something we can reproduce.
Comment: FYI, it looks like this commit (https://github.com/swig/swig/pull/560/files) attempted to fix a similar issue...
Answer: That is strange, just recompiled everything from scratch. Then I tested your simplified example (if understood correctly):
Mytest.i:
%module mytest
%{
    #include <list>
     using namespace std;
%}

%include "std_list.i"
namespace std {
    %template(Ints) list<int>;
}

Compile steps:
swig -Wall -c++ -python -py3 -o mytest_wrap.cpp mytest.i
g++ -c -g -ansi mytest_wrap.cpp -I/usr/local/include/python3.6m/ -fPIC -o mytest_wrap.o
g++ -g -ansi -o _mytest.so mytest_wrap.o -shared

Then, after importing mytest module to python, everything works like a charm.
Tested configurations:

dockerized Ubuntu16.04: Python 3.6.1, SWIG 3.0.12, g++ 5.4.
dockerized Centos6: Python 3.6.1, SWIG 3.0.12, g++ (4.9.2 and 4.4.7)
Comment: Thanks for testing. I should mention we tried with g++ 4.6 and g++ 4.9 on Centos 6, and MSVS Pro 2013 on Windows.
Comment: @DevanWilliams Works for me also on Centos6/g++ 4.6. Does this simple proposed example produce exactly the same problem? Is there any compilation warning?
Answer: Though it's an old question relatively, but recently I encountered a similar issue (<built-in function delete_qpol_iterator_t> returned a result with an error set) while dealing with SELinux and setools in CentOS7 docker. Building and installing libsepol and libselinux from source code might solve the problem.
So I guess updating relevant libs and other dependencies might be useful.


Percorrer um dict até ficar vazio no Python

Question: Gostaria como fazer para percorrer enquanto uma lista composta de valores e chaves for diferente de zero, adiciona apenas os valores (values()) em uma lista? O código que tenho é esse:
hey = ['item1', 'item2', 'item3', 'item4']
print("hey", hey)
lol = [32, 54, 56, 64]
print("lol", lol)
lil = dict(zip(lol, hey))
print("lil: ",lil)
pop = list(zip(lil.values(), lil.keys()))
print("pop sem ordenar: ", pop)

sorted(pop, reverse=True)
print("pop ordenado: ", pop)

#for i in lil:
     #  print("i: ",i)
     #  print("lil[i]: ", lil[i])

max_value = max(pop)

print("max_value: ", max_value)
novo_lil = lil[max_value[1]]
del lil[max_value[1]]
print("lil nova: ",lil)

Tentei fazer isso, mas não funcionou:
hey = ['item1', 'item2', 'item3', 'item4']
print("hey", hey)
lol = [32, 54, 56, 64]
print("lol", lol)
lil = dict(zip(lol, hey))
print("lil: ",lil)
pop = list(zip(lil.values(), lil.keys()))
print("pop sem ordenar: ", pop)

sorted(pop, reverse=True)
print("pop ordenado: ", pop)

#for i in lil:
     #  print("i: ",i)
     #  print("lil[i]: ", lil[i])

max_value = max(pop)

while not(lil[max_value[1]]):
    print("max_value: ", max_value)
    novo_lil = lil[max_value[1]]
    del lil[max_value[1]]
    print("lil nova: ",lil)

Alguém pode auxiliar-me? O que estou fazendo na verdade é ordenar um dict e depois eu adiciono somente os valores dele em uma lista, apenas isso.
Comment: Eu não entendi sua dúvida, mas percebi que está usando a função sorted de forma errada, você deve fazer assim "pop = sorted(pop,reverse=True)". Se puder explicar melhor a dúvida.
Comment: Certo @PauloHenriqueCardoso, é assim: tenho duas listas. Cada valor de hey corresponde a um valor de lol. Logo 'item1' tem valor 32, 'item2' tem valor 54 e assim por diante! Preciso ordenar a lista hey com base na lista lol em forma decrescente, de forma que lol fique: [64, 56, 54, 32] mas a lista hey também deve ser ordenada correspondente com cada valor de lol: hey = ['item4', 'item3', 'item2', 'item1']
Comment: A forma que encontrei com meu amigo @Miguel foi de relacioná-los por meio de um dict como é feito em: lil = dict(zip(lol, hey))
Comment: Então eu transformo esse meu dict em uma lista e ordeno ela, como você ali corrigiu. Já que não é possível ordenar um dict, pensei em pegar o maior valor do dict e adicionar por ordem em uma lista, mas apenas seus values()
Comment: Para que no final eu tenha hey = ['item4', 'item3', 'item2', 'item1'] ordenado com base na lista lol, consegui explicar?
Comment: É que é um pouco difícil de explicar mesmo, peço desculpas por isso.
Comment: Ainda não sei se entendi, mas o seu problema parece ser o fato de o dicionario não ser ordenado, para isso você pode usar o [Ordered dict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) da biblioteca Collections. Mas veja se essas duas linhas de codigo apos ordenar a lista "pop" resolvem seu problema :for i in range(len(hey)):
     hey[i] = pop[i][0]
Comment: pot favor, munde o rsumário - ("enunciado") da questão. Atualmente não tem nada em comum com o problema exposto.
Answer: Nossa - - muita complciação para coisa que fica bem simples em Python.
Dicionários tem os métodos keys, valuese items que permitem acesso aos seus membros, e a poderosa construção de list-comprehension, que deixa você aplicar qualquer expressão em cada item de uma sequência para gerar uma lista.
ENtão é só fazer:
hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

dct = dict(zip(lol, hey))
result = [valor for chave, valor in sorted(dct.items(), reverse=True)]

Onde dct é um dicionári que relaciona as duas listas, como você já fez - aí percorremos todos os itens desse dicionário já ordenados pela chave na chamada ao "sorted" - como você quer em ordem decrescente, usamos o "reverse". E, de cada item, pegamos o segundo valor - que é o valor associado na primeira lista original.
Answer: Para ordenar uma lista de acordo com a outra eu desenvolvi a seguinte solução:
hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

''' vamos cria uma lista de transposição com a posição original
e a nova posição do item. '''
transposicao = []
for posicao_nova, i in enumerate(sorted(lol, reverse=True)):
    posicao_original = lol.index(i)
    transposicao.append([posicao_nova, posicao_original])

# após guardar as posições, efetivamente alteramos a lista lol
lol = sorted(lol, reverse=True)

# agora utilizamos a lista de transposição para reordenar a lista hey
nova_hey = []
for i in transposicao:
    nova_hey.append(hey[i[1]])

hey = nova_hey

print(hey, lol)

O resultado será o desejado: ['item4', 'item3', 'item2', 'item1'] [64, 56, 54, 32]
Uma versão mais simples e mais "pythonica":
from operator import itemgetter

hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

# junta as listas e ordena de acordo com os valors da segunda lista     (lol no caso)
ordena_junto = sorted(list(zip(hey, lol)), key=itemgetter(1), reverse=True)

# extrai as listas ordernadas
hey, lol = zip(*ordena_junto)
print(hey, lol)

Resultado: ('item4', 'item3', 'item2', 'item1') (64, 56, 54, 32)
Espero que tenha ajudado a resolver o seu problema.


Erro ao conectar no SQL Server utilizando CodeIgniter

Question: Estou com um erro ao conectar o banco em meu projeto CodeIgniter, estou usando o SQL Server.
<code>$db['sql'] = array(
    'dsn'     => 'DRIVER={SQL Server}; SERVER=HOSTPT-01407; DATABASE=localidade;',
    'hostname' => 'HOSTPT-01407',
    'username' => 'user123',
    'password' => 'password',
    'database' => 'localidade',
    'dbdriver' => 'odbc',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE) ;
</code>
O erro que aparece é o seguinte:
<code>**A Database Error Occurred**

Unable to connect to your database server using the provided settings.

Filename: C:\wamp\www\ProjetoGuiaFacil\system\database\DB_driver.php

Line Number: 124
</code>
Answer: <code>$db['sql'] = array(
    'Database'     => 'DRIVER={SQL Server}; SERVER=HOSTPT-01407; DATABASE=localidade;',
    'hostname' => 'NomedoServidor/SQLEXPRESS',
    'username' => 'user123',
    'password' => 'password',
    'database' => 'localidade',
    'dbdriver' => 'sqlsrv', // alterando para SQL server
    'dbprefix' => '',
    'pconnect' => TRUE, // alterando para true, para connectar
    'db_debug' => TRUE, // tornando o debug ativo do banco de dados, para que em caso de erro, exiba a mensagem: "Ocorreu um erro no banco de dados"
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE) ;
</code>
Comment: Selecione o código e use o botão `{ }` para formatar.
Comment: Organize o código no sublime para ficar legível, ou qualquer editor de texto ou IDE que esteja usando.
Comment: ou ` ` em volta do código


Confused with creating an ODBC connection, apparently I have two separate odbcad32.exe files?

Question: Alright, this is my first time working with this so forgive me if I'm a little confusing or vague.
I have a server with Windows Server 2008 Standard without Hyper-v (6.0, Build 6002). I'm running a small website off this server and using a Microsoft Access database to store some information coming in through the website. I'm sure the PHP I have written to open the ODBC connection is correct as it has worked for me when I created this website in a testing environment on a laptop.
My current issue now is that it seems like I have two different odbcad32.exe's, and one doesn't appear to have a driver for a .accdb file, and only a .mdb file. The other has a driver for both.
The first one I speak of has a driver titled 'Driver do Microsoft Access (.mdb)', the second one has a driver titled 'Microsoft Access Driver (.mdb, .accdb)'. I access the first odbcad32.exe by going to C:\Windows\SysWOW64\odbcad32.exe, and then the one that seems to have the driver I need I go to Control Panel->Administrative Tools->Data Sources(ODBC) and simply create a new connection in the System DNS tab.
Whenever I make changes to the one that I access through the Control Panel, I see no changes, however if I use the odbcad32.exe file in SysWOW64 I do get some changes in the errors that come back to me. The main difference I noticed is that when I set up an ODBC connection with the Control Panel method it said it simply couldn't find the ODBC connection, but when I made a .mdb connection in the SysWOW64 one (and pointed it to a .accdb file) it says
<code>Cannot open database '(unknown)'. It may not be a database that your application recognizes, or the file may be corrupt.
</code>
Which makes it seem like it is this odbcad32.exe version in SySWOW64 that is being recognized as the 'correct' one. Is there any way to fix this?
I've tried to be as thorough as possible but if I've been confusing or left anything out let me know.
Answer: The executable in system32 is the 64 bit version while the copy in syswow64 is the 64 bit version. Each one works with different sets of drivers based on the architecture of the executable you're running.
The version you want to run depends on the architecture of the executables that need to load the drivers.
Most often, PHP runs as a 32 bit process for CGIs, but you'll need to double check your environment and make sure the appropriate drivers are installed.
Comment: Well it appears the syswow64 is the one actually being run. I'm assuming there is a way to update that .exe with the appropriate drivers?
Comment: Install the 32 bit Microsoft Access Database Engine Redistributable and you should be fine.


How are child piano prodigies taught so quickly?

Question: Can you create prodigies or are they born? I'm mostly curious how teachers handle a student like this, and what methods they would use.
Please give credentials before you answer.
Edit 1: I was thinking it might help if I created a case. Let's say the student is 3 years old, shows incredible ability to learn and perform works on the piano, and the parents are on board. How can a teacher turn this child into a prodigy?
Edit 2: People misunderstood what I meant by 'credentials' (My own fault for not being clear enough!). By credentials, I want to know: your teaching experience in years, and if you've actually been able to teach a prodigy. For example, my creds would be: Have taught piano at both a larger studio and my own private studio for a little over 10 years, I've also taught some online YouTube music lessons, skype lessons. My greatest success with a student was a 15 year old who in 3 years went from beginner piano up to Liszt Hungarian Rhapsody no 2, without skipping anything, and placing either 1st or 2nd in competitions against students who had been playing 10+ years.
People were wanting me to define what a prodigy is: The google definition is: a person, especially a young one, endowed with exceptional qualities or abilities.
"a Russian pianist who was a child prodigy in his day"
As an example: I'd consider someone like Emily Bear to fit with that, but there are many other examples.
The essence of what I'm wanting to know is, When a child prodigy is being taught, how does the teacher take advantage of the prodigy's talents, and not waste the opportunity? What is a good practice regime? Should they be taught a different method which skips some elements, or the same method and let the prodigy accelerate their own progress due to their natural abilities?
Comment: Can you instead of giving a hypothetical, give an example of a pianist that you consider a prodigy? In my teaching experience, the single greatest factor in how much and how quickly a student learns is their love for the instrument and the playing of it, which leads to increased practice time. As long as a student does not injure themselves, practice is king. Having perfect pitch also seems to help, but practice is more important by a lot.
Comment: They completely forgo all other parts of a healthy childhood.
Comment: What sort of credentials should we present before answering? A teaching degree? Or would book work on known, past cases be sufficient?
Comment: The term prodigy assumes inborn talent. Therefore they are born like that. The 3 yr old is already a prodigy - perhaps an undiscovered one, but nevertheless a prodigy. " When I was teaching young Wolfgang, I had a heck of a job keeping up with him".  Our credentials or those of the prodigies we've discovered?
Comment: "Can you create prodigies or are they born?"  I think your search for musical "credentials" is misplaced...understanding what makes a prodigy a "prodigy" is probably more a study in either semantics and or science, depending on where you see the issue.
Answer: Prodigies cannot be created - except at conception. The term is used for people who have an innate ability. Few are so blessed, which is one reason they are so remarkable. They are taught so quickly because they are prodigies.
Credentials are irrelevant for this question, unless I'm missing something.
Handling cases like this can be a mixed blessing. A prodigy will learn extremey fast, but could either be a perfectionist or someone who 'gets that concept', but needs to move swiftly on to the next, thus not feeling the need to play a piece perfectly. Good or bad? your decision.
Keeping up is difficult, not because the prodigy knows more than the teacher, but because he will often leave the teacher on a point, which he thinks he understands, although the teacher is aware of subsequent implications that need covering; the prodigy happy that he knows all about that part.
It's a balancing act between keeping the challenges coming, and ensuring that the prodigy actually understands enough to build on. Although, for me, understanding everything just isn't necessary. If you disagree with that - you drive a car, don't you? Please explain how the gearbox works. Oh, you can't - so you aren't a very good driver, then...
There is great pleasure to be derived from teaching a prodigy, but it's also very, very hard work.
Comment: What's your background? How long have you taught? What's the greatest success you've achieved with a student? What methods did you use to attain success? Break down those methods so we could try them ourselves with our own students. Thank you. ^_^
Comment: +1 for this solid extensive answer. *(Okaaay, maybe the +1 is partly influenced by "Prodigies cannot be created, except at conception")* :)
Answer: (I feel like the "credentials" thing is a red herring. I've seen music theory "teachers" on here confused by first-semester concepts. So I'm not addressing it.)
My understanding of this word in English is that the very definition of "prodigy" implies some pretty serious innate abilities. So it's less about teaching children quickly and more about child prodigies simply not needing much teaching in order to get to a high level.
Thus it's less about "turning" a child into a prodigy and more about the child winning the genetic lottery.
A child prodigy of course needs good teachers in order to reach the highest level, but in the case of the prodigy, the initial talent comes from the student him/herself. In your case, if the three-year old shows an incredible ability to learn and perform, they may already have this (woefully undefined) "prodigy" status. Find them a university teacher, quick.
Comment: I, and probably others, need to know why this has been downvoted. Try to give a reason - otherwise it looks like trolls.
Comment: (Credentials was just so I have an idea of your background. I don't care about degrees, so much as actual experience.)
I'd like a suggested practice regiment as an answer.
Comment: @Tim I agree. This got a +1 from me; I cannot understand why it deserved two downvotes. To be fair, though, it may have resulted from OP's question seemingly being bypassed (the question is being refuted, which may have been misunderstood).


What's a good open source solution that supports push e-mail?

Question: Currently using Exim4 + courier-imaps + spamassassin but would like to get push e-mail on my iPhone and Android devices!
Answer: I am using dovecot, which allows me to fetch mail with my android. If your email client supports IMAP Idle you will get new mail immediately.
Found this: http://dovecot.org/list/dovecot/2010-April/048171.html
Comment: Thanks -- the problem is there aren't any mail clients for mobile devices that support IMAP idle.  Once the phone goes to sleep the TCP/IP connections die.
Comment: With dovecot there seems to be a possible solution to get real push support: http://www.cklog.net/push-email-with-dovecot-mail-server/