How to calculate the mean and CI for a percentage

Question: I have some data that is percent reduction, i.e., -%, from a study and I want to be able to summarize the average percent reduction from my n = 20 samples, and to also provide a confidence interval. I thought one way to do this would be to use the usual way people proceed, i.e.,
$$(\bar p-z_{\alpha/2}\times\frac{\sigma}{\sqrt{n}},\,\bar p+z_{\alpha/2}\times\frac{\sigma}{\sqrt{n}})$$
where $\bar p$ is the average of the percent reductions and $\sigma$ is the standard deviation of the percent reduction. However, I am hesitant to calculate the confidence interval this way because doesn't this only work when the data is normally distributed?  I know that my data isn't because it is restricted to the values $[-100,0]$ and so not the whole real line.
Is there an alternative way to calculate the interval for the average? Or is the above way fine?
Comment: @COOLSerdash I have the individual pre and post values
Comment: Are the individual values (pre/post) available or do you just have the percentage reduction?
Comment: Could you please review the provided answers and check if any of them satisfied your question? If yes, please consider to accept one. I want to award the bounty to the answer that is most useful to you. Thank you.
Answer: The data size is small, so I recommend bootstrap confidence intervals.
Resample 20 observations with replacement from your dataset, compute your percent reduction on that resample, and repeat 1000 times.  Your x% confidence interval is simply the $\frac{1 - x}{2}$ quantile of your collection to the $\frac{100 - x}{2}$ quantile.
One benefit of this approach is that your CI will "automatically" incorporate the asymmetry inherent in the problem.  There will be no statistics in your collection that are e.g. less than zero because the way you calculate your stat makes that impossible.  Doing anything based on the well-known standard error of $\hat{p}$ will give you a CI based on a normal distribution, which will have nonzero density for all values of p, even impossible ones like -1.
Comment: Note that "you should use the bootstrap" does not necessarily follow from "the sample is small." Percentile confidence intervals can often have the wrong coverage probability in small samples. See for eg. this question with answers and comments https://stats.stackexchange.com/questions/112147/can-bootstrap-be-seen-as-a-cure-for-the-small-sample-size
Comment: My reasoning from "small sample" to "bootstrap" was a little different than the main one discussed in that thread (avoiding parametric assumptions).  My reasoning is that the computational burden of the bootstrap is low when the data size is small.  Maybe a more accurate statement would have been "your data size is small and your statistic of interest is quick to compute, so bootstrap"
Answer: Let me see if I understood your question correctly.

You have a sample of n = 20;
For each observation in this sample you have computed a percentage reduction as a consequence of some treatment: i.e.

\begin{equation}p_i =\frac{x_i,t - x_{i,t-1}}{x_{i,t-1}}\end{equation}
where $x_{i,t}$ is the i-th observation in your sample after the treatment and $x_{i,t-1}$ is the i-th observation in your sample before the treatment.

These percentage reductions you have taken and averaged:

\begin{equation} \hat{p} = \frac{1}{20}\sum_{i=1}^{20} p_i\end{equation}
to estimate a parameter $p$ in the population: the percentage reduction in the population on average as a result of the treatment. And what you're interested in is computing a confidence interval for this RATIO (I did not realize that this was a ratio of two random variables that was being estimated when I wrote this).
If this is correct, then what I suggest you use is a paired sample t-test: https://en.wikipedia.org/wiki/Student%27s_t-test#Dependent_t-test_for_paired_samples
The value of $\hat{p}$ is a random variable as it will differ from sample to sample. If the sample is large enough (usually n > 30), then the distribution of $\hat{p}$ over many simple random samples will be normally distributed according to the Central Limit Theorem. This sample is somewhat small, and you probably don't have a very reliable estimate of the population variance therefore (it's unknown), so for that reason you use the T-distribution which is approximately normal for large samples.
The reason for using the paired T-test is that your observations are not independent. The percentage reduction is computed, if I understood you correctly, by comparing the i-th observation before and after a treatment. If there are two groups, however, that you're comparing, then an ordinary T-test will do.
Hope that this helps!
Edit: what I (stupidly!) forgot here is to mention that you have a ratio estimator. This poses some problems for using a T-test. $\hat{p}$ is the quotient of two random variables. In addition, your estimate will be biased. See here https://en.wikipedia.org/wiki/Ratio_estimator. It's explained there how you can adjust for this.
Answer: One very reasonable approach is to log-transform the data (final values and pre-values), perform a linear regression/ANCOVA on the log-transformed data. Then you backtransform (simply exp(x)) to the original scale.
The result can be interpreted as the ratio of geometric means compared to the pre-values. I would then tpically interpret something like 0.8 as a 20% reduction.
This is typically much better behaved than analyzing calculated percentage change values (in particular the standard deviation does not tend to be constant across different values and various other problems) and also ensures that confidence intervals lie within the possible percentage changes (i.e. values cannot be lowered by more than 100%).
Answer: A common approach to this would to use a risk ratio and create the confidence interval around logged risk ratio. The risk ratio is the ratio of the two proportions and can be computed as
$$ RR = \frac{p_1}{p_2} $$
where $p_1$ is the proportion for group 1, and $p_2$ is the proportion for group 2. Working from a 2 by 2 frequency table with the cell frequencies represented by $a$, $b$, $c$, and $d$ (that is, $a$ and $c$ are the number of successes for groups 1 and 2, respectively, and $b$ and $d$ are the number of failures for groups 1 and 2, respectively), we can compute the risk ratio as
$$ RR = \frac{a/(a+b)}{c/(c+d)} $$
The standard error of the logged risk ratio is computed as
$$ se = \sqrt{\frac{b}{a(a+b)} + \frac{d}{c(c+d)}}$$
Thus, we can compute the 95% confidence interval as
$$ln(RR) \pm 1.96(se) $$
Taking the exponent of the upper and lower confidence limits will give you the confidence interval for the risk ratio
$$ RR = e^{ln(RR)} $$
You can convert the risk ratio into your original question of percent reduction (assuming the risk ratio is less than 1) with the following
$$ \%~reduction = (1-RR) \times 100 $$
You could apply this to the limits of the confidence interval.
Note that if the risk ratio is greater than one, you would determine the % increase as
$$ \%~increase = (RR-1) \times 100 $$


Connect to custom GTK signals defined in Glade file

Question: I want to connect a handler to a custom signal. In my glade file I have a window with some buttons. The window is loaded like this in Rust:
let glade_src = include_str!("views/window.glade");
let builder = gtk::Builder::new_from_string(glade_src);
let window: gtk::ApplicationWindow = builder.get_object("Window").expect("Couldn't get window view");
window.set_application(Some(app));

A button in this window has this signal defined:
<signal name="clicked" handler="_on_start_clicked" swapped="no"/>

In Python I can connect using simple method annotations:
@Gtk.Template.Callback()
def _on_start_clicked(self, sender):
    print("start clicked")

But how can I connect a function in Rust to this signal?
AFAIK I don't have such annotations in Rust. I'd need something like window.connect_signal("_on_start_clicked", handler);
I'm using Rust and the gtk crate.
Comment: Please, add the gtk-rs tag
Answer: This seems to be very new. The pull request is actually not in a stable release of gtk crate (as of v0.7.0). By using the git repo directly I managed to connect signals using Builder::connect_signals() like this:
// the handler
fn on_start_clicked(param: &[glib::Value]) -> Option<glib::Value> {
    println!("on_start_clicked fired!");
    None
}

// ...

// connect all signals
builder.connect_signals(|builder, handler_name| {
    match handler_name {
        // handler_name as defined in the glade file => handler function as defined above
        "_on_start_clicked" => Box::new(on_start_clicked),
        _ => Box::new(|_| {None})
    }
});

If still not in stable release use this dependency in Cargo.toml file:
[dependencies]
glib = { git = "https://github.com/gtk-rs/glib.git" }

[dependencies.gtk]
git = "https://github.com/gtk-rs/gtk.git"
features = ["v3_22"]

Comment: I know this was posted some time ago but have you worked out how to use the param argument for on_start_clicked? I cannot seem to get the gtk::ApplicationWindow out of [glib::Value].
Comment: Did someone managed to do it in rust + gtk4?


Why some functionality of my drupal site is different on different PCs?

Question: I created a site but when I log in from another PC (exact same site), some things are different.
Like on my laptop, my ajax loader is working beautifully but it lags on my office computer.
There is a message on successful image update (from media module) on my PC but there is no message in my laptop (however that should be the case).
What's happening here? I'm lost.
UPDATE
I saw a JavaScript error on my PC which is very much different than the JS error on my laptop. They are the same file, same webroot and same website. Even after turning off my development environment, I am not going further.
UPDATE
Problem Solved, the origin of the issue was JQuery Conflict. After defining different reference variables, my problem is free. Although I still don't understand why this was not a problem in my machine. Is there a mechanism that I'm missing?
Comment: different browsers or same?
Comment: Google Chrome, I tried on firefox, incognito of those and I checked in console. No luck yet
Comment: Is it related to [this](http://stackoverflow.com/questions/833883/weird-chrome-prototype-jquery-conflict)?
Comment: I checked. The problem was not limited to chrome. Thanks for the link @JimmyKo
Answer: The origin of the issue was Jquery Conflict. After defining different reference variables, my problem is free.


golang Couchbase n1ql query pass params to?

Question: I'm trying to find a way to pass parameters to query, but not quite sure how. The API on the web site looks a little bit outdated?
myQuery := gocb.NewN1qlQuery("SELECT * FROM default")
rows, err := myBucket.ExecuteN1qlQuery(myQuery)
if err != nil {
    fmt.Printf("N1QL query error: %s\n", err)
}
var row interface{}
for rows.Next(&row) {
    fmt.Printf("Row: %+v\n", row)
}
if err := rows.Close(); err != nil {
    fmt.Printf("N1QL query error: %s\n", err)
}

Because, actually ExecuteN1qlQuery takes two params:
func (b *Bucket) ExecuteN1qlQuery(q *N1qlQuery, params interface{}) (ViewResults, error)

I am not sure just how to use it... Like I would like to create a query with placeholders, and pass values to  ExecuteN1qlQuery via params. Like with SQL (prepare -> execute). For example something like that:
    myQuery := gocb.NewN1qlQuery("SELECT * FROM default where a=? and b=?")
    rows, err := myBucket.ExecuteN1qlQuery(myQuery,[]string{"b","c"})
    if err != nil {
        fmt.Printf("N1QL query error: %s\n", err)
    }
    var row interface{}
    for rows.Next(&row) {
        fmt.Printf("Row: %+v\n", row)
    }
    if err := rows.Close(); err != nil {
        fmt.Printf("N1QL query error: %s\n", err)
    }

Answer: The example you posted for how to do do this is from our developer guide repo on github:
https://github.com/couchbaselabs/devguide-examples/blob/master/go/query-placeholders.go.
Basically, you're using $ which references an interface and a corresponding positional parameter beginning with 1.
For your example it would look something like:
// Setup a new query with a placeholder
myQuery := gocb.NewN1qlQuery("SELECT * FROM default where a=$1 and b=$2")

// Setup an array for parameters
var myParams []interface{}
myParams = append(myParams,"foo")
myParams = append(myParams,"bar")

// Execute Query
rows, err := bucket.ExecuteN1qlQuery(myQuery, myParams)
if err != nil {
    fmt.Println("ERROR EXECUTING N1QL QUERY:", err)
}

// Iterate through rows and print output
var row interface{}
for rows.Next(&row) {
    fmt.Printf("Results: %+v\n", row)
}

Comment: Mike, we are constantly working to improve the documentation--especially the dev guide.  Thanks for posting this question.
Comment: Do you think my link to the repo was not good enough? :-)
This example solved all problems I had.
The problem was to find the example, it was not quite straight way, may be because I was expected more from couchbase  site
Answer: Just found example
        myQuery := gocb.NewN1qlQuery("SELECT airportname, city, country FROM `travel-sample` " +
        "WHERE type='airport' AND city=$1 ")

    // Setup an array for parameters
    var myParams []interface{}
    myParams = append(myParams, "Reno")

    // Execute Query
    rows, err := bucket.ExecuteN1qlQuery(myQuery, myParams)


Exercício da Árvore Utópica, Árvore da Vida etc. etc

Question: Bom dia! Estou fazendo o curso do Santander, e o último desafio é o famoso cálculo da altura da árvore da vida. Estou com um problema bem específico. Antes, segue o enunciado:

As árvores utópicas  crescem de uma forma particular, em dois ciclos:
cada primavera dobram seu tamanho cada verão crescem um metro Se Laura
  planta uma árvore utópica com um metro, no final do outono, qual seria
  sua altura depois de N ciclos?
Alguns exemplos:
si N = 0, sua altura será 1 metro (não cresceu nada);
si N = 1, sua altura será de 2 metros (dobrou a altura na primavera)
si N = 2, sua altura será de 3 metros (cresceu um metro mais no verão)
si N = 3, sua altura será de 6 metros (dobrou a altura na primavera
  seguinte)
E assim ... Escreva a função alturaArvoreUtopica, que utilize uma
  quantidade de ciclos de crescimento, e retorne a altura resultante da
  árvore de Laura.

Então, como a plataforma é meio ruim, eu costumo fazer o código no CodePen, testar e depois passar para a plataforma no curso. Meu código ficou assim:
function alturaArvoreUtopica (ciclos) {
  var altura = 1;
  if (ciclos == 0) {
    altura = 1;
  } else {
  for (var i=1; i<=ciclos; i++) {
    if (i % 2 == 0) {
      altura += 1;
    } else {
      altura = altura*2;
    }
    }
    return altura
  }}

No CodePen o código funcionou bem em todos os testes, porém, ao rodar o código na plataforma surgiu o seguinte erro: Expected undefined to equal 1.
Alguém sabe o que pode ter ocorrido? Será que foi algum detalhe que deixei passar ou eu devo refazer o código de forma diferente?
Comment: Sua pergunta é sobre  uma ferramenta de testes de terceiros. Nem é sobre uma ferramenta de testes padronizada. A pergunta o uso dessa ferramenta de testes deveria ser feita pra quem fez a ferramenta ou para quem está a usando como método didático.
Answer: Vc esqueceu o return pro caso 0. Altere pra:
function alturaArvoreUtopica (ciclos) {
  var altura = 1;
  if (ciclos == 0) {
    altura = 1;
    return altura; // aqui
  } else {
    for (var i=1; i<=ciclos; i++) {
      if (i % 2 == 0) {
        altura += 1;
      } else {
        altura = altura*2;
      }
    }
    return altura;
  }
}

console.log(alturaArvoreUtopica(0))

Pelo que vc falou e pela mensagem, seu código passou provavelmente por um ciclo de testes com valores diferentes. Quando vc chama a função original com o valor 0 o retorno está vindo undefined. Deve ser só isso.
Repare que o último return está dentro do else.
Se fizer a função assim fica mais fácil de ler e entender:
function alturaArvoreUtopica (ciclos) {
  var altura = 1;
  if (ciclos == 0)
    altura = 1;
  else
    for (var i=1; i<=ciclos; i++) {
      if (i % 2 == 0)
        altura += 1;
      else
        altura = altura*2;
    }
  return altura;
}

E essa é pra vc estudar um pouco:
let alturaArvoreUtopica2 = (ciclos) => {
  let altura = 1;
  if (!ciclos)
    return 1;

  [...Array(++ciclos).keys()]
    .slice(1)
    .forEach((_, i)=>(i + 1)%2 ? altura *= 2 : altura++);
  return altura;
}

Comment: Deu certo! Realmente foi uma falta de atenção minha. Muito obrigado também pela dica na organização do código, como estou começando acabo não me atentando a isso e agora percebo como o meu código estava bem bagunçado hahaha
Comment: Que bom que deu certo... editei a resposta com um forma mais avançada pra incentivar a vc progredir um pouco em js :)
Comment: Muitas vezes a identação de código faz com que vc entenda errado o código. Por exemplo, na sua função original dá a entender que o último return está antes da saída da função quando está dentro do else. Uma coisa que ajuda bastante é usar uma IDE que tenha um formatador automático de código.  :)


Pandas: dropping all columns with nans, 0, and NA from DataFrame

Question: I have a DataFrame that looks like this:
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8],
                'B': [0, np.nan, np.nan, 0, 0, 0],
                'C': [0, 0, 0, 0, 0, 0.0],
                'D': [5, 5, 5, 5, 5.6, 6.8],
                'E': ['NA', 'NA', 'NA', 'NA', 'NA', 'NA'],})

How would I drop all the NA, Nans and 0 in the columns so I would get the following output?
df2 = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8],
                'D': [5, 5, 5, 5, 5.6, 6.8],})

So far I know .dropna() will get rid of all the nan also I tried df2=df[~(df==0).all(axis=1)] and it did not work.
Comment: Do you want to be left with just columns 'C' and 'D' (not 'A' and 'D' as is your example)?
Comment: @ajcr I want just A and D left since they have data that does not have a column with all 0, Nan or NA
Answer: You could try using df.isin() and all() to find an array of columns which don't contain only null values and then use this array to select the relevant columns of df:
>>> df[df.columns[(~df.isin([NaN, 'NA', 0])).all().values]]
     A    D
0  1.0  5.0
1  2.1  5.0
2  NaN  5.0
3  4.7  5.0
4  5.6  5.6
5  6.8  6.8

Or more concisely: df.loc[:, (~df.isin([NaN, 'NA', 0])).all()]
Comment: You forgot the np in front of NaN
Answer: >>> df
     A   B  C    D   E
0  1.0   0  0  5.0  NA
1  2.1 NaN  0  5.0  NA
2  NaN NaN  0  5.0  NA
3  4.7   0  0  5.0  NA
4  5.6   0  0  5.6  NA
5  6.8   0  0  6.8  NA
>>> f = df.replace([0,'NA'], np.nan).apply(lambda x: any(~x.isnull()))
>>> f
A     True
B    False
C    False
D     True
E    False
dtype: bool
>>> df.loc[:,f]
     A    D
0  1.0  5.0
1  2.1  5.0
2  NaN  5.0
3  4.7  5.0
4  5.6  5.6
5  6.8  6.8


Can someone define efficiency?

Question: There are lots of questions about efficiency in CrossValidated, but I am no a sophisticated statistician. All I want is a simple layman's definition of efficiency.
Thank you :)
Answer: Here is the money quote from Wikipedia:

Essentially, a more efficient estimator, experiment or test needs fewer samples than a less efficient one to achieve a given performance.

You can also look at the Wikipedia entry on "efficient estimators".

Can someone define efficiency?


Determine if Magento module is enabled

Question: What is the best way to determine if a particular module is enabled/active in Magento?  I've tried using class_exists to check if my code has been loaded and parsed by PHP but lately I've noticed its pretty unreliable (returns true even when I delete the module's .xml configuration).
Is there a core function I can call?
Answer: If you would like to use a build in function just use
Mage::helper('core')->isModuleEnabled(<module name>);

It is implemented in
Mage_Core_Helper_Abstract

Comment: actually you should mention that module name sould be equal to : **MyCompany_MyModule**
Comment: Just fyi, this method was introduced to magento in CE 184.108.40.206, for lower version compatibility use the ```getModuleConifg``` solution
Answer: Here's another option that is a more elegant way of finding out the status:
Mage::getConfig()->getModuleConfig('modulename')->is('active', 'true')

Comment: I really like this method, it's very simple yet elegant. Thanks!

Determine if Magento module is enabled


Agrupar por data e receber total de registros de cada data e montar outra matriz

Question: [
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },

]

Olá,
preciso pegar do array acima o total de registro de cada data e criar uma outra matriz de objetos contendo o próprio nome e total como valores de novas chaves por exemplo:
[{
        "a": "23-04",
        "b": 3
    }, {
        "a": "23-05",
        "b": 3
    },
    {
        "a": "23-06",
        "b": 5
    }
]

Pode ser com es6, map, reduce ou mesmo com lodash/undescore
Agradeço a quem puder mastigar isso pois to a 3 dias e não sai do jeito que preciso
Answer: Dois exemplos que parecem funcionar...

var origem = [
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
];

var result1 = Object.entries(origem.reduce((acc, o) => (acc[o.data] = (acc[o.data] || 0) + 1, acc), {}))
    .map(([a, b]) => ({ a, b }));

let counts = {};
origem.forEach(el => counts[el.data] = (counts[el.data] || 0) + 1);
var result2 = Object.entries(counts).map(([a, b]) => ({ a, b }));

console.log(result1);
console.log(result2);
Comment: Para vc tenho certeza que foi apenas alguns minutos no teclado para ajudar uma desconhecida, para mim, foi um alívio que já sofria a 3 dias. Seu código não só parece funcionar: ele é perfeito para meu propósito e caiu como uma luva inclusive resolvendo as chaves a e b com map....Meu muito obrigada a vc meu querido!!!


Como criar um aquivo.h?

Question: Para que serve um arquivo.h e que melhoria ele traz para o programa em C++?
Comment: Seria melhor esclarecer melhor o que você quer saber porque é do mesmo jeito que se faz qualquer outro arquivo.
Answer: Os arquivos com extensão .h ou .hpp como gostam alguns para diferenciar dos arquivos de cabeçalho do C, costumam ser usados para colocar código necessário para compilação de outras partes de uma aplicação.
Quando criamos uma aplicação, ou mesmo uma biblioteca, algumas informações são necessárias para compilar. Alguns exemplos são as classes, as estruturas, as constantes estáticas e a declaração das funções (os chamados protótipos). No caso das classes e estruturas estamos falando de diversos elementos, incluindo aí assinatura dos métodos.
Basicamente o que não é necessário para a compilação são os algoritmos, ou seja o código dentro doas funções ou métodos. Estes podem ser compilados para código binário e não são mais necessários para o processo de compilação. Pelo menos na maior parte dos casos.
Ainda existem os casos onde se deseja fazer o inline do código ou ele for gabaritado (template).
Este arquivo é uma forma de organizar o código e facilitar a inclusão deste código em outros arquivos.
Ao contrário do que alguns possam pensar, este arquivo tem código normal que bem poderia estar em um arquivo .cpp. É claro que se todas estas declarações citadas estiverem no arquivo .cpp perde-se flexibilidade. Fica complicado usar o seu conteúdo em outro lugar.
Um arquivo que inclua um .hpp após pré-processado passar ter o conteúdo do .hpp como sempre estivesse escrito nele. Ou seja, o arquivo é como se fosse copiado para o arquivo que vai ser compilado.
Então no arquivo .cpp você tem a definição dos algoritmos e no .hpp você tem a declaração. Note que isto é uma convenção universalmente adotada mas nada impede de fazer de um jeito diferente. Só não existe motivo para inventar outro jeito. Com ele você pode ter ganhos no tempo de compilação, além de organizar melhor o que estrutura de dados e o que é algoritmo.
Se você tiver um arquivo .cpp assim:
void teste();

void main() {
    teste();
}

void teste() {
    printf("teste");

Você ou só pode usar a função teste() neste arquivo ou então precisa incluir o código junto, o que pode complicar por existir o main(), além de gastar tempo com a compilação de algo que já deve estar compilado. Claro que é possível guardar (#ifdef) o trecho para não incluir o que não precisa, mas pode acabar complicado o compilação normal do arquivo e coloca coisa no arquivo que não são necessárias para ele.
Se separar assim no teste.hpp:
void teste();

E o main.cpp ficando assim:
void main() {
    teste();
}

void teste() {
    printf("teste");

Você pode usar a função teste() em qualquer outro lugar. Vamos imaginar que crie um novo arquivo .cpp assim:
#include "teste.hpp"
void funcao() {
    teste();
}

Isto funciona porque a declaração da função será inclusa no arquivo, mesmo que o código efetivo da função não seja. Após o pré-processamento este código ficará:
void teste();
void funcao() {
    teste();
}

Coloquei no GitHub para referência futura.
Answer: Amigo, o arquivo .h é um cabeçalho, um arquivo de configuração, lá você pode definir constantes, incluir bibliotecas, coisas que serão usadas no seu main (programa principal). Você cria um .h e inclui no seu programa principal.
Separando tais funcionalidades, você tem maior manutenibilidade em seu código fonte, por exemplo se quiser usar outra biblioteca é só inseri-la no .h e automaticamente seu programa a usará,  e também poderá usar o mesmo .h em outros programas.
Espero ter ajudado.

Como criar um aquivo.h?


Stopped $L^2$ - martingale is again $L^2$ integrable

Question: Given a $L^2$ martingale $X_t$, for a finite stopping time $T$, is it true that $X_T$ is again $L^2$ integrable?
If $X_t$ is additionally uniform integrable, then we can use Jensen-inequality:$$E[X_T^2]=E[E[X_\infty\mid F_T]^2]\leq E[X_\infty^2]$$ to obtain the $L^2$ integrability of $X_T$ provided $X_\infty$ is square integrable.
However, I don't know if the statement is still true without the assumption on uniform integrability and $X_\infty^2$ is integrable.
Answer: No, this is, in general, not true.
Let $(B_t)_{t \geq 0}$ be a one-dimensional Brownian motion, and let $X$ be a random variable which takes values in $(0,\infty)$ and which is independent from $(B_t)_{t \geq 0}$. Clearly, $(B_t)_{t \geq 0}$ is an $L^2(\mathcal{F}_t)$-martingale with respect to the filtration
$$\mathcal{F}_t := \sigma(X, B_s; s \leq t).$$
If we set
$$T(\omega) := \inf\{t \geq 0; |B_t(\omega)| \geq X(\omega)\},$$
then it is not difficult to see that $T$ is a finite $\mathcal{F}_t$-stopping time. Moreover, it follows from the continuity of the sample paths of Brownian motion that $|B_T| = X$ almost surely. In particular,
$$\mathbb{E}(B_T^2) = \mathbb{E}(X^2),$$
and therefore $B_T \in L^2$ if, and only if, $X \in L^2$.
Comment: Would you mind to give an example of such $X(\omega)$
Comment: @quallenjäger What do you mean by "such $X(\omega)$"? You can pick any random variable which is not square integrable, for instance a random variable with distribution $\mu(dx) = c 1_{(0,\infty)}(x) \frac{1}{x^2+1} \, dx$ where $c>0$ is chosen such that $\mu(\mathbb{R})=1$.
Comment: Thanks, I was looking for the distribution function, which is given by your comment. Everything is clear. Thanks
Comment: @quallenjäger You are welcome.
Answer: There is also Doob's example:  Let $F$ be any distribution on the real line. Choose the appropriate function $g$ so that $g(B_1)$ has distribution $F$, and then define $T:=\inf\{t>1: B_t=g(B_1)\}$. Clearly $T$ is a.s. finite by the recurrence of Brownian motion, and $B_T$ has distribution $F$. And this $T$ is a stopping time of the filtration of the given Brownian motion.


How to redirect to any url after login in redirect?

Question: I want to redirect my user to any url that he types in after logging in
for example; my user types in the browser, http://localhost:3000/login/tickets,
If he has not logged in I would need the program to load the login page, and after login, the program redirects to this page, I can do it with a single page but I wanted it to be dynamic, something like this.
    isAuthenticated()
      ? (
        <Component {...props} />
        ) : <Redirect to=`/login?next=${this.props.location.search}` />
      )}

soon this redirect would load the login page with the tag next
Answer: My solution was to do essentially what you describe. I made a HOC to wrap my route's component in if it requires that the user be logged in:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter, Redirect } from 'react-router-dom';

/**
 * Higher-order component (HOC) to wrap restricted pages
 */
export default function LoggedInOnly(BaseComponent) {
    class Restricted extends Component {
        state = {};
        static getDerivedStateFromProps(nextProps) {
            const { history, location } = nextProps;
            if (!nextProps.isLoggedIn) {
                history.replace({ pathname: '/signin', search: `dest=${encodeURIComponent(location.pathname)}` });
            }
            return null;
        }
        render() {
            const { location, staticContext } = this.props;

            if (this.props.isLoggedIn) return <BaseComponent {...this.props} />;

            const destinationURL = `/signin?dest=${encodeURIComponent(location.pathname)}`;
            if (staticContext) staticContext.url = destinationURL;

            return <Redirect to={destinationURL} />;
        }
    }

    const mapStateToProps = state => ({
        isLoggedIn: !!state.globalUserState.loggedInUserEmail,
    });

    return withRouter(connect(mapStateToProps)(Restricted));
}

I also set the url on the static context in my case so I can handle redirects appropriately in server side rendering. If you're not doing the same you can ignore that part.
For using it, though, I redirect after my SSR render function, like so:
if (context.url) {
    console.log(`Redirecting to URL ${context.url}`);
    return res.redirect(context.url);
}

A route using this would look like:
<Route path="/preferences" component={LoggedInOnly(SettingsView)} />

On my login page I grab the url parameters to see if there's a destination. If there is, I redirect there on login success.
I do this using query-string and the search component of the location:
const { destination } = queryString.parse(props.location.search);

The above assumes you're using withRouter to get the location info in the props.
On authentication success in the client I simply redirect to destination if it exists:
window.location.href = this.props.destination;

You could also use history.push or similar to accomplish the above.
In my case, as you can see, I'm using redux to track the logged in user state.
Answer: you need to update state by taking a variable and apply check  wether it has been changed or not, if yes then redirect to desired page ,if not revert back. Since you have not posted your whole code .You can refer to this video for wider and clear perspective :
https://www.youtube.com/watch?v=zSt5G3s3OJI
Comment: Basically the redirect will send the user to the login screen, but now I want that besides sending to the login screen send with the next mark so that dps login he will be redirected
Answer: You can accomplish what you need by doing some thing like this:
if(isAuthenticated)
  this.props.history.push('/login', {lastPage: this.props.location.match})

and after user gets logged in you cant redirect him to passed param lastPage!
Another way is to store lastPage in redux and access it after user get logged in.
Answer: I had the same problem, i made a HOC to solve it.
import React from "react";
import { connect } from "react-redux";
import Login from "../../Auth/Login";
import { withRouter } from "react-router-dom";
import qs from "querystring";

const signInPath = "/signin";
const signUpPath = "/signup";
const forgotPassPath = "/forgot";
const resetPassPath = "/resetpassword";
const returlUrlPath = "returnUrl";

const allowedPaths = pathname =>
  pathname === signInPath ||
  pathname === signUpPath ||
  pathname === forgotPassPath ||
  pathname === resetPassPath;

const homePath = "/";

export default Component => {
  class AuthComponent extends React.Component {
    componentDidMount() {
      this.checkAuthentication();
    }

    componentDidUpdate(nextProps) {
      if (
        nextProps.location.pathname !== this.props.location.pathname ||
        this.props.loggedIn !== nextProps.loggedIn
      ) {
        this.checkAuthentication();
      }
    }

    checkAuthentication() {
      const {
        loggedIn,
        history,
        location: { pathname, search }
      } = this.props;
      if (!loggedIn) {
        if (!allowedPaths(pathname)) {
          const returlUrl =
            pathname.length > 1
              ? `${returlUrlPath}=${pathname.replace("/", "")}`
              : undefined;
          history.replace({ pathname: signInPath, search: returlUrl });
        }
      } else if (search) {
        const parsedSearch = qs.parse(search.replace("?", ""));
        if (parsedSearch.returnUrl) {
          history.replace({ pathname: parsedSearch.returnUrl });
        } else {
          history.replace({ pathname: homePath });
        }
      } else if (
        history.location.pathname === signInPath ||
        history.location.pathname === signUpPath
      ) {
        history.replace({ pathname: homePath });
      }
    }

    shouldRedirectToLogin() {
      const {
        location: { pathname }
      } = this.props;
      return (
        !this.props.loggedIn &&
        pathname !== signUpPath &&
        pathname !== forgotPassPath &&
        pathname !== resetPassPath
      );
    }

    render() {
      return this.shouldRedirectToLogin() ? (
        <Login></Login>
      ) : (
        <Component {...this.props}></Component>
      );
    }
  }
  return withRouter(
    connect(({ user: { loggedIn } }) => {
      return {
        loggedIn
      };
    })(AuthComponent)
  );
};

Answer: Thanks for all, after a lot of research i get only:
const  params  = (this.props.children.props.computedMatch.url);
       return <Redirect to={`/login/?next=${params}`} />;


Boundedness of sequence $ \{||T_n || \} $ in Banach space.

Question: I take a new course Funcional analiysis, and I need to prove:
Let $E$ and $F$ Banach spaces and  $T_n (n = 1,2,...)$ linear continuous operators from $E$ in $F$. Suppose that  for all $x \in E$ and for all $f \in  F^*$ sequence of numbers $ \{f (T_n x) \}$ is bounded.
 Then  sequence  $ \{||T_n || \} $ is bounded.
 Where $ F^* $ denotes dual space.
Could anyone help me?
Comment: What have you done?
Answer: This is a straight application of Banach Steinhauss.
https://en.wikipedia.org/wiki/Uniform_boundedness_principle
Comment: Yes, that's it. Thank you.


Is there a predefined function for "(lambda **x: x)"

Question: I found (lambda **x: x) is very useful for defining a dict in a succinct way, e.g.
xxx = (lambda **x: x)(a=1, b=2, c=3)

Is there any pre-defined python function does that?
Comment: How about `dict`?
Answer: The dict function/constructor can be used in the same manner.
>>> (lambda **x: x)(a=1, b=2, c=3) == dict(a=1, b=2, c=3)
True

See help(dict) for more ways to instantiate dicts. You are not limited to just defining them with {'a': 1, 'b': 2, 'c': 3}.
Answer: Try the {} literal dictionary syntax. It is quite succinct. See 5.5. Dictionaries in the Data Structures tutorial.
>>> xxx = {'a': 1, 'b': 2, 'c': 3}
>>> xxx
{'a': 1, 'b': 2, 'c': 3}


How are the coefficients computed in multivariable logistic regression in R statistics?

Question: I'm going crazy, because I can't find a simple description how the coefficients are calculated in R statistics in the multivariable logistic regression (and I'm not a mathematician).
Are they standardised? So i.e. when I have x ~ y1 + y2 and the coefficient for y1 = 0.2, is this the coefficient in the model when the parameter y2 is 0, the mean of y2 or somehow all the parameters of y2?
Sorry, I'm stuck on this simple question ...
p.s.: I also have an interaction y1:y2 if this changes anything ...
Answer: From ?glm you can learn that

The default method "glm.fit" uses iteratively reweighted least squares
  (IWLS)

But what you really seem to be asking is "are the parameters standardised?". The answer is no. The basic GLM model can be defined with a linear combination
$$ \eta = \beta_0 + \beta_1 X_1 + \beta_2 X_2 $$
that is passed through the link function $g$:
$$ g(E(Y)) = \eta $$
so to obtain fitted values you multiply $X_1$ by $\beta_1$ and $X_2$ by $\beta_2$, sum them up and add $\beta_0$, output of this operation is passed through link function (e.g. logit). You can find some general introduction to logistic regression in here (it focuses on Bayesian estimation but also describes the general model), and about link functions here and here.
There are also $t$ (in lm) or $z$ (in glm) values that are $\beta_1/\mathrm{SE}(\beta_1)$ and $\beta_2/\mathrm{SE}(\beta_2)$ respectively, those values are sometimes called the standardized parameters.
Comment: Okay, I couldn't really imagine it how it works in the formula, but when it's not standardized t makes more sence to me... So the coefficient of y1 is also not the coefficient for the mean of y2, so a "general" coefficient for all the values of y2. Thank you!
Comment: A minor correction: standardization (with all of its pitfalls) involves standard deviations, not standard errors.  Consistent with what's above, if one were to do standardization (not recommended) it is needed only on the right hand side for logistic regression, because the left hand side is unitless.
Comment: @FrankHarrell you're right, this paragraph was taken out of context and misleading.
Comment: @Marry if this answers your question you can "accept" the answer (the "v" sign), see http://stats.stackexchange.com/tour for learning more about how the site works.


How to use display tkinter GUIs in Flask or is there a way turning it into html

Question: I made this Tkinter GUI and i recently started learning flask.i wanted to add tkinter to my flask website do i have to somehow convert it into HTML?
Comment: You cannot use a desktop GUI application inside Flask.  You need to convert it using HTML/CSS/JavaScript.
Answer: Tkinter is designed for desktop UI, and it would require a lot of work to rewrite the drawing part of tkinter to render HTML, so I can say that it's just impossible.
I'd suggest you looking into the templates rendering of Flask https://flask.palletsprojects.com/en/1.1.x/quickstart/#rendering-templates
That said, you'd need to do describe your UI in the HTML file and make your Flask HTTP endpoint render this file.


How can I get maximum value from Firebase in my React App

Question: I want to get data having max value. I have an auction app where people can bid so I want to find the highest value to award that product to max value. What are the ways for it?
Answer: In your database's rules make the list of bids be indexed on the price. Something like:
"bids": {
      ".indexOn": "price"
}

Then in your code you would use a query to only fetch 1 entry from an item's bids:
ref.orderByChild("bids").limitToFirst(1).on("child_added", function(snapshot) {

Which should give you the highest bid, if it gives you the lowest then just switch limitToFirst to limitToLast.


For a given $r$, finding $p,q$ such that $p^{\frac{q-1}{r}}=1\pmod q$

Question: The following is a part of a problem from Marcus's Number Fields, which has been discussed here and here:
a) Show that there exist primes $p,q$ such that $p$ splits into $r$ distinct primes in the $q-$th cyclotomic field $K.$
We know that number of prime factors in the splitting of $p$ in $\mathbb{\zeta_q}=r=\frac{q-1}{f}$,where $f$ is the order of $p$ modulo $q$(here we are assuming $p\ne q$). Thus we have to find two pairs of prime numbers $(p,q)$ such that order of $p$ modulo $q$ is $\frac{q-1}{r}$. But this looks hard to do, so I was wondering if it is the correct way to approach. If not, a hint towards the correct direction will be appreciated.
There is an answer here to a similar question, which is not satisfying to me.
Comment: I think your reduction to the question "Find $p,q$ such that $p$ has order $\frac{q-1}{r}$ mod $q$" is a step towards the right answer. Indeed, now you just need to argue that there exists some $q$ such that $r\mid q-1$, and use that for any divisor of $q-1$, there exists an element mod $q$ with that order. Then argue why a prime must exist in this residue class.
Comment: One way to do both of these arguments is to use Dirichlets theorem on arithmetic progressions.
Comment: There's a difference between "find" and "prove such $(p,q)$ exist."
Comment: What dou you mean by $\zeta_q=r=\frac{q-1}f?$ Don't abuse the equals sign this way.
Answer: Comment: Does this idea help?
$$p^{\frac {q-1}r}=kq+1$$
$$[(p-1)+1]^{q-1}=(kq+1)^r$$
$$m(p-1)(q-1)=n(r)(kq)$$
$(q, q-1)=1$
1)Suppose $(m, n, p-1)=1$, then we must have:
$\begin{cases}q|p-1\\ r|q-1\end{cases}$
2)Suppose $(m,n, q-1)=1$, then we must have:
$\begin{cases}r|p-1\\ q|q-1\end{cases}$
These can be the conditions for p and q for a give r.


Get type of product of two different templates

Question: Consider the following struct:
template<typename R, unsigned short nCols, unsigned short nRows>
struct Matrix{
  std::array<std::array<R, nRows>, nCols> data;
  Matrix<R, nCols, nRows>(){
  }
}

Now I want to implement multiplication function, but that might change the type. For example, I could have a matrix of integers and multiply it with a float. Then the new matrix would of course be of the type float. How would I implement this? This doesn't work:
template<typename S>
Matrix<R*S, nRows, nCols> mul(const S& s){
  Matrix<R*S, nRows, nCols> result;
  for( unsigned short i = 0; i < nCols; ++i ){
    for( unsigned short j = 0; j < nRows; ++j ){
      result = data[i][j] * s;
    }
  }
  return result;
}

MWE:
template<typename R, unsigned short nCols, unsigned short nRows>
struct Matrix{
  std::array<std::array<R, nRows>, nCols> data;
  Matrix<R, nCols, nRows>(){
  }

  template<typename S>
  Matrix<R*S, nRows, nCols> mul(const S& s){
    Matrix<R*S, nRows, nCols> result;
    for( unsigned short i = 0; i < nCols; ++i ){
      for( unsigned short j = 0; j < nRows; ++j ){
        result = data[i][j] * s;
      }
    }
    return result;
  }
}

int main(){
    Matrix A<int, 2, 2> A;
    A.data[0][0] = 1;
    A.data[0][1] = 2;
    A.data[1][0] = 3;
    A.data[1][1] = 4;
    A.mul(3.141f);
    return 1;
}

Answer: You need to use decltype.
One possible option is:
decltype(std::declval<R>() * std::declval<S>())

For brevity, std::declval<R>() can be replaced with data[0][0].
The second operand can also be replaced with s.data[0][0] if you use trailing return type: auto mul(const S& s) -> decltype(...).

Alternatively, since R and S are probably default-constructible, you can get away with
decltype(R{} * S{})


How should I write this passage to make it the most readable?

Question: Been writing something and was wondering how I should notate these measures to ensure readability.
These three ideas are floating around in my head but if anyone else has input please send it my way.
Comment: Ledger lines are usually not a problem if one of the notes is on the staff, as long as the intervals are not too big. For example, in the first measure I can tell at a glance that the interval is a fifth, so I only need to look at the upper note to know what to play. I don't need to count ledger lines.
Comment: I need to ask: how did you come up with the first one?
Answer: Certainly not the first.  The second is unobjectionable.  But why not the third?  It's the standard notation, and is just fine.
Comment: Fair point. I suppose there really aren't that many ledger lines now that I think about it.
Comment: @ConnorSannipoli No worse than the second option.
Answer: I'd go with the second or the third, depending on the clef that you need before and after this passage.
The first one feels more uncomfortable that the others.
Answer: I'd guess you're trying to improve readability by reducing the use of ledger lines? below or above? The thing is, the piano is an instrument which is notable for it's range (on paper, a wider range of pitches than a standard orchestra). So pianists have to handle these a lot, and most will be used to reading off either end of the score (depending on their level of ability).
I'd usually consider using 8va marks or changing clef if...

The entire passage is outside of the clef.
It's a repetition of a previous passage, moved up or down by an octave (I.E. so the score looks the same with the octave shift).
You've having to space the staves further apart to fit the stray notes in.
The pianist needs to literally sit in a different place to play the piece.

These are just guidelines, anyway. There's a judgement call to be made here.

Also worth considering, if your player is uncomfortable with this, you could try inverting the two notes in the right hand. With the repeating F at the bottom and the moving line played above it. (This would have the dual effect of making the moving notes act as the main melody. Which is probably better if it's a solo piano piece, but might steal attention if there's also a melodic instrument playing).
Comment: I don't believe I've ever seen a 8va above a bass clef, or an 8vb below a treble.  At least not in piano or other keyboard music, which is what I have the most experience with.  Just switch clefs or use ledger lines.
Comment: @DarrelHoffman I've seen it for instruments which typically use the same clef but can go further.


replace multiple strings in one line with sed

Question: I have a list of packagenames and want to delete some of those with sed
echo "package1 package2 package24 package44 package66 package12345" > benoetigte_pakete.list

How can I delete some of those that are in another list?
dellist="package24|package66"

I tried
cat benoetigte_pakete.list | sed "s/(package24|package66)//"

but that doesn't work.
Answer: In sed regexps you have to escape (, |, and ).
You also need to use the g modifier so it replaces all matches on the line, not just the first match.
dellist="package24|package66"
# escape the pipes
dellist=${dellist//|/\\|}
sed "s/\b\($dellist\)\b//g" benoietigte_packete.list

I've added the \b so it only matches whole words.
Depending on the version of sed you have, you can also use the -E or -r options to use extended regular expressions.
Comment: Why not just use `-r` or `-E`? `|` doesn't need to be escaped in extended regex syntax.
Comment: You need to add some parentheses and anchors or that would change `package246` to `6`, etc.
Comment: Is there a way to add those `\\` automatically before the pipe?
Comment: You can use string substitution to add the backslashes, see my update
Comment: I used `-r` without pipe escapation now (debian wheezy). Thanks a lot!
Comment: I guess that would be `dellist=${dellist//|/\\b\\|}`


How to reset progress bar to zero after 'n' number of iterations? WPF

Question: I added a progress bar to a WPF application that counts how many times a gesture is performed. But I want the progress bar to reset to zero after 20 iterations.
I tried to achieve this in the below code but when the bar gets to 20 it keeps counting and progress shows full. My question is how do I fix my loop to allow for this?
void matcher_GestureMatch(Gesture gesture)
{
    scoreProgBar.Maximum = 20;
    lblGestureMatch.Content = gesture.Name;
    if(scoreCntr == 20)
    {
        scoreCntr.Equals(0);
    }
    scoreCntr++;
    scoreProgBar.Value = scoreCntr;

    lblScoreCntr.Content = scoreCntr;

}

Answer: This line:
scoreCntr.Equals(0);

Doesn't do what you probably think it does. It will compare the current object instance (scoreCntr) to the other object passed as the parameter (0).
You probably want something like this:
if(scoreCntr == 20)
{
    scoreCntr = 0;
}

Comment: Oh yeah it compares if the two `objects` are equal not assigning a value. Should have caught that one.
Comment: We've all been there before ;) If this answers your question, please accept it as the answer so that it may help others.
Answer: scoreCntr = 0;

not
scoreCntr.Equals(0);

Answer: May be something like this,
void matcher_GestureMatch(Gesture gesture)
{
    scoreProgBar.Maximum = 20;
    lblGestureMatch.Content = gesture.Name;
    if(scoreCntr == 20)
    {
        scoreCntr = 0;
    }
    else
    {
        scoreCntr++;
    }

    scoreProgBar.Value = scoreCntr;
    lblScoreCntr.Content = scoreCntr;

}

Answer: **U can try this :
        }**` if (progressBar1.Value == 100)
        {
            progressBar1.Value = 0;
        }**`


Laravel 7 eloquent whereIn and where not working

Question: I have a record in my database that looks like this:
id | roles
----------
1  | ["test"]

I do this eloquent query:
UserModel::withTrashed()
      ->whereIn('roles', ['test'])
      ->where('id', 1)
      ->exists();

This returns false what am I doing wrong here?
Comment: Your attribute `roles` is JSON, then you can't use the SQL `IN` (wrapped by `whereIn`).
Comment: I agree with @Shizzen83, I don't think you should query db by exact JSON either.
Comment: Which Laravel version do you use?
Comment: @Shizzen83 laravel 7.x
Comment: Do you mind replacing your JSON attribute by an integer? (only in database) If no, I have a solution
Answer: Apparently this exists:
->whereJsonContains('roles', ['test'])

Then it works great.


Maximum training error for a decision tree

Question: For any dataset $D$, with the label space containing m labels. Using decision tree, can we calculate the maximum training error on that?
Yes I have to admit, it's a homework question and I have completely no clues on that. Could any one gives me some hint on that? And what is label, does it mean edges of the tree?
Comment: Hi Xupeng, welcome to Cross-validated. It is a good question. However, if it is a homework question, please add the tag "homework".
Comment: Also you can add latex notations if you use the \$ symbol. E.g. for any dataset \$D\$..
Answer: A decision tree is a classification model. You can train a decision tree on a training set $D$ in order to predict the labels of records in a test set. $m$ is the possible number of labels. E.g. $m = 2$ you have a binary class problem, for example classifying patients who might either have or not have a disease; $m > 2$ you have multi-class problem, for example if you had to classify news in "politics", "sport", and "culture".
Think about how decision trees work. I wrote an explanation here. The hint I can give to you is that in your homework attributes are not relevant to the class. Also, think about the way decision trees classify records on leaf nodes.
Comment: So does it mean the dataset that may meet the maximum training error here has to be the worst one (one with the highest entropy) ?
Comment: Yes, I think you have to think about the worst dataset where your decision tree is just a root node.
Comment: Do you mean considering one root node situation is good enough? I am confused because of I know nothing about the information of node, which centers in the decision tree theory.
Comment: I mean, what is the worst case for a decision tree? that attributes are totally unpredictive to the class. In this case you wouldn't even grow a decision tree. You would just have a single root node, which can also be seen as a single leaf node. Now you have just to think about how you classify records on a leaf node: majority voting.
Comment: Does it mean in the worst case we can't even select a proper feature to grow the tree? So what should I do now? Randomly allocate m classifications? What does the majority means here?
Comment: Yes, in the worst case you cannot even grow a tree. You don't randomly label the records, you label them with just single label, the most frequent label: this is majority class.
Comment: I think it would be (1-1/k)?
Comment: What is $k$? the solution here is $1 - \frac{\text{ number of records from majority class}}{\text{total number of records}}$


How should I migrate a zfs pool to Windows Storage Spaces?

Question: I have a single hard drive that I want to migrate to Windows Storage Spaces ReFS file system for better Windows compatibility. Obviously copying all the data to another disk and back is a last resort; so, is there a better way?
Answer: The only way to migrate from a given filesystem to a different one/different storage, regardless of the filesystem type is to physically copy all the files. ZFS is no exception from this rule.
There's no conversion tools.


Convert time in Ruby (Sinatra Framework)

Question: I am really new to ruby.
Could i ask you to convert time in ruby, from this:
created_at = 2021-06-25T00:00:00.000Z

to unix time like this
1632928828

what i've tried to convert to unix time:
Time.parse(created_at).in_time_zone('Asia/Jakarta').beginning_of_day.to_i

but it returns nil.
Comment: Your code results in `1624554000` (as long as you have required `active_support/all`). Please describe your issue in more detail and show an example which allows us to actually reproduce your problem.
Comment: sorry my bad, turns out `created_at` need to convert to string by added `to_s`, so it will be `created_at.to_s`
Comment: Seems like `created_at` is already a time-like object. Did you try `created_at.in_time_zone('Asia/Jakarta').beginning_of_day.to_i`?
Answer: turns out created_at need to convert to string by added to_s, so it will be created_at.to_s


Why does my beta regression look linear when plotted?

Question: Im using a beta regression to model since my dependent variable is confined between [0,1]. However, when I plot the relationship between x and y via my beta regression, the effect looks linear. When doing a linear scatterplot, the lines are almost identical. This is unlike any other beta regressions that I've seen so far, and I wonder what I might be doing wrong.
My code looks like this:
library(betareg)

vb=betareg(dep ~ pctDFNB, data=v, link="loglog")
vb2=betareg(dep ~ pctDFNB, data=v, link="logit")

# PLOT
ggplot(v, aes(x = pctDFNB, y = dep)) +
  geom_point(size = 4, aes(fill = party), shape = 21) +
  scale_fill_grey() +
  geom_line(aes(y = predict(vb, v),
                colour = "log-log", linetype = "log-log")) +
  geom_line(aes(y = predict(vb2, v),
                colour = "logit", linetype = "logit")) +
  scale_colour_manual("", values = c("red", "blue")) +
  scale_linetype_manual("", values = c("solid", "dashed")) +
  theme_bw()

And the plot I receive looks like this:

For information, my beta distribution looks like this:
EDIT: Thanks for your answers, they are truly insightful and appreciated!
Answer: The first thing I notice is that the relationship between the input and output is approximately linear, so from an empirical point of view I'd expect the fitted model to replicate this relationship.
If you look at the range of your dependent variable, the range is around $0.4$ to $0.6$. The non-linearity in beta regression  typically occurs  is most evident when the outcome is closer to $0$ or $1$. In fact, if we plot the link functions you used, we can see that they are very close to linear for $0.4<\text{dependent}<0.6$, thus the non-linearity induced by the link function is very minor for your model. Although the relationship is approximately linear, I think that a beta regression is still an appropriate model since your dependent appears to be a proportion.
Answer: When the outcomes are very close to 0.5, the model on the response scale is nearly linear. The plot below demonstrates this.  In black, I have plotted the inverse of the logit function (which is what your model would look like were you to extrapolate).  in red is a linear approximation centred around 0.
See how the red and black line are on top of one another approximately between y=0.4 and y=0.6?  The logit function is very nearly linear in that neighbourhood, which is where your data lay.  Try extrapolating the predictions out farther.  You will see the model bottom out at 0 and top out at 1 when your predictor is large enough.
Answer: As the other answers have already noted, your relationship is almost linear, and this is picked up by the beta regression. (More precisely, by the logit link. This is where any "curved" shape would come from, not from the shape of the beta distribution as such. You may be misunderstanding the roles of the logit link function and the distributional assumptions.)
Compare a beta regression model for the built-in ReadingSkills dataset:

We see how the relationship between iq and accuracy is almost linear, as in your data, for participants with dyslexia - but it is noticeably curved for participants without dyslexia.
R code:
library(betareg)
data(ReadingSkills)
iq_predict <- with(ReadingSkills,seq(min(iq),max(iq),by=.01))   # for plotting predictions

with(ReadingSkills,plot(iq,accuracy,pch=19,las=1))
with(subset(ReadingSkills,dyslexia=="yes"),points(iq,accuracy,pch=19,col="red"))
with(subset(ReadingSkills,dyslexia=="no"),points(iq,accuracy,pch=19,col="blue"))
model <- betareg(accuracy~iq*dyslexia,data=ReadingSkills,link="logit")
lines(iq_predict,predict(model,data.frame(iq=iq_predict,dyslexia="no")),col="blue")
lines(iq_predict,predict(model,data.frame(iq=iq_predict,dyslexia="yes")),col="red")
legend("bottomright",lwd=1,pch=19,col=c("blue","red"),legend=c("No dyslexia","dyslexia"))


Finding first integrals of $\frac{dx}{(z-y)^2}=\frac{dy}{z}=\frac{dz}{y}$

Question: I have $y^2-z^2=C_1$ which follows easly from $\frac{dy}{z}=\frac{dz}{y}.$ Second should be $x+y(y-z)=C_2,$ but I don't know how to derive it.
Answer: Hint :
$$\frac{\,dx}{(z-y)^2}=\frac{\,d(y-z)}{z-y}$$
$$\implies \,dx+(y-z)\,d(y-z)=0.$$
Comment: @Fallen Apart : This is a general property of equal frations : $$\frac{A}{B}=\frac{C}{D}=\frac{A-C}{B-D}$$ Expand it to prove it.
Comment: $\frac{dy}{z}-\frac{dz}{y}$ is NOT equal to $\frac{dy-dz}{z-y}$, but : $$\frac{dy}{z}=\frac{dz}{y}=\frac{dy-dz}{z-y}$$ This is true only if $\frac{dy}{z}=\frac{dz}{y}$
Comment: Remember, more generally : $$\frac{A}{B}=\frac{C}{D}=\frac{c_1A+c_2C}{c_1B+c_2D}$$, with $c_1$ and $c_2$ constants.
Comment: I believe I do not understand fundamental ideas. How did you get
$$\frac{\,dx}{(z-y)^2}=\frac{\,d(y-z)}{z-y}?$$
Comment: Keeping 1st ratio fixed and Subtracting 2nd & 3rd ratios..Read your text book first carefully...
Comment: Why am I allowed to do so? (it make no sense to me) Can you give me reference to some book  or webside with good explenation (I can't find any)? The problem is that I have some fundamental problems with solving this kind of exercise. I do understand method of characteristics, but when comes to doing exercise I stuck.
Comment: Btw. did you just done the following: $$\frac{\,dy}{z}-\frac{\,dz}{y}=\frac{\,d(y-z)}{z-y}?$$
Comment: @JJacquelin So you says
$$\frac{A}{B}=\frac{C}{D}\implies\frac{A}{B}=\frac{C}{D}=\frac{A-C}{B-D}$$
I would never figure it out. You are my hero!


Definir variável como null em uma Query no php

Question: Tenho a seguinte QUERY no meu sistema:
<code>$Query = "SELECT * FROM Monit WHERE
    ($Modulo IS NULL OR Modulo = '$Modulo') AND
    ($Usuario IS NULL OR Usuario = '$Usuario') AND
    ($Data IS NULL OR Data_reg = '$Data')
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);

    while($line = mysqli_fetch_array($execute)){
        echo $line['Modulo'];
    }
</code>
Para fazer os teste se ela funcionaria quando entrasse algum valor NULL defini as variáveis com estes valores:
<code>$Modulo = "NULL";
$Usuario = "NULL";
$Data = "NULL";
</code>
E funciona perfeitamente desta forma.
Porém, se defino as entradas dessa forma:
<code>$Modulo = "NULL";
$Usuario = "roberto";
$Data = "NULL";
</code>
Não funciona pq fica faltando as aspas simples ' '
Se coloco dessa forma:
<code>$Modulo = "NULL";
$Usuario = "'roberto'";
$Data = "NULL";
</code>
A query não funciona, e se adiciono as aspas simples direto na query:
<code>$Query = "SELECT * FROM Monit WHERE
    ($Modulo IS NULL OR Modulo = '$Modulo') AND
    ('$Usuario' IS NULL OR Usuario = '$Usuario') AND
    ($Data IS NULL OR Data_reg = '$Data')
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);

    while($line = mysqli_fetch_array($execute)){
        echo $line['Modulo'];
    }
</code>
Funcionará, porém, se retornar o valor NULL nas variáveis não retornará nada;
Não sei se ficou muito claro, mas basicamente não sei como definir as variaveis que estarão na query como nulas.
Answer: Não sei se é uma solução muito elegante mas você pode validar se a variável está preenchida antes de montar a query e manter as aspas simples:
<code>if($Modulo == NULL) $Modulo = '';
if($Usuario == NULL) $Usuario = '';
if($Data == NULL) $Data = '';

$Query = "SELECT * FROM Monit WHERE
    ($Modulo = '' OR Modulo = '$Modulo') AND
    ($Usuario = '' OR Usuario = '$Usuario') AND
    ($Data = '' OR Data_reg = '$Data')
    ORDER BY Data_monit DESC LIMIT 0,10";
    $execute = mysqli_query($conexao, $Query);
</code>
Comment: Valeu @rLinhares, só tive que colocar as aspas nas variáveis mas a logica funcionou :D
Comment: Então eu mantenho as aspas simples nas variáveis  antes do IS NULL?
Comment: Foi mal, @Shinchila_Matadora, removi; veja se resolveu


unable to load images (error 404) with domain/subdirectory for laravel on nginx 1.13

Question: i am having trouble to load images that saved in default images directory laravel (laravelroot/public/images). i've set the laravel on http://domain/laravelroot. here is the configurations :
server {
    listen 80;
    server_name localhost;
    index index.php;
    root /usr/share/nginx/html;

location / {
         try_files   $uri $uri/ /index.php?$query_string;
    }

location ~ /.well-known {
            allow all;
    }

location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
    access_log        off;
    log_not_found     off;
    expires           360d;
    }

location ^~ /laravelroot {
            alias /usr/share/nginx/html/laravelroot/public;
            try_files $uri $uri/ @laravelroot;

            location ~ \.php {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.1-fpm.sock;
                fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/laravelroot/public/index.php;
                }
        }

    location @laravelroot {
        rewrite /laravelroot/(.*)$ /laravelroot/index.php?/$1 last;
    }

on element inspect , its domain refer to http://localhost/imagefile. when i open the images on the new tab, and change the url to http://localhost/laravelroot/images/imagefile.png its loaded.
I've tried to put images location in laravelroot directives.
location ^~ /laravelroot {
                alias /usr/share/nginx/html/laravelroot/public;
                try_files $uri $uri/ @laravelroot;

            location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
                  alias /usr/share/nginx/html/laravelroot/public/images;
                  access_log        off;
                  log_not_found     off;
                  expires           360d;
                  }

            location ~ \.php {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.1-fpm.sock;
                fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/laravelroot/public/index.php;
                }
        }

and didnt work. spent few hours but no clue today
Answer: i found the problem. the laravel itself need to set the base path for images.
i put all assets in the public folder, then use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('images/picture.png') }}
Which generates the follow HTML code:
http://localhost/images/picture.png
seems a bit too far from serverfault. but thanks anyway.


what is the difference if i return "YES" or "NO" when i call textFieldShouldReturn

Question: This is the text field delegate method  but i have doubt about return type
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
  [textField resignFirstResponder];

   return NO;
}

and this is the same method with different return type
-(BOOL)textFieldShouldReturn:(UITextField *)textField
 {
   [textField resignFirstResponder];

   return YES;
 }

by both we can hide key board in i phone . but what is the meaning of return type "YES" or "NO". I am not seeing any difference.
Comment: @ott-- corrected that `bug` !
Answer: In addition to the other answers here (which essentially confirm there's no major difference, no auto-resigning of the first responder by returning YES, etc.), I've discovered a strange occurrence completely dependent on the return value, specifically for a UITextField with autocorrection.
Assume the following scenario:

You have a UITextField with autocorrection enabled
You've implemented the delegate method something like this (where the text field gets resigned):

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.myAutocorrectingTextField) {
        [self.myAutocorrectingTextField resignFirstResponder];
    }
    return YES;
}

You run the app, type "Cable" into the text field, then press the return key, resigning it as first responder.

The outcome when returning YES:

The text field's text will have been changed from "Cable" to "Cables"!

I have tested a handful of other words that respond similarly:

"Stuff" changed to "Stuffs"
"Ten" to "Tens"
And, one time "Car" changed to "Carl", another time "Car" changed to "Carp"

The outcome when returning NO:
Normal. The text field's text will not have been changed.
In Summary...
When returning YES, the text field may autocorrect already-correct words. It does not, however, present one of those "autocorrect text bubbles", because these are legitimate words.
When returning NO, the text field will not autocorrect already-correct words.
Note:
In both cases, incorrectly-spelled words will always be corrected. For example:

If you were to type "Wev", an "autocorrection text bubble" should appear with the text "Web". If you hit the Return key, regardless of the delegate's return value, the text will be replaced with the correction.
Answer: One difference that I see based on personal experience is that if you return YES, auto correction and auto capitalization are triggered, if you return NO, they are not. There might be other things done, but that's all I could notice so far.
That's what they mean by "default behavior".
Answer: The most important difference I've found is that if the text field emits the control event UIControlEventEditingDidEndOnExit, this will cause the text field to resign first responder unless textFieldShouldReturn is implemented to return NO.
Answer: The textFieldShouldReturn is a place where you can handle the Return button on the keyboard.
textFieldShouldReturn asks the delegate if the text field should process the pressing of the return button.
If you implement your own code to process the return button you should return NO, or return YES for it to be handled in the default way.
The IOS Docs state:
The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped.
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html
Comment: You've basically just posted the contents of Apple's reference. There's no new information or insight here.
Comment: @CraigMellon He's obviously asking what the default behavior is.
Comment: I've answered his question.  He asked what the difference is, and the difference is if you return YES it will be handled in the default way, if you return NO it wont be handled the default way and you implement custom behavior.  How can you down vote me for giving him the information.  There isn't much more to it.
Comment: northernman and  Adlai Holler  are right,  Craig Mellon has added nothing to this conversation and has not given a good or correct answer here.

Fabien Warniez's answer is so much better, so is beebcon's. Can someone change the correct answer to be one of those?
Comment: this post was from 2012 and although I do agree beebcon's answer is much better it was added over a year after.  Have people not got anything better to do than go through all the old questions and nit pick about them.  I've been using and posting on stack overflow for nearly 10 years, have 5 times more rep than you and you comment stuff like that. Why not spend your time better by answering some questions???


Dynamic Web fields

Question: What I'm trying to do is I have a User profile page that I got with basic fields etc, But now I want to add 2 additional field types and I'm not doing to well with them.
Basically the fields are the same, I have a dynamic selection with list 2 depending on list 2 selection, but I need to be able to have a button for adding more of these fields, and likewise if user edits his profile it needs to be able to remove a specific one.
The 2nd is just a free text field but also needs to be able to add more and then remove specific. I'm not 100% sure how I'll store these in the database as well. I'm using MySQL for this all.
Comment: please share relevant code
Answer: Update:
Well I figured it out using a ajax method ^_^
sorry I didn't include the original code I had 50 things on my mind.
Basic code:
mysql Data pull:
$getCountries = "Select * from countries";
$CountriesResult = mysqli_query($con, $getCountries);

PHP Code:

Location:
    <select id="country" class="form-control" required name="country" onchange="getprov(this.value);" >
        <option value="">--Select country--</option>
            <?php
                while($country_dataRow = mysqli_fetch_array($CountriesResult)){
            ?>
            <option value="<?php echo $country_dataRow['Country_ID']; ?>"><?php echo $country_dataRow['name']; ?></option>;
            <?php } ?>
    </select>

Then Java Scripting
function getprov(val){
$("#province-data").html("");
    setTimeout(function(){
        $.ajax({
        type:   "POST",
        url:    "ajax_call.php",
        data:   "Country_ID="+val,
        success:    function(data){
                        $("#province-data").html(data);
                    }
        })
    }, 500);
};

lastly the Ajax_call.php
$getProvince = "Select * from province where Country_ID='$country_id' order by Province asc";
$ProvinceResult = mysqli_query($con, $getProvince);

<select id="province" class="form-control" required name="province" onchange="getcity(this.value);">
    <option value="">--Select Province--</option>
    <?php while($province_dataRow = mysqli_fetch_array($ProvinceResult)){ ?>
        <option value="<?php echo $province_dataRow['Province_ID']; ?>"><?php echo $province_dataRow['Province']; ?></option>
    <?php } ?>
</select>

I'm still working on the adding multiple entries on the system.

Dynamic Web fields


unable to get banner to scroll down

Question: My Banner will not move down as the user scrolls down, and my button in the upper left of my image will not remove my image.
My banner will move down while the user scrolls down, but that is without the button in the upper left corner.

document.getElementById("click").addEventListener("click", closeImage, false);

function closeImage() {
  var d = document.getElementById("wall");
  var d_nest = document.getElementById("image");
  var taway = d.removeChild(d_nest);
}
.container {
    position: relative;
    width: 50%;

    }
    .container img {
     width: 100%;
     height: auto;
     }
    .container .btn {
     position: absolute;
       top: 5%;
       left: 85%;
    .sticky {
    position: fixed;
      position: sticky;
      top: 0;
      width: 100%;
   }

  <button class="btn" id="click">Button</button>

Some text

Stuck in a rut, main goal is to figure out how my banner can scroll down with my button in the image, and to figure out how to exit the banner once the button is clicked.
Comment: Hi, could you please also post the relevant css and javascript and explain specifically what the problem is with them?
Comment: Are you using display: sticky?
If so you need to define either a top, left, right, or bottom position
Comment: here is css code,, banner will not move down when i move the scroll bar
Comment: .container {
    position: relative;
    width: 50%;

    }
    .container img {
     width: 100%;
     height: auto;
     }
    .container .btn {
     position: absolute;
       top: 5%;
       left: 85%;
    .sticky {
    position: fixed;
      position: sticky;
      top: 0;
      width: 100%;
   }
Comment: I am using .sticky  ..  my image is able to move down with the scroll bar, but when I add a button in the upper left, my image will not move
Comment: do not call that cariable throw:-)
Comment: The full html and CSS are required mate, please post them
Answer: You cannot name a variable throw, you will get the exception "Uncaught SyntaxError: Unexpected token throw". Throw is a reserved key word for throwing exceptions.

var throw = '';

unable to get banner to scroll down


mergBanner won't allow save as standalone in Livecode 8

Question: I had the mergBanner extension working fine until I upgraded to Livecode 8. Now it won't let me save my app as a standalone unless I delete the copy file and associated code.
Do I need to download mergbanner2 or is it likely to be something else? Thanks
Answer: LiveCode externals are compiled against multiple iOS SDKs and the LiveCode standalone builder will pick the right binary to use depending on which iOS SDK you are building against. mergBanner 1 has not been compiled against the full range of SDKs that available in LiveCode 8 so yes in order to use mergBanner with newer versions of Xcode & LiveCode you will need to upgrade to the new version.


serial port wieird behavour on ubuntu

Question: So I have a .net application that I intend to release to (windows, mac, linux), One of the functions of the app is to read and write bytes to serial port, I have tested it on two PCs, Here are the result
Ubuntu version: Ubuntu 22.04.1 LTS
Serial Port Settings:
Baud Rate: 115200
Stop Bits: 1
Parity: None
RTS: True
DTR: True
Handshake: XOnXOff or None (Depending on experiment)
Experiment 1
Operating system: Windows
Details: Sending and receiving bytes works perfecty
Experiment 2
Operating system: Ubuntu
Details: Sending works, but receiving is a different story
Receiving bytes on Linux

On The first test i tried receiving a frame of 138 bytes (which I know is being correctly sent because I had already received them on windows) , but instead of receiving 138 bytes I receive 140 bytes with 0x00 at the start and another 0x00 in the middle
Then I set handshake to XONXOFF which solves the problem and I could receive the 138 bytes correctly
On the second test I tried receiving a frame of 10 bytes but instead of 10 I received 9 only missing a 0x11 byte in the middle (This is while the handshake still XONXOFF),
Then I set handshake to None and suddenly I could receive the 10 bytes correctly

So as you can see I am in a pretty bad situation setting handshake to XONXOFF works for big frames only and setting it to none works for small frames only, (ON UBUNTU)
Here is the code (although I think that it is not relevant because this bug is reproducible on any ubuntu machine with C#, and I have already several C# serial tools that gave the same result)
<code>public class RS232Service : IDisposable, IRS232Service
{
public event EventHandler<ReceivedSerialDataEventArgs>? DataReceived;
public event EventHandler<FrameEventArgs>? DataSent;

private SerialPort _comPort = new();
private readonly List<byte> _receivedDataBuffer = new();

public void Dispose()
{
    _comPort.Dispose();
    GC.SuppressFinalize(this);
}

public void Connect(SerialPort comPort)
{
    _comPort = comPort;
    if (_comPort.IsOpen) return;
    _comPort.ReadTimeout = 1000;
    _comPort.DataReceived += OnComPortDataReceived;
    _comPort.Open();
}

public void Disconnect()
{
    if (_comPort.IsOpen)
    {
        _comPort.Close();
    }

    _comPort.DataReceived -= OnComPortDataReceived;
}

private void OnComPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    ReceivedSerialDataEventArgs objReceivedSerialDataEventArgs = new ReceivedSerialDataEventArgs();
    int dataLength = _comPort.BytesToRead;
    byte[] data = new byte[dataLength];
    int nbrDataRead = _comPort.Read(data, 0, dataLength);
    if (nbrDataRead == 0)
        return;
    Console.WriteLine("Got data length: " + dataLength);
    _receivedDataBuffer.AddRange(data);
    int parsedbytes = 0;
    if (DataReceived != null)
    {
        objReceivedSerialDataEventArgs.ReceivedData = _receivedDataBuffer;
        DataReceived(this, objReceivedSerialDataEventArgs);
        parsedbytes = objReceivedSerialDataEventArgs.ReadLength;
        _receivedDataBuffer.RemoveRange(0, parsedbytes);
    }

    Console.WriteLine("removed length: " + parsedbytes);
}

public bool IsConnected()
{
    return _comPort.IsOpen;
}

public void SendData(byte[] data, string dataDescription)
{
    _comPort.Write(data, 0, data.Length);
    DataSent?.Invoke(this, new FrameEventArgs(data, dataDescription));
}
</code>
}
****NOTE: **** For some reason there is a tool called moserial on ubuntu which somehow works perfectly with the 138 bytes and the 10 bytes frame when the handshake is XONXOFF (ie it does not lose the 10th byte of the 10 bytes frame)
Comment: Suggest you study the man page for termios. There's a lot more to configuring a Linux serial terminal than just baud rate, character framing, and flow control.  E.G. certain conditions will cause insertion of null characters.  If the serial terminal is not in raw mode, then you might see some "*weird behavour* [sic]".
Comment: The following may be helpful: https://stackoverflow.com/a/70614758/10024425, [SerialPort.NewLine](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.newline?view=dotnet-plat-ext-6.0&viewFallbackFrom=net-6.0), and [SerialPort.ReceivedBytesThreshold](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.receivedbytesthreshold?view=dotnet-plat-ext-6.0). You really should read all of the [SerialPort](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=dotnet-plat-ext-6.0) documentation though.
Comment: So How can I set the .net serial port to raw mode?
Comment: @sawdust The problem is currently I am not able to set raw mode in my app, but even when I set it via stty in the command there is still insertion of null characters
Comment: If you want more than vague comments, then stop writing vague summations and provide details.  For a start, PCs nowadays don't have COM ports, so what are you using?
Comment: My setup is I have a texus instrument "tiva C" board connected to my laptop running ubuntu via usb to micro-usb cable and the device name is /dev/ttyACM0 (if that is relavent)
Comment: Why does this "*tiva C*" board send packets of 138 or 10 bytes? Are these responses to request messages, or unsolicited? If these messages contain bytes other than text in ASCII code, then software flowcontrol (i.e. XON/XOFF) is inappropriate. But why does this link require flowcontrol? (The system buffer is 4KB.) IOW does this link use a request-response dialog, or is this "*tiva C*" board sending unsolicited packets???
Comment: This link does not require flowcontrol at least on Windows but on ubuntu I could not receive the 138 bytes without the inserted 0x00 until I used flowcontrol (I do not know why it only works with flowcontrol) If you know how can I receive the 138 without the inserted 0x00 it would solve my problem
Comment: @sawdust some packets are unsolicited and others are request-response dialog for example the 138 bytes packet that I am having the problem with is unsolicited while the 10 bytes packet that is working are responses
Answer: You can't use XON/OFF flow control for binary data.  The missing 0x11 byte is an XON that will be eaten by the serial driver on the receiving end.  You have to use hardware flow control like RTS/CTS for binary data, but both ends and the cable must support it.

serial port wieird behavour on ubuntu


How to invoke passed method which has argument in kotlin?

Question: I am trying to invoke a method with argument received as an argument but not able to do so. Here is what I am trying.
I have a method which gets me alert dialog object like below.
fun getAlertDialog(
title: String,
positiveButtonText: String,
positiveClickAction: (() -> Unit)) {
someTextView.setOnClickListener {
positiveClickActin.invoke()
}

and the above can be called like below
val dialog = getAlertDialog("Title", "Ok", ::clickedOk)

considering clickedOk is a void method like below
fun clickedOk() {
println("clicked")
}

But I am stuck when i want to pass a method with argument. Let's say I want to print some variable. The getSimpleDialog method can be changed as below.
fun getAlertDialog(
title: String,
positiveButtonText: String,
positiveClickAction: ((any: Any) -> Unit))
someTextView.setOnClickListener {
positiveClickActin.invoke() //this cannot be achieved now as the method takes an argument
}

and call it as
val dialog = getSimpleDialog("Hello", "ok", { variable -> println("clicked $variable")})

but i cannot invoke this method in the getSimpleDialog's on click listener. How do I achieve it?
Answer: You can either call
positiveClickActin.invoke(param)

or simply,
positiveClickActin(param)

Similarly for no parameter case you can use
positiveClickActin()

Instead of calling invoke().
While reading in the doc, the invoke() looks to be useful while having mixed of java and kotlin code. (but I might be wrong here as I am still new in kotlin)
Comment: Thanks for your answer. I am looking for a way to find that param to pass it. That's where I am stuck. Let me know if you know how  to access that param within the method.


What is the best SDN Controller for research purposes?

Question: I am interested in starting my research in the field of SDN. I looked around the internet for which SDN controller is the most suitable for research purposes, but it seems that the SDN community does not agree on a specific controller.
I would like to get advice about which controller is optimum taking into consideration the following:

Preferably uses Python environment (I am an intermediate Python user but not a professional).
Provides a decent level documentation as to how to use different network components (I will be simulating a complete network from hosts to core routers).
Provides a GUI for configuration or at least a graphical representation of the simulated network.
Best supported with an online community in case of future issues of concepts and connectivity.

During my online research I found that most people recommend POX. Although after setting it up and using its basic functions, I did not feel that it is the most suitable.
Really appreciate your help and time regarding this issue.
Answer: There are many solutions and what is the best depends on the individual needs.
If you prefer to use Python. Look at the Ryu controller if POX does not match your requirements. Ryu is Python based an has a good documentation. In combination with Mininet and MiniEdit as GUI it perhaps fulfills your requirements. But I think there is no best solution you have to look with which you can work best. Try different solutions ...
Comment: Thanks for the reply !! just a followup question...in the documentations, tutorials.etc. always the functionality that is described is for a Switch (best case scenario a L3 switch). If I need a more complex network component (e.g. a router, DHCP server, Access Points, Fibre Channel links,etc...), do I have to write the APIs myself or maybe there is ready to use libraries that I can take advantage of ?
Answer: In the open source world there are two major players as sdn controller, ONOS and Opendaylight. Both are mostly written in java.
Many commercial controllers are based on these two open source controllers.

Brocade SDN Controller is built directly from OpenDaylight code
Huawei launched the ONOS-based Agile Controller 3.0

They are both big communities, both have active mailing lists and documentation, also UI.
You can find your needs from these controllers.


How to diagonalize an $N\times N$ symmetric matrix? ($N>3$, show an example of $N=5$)

Question: Example and basic theory will help. These things can be done for $3\times 3$ fruitfully, but problem arises after $N\ge 5$. Basic theory will be helpful (if posted),  as it will help to generalize to any ill condition situation (using higher level concepts of-course).
Comment: Please don't use all caps in the title. The users of this site don't like being yelled at.
Comment: Are you looking for a primer in some numerical methods? Or do you mean an anayltic treatment?
Comment: An analytic treatment.
Comment: Theoretically, there is nothing different between diagonalizing a $3\times 3$ (or even $2\times 2$) matrix and a general $N\times N$ matrix. If you can do the $3\times 3$ case, which I assume you can since you do not want a $3\times 3$ example, then what difficulties are you having in generalizing to $N\times N$?
Answer: For your matrix $A$, find all eigenvalues and corresponding eigenvectors, then let $P$ be the matrix whose columns are the eigenvectors of $A$, then $P^{-1}AP=D$, where $D$ is diagonal, and the diagonal entries of $D$ are the eigenvalues of $A$.
Comment: I may be wrong, but I think the OP's issue is that the process of actually finding the eigenvalues and vectors analyically becomes almost impossible for larger matrices.
Comment: For greater than or equal to 5, these things may not even give any analytic solution. Now think it how to reduce a 5X5 matrix to a lower one where analytic solution can be calculated.
Comment: Perhaps considering upper/ lower triangular matrices would be a good way to go.
Comment: You mean to say Block matrix form, then solving them individually. After than lacing them where they sit.
Answer: For example, let's try
$$ A = \left[ \begin {array}{ccccc} 3&-2&1&2&-2\\ -2&-1&0&0
&2\\ 1&0&1&-1&-3\\ 2&0&-1&1&-2
\\ -2&2&-3&-2&-1\end {array} \right] $$
Its characteristic polynomial is $P(\lambda) = \det( \lambda I - A) = \lambda^5 - 3 \lambda^4 - 33 \lambda^3 + 41 \lambda^2 + 96 \lambda - 6$, which happens to
be irreducible.  The polynomial is not solvable using radicals.
Now an eigenvector for eigenvalue $r$ is a vector in the null space of $A - r I$.
I want to do my computations symbolically.  One trick is to just look at the top $4$ rows of $A - rI$ and row-reduce.  We find that a vector in the null
space is
$$ \left[ \begin {array}{c} -2\,{r}^{3}-9\,{r}^{2}+20\,r+15
\\ 2\,{r}^{3}-6\,{r}^{2}+8\,r-12
\\ -3\,{r}^{3}+9\,{r}^{2}+19\,r-9
\\ -2\,{r}^{3}+5\,{r}^{2}-6\,r-21
\\ {r}^{4}-4\,{r}^{3}-8\,{r}^{2}+18\,r+9\end {array}
 \right]
$$
Normalize by dividing by the square root of the sum of the squares, which
(after simplifying using $P(r)=0$) happens to be
$$ \sqrt{1266\,{r}^{4}-3300\,{r}^{3}-1140\,{r}^{2}+5772\,r+666}$$
...
Comment: can you provide me some references to the above done algebra, it will help me in understanding the problem which I have to solve.


Let p be an odd prime and let g be a primitive root modulo p.

Question: Let p be an odd prime and let g be a primitive root modulo p.

Prove that $g^k$ is a quadratic residue modulo p if and only if k is even.
Use (a) to give a quick proof that the product of two nonresidues is a residue, and more generally that $(\frac{a}{p})(\frac{b}{p})=(\frac{ab}{p})$
Use (a) to give a quick proof of Euler's Criterion $a^{\frac{p-1}{2}} \equiv (\frac{a}{p}) (\mod p)$
Answer: For $(1)$, note that $g$ generates the multiplicative group $\mathbb{Z}_p^\times = \mathbb{Z}_p$ \ $\{0\}$.  A quadratic residue $a \pmod{p}$ exists if there is an $x$ such that $x^2 = a \pmod{p}$.
Well, rewrite $x$ in terms of the generator $g$ and square it.  For the other direction, simply use properties of exponentiation to rewrite $g^k$ as $(g^n)^2$ for some $n$.  This will be a quadratic residue by definition.

For $(2)$, simply rewrite your two non-residues in terms of the generator and multiply them together.  Is $k$ then even?  If so, it is a quadratic residue.

For $(3)$, I'm not used to the Legendre symbol, so I will rewrite what you are trying to prove as:
If $a$ is a quadratic residue, then $a^{\frac{p-1}{2}} \equiv 1 \pmod{p}$.  Otherwise, $a^{\frac{p-1}{2}} \equiv -1 \pmod{p}$.
This isn't so bad.  If $a$ is a quadratic residue, then $a = g^k$ for some even $k$.  Hence, $a^{\frac{p-1}{2}} = (g^n)^{p-1} = (g^{p-1})^n = 1^n = 1.$  Use similar methods if $a$ is not a quadratic residue.
Answer: For (1):
One direction is easy: if $k$ is even say $k=2m$, then $g^k=(g^m)^2$, hence $x=g^m$ is a solution to the equation $x^2 \equiv g^k \pmod{p}$.
For the other direction: assume that $g^k$ is a quadratic residue, this means $x^2 \equiv g^k \pmod{p}$ has a solution $x_0 \in \mathbb{Z}_p$. But $g$ being a primitive root implies that $\exists s \in \mathbb{N}$ such that $x_0=g^s$. Thus
$$g^{2s} \equiv g^k \pmod{p}.$$
Since the order of $g$ is $p-1$, therefore $p-1$ divides $2s-k$. Now $p-1$ is even and so is $2s$, thus $k$ must be even.
Try other parts and see if you can proceed.


Do I need a global state in my Reactjs app?

Question: I am working in an app to read the most viewed news in the last 7 days using the NY Times API (https://developer.nytimes.com/docs/most-popular-product/1/overview) filtered by sections. You will understand better watching my user interface right now:

So, the problem is I would like when I click, for instance, on New York section, the news to appear below the sections. For that I have created my ListOfNews component, which would have inside it News component. But, when I click on a section, what happens it what you can see at the next image:

The salmon background color is just to know well size of the box. Ok. Let's jump into the code. Here the code of my Section component:
import React, { useState } from 'react';
import { getNewsAttributes } from '../helpers/helpers';
import getNewsFilteredBySection from '../services/getNewsFilteredBySection';
import ListOfNews from './ListOfNews';

export default function Section({ section }) {

  const [news, setNews] = useState(null);

  function showEvent(e) {
    const sectionSearched = e.target.innerText;
    getNewsFilteredBySection(sectionSearched)
      .then((response) => {
        const filteredResults = response;
        const newsAttributes = getNewsAttributes(filteredResults);
        setNews(newsAttributes);
      })
  }

  return (
    <>

{section}

      {news !== null ? <ListOfNews newsAttributes={news} /> : null}
    </>

  )

};

Here the code of my ListOfNews component:
import React from 'react';

    export default function ListOfNews({ newsAttributes }) {

        return (

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose injected humour and the like.

        )

    };

And later I would have to pass the newsAttributes to the News component, where I would render the title, the image, and the abstract of the news. So, here are my questions:
a) How can I achieve my ListOfNews component to render below all the sections, no matter which section I click? I suppose the problem is currently in my logic, since I am returning this component with the component Section.
b) I suppose, the problem is that logic is implemented in the Section component, so which could be a good way of implementing this? Do you think implementing the logic in a outer helper could work? Or maybe should I need a global state manager? In this case... which one do you think would fit the best my needs? Redux? Maybe useContext would be enough? Thanks a lot :)
Answer: I think what you are doing is repeating the Section component right, as a result when you render a section, it also renders the news, and then the next section gets rendered.
So what you should do is first render sections, and then render the selected section's news. In order to do that you need to store the selected section in the outer component. so move all the non rendering code to outer/parent component, and pass in the eventHandler function showEvent to the section component.
Now the outer function will fetch and store the news.
your outer functions render should look something like this;
sections.map(section =>

)
{news !== null ? <ListOfNews newsAttributes={news} /> : null}

I hope that makes sense.
Regarding your second question, looks like you are pretty new to react, so I would recommend not to do that yet. If your project is just this component you definetely dont need it, if you have a lot of component that need to share state, you might need one, context can definetely help, but I see that you are fetching some data, and react-query might also help, as it does some caching, and fairly well documented and not so hard to start with.
Comment: You need a new component, an outer one that renders the section and the news. The outer component will do the fetch, as I tried to explain. Section component wil just list the selectable sections, and will pass the click event to the wrapper component.
Comment: I have some doubts:

1) Ok, I am passing the properties to Section component. So, what should I render there? I didnt got it well.
2) And, ok, I have all the logic in my ListOfSections component so... ¿How my Section component will know there has been a change in the state (because I am passing the event handler, which modifies a state (setNews) but i am not receiving news? ¿How could I obtain news in order to use it in my News and List of News component? First, it would be a prop to my List of News and it would pass later to my News, where it would be rendered. Thanks.