How find this limit $\lim_{n\to\infty}\underbrace{\sin{\sin{\cdots\sin{x}}}}_{n},x\in R$

Question: Find this limit
$$\lim_{n\to\infty}\underbrace{\sin{\sin{\cdots\sin{x}}}}_{n},x\in R$$
My idea: let
$$f(x)=\underbrace{\sin{\sin{\cdots\sin{x}}}}_{n}$$
then
$$f(x+2\pi)=f(x)$$,so we only consider $x\in[0,2\pi]$,
so define sequence $a_{n}$ such $$a_{1}=\sin{x},a_{n+1}=\sin{a_{n}}$$
so I think we can Discussion of x.can you someone have methods?
other idea:
$$|a_{n+2}-a_{n+1}|=|\sin{a_{n+1}}-\sin{a_{n}}|\le |a_{n+1}-a_{n}|$$
Comment: Possibly related : http://math.stackexchange.com/questions/45283/compute-lim-limits-n-to-infty-sin-sin-dots-sin-n/45287#45287
Comment: If there is an limit $L$ then it is easy to show that $L=\sin L$. No matter where you start, the sequence ends up either small negative and increasing, bounded above by $0$ or small positive and decreasing, bounded below by $0$ (or, exceptionally, constant at zero) - hence has a limit.
Comment: It approaches 0 as quickly as $1/\sqrt{n}$, according to this previous answer: http://math.stackexchange.com/questions/3215/convergence-of-sqrtnx-n-where-x-n1-sinx-n
Answer: $\sin$ is an increasing function in $[-\pi/2,\pi/2]$. The maximum value here is $1$.
Therefore the maximum of $\sin(\sin(x))$ is $\sin(1)$, which is less than $1$, because $\sin(x)\lt x \forall x\gt0$(try to prove by yourself)
Similarly adding another iteration will again decrease the value.
But the value is bounded from below, because with positive input below $\pi/2$, the value will never be negative.
Clearly our required limit is $0$.
You can also show that if you start at the other extreme of $-1$, then it is increasing and bounded above by $0$. Everything else is a subclass of these two cases.
Comment: Or the case where $x=0$
Comment: @MarkBennet yes I noticed. Trivial though, also it does count as "everything else" :)
Answer: The same question has already been asked only a few days ago. Obviously, were such a limit to exist, we can write $L=\sin L$, whose only solution is $L=0$.
Answer: Rigorous solution:
Suppose the sequence does not converge to $0$. Without loss (take a subsequence if necessary) assume that  $\exists \epsilon>0$ such that$  \ \ \forall n \geq 2$ we have that $a_n \in [\epsilon,\sin(1)]$.
By the Banach Fixed Point Theorem (noting that $\sup_{x \in [\epsilon,1] } |\sin(x)| = \cos(\epsilon) \in (0,1) $) we see that the limit $\lim_{n \rightarrow \infty}a_n$ exists and is a fixed point of the equation $\sin(x) = x, x\in [\epsilon,1]$.
There is no solution to this equation; the only solution of the equation $\sin(x) = x$ is $x=0$.
NB Banach Fixed Point Theorem: http://en.wikipedia.org/wiki/Banach_fixed-point_theorem
Comment: @Did OK, this is what I meant (but not what I wrote!).


Do the mean and standard deviation of the sum of independent normal random variables $X$ and $Y$ equal $\mu_X+\mu_Y$ and $sd_X+sd_Y$?

Question: I was following with Chapter 4 of famous 'Statistical Inference 2nd ed' textbook (Casella, Berger) and discovered that if X is a randomly normally distributed variable, and so is Y, and both of them are independent, therefore the distribution of the sum of equal length random vectors X + Y has the parameters mu_XY = mu_X + mu_Y and sd_XY = sd_X + sd_Y
Just for check that statement I performed a simulation in R with a following code:
<code>> rnd_vec_X <- rnorm(10000, mean = 10, sd = 3)
> rnd_vec_Y <- rnorm(10000, mean = 20, sd = 7)
> rnd_vec_XY_sum <- rnd_vec_X + rnd_vec_Y
> mean(rnd_vec_XY_sum)
[1] 30.05607
> sd(rnd_vec_XY_sum)
[1] 7.564628
</code>
Indeed, the mean of the sum of there independent random variables is ~30 (20 + 10), as predicted by theory. But why the standard deviation is so far from 10 (7 + 3)? I performed nearly twenty simulations with different seeds and different sample sizes... No luck.
I guess something is wrong with my code or with my understanding of the topic. But what?
Answer: Under independence (in fact, already under lack of correlation), the variance of the sum is the sum of the variances,
$$
\sigma^2_{X+Y}=\sigma^2_{X}+\sigma^2_{Y}
$$
Incidentally, this result does not rely on normality.
It is, therefore, not true that
$$
\sqrt{\sigma^2_{X+Y}}=\sqrt{\sigma^2_{X}}+\sqrt{\sigma^2_{Y}},
$$
i.e., the sum of the standard deviations is not the standard deviation of the sum  - simply because the square root of a sum is not the sum of the square roots.
In your example, $X$ and $Y$ have variances 9 and 49, respectively, so that the population standard deviation is
<code>> sqrt(3^2+7^2)
[1] 7.615773
</code>
which agrees with your simulation.


Como organizar um Array por ordem de Hora?

Question: Tenho duas listas com formato de TimeSpan e outra com formato de String. Preciso organizar essas duas listas para crescente e decrescente.
        List<string> horaString = new List<string>()
        {
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };

        List<TimeSpan> horaTimespan = new List<TimeSpan>()
        {
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5),
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5),
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5)
        };

Comment: Procure por Split String no Google (para dividir a string em array de string, separando por ":"(dois-pontos)), depois transforme as 3 string e um único valor inteiro (valor = hora*3600 + minuto*60 + segundos), e ordene por ele (procure pelo algoritmo QuickSort)
Answer: Você pode usar o método OrderBy e OrderByDescending.
        List<string> horaString = new List<string>()
        {
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };

        List<TimeSpan> horaTimespan = new List<TimeSpan>()
        {
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5),
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5),
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5)
        };

        horaString = horaString.OrderBy(p => p).ToList();
        horaTimespan = horaTimespan.OrderBy(p => p.Hours).ToList();

        Console.WriteLine("String crescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span crescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

        horaString = horaString.OrderByDescending(p => p).ToList();
        horaTimespan = horaTimespan.OrderByDescending(p => p.Hours).ToList();

        Console.WriteLine("String decrescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span decrescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

Veja funcionando no .Net Fiddle
Comment: Está certo, vou ajustar
Comment: só não precisa da conversão pra  TimeSpan, se fosse data sim,
Answer: Procure por Split String em C# (para dividir a string em array de string, separando por ":"(dois-pontos)), depois transforme as 3 string em um único valor inteiro (criando uma lista de inteiros)
hora = array[0];
minuto = array[1];
segundos = array[2];
valor = hora*3600 + minuto*60 + segundos

, e ordene por ele usando o exemplo
https://stackoverflow.com/questions/3738639/sorting-a-listint.
Depois retorne o inteiro para o valor original
hora = valor/3600;
valor -= hora*3600;
minuto = valor/60;
valor -= minuto*60;
segundos = valor;


SVM formulation

Question: Here is an extract of an article. They are solving a One Vs  One classification problem.
What does "y" stands for ? It is a bias ?
The way they are expressing the minimization problem is quite confusing...
Answer: In this formulation $\gamma$ serves as the bias term. This form is equivalent to adding on an extra dimension to $x$ where the value in that dimension is always $-1$.
$y$ is in fact an error vector - it represents how far the classification of each point is from the desired value of $1$. Note that since $y$ contributes as $||y||^2$ to the objective, this formulation is actually trying to find $w$ and $\gamma$ as a regression - where points in $A+$ should be $1$ and points in $A-$ should be $-1$, and the loss is symmetric for each class around those value. For classification one would generally have a hinge-loss (or similar).
Comment: So that means this formulation will try to avoid points too well classified (too big values of points in A+ per instance) ?
Comment: Yes, that's right.

SVM formulation


Criar uma tabela separando datas por trimestre com React e Node

Question: A tabela precisa ficar assim:

Ela está assim:

Já consegui criar uma tabela usando o Sequelize com os dados de cada unidade, com cnpj e tudo mais, e fiz uma tabela de datas relacionada a essa tabela de unidades. a relação ficou o seguinte:
db.unidades = require("./CompreBem/unidades.js")(sequelize, Sequelize);
db.datas = require("./CompreBem/datas.js")(sequelize, Sequelize);

db.unidades.hasMany(db.datas, { as: "datas" });
db.datas.belongsTo(db.unidades);

A tabela está em React, no componente da tabela ficou o seguinte:
<TableContainer component={Paper}>

          <TableHead>
            <TableRow>
              <TableCell className={classes.teste} align="right">  </TableCell>
              <TableCell align="right">Unidade</TableCell>
              <TableCell align="right">Nº CTI</TableCell>
              <TableCell align="right">CNPJ</TableCell>
              <TableCell align="right">Trim.1</TableCell>
              <TableCell align="right">Trim.2</TableCell>
              <TableCell align="right">Trim.3</TableCell>
              <TableCell align="right">Trim.4</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {Object.keys(unidades).map((unidade, i) => (
              <TableRow className={classes.row} key={i}>
                <TableCell align="right">{unidades[unidade].numero}</TableCell>
                <TableCell align="right">{unidades[unidade].unidade}</TableCell>
                <TableCell align="right">{unidades[unidade].ntci}</TableCell>
                <TableCell align="right">{unidades[unidade].cnpj.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5") }</TableCell>
                <TableCell align="right">1</TableCell>
                <TableCell align="right">2</TableCell>
                <TableCell align="right">3</TableCell>
                <TableCell align="right">4</TableCell>
              </TableRow>
            ))}
          </TableBody>

      </TableContainer>

Eu fiz um useState para a tabela unidades, fiz a requisição axios e fiz esse tratamento para que apareça na tabela, agora eu preciso que fique as últimas datas de cada trimestre nas suas respectivas unidades. A requisição que eu faço para pegar esses dados fica nesse formato:

Por favor, estou me quebrando nesse código, não consigo pensar em uma maneira de mostrar esses trimestres.
Answer: Se os registros de datas vem ordenadas dentro de cada unidade imagino que possa fazer desta forma:
{Object.keys(unidades).map((unidade, i) => (
          <TableRow className={classes.row} key={i}>
            <TableCell align="right">{unidades[unidade].numero}</TableCell>
            <TableCell align="right">{unidades[unidade].unidade}</TableCell>
            <TableCell align="right">{unidades[unidade].ntci}</TableCell>
            <TableCell align="right">{unidades[unidade].cnpj.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5") }</TableCell>
            <TableCell align="right">unidades[unidade].datas[0]['data']</TableCell>
            <TableCell align="right">unidades[unidade].datas[1]['data']</TableCell>
            <TableCell align="right">unidades[unidade].datas[2]['data']</TableCell>
            <TableCell align="right">unidades[unidade].datas[3]['data']</TableCell>
          </TableRow>
        ))}

Pode colocar um ternario para verificar se tem o indice do array para não dar nenhum erro exibindo uma outra informação.
Toda o agrupamento de datas para as unidades pode ser feita no proprio service no back-end, fazendo com que o front-end so exiba.
Comment: Você é um deus, eu não precisava mais dessa condição de trimestre, mas sua resposta resolveu toda minha vida, muito obrigado, no final era só usar ['data'], eu já estava fazendo map com filter com não sei mais o que. muito obrigado mesmo.


Closed-form of $\int_{a}^{b}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx$ for some $a<b$

Question: In this question I asked to prove that
$$\int_{0}^{1}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx=\frac{\pi e}{24}.$$
If we take a look at the plot of the integrand, then we could see some symmetry-property.

Because the integrand is symmectic to the $y=1/2$ line, it is also true, that
$$\int_{0}^{1/2}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx=\int_{1/2}^{1}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx=\frac{\pi e}{48}.$$
Question. Is there a close-form of $I(a,b)=\int_{a}^{b}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx$ for some else $a<b$? If it is too hard, then is there a closed-form for some $a<b$, just for the real or imaginary part? For example
$$\Re \left[ \int_{1}^{3/2}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx \right],$$
$$\Re \left[ \int_{3/2}^{2}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx \right],$$
or
$$\Im \left[ \int_{1}^{2}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx \right]?$$
Comment: I think we'd be pushing our luck asking for a closed form for general limits $a,b$. Closed forms might exist when the limits coincide with zeros of the integrand, perhaps.
Comment: @DavidH This is why I asked these three specific integrand limits at the end of the question. Of course anything else would be nice.
Answer:
Is there a close-form of $I(a,b)=\displaystyle\int_{a}^{b}\sin{(\pi x)}x^x(1-x)^{1-x}\,dx$ for some other $a<b$?

Yes, of course there is. An infinity of them, in fact. But, in that case, a and b will lack a closed form. :-) For instance, all rational and algebraic numbers possess a closed form expression. Now, limiting ourselves to those in between $0$ and $\dfrac{e\pi}{24}$, which themselves are infinite in number, for each of them there are infinitely many solutions a and b within the interval $[0,1]$, so that $I(a,b)$ will be equal to that particular rational or algebraic value, since $f(t)=I(a,t)$ is a monotonous function for any t in $[a,1]$. So I assume that you are interested in triplets $\Big(a,b,I(a,b)\Big)$, other than the ones already mentioned, and where all three values have a closed form, in which case the answer would be that no others are known to exist $($key word here being "known", since proving this is, to my knowledge, still an open problem$)$.
Comment: By closed form of an algebraic number I mean its minimal polynomial. I am not implying solvability in terms of radicals.


Como concatenar uma variável no meio de outra variável?

Question: Gostaria de fazer com que o conteúdo de uma variável formasse outra variável, por exemplo:
$name = 'clientes';
$default_$name_list = "Lista de clientes";

Quero fazer com que a variável default seja $default_clientes_list, há alguma maneira de fazer isso em PHP?
Answer: Você pode chegar a algo parecido usando variáveis variáveis no PHP.
$name = 'clientes';
$lista_var = "default_{$name}_list";
$$lista_var = "Lista de clientes";

echo $default_clientes_list;

Veja funcionando.
Ou até simplificando mais um pouco sem atribuir para a variável intermediária.

$name = 'clientes';
${"default_{$name}_list"} = "Lista de clientes";

echo $default_clientes_list;

Na minha opinião, não recomendo seguir essa linha. Isso prejudica bastante a legibilidade do código sem ter um benefício aparente. Só deixa mais complexo e difícil para quem vai ler o código.
Comment: Boa resposta. Só para reforçar que essa prática é ma, adiciono outro ponto ao que você já disse. É possível de também substituir valores de outras variáveis locais que existam com o nome gerado, sem que a pessoa se aperceba, criando bugs difíceis de detetar. [Pequeno exemplo](http://sandbox.onlinephpfunctions.com/code/7d81ecd83187b65beca45f0fe2c325b8e2f4570d)
Answer: Olha não sei se isso você pode fazer, mas você pode fazer em array.
Por exemplo:
$name="clientes";
$defaultList['clientes']= "Lista de clientes";
$defaultList['representantes'] = "Lista de representantes";

e aí você puxa o que quer:
echo $defaultList[$name]; // Lista de clientes;

Answer: No seu exemplo não funciona pois o PHP está procurando pela variável $name_list, que não existe.
Para obter o efeito que você quer, acho que seria desta forma.
$varName = sprintf("default_%s_list", $name /* ou 'clientes' */);
$$varName = /* você terá uma variável $default_clientes_list com o valor que passar aqui */;

Entretanto também não recomendo esta prática. Neste caso e em vários outros parecidos acredito que seja melhor o uso de Arrays.


Openai keeps throwing RateLimitError without letting through even a single request

Question: I am trying to follow a Langchain tutorial. The code below:
from langchain.document_loaders import WebBaseLoader
from langchain.indexes import VectorstoreIndexCreator

# Load document from web (blogpost)
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")

data = loader.load()

# Split the text
from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
all_splits = text_splitter.split_documents(data)

# Embed and store the splits in a vector db (chroma)
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())

question = "what are the approaches to task decomposition"
docs = vectorstore.similarity_search(question)
print(len(docs))

I keep getting the following error trace:
Retrying langchain.embeddings.openai.embed_with_retry.<locals>._embed_with_retry in 4.0 seconds as it raised RateLimitError: You exceeded your current quota, please check your plan and billing details..

The API is not allowing even a single request to go through. So, the RateLimitError is confusing.
Is there something which needs to be optimized in my code, or is there a workaround/fix for this?
Comment: @RokBenko Yes. That answers my question. Upgrading the account to a paid plan by setting up a payment option solved the problem.
Comment: Does this answer your question? [OpenAI ChatGPT (GPT-3.5) API error 429: "You exceeded your current quota, please check your plan and billing details"](https://stackoverflow.com/questions/75898276/openai-chatgpt-gpt-3-5-api-error-429-you-exceeded-your-current-quota-please)
Answer: I referred to this forum post about a similar issue. The solution seem to be adding a payment mode to the OpenAI account, which makes it a paid account.
Once the account gets converted to a paid account, the RateLimitError stopped popping up, and the requests are getting processed fine.


I need help understanding modular arithmetic

Question: I need help understanding modular arithmetic. I know that modular arithmetic is instead of going to one o´clock you go to 13 o´clock but Im not sure. I got this off of wikipedia but anyone can put an answer on there. Am I correct? I need help understanding modular arithmetic. Are there multiple modular arithmetic? I need help understanding modular arithmetic.
Comment: Make your question more specific please
Comment: Please look at my profile before voting, answering it or commenting
Comment: How would I make it more specific?
Comment: I don know much more about modular arithmetic
Answer: Modular arithmetic is basically being concerned about remainders. We write $12 \equiv 5 \pmod{7}$ because the remainder when $12$ is divided by $7$ is $5.$ The clock analogy gives a perfect way to picture this.
You're at a Navy hospital, walking around, and you see an announcement for a talk to be given at 1500 hours. What time is that? Well, the military (and some countries around the world) work on a 24-hour clock, so you'd have to work modulo 12. In particular,
$$ 15 \equiv 3 \pmod{12}$$
so you'd go to this talk at 3:00.
There are many tricks to modular arithmetic that are best learned by practice. The best way to learn is by doing, so start small.
Comment: In a Navy hospital, 1500 hours is called 6 bells. So 1500 hours is 3 (mod 12) which is 3 mod 4 times two (it advances one bell every 1/2 hour) to make 6. Still an exercise in modular arithmetic but a little more complicated.


Is it possible to access the ZFS checksums to compare files

Question: I have a FreeNAS 8 machine (FreeBSD 8.2-RELEASE-p1) with two different shares on it. I'm migrating files from Share1 to Share2. The Shares have different directory structures and naming conventions. I'm looking for a way to verify that a file on Share1 actually exists (and is accurate) on Share2.
My plan is basically to checksum every file on both Shares and make sure that all the checksums in the Share1 set exist in the Share2 set. I can do this relatively easily with a bash script, but it'll take a long time to generate each of the checksum sets. My question is: Is it possible to access the native ZFS checksums to use them for this comparison?
Answer: I don't believe it is possible to extract the block level checksums from a ZFS filesystem, but since the checksums are at the block level, not the file level, it probably wouldn't help you anyway.
A while back I wrote a couple of programs for producing a manifest of a filesystem and for comparing an existing filesystem with that manifest.
Here's chksum.pl
<code>#! /usr/bin/perl
#
# generate a system manifest
#

use strict;

use File::Find;
use Digest::MD5;

our %config;

$| = 1;

&main;
exit;

sub initialize {
    my ($exclude_next, $include_next, @ex, @in, @ex_pats, @in_pats, %in, @x);

    # the exclude/include list looks like what you would pass to rsync
    my $elist = ['--exclude' => '/var/log',
                 '--exclude' => '/var/tmp',
                 '--exclude' => '/tmp',
                ];

    foreach my $op (@$elist) {
        if ($op eq '--exclude') {
            $exclude_next = 1;
        } elsif ($op eq '--include') {
            $include_next = 1;
        } elsif ($op eq '--delete') {
            # ignore
        } else {
            if ($exclude_next) {
                push(@ex, $op);
            } elsif ($include_next) {
                push(@in, $op);
            } else {
                warn "don't know what to do with $op\n";
            }
            $include_next = 0; $exclude_next = 0;
        }
    }

    $config{'exclude_list'} = \@ex;
    $config{'include_list'} = \@in;
    @ex_pats = map(glob($_), @ex);
    @in_pats = map(glob($_), @in);

#    print STDERR "exclusion patterns:\n", join("\n", @ex_pats), "\n\n";
#    print STDERR "inclusion patterns:\n", join("\n", @in_pats), "\n\n";

    # remove exclusions that exactly match inclusions
    foreach my $pat (@in_pats) {
        $in{$pat}++;
    }
    foreach my $pat (@ex_pats) {
        next if $in{$pat};
        push(@x, $pat);
    }

    $config{'ex_pats'} = \@x;
}

sub wanted {
    my($type, $extra);

    my $path = $File::Find::name;

    my @ex = grep($path =~ m"^$_", @{$config{'ex_pats'}});

    my($mode, $uid, $gid, $dev) = (lstat($path))[2,4,5,6];

    if (scalar(@ex) > 0) {
        # if we're excluding, and it was a dir, don't bother to descend
        $File::Find::prune = -d _;
        return;
    }

    $mode &= 07777;                             # mask off mode bits
    if (-d _) {
        $type = "dir ";
    } elsif (-l _) {
        $type = "link";
        $extra = "\"" . readlink($path) . "\"";
    } elsif (-f _) {
        $type = "file";
        $extra = &md5sum($path);
        return unless defined($extra);
    } elsif (-p _) {
        $type = "pipe";
    } elsif (-S _) {
        $type = "sock";
    } elsif (-b _) {
        $type = "bdev";
        $extra = "\"" . ($dev >> 8) . " " . ($dev & 0377) . "\"";
    } elsif (-c _) {
        $type = "cdev";
        $extra = "\"" . ($dev >> 8) . " " . ($dev & 0377) . "\"";
    } else {
        $type = "unk ";
    }

    printf "%s 0%04o %d %d \"%s\"", $type, $mode, $uid, $gid, $path;
    print " $extra" if $extra;
    print "\n";
}

sub md5sum {
    my $file = shift;
    my $context = Digest::MD5->new;
    unless(open(F, $file)) {
        warn "WARNING: couldn't open $file: $!\n";
        return;
    }
    $context->addfile(*F);
    close(F);
    my $digest = $context->hexdigest;
    return($digest);
}

sub main {
    &initialize;

    &find({no_chdir => 1, wanted => \&wanted}, '/');
}
</code>
and here's verify_sum.pl
<code>#! /usr/bin/perl

# verify that a system matches the sum file produced by chksum.pl

use strict;

use File::Find;
use Digest::MD5;
use Text::ParseWords;

our %config;

$| = 1;

&main;
exit;

sub initialize {
    my ($exclude_next, $include_next, @ex, @in, @ex_pats, @in_pats, %in, @x);

    my $elist = ['--exclude' => '/var/log',
                 '--exclude' => '/var/tmp',
                 '--exclude' => '/tmp',
                ];

    foreach my $op (@$elist) {
        if ($op eq '--exclude') {
            $exclude_next = 1;
        } elsif ($op eq '--include') {
            $include_next = 1;
        } elsif ($op eq '--delete') {
            # ignore
        } else {
            if ($exclude_next) {
                push(@ex, $op);
            } elsif ($include_next) {
                push(@in, $op);
            } else {
                warn "don't know what to do with $op\n";
            }
            $include_next = 0; $exclude_next = 0;
        }
    }

    $config{'exclude_list'} = \@ex;
    $config{'include_list'} = \@in;
    @ex_pats = map(glob($_), @ex);
    @in_pats = map(glob($_), @in);

#    print STDERR "exclusion patterns:\n", join("\n", @ex_pats), "\n\n";
#    print STDERR "inclusion patterns:\n", join("\n", @in_pats), "\n\n";

    # remove exclusions that exactly match inclusions
    foreach my $pat (@in_pats) {
        $in{$pat}++;
    }
    foreach my $pat (@ex_pats) {
        next if $in{$pat};
        push(@x, $pat);
    }

    $config{'ex_pats'} = \@x;
}

sub md5sum {
    my $file = shift;
    my $context = Digest::MD5->new;
    unless(open(F, $file)) {
        warn "WARNING: couldn't open $file: $!\n";
        return;
    }
    $context->addfile(*F);
    close(F);
    my $digest = $context->hexdigest;
    return($digest);
}

sub wanted {
    my $path = $File::Find::name;

    my @ex = grep($path =~ m"^$_", @{$config{'ex_pats'}});

    if (scalar(@ex) > 0) {
        # if we're excluding, and it was a dir, don't bother to descend
        $file::Find::prune = -d $path;
        return;
    }

    if (! $config{'seen'}->{$path}) {
        warn "new file: $path\n";
        $config{'new'}++;
    }
}

sub main {
    $config{'mismatch'} = 0;
    $config{'missing'} = 0;
    $config{'new'} = 0;

    &initialize;

    while (<>) {
        chomp;
        my ($type, $mode, $uid, $gid, $path, $extra) = &shellwords($_);
        my ($etype, $eextra);

        $mode = oct($mode);
        my($emode, $euid, $egid, $edev) = (lstat($path))[2,4,5,6];

        if (! -e _) {
            warn "missing file: $path\n";
            $config{'missing'}++;
            next;
        }

        $emode &= 07777;
        if (-d _) {
            $etype = "dir";
        } elsif (-l _) {
            $etype = "link";
            $eextra = readlink($path);
        } elsif (-f _) {
            $etype = "file";
            $eextra = &md5sum($path);
            return unless defined($eextra);
        } elsif (-p _) {
            $etype = "pipe";
        } elsif (-S _) {
            $etype = "sock";
        } elsif (-b _) {
            $etype = "bdev";
            $eextra = ($edev >> 8) . " " . ($edev & 0377);
        } elsif (-c _) {
            $etype = "cdev";
            $eextra = ($edev >> 8) . " " . ($edev & 0377);
        } else {
            $etype = "unk";
        }

        if ($type ne $etype) {
            warn "mismatch file type ($type vs $etype): $path\n";
            $config{'mismatch'}++;
        } else {
            # types are the same, compare other factors

            if ($mode != $emode) {
                warn sprintf("mismatch mode (0%o vs 0%o): %s\n", $mode, $emode, $path);
                $config{'mismatch'}++;
            }
            if ($uid != $euid) {
                warn "mismatch uid ($uid vs $euid): $path\n";
                $config{'mismatch'}++;
            }
            if ($gid != $egid) {
                warn "mismatch gid ($gid vs $egid): $path\n";
                $config{'mismatch'}++;
            }
            if ($extra ne $eextra) {
                if ($etype eq 'link') {
                    warn "mismatch link target ($extra vs $eextra): $path\n";
                } elsif ($etype eq 'file') {
                    warn "mismatch file checksum ($extra vs $eextra): $path\n";
                } elsif ($etype eq 'bdev' or $etype eq 'cdev') {
                    warn "mismatch device node ($extra vs $eextra): $path\n";
                }
                $config{'mismatch'}++;
            }
        }

        $config{'seen'}->{$path}++;
    }

    # now walk the filesystem looking for "new" files

    &find({no_chdir => 1, wanted => \&wanted}, '/');

    print "$config{'mismatch'} files changed\n";
    print "$config{'missing'} files missing\n";
    print "$config{'new'} new files\n";

    if ($config{'mismatch'} > 0 or
        $config{'missing'} > 0 or
        $config{'new'} > 0) {
        exit 1;
    }

    exit 0;
}
</code>
You'll probably want to tweak these scripts a bit for things like the exclude list, root directory of the comparison, etc.
Comment: Thank you. Unfortunately, the FreeNAS release I have doesn't have perl on it. I wrote a simple bash script to create a list of hashes that I'll move to another machine with perl to check. The script I wrote is based off [this post](http://www.cafewebmaster.com/how-recursively-create-md5-and-sha1-sum-your-files). Works well for me when updated to ignore hidden files and setup to output to a file. (e.g. `find /mnt/tank01 \( ! -regex '.*/\..*' \) -type f -exec ~/sum.sh '{}' \; > full-tank01-list.txt`)
Comment: If you've installed bash in FreeNAS (`pkg install bash`), you can use bash 4's "globstar" option to make a list: `shopt -s globstar; md5 **/* > /tmp/files.md5`. Then on your target, use process recirection: `shopt -s globstar; diff /path/to/files.md5 <(md5 **/*)`. The result show show you missing or added files, along with mismatched MD5s. You could do similar things with more typing without bash, of course.


Does Microsoft support Exchange 2010 on Server 2008 R2 with Active Directory?

Question: Will Microsoft provide support for Exchange 2010 installed on Server 2008 R2 with Active Directory? I know they advise against this. They have for the past four Exchange versions. The concern is will they provide support?
Comment: I take it you mean both roles on the same server?
Answer: It is supported, but not recommended.
Answer: This is pretty much what is done with SBS (exactly what is going to be done with SBS7). It's a compromise in security, performance, and stability. That being said, it is a supported configuration.


Differences between railties and engines in Ruby On Rails 3

Question: I read a few documents on these arguments, but I did not understand clearly what they are, what are the differences between them and if one of them fits my needs.
I need to write a piece of application which can be plugged in other application and I want to include it in other applications as a gem. Essentially I need a couple of models, one controller and no views, plus some initialization, support for configuration parameters coming from the hosting app and a generator.
Am I on the right way?
What should I read to understand how to do that?
Update:
A very nice article with a lot af details can be found here.
Essentially:

Railtie is the core of the Rails Framework and provides several hooks to extend Rails and/or modify the initialization process.
A Rails::Engine is nothing more than a Railtie with some initializers already set. And since Rails::Application and Rails::Plugin are engines, the same configuration described here can be used in all three.
Comment: I just released my first gem written as a Rails::Engine, it's available on [Github](https://github.com/fabn/google_authentication) thanks for the hint.
Comment: Related: http://stackoverflow.com/questions/6118905/rails-3-1-engine-vs-mountable-app/17263429
Answer: Railtie can probably do what you describe, but it may be more desirable to use an engine.  The engine can have its own configuration and also acts like a Rails application, since it allows you to include the /app directory with controllers, views and models in the same manner as a regular Rails app.
Read this blog for more info
Comment: Very nice pointer, it does explain a lot of things. Moreover, there is a link with a very interesting document which explain differences even better. I'll update my question to add that link.
Answer: Rails::Engine inherits all the functionality from Rails::Railtie and adds some more (Engine < Railtie source code [docs in the source are pretty good]).
Basically, railtie (== your class that inherits from Rails::Railtie) gives you all you need to interact with Rails app processes.
And engine (== your class that inherits from Rails::Engine) is railtie +

some initializers set (with help of initializer method): makes your engine's Rails app-like folder structure loadable into the real app, so that

engine will automatically load app/models, app/controllers, app/helpers into your real app, load routes from config/routes.rb, load locales from config/locales/*, and load tasks from lib/tasks/*.

You can see initializers set with this code:
require 'rails/all'
Rails::Railtie.initializers.map(&:name) #=> []
Rails::Engine.initializers.map(&:name)  #=> [:set_load_path, :set_autoload_paths, :add_routing_paths, :add_locales, :add_view_paths, :load_environment_config, :append_assets_path, :prepend_helpers_path, :load_config_initializers, :engines_blank_point]

some convenience methods, such as isolate_namespace.
Comment: You forgot to `map`: `Rails::Engine.initializers.map(&:name)`


GCC: cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in

Question: I am trying to build a C++ project in VS 2019 GUI and the GCC/G++ compiler.
My GCC/G++ profile is as follows:
Microsoft Windows [Version 10.0.19043.1288]
(c) Microsoft Corporation. All rights reserved.

C:\Users\pc>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=C:/Program\ Files\ (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/../libexec/gcc/i686-w64-mingw32/8.1.0/lto-wrapper.exe
Target: i686-w64-mingw32
Configured with: ../../../src/gcc-8.1.0/configure --host=i686-w64-mingw32 --build=i686-w64-mingw32 --target=i686-w64-mingw32 --prefix=/mingw32 --with-sysroot=/c/mingw810/i686-810-posix-dwarf-rt_v6-rev0/mingw32 --enable-shared --enable-static --disable-multilib --enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --disable-sjlj-exceptions --with-dwarf2 --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=i686 --with-tune=generic --with-libiconv --with-system-zlib --with-gmp=/c/mingw810/prerequisites/i686-w64-mingw32-static --with-mpfr=/c/mingw810/prerequisites/i686-w64-mingw32-static --with-mpc=/c/mingw810/prerequisites/i686-w64-mingw32-static --with-isl=/c/mingw810/prerequisites/i686-w64-mingw32-static --with-pkgversion='i686-posix-dwarf-rev0, Built by MinGW-W64 project' --with-bugurl=https://sourceforge.net/projects/mingw-w64 CFLAGS='-O2 -pipe -fno-ident -I/c/mingw810/i686-810-posix-dwarf-rt_v6-rev0/mingw32/opt/include -I/c/mingw810/prerequisites/i686-zlib-static/include -I/c/mingw810/prerequisites/i686-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/c/mingw810/i686-810-posix-dwarf-rt_v6-rev0/mingw32/opt/include -I/c/mingw810/prerequisites/i686-zlib-static/include -I/c/mingw810/prerequisites/i686-w64-mingw32-static/include' CPPFLAGS=' -I/c/mingw810/i686-810-posix-dwarf-rt_v6-rev0/mingw32/opt/include -I/c/mingw810/prerequisites/i686-zlib-static/include -I/c/mingw810/prerequisites/i686-w64-mingw32-static/include' LDFLAGS='-pipe -fno-ident -L/c/mingw810/i686-810-posix-dwarf-rt_v6-rev0/mingw32/opt/lib -L/c/mingw810/prerequisites/i686-zlib-static/lib -L/c/mingw810/prerequisites/i686-w64-mingw32-static/lib -Wl,--large-address-aware'
Thread model: posix
gcc version 8.1.0 (i686-posix-dwarf-rev0, Built by MinGW-W64 project)

C:\Users\pc>

I am getting the following errors:
>------ Rebuild All started: Project: mySolutionFolder, Configuration: Mingw64-Release ------
  [1/1] Cleaning all built files...
  Cleaning... 0 files.
  [1/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/hist.dir/apps/mySolutionFolder/hist.cc.obj -MF src\CMakeFiles\hist.dir\apps\mySolutionFolder\hist.cc.obj.d -o src/CMakeFiles/hist.dir/apps/mySolutionFolder/hist.cc.obj -c ../../../src/apps/mySolutionFolder/hist.cc
  FAILED: src/CMakeFiles/hist.dir/apps/mySolutionFolder/hist.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/hist.dir/apps/mySolutionFolder/hist.cc.obj -MF src\CMakeFiles\hist.dir\apps\mySolutionFolder\hist.cc.obj.d -o src/CMakeFiles/hist.dir/apps/mySolutionFolder/hist.cc.obj -c ../../../src/apps/mySolutionFolder/hist.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  [2/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/alignment/Target.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\alignment\Target.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/alignment/Target.cc.obj -c ../../../src/core/alignment/Target.cc
  FAILED: src/CMakeFiles/mySolutionFolder.dir/core/alignment/Target.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/alignment/Target.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\alignment\Target.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/alignment/Target.cc.obj -c ../../../src/core/alignment/Target.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  [3/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/seqc.dir/apps/mySolutionFolder/seqc.cc.obj -MF src\CMakeFiles\seqc.dir\apps\mySolutionFolder\seqc.cc.obj.d -o src/CMakeFiles/seqc.dir/apps/mySolutionFolder/seqc.cc.obj -c ../../../src/apps/mySolutionFolder/seqc.cc
  FAILED: src/CMakeFiles/seqc.dir/apps/mySolutionFolder/seqc.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/seqc.dir/apps/mySolutionFolder/seqc.cc.obj -MF src\CMakeFiles\seqc.dir\apps\mySolutionFolder\seqc.cc.obj.d -o src/CMakeFiles/seqc.dir/apps/mySolutionFolder/seqc.cc.obj -c ../../../src/apps/mySolutionFolder/seqc.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  [4/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/alignment/TMAlign.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\alignment\TMAlign.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/alignment/TMAlign.cc.obj -c ../../../src/core/alignment/TMAlign.cc
  FAILED: src/CMakeFiles/mySolutionFolder.dir/core/alignment/TMAlign.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/alignment/TMAlign.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\alignment\TMAlign.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/alignment/TMAlign.cc.obj -c ../../../src/core/alignment/TMAlign.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  [5/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderEnvironment.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\mySolutionFolderEnvironment.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderEnvironment.cc.obj -c ../../../src/core/mySolutionFolderEnvironment.cc
  FAILED: src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderEnvironment.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderEnvironment.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\mySolutionFolderEnvironment.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderEnvironment.cc.obj -c ../../../src/core/mySolutionFolderEnvironment.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  [6/795] C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderVersion.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\mySolutionFolderVersion.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderVersion.cc.obj -c ../../../src/core/mySolutionFolderVersion.cc
  FAILED: src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderVersion.cc.obj
  C:\PROGRA~2\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\g++.exe  -IC:/ProgramData/Miniconda3/Library/include -I"C:/Program Files (x86)/GnuWin32/bin" -I../../../src -Wall -O3 -pthread -std=c++0x  -m64     -DSQLITE3 -O3 -DNDEBUG -O2 -g -DNDEBUG -std=gnu++11 -MD -MT src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderVersion.cc.obj -MF src\CMakeFiles\mySolutionFolder.dir\core\mySolutionFolderVersion.cc.obj.d -o src/CMakeFiles/mySolutionFolder.dir/core/mySolutionFolderVersion.cc.obj -c ../../../src/core/mySolutionFolderVersion.cc
  cc1plus.exe: sorry, unimplemented: 64-bit mode not compiled in
  ninja: build stopped: subcommand failed.

Rebuild All failed.

How can I resolve this?
Answer: You should decide if you are compiling a 32-bit or a 64-bit program.
For a 32-bit program, remove -m64 from the command line, and any other arguments that look inappropriate.
For a 64-bit program, you need to find a GCC that targets x86_64.  The target triple very commonly used is x86_64-w64-mingw32.  Your current version of GCC is for the i686, which means 32-bit.
Comment: I am not compiling from command-line. I am using VS 2019 GUI.
Comment: There must be a settings window somewhere where you can decide what compiler to use or what options to pass to it.
Comment: @user366312 You are using VS 2019 GUI, but you are working on a CMake project with MinGW toolchain. Check your CMake files/settings to see your settings.


Apache poi method to write data to an existing workbook

Question: This is my class to read and write existing excel files. I have been calling these functions in the main class by passing the filePath and fileName.
   public class NewExcelFile {

    Workbook workbook;

    /******* Methods *******/
    // returns a workbook on giving the excel file's path and name
    public Workbook readExcel(String filePath, String fileName) {
        // Create object of File class to open xlsx file
        File file = new File(filePath + "\\" + fileName);
        // Create an object of FileInputStream class to read excel file
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println("Error: Unable to find " + fileName + " in "
                    + filePath);
            e.printStackTrace();
        }
        Workbook workbook = null;
        // Find the file extension by spliting file name in substring and
        // getting only extension name
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        // Check condition if the file is xlsx file
        if (fileExtensionName.equals(".xlsx")) {
            // If it is xlsx file then create object of XSSFWorkbook class
            try {
                workbook = new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // Check condition if the file is xls file
        else if (fileExtensionName.equals(".xls")) {
            // If it is xls file then create object of XSSFWorkbook class
            try {
                workbook = new HSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        this.workbook = workbook;
        return workbook;

    }

    public void writeExcel(String filePath, String fileName, String sheetName,
            String dataToWrite, int rowno) {

        System.out.println("WriteExcel" + filePath + " " + fileName + " "
                + sheetName + " " + dataToWrite + " " + rowno);

        Workbook newWorkbook = readExcel(filePath, fileName);
        Sheet sheet = newWorkbook.getSheet(sheetName);
        System.out.println("Sheet: " + sheet.getSheetName());

        Cell resultcell;

        ******resultcell = sheet.getRow(rowno).createCell(8);
        resultcell.setCellType(Cell.CELL_TYPE_STRING);
        resultcell.setCellValue(dataToWrite);

        CellStyle style = workbook.createCellStyle();
        if (dataToWrite == "P") {
            style.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
            style.setFillPattern(CellStyle.ALIGN_FILL);
            resultcell.setCellStyle(style);
        } else if (dataToWrite == "F") {
            style.setFillBackgroundColor(IndexedColors.RED.getIndex());
            style.setFillPattern(CellStyle.ALIGN_FILL);
            resultcell.setCellStyle(style);
        }
        // Create an object of FileOutputStream class to create write data in
        // excel file
        File file = new File(filePath + "\\" + fileName);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        }

        // write data in the excel file and close output stream
        try {
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            System.out.println("Error in writing to file");
            e.printStackTrace();
        }

    }

When I get a workbook in the main using readExcel and call this function:
Row row = testScriptsSheet.getRow(24);

I get the correct row and am able to call all functions on this row.But for the exact same row in the exact same sheet in the writeExcel(), I get a null pointer exception(the line preceded by *** in the code above). getRow() gives me null here. What am I doing wrong here?
Also, should I keep workbook as a data member and domyNewExcelFile.workbook whenever I need it or keep it as a variable returned from the readExcel in the main class?
Also I was wondering what is happening now that I am not closing the inputStream at the end of the readExcel function. I get the same error whether I close the inputStream or not.
EDIT - Adding the main function
public class NewDriver {

public static void main(String[] args) {
    System.out.println("Starting the framework");
    // initialise the workbook
    NewExcelFile testExecution = new NewExcelFile();
    testExecution.readExcel(System.getProperty("user.dir") + "\\",
            "abc.xlsx");

    // initialise sheets of workbook
    Sheet testSuiteSheet = testExecution.workbook.getSheet("TestSuite");
    Sheet testScriptsSheet = testExecution.workbook.getSheet("TestCases");
    Row row = testScriptsSheet.getRow(24);//gives the correct row

    //calling writeExcel gives npe in that line

        }
    }
}

}
Comment: Is there a reason why you're not using `WorkbookFactory` for opening the workbook? Much much simpler than most of the code you've written. See the [POI quick guide](http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream) for an example
Comment: I was thrown this exception
Exception in thread "main" org.apache.poi.POIXMLException: java.io.IOException: Can't obtain the input stream from /docProps/app.xml
 at org.apache.poi.POIXMLDocument.getProperties(POIXMLDocument.java:148)
 at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:199)
 at NewNewExcelFile.writeExcel(NewNewExcelFile.java:79)
 at NewNewRunTestSteps.runCase(NewNewRunTestSteps.java:67)
 at NewNewRunTestSteps.runCase(NewNewRunTestSteps.java:27)
 at NewNewDriver.main(NewNewDriver.java:69)
Answer: From the docs the getRow(int) method:

Returns the logical row (not physical) 0-based. If you ask for a row
  that is not defined you get a null. This is to say row 4 represents
  the fifth row on a sheet.

So when a row is not defined, you must first create the row and then create the cell.
Comment: My 24 is 0-based. The row is also defined. I am able to read that exact row in the main using the workbook returned from the readExcel() function.
Comment: Are you sure that row has some data? If it does not, the row may not be defined.
Comment: It does. Printing it out on the main gives the xml also
Answer: As per my understanding it seems a conceptual error. Before calling WriteExcel() method, all the changes that you have made in main method are in buffer, not written in the excel sheet/workbook present in your harddisk. But in WriteExcel() method you are not passing the sheet or workbook you kept in buffer, but the address of the one physically present in the hard drive. So any change you have done in main function is not there, hence showing null pointer exception.
e.g. I have one workbook in say my D Drive, having value 1 in A0. Now I have programmatically made it 2 but not perform the write operation, and put the execution on hold. Meanwhile I went to my D drive and open the sheet there will be 1 not 2, as the updated value is in buffer, till I have perform write operation on that workbook.
Suggestion: Instead of passing the address of the workbook, why not you just pass the workbook you have used in main method.
UPDATE: Not the main method but readExcel(String filePath, String fileName) method actually.
Comment: I tried passing the workbook. Same error.
Also, I am not making any changes to the workbook in the main method. I was just reading the cells there. I was hoping to make writeExcel() to make the changes. What you says make sense, but then I don't know where to close the output and input streams.
Comment: Where are you got that `Row row = testScriptsSheet.getRow(24);` is throwing no error. If `Row row = newWorkbook.getSheet(sheetName).getRow(rowno);`throws exception it precisely means that sheet has not such row. Can you provide some more information on that. Also `readExcel()` seems directly picking the file from harddrive, not from any method, so any update will not reflect on that.
Comment: Added the main function


Is $f(t)=O(t^{\alpha})$ with $f$ continuous equivalent to $f(t)<K.t^{\alpha}$ a.e.?

Question: Let $f$ be a continuous real-valued function. Is $f(t)=O(t^{\alpha})$ equivalent to $f(t)\lt K.t^{\alpha}$ almost everywhere for some absolute positive constant $K$?
Answer: See the definition of Big O in https://en.wikipedia.org/wiki/Big_O_notation.
If by "almost everywhere" you mean that $\exists \: t_0$ such that for all $t\geq t_0$, and if you use $|f(t)|$ in stead of $f(t)$ then yes, it is correct.
Comment: That was actually the goal of my question. Thanks for clearing my doubts.
Comment: By "almost everywhere" I mean on $(t_{0},\infty)\setminus J$, where $J$ has Lebesgue measure $0$.
Comment: The function $f$ is continuous, so a measure $0$ set won't really make a meaningful difference. Up to increasing $K$, everything stays the same even if we remove $J$.
Answer: You need to specify if you are interested in the regime $t\to\infty$ or in $t\to0$.
Let me take the regime $t\to\infty$ as an example.
By definition, $f(t)=O(t^\alpha)$ as $t\to\infty$ means that
there is $T$ and $C$ such that
$$
|f(t)|\leq C|t|^\alpha
\qquad\textrm{whenever}\quad
|t|>T.
$$
So it does not need to be bounded almost everywhere. For example, the function $f(t)=\frac1t$ satisfies
$f(t)=O(1)$ as $t\to\infty$ but it blows up as $t\to0$.


Hard problem Relationship between CDH and Discrete Log

Question: In Number Theory,
Given the Diffie Hellman tuple (ga,gb,gab),
Will the given info be helpful in finding the discrete log of g ,i.e a or b?
Edit: That is can we use the solution of a Computational Diffie Hellman Problem to solve a Discrete Log. It is known that the converse is true!
Answer: A paper (note: SpringerLink, may require subscription) called "Separating Decision Diffie–Hellman from Computational Diffie–Hellman in Cryptographic Groups" published in '03 in the Journal of Cryptology has the following quote,
"In 1994 Maurer used a variation of the elliptic curve factoring method to give strong
evidence that CDH and DL are probably equivalent (see [9]). This approach was formalized
by Maurer and Wolf in [10] and finally appeared as a journal version in [11]." (where CDH = "Computational Diffie-Hellman" and DL = "Discrete Log")
Where the relevant citations are included below.
The paper goes on to say "Our goal in this paper is to merge the two approaches
and to construct a family of groups where CDH and DL are equivalent and presumably
hard". Assuming "equivalent" here means CD reduces to DL and DL reduces to CDH, this seem relevant.
So while this isn't a complete answer, the answer might be that at least occasionally we can use a CDH solution to solve a DLog. (Note: I haven't read this paper (yet) so I don't know that they actually met their goal, so this too might be wrong! If someone familiar can confirm whether or not they did, that would be great--I don't have the time or battery life right now to do so.)
I suspect [11] might shed more light on the issue, if you can find it (I haven't looked), and there may be more recent results.
"[9] U. Maurer. Towards the equivalence of breaking the Diffie–Hellman protocol and computing discrete
logarithms. In Advances in Cryptology -CRYPTO'94, volume 839 of Lecture Notes in Computer Science,
pages 271–281. Springer-Verlag, Berlin, 1994.
[10] U. Maurer and S. Wolf. Diffie–Hellman oracles. In N. Koblitz, editor, Advances in Cryptology - Crypto
'96, Volume 1109 of Lecture Notes in Computer Science, pages 268–282. Springer-Verlag, Berlin, 1996.
[11] U. Maurer and S. Wolf. The relationship between breaking the Diffie–Hellman protocol and computing
discrete logarithms. SIAM Journal on Computing, 28(5):1689–1721, 1999."
Comment: One comment, though: the problem as posed is not exactly CDH as I understand it; isn't CDH the problem of, given $g$, $g^a$ and $g^b$, find $g^{ab}$ without knowing $a$ and $b$? Here we are given $g^a$, $g^b$, and $g^{ab}$, and we are trying to find $a$ or $b$; (it's not clear to me if we are also given $g$ or not).
Comment: @Arturo, you're right in your description of CDH and that the first question posed is different from it, but the asker also asks "That is can we use the solution of a CDH Problem to solve a DL?" and this is what I've attempted to answer. The first question asked sounds a lot like does the discrete log problem reduce to the pairing inversion (PI) problem (under some specific constraints). Note that since CDH <= PI and PI <= DL, the questions are similar in that if DL <= PI and PI <= CDH, then DL <= CDH, and I've tried to skip the PI problem that is presented ("<"= means poly-time reduction)
Comment: Good points. Thanks for calling my attention to them. I do note that the OP says "That is...", which suggests a belief that the first question is the same as the second. It might be worth noting that the two are not quite equivalent.


Interpreting diagnostics and tests with time series data

Question: I am analysing the effect of monetary policy on output and inflation during crisis and after. Monetary policy is represented by exchange rate, interest rate, money supply and indicator of systemic risk + dummy financial crisis.
I´ve chosen multiple regression analyses with time series to assess differences. The response variable, being a time series, has autocorrelation and  heterogenity. I tried to change functional forms in different combination, I used logarithm and finally first differences for all responses. However, after performing these transformations, statistical tests still indicated that autocorrelation was present in these data.
My questions:

In model with the first differences, the Durbin-Watson test obtains the test statistic 2.6. I interpret this as do not reject the null hypothesis, these data are consistent with a lack of autocorrelation. Is this interpretation right? Please reference the image
.
I worry that the correlogram residuals looks strange. I don´t understand what this means. Please check the second image. Do somebody know what does that mean?
If I use Breusch-Godfrey test or Ljung Box test of autocorrelation with 20 lags, results show, that there is not autocorrelation, but when I use only 5 lags, the Ljung Box p-value is under 0.05 and we reject the null hypothesis at the 0.05 level and conclude there is autocorrelation.  Are these results contradicting one another? How do I choose which set of results to report?
Comment: Welcome to the site. Questions about software are not on-topic on CV, however, interpreting output and such is!
Answer: Not sure if the answer is still useful for you after all these months have passed, but here goes:
@1: In your first regression there is evidence of negative first-order autocorrelation, as indicated by "rho", by the Durbin-Watson stat, and by the first bars in the correlograms (which repeat the rho value, but give you confidence intervals as well). So no, I don't think your suggested interpretation is right.
I'm not entirely sure what you mean with "looks strange", the different signs of the autocorrelations at different lags are certainly allowed and possible. But you're right that simple processes such as an AR(1) wouldn't look like that. There could be MA terms in the residuals, but the most important thing is that you are estimating an equation without dynamics (only contemporaneous terms), and it is not too surprising that there is still serial correlation left.
@2: At face value the different test results indeed contradict each other. However, it is obvious that the autocorrelation at lags 1,2,3,5 is relevant. Your test up to lag 20 is mixing in a lot of insignificant partial effects and thus destroys the power of the test. This is an example of the old mantra that a non-rejection shouldn't be treated as an acceptance of the null hypothesis. It is true that in general it is not clear or easy which lag length should be tested. But in this case I think the case is pretty clearcut, namely that there is a problem with remaining autocorrelation.


How to remove audio permission for React-Native-Camera with RN CLI

Question: I'm developing an app for taking a profile image with the react-native-camera library.
That app does not have a recording feature. so it will not require audio permission. but that RNCamera asks for "record audio" permission. So how to remove that permission from my app.
Please help me, (Thanks in Advance).
I do not want to appear dialog box asking for audio recording rights as shown in Figure 1

Here is my code:
<RNCamera
        ref={cameraRef}
        type={cameraType}
        ratio={'4:3'}
        style={styles.preview}
        captureAudio={false}
        androidCameraPermissionOptions={{
          title: 'Permission to use camera',
          message: 'We need your permission to use your camera',
          buttonPositive: 'Ok',
          buttonNegative: 'Cancel',
        }}>
        <Box
          style={{
            width: '100%',
            paddingBottom: 50,
            flexDirection: 'row',
            justifyContent: 'space-around',
            alignItems: 'center',
          }}>
          <TouchableHighlight
            style={styles.clsButton}
            onPress={() => {
              close();
            }}>
            <Image source={assets.CloseIcon} style={styles.clsButtonIcon} />
          </TouchableHighlight>
          <TouchableHighlight
            style={styles.captureButton}
            onPress={captureHandle}>
            <Image source={assets.Camera} />
          </TouchableHighlight>
          <TouchableHighlight
            style={styles.switchButton}
            onPress={handleCameraSwitch}>
            <Image style={styles.switchIcon} source={assets.SwapCameraIcon} />
          </TouchableHighlight>
        </Box>
      </RNCamera> ```

Answer: You can pass: captureAudio={false} to the RNCamera component.
<RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={styles.preview}
          type={RNCamera.Constants.Type.back}
          flashMode={RNCamera.Constants.FlashMode.on}
          captureAudio={false}
          onGoogleVisionBarcodesDetected={({ barcodes }) => {
            console.warn(barcodes[0].data);
            if (!Utils.isNull(barcodes[0].data) & this.isCan) {
              this.runAction(barcodes[0].data)
            }
          }}
/>


direct sum to get a vector space

Question: Concerning  this question I asked (specifically my last comment), is it true that the formula  $$L\oplus \ker S =H$$
holds in a finite dimensional vector space, where $S:H\rightarrow H$ is linear operator, $(b_1,\ldots,b_k)$ is a basis of the image of $S$ and $L$ consists of the preimages of the $b_i$ under $S$, i.e. $l_j\in L$ is such that $l_j\in S^{-1} (b_j)$ ?
If we equip $H$ with an inner product, such that $S$ becomes selfadjoint, would then $$\text{im} S\oplus \ker S =H$$ hold ? (Or can you give a counterexample?)
Answer: If you have $S : H \to H$ a projection, i.e. a linear map such that $S^2 = S$ then it is true that
$$H = \ker S \oplus \textrm{im} S.$$
Answer: It is true that if $L$ is any complementary subspace of $\ker S$, a space that satisfies $H=L\oplus\ker S$, then $S$ maps $L$ isomorphically to $\mathrm{im}\,S$. But you cannot define $L$ as the set of the preimages of the $b_i$ under S, since that is not a vector space but rather the union of $k$ distinct cosets of $\ker S$ (for any preimage, adding anything in $\ker S$ to it gives a preimage of the same element, and these fill one such coset). What you probably intend is to choose a preimage for every $b_i$ and then take the subspace spanned by those vectors; this is indeed a way to obtain a complementary subspace of $\ker S$ (and every choice of preimages gives a different $L$).
As for the other statement, $S$ being selfadjoint is indeed sufficient to have $\text{im}\, S\oplus \ker S =H$, but it is nowhere near necessary. Indeed $S$ diagonalisable is also sufficient, the direct sum then being that of the sum of eigenspaces for all nonzero eigenvalues, and of $0$-eigenspace (kernel).
Answer: No, the statement does not hold: $L$ isn't a vector space. If you define $L$ to be the span of (some choice of) preimages of the $b_i$ it will be true: by rank-nullity all you need prove is that $L \cap \ker S = \{ 0 \}$, but this is clear because $f|_L$ is one-to-one.
Suppose $S$ is self-adjoint with respect to some inner product $(,)$.  Let $x \in \ker S \cap \operatorname{im} S$.  Then $(x,x) = (x,Sy)$ for some $y$, and by self-adjointness, $(x,Sy)=(Sx,y)=(0,y)=0$.  So $\ker S \cap \operatorname{im} S = \{0\}$.  It follows that $H = \ker S \oplus \operatorname{im} S$.
Comment: I understand, that this argument with selfadjointness also works in the infinite dimensional setting ?
Comment: it shows that $\ker S \cap \operatorname{im} S = \{0\}$ in the infinite-dimensional setting.

direct sum to get a vector space


Concatenar n caracteres de uma palavra digitada

Question: Quero fazer um programa na qual o usuário digite uma palavra qualquer e fique armazenada em um string, logo após é necessário armazenar essa mesma palavra em outra string só que na forma inversa, por exemplo se foi digitado "BRASIL" quero que retorne "LISARB". Consegui inverter as posições dos caracteres, no entanto não consigo concatenar os caracteres para que os mesmos sejam exibidos em uma linha só.
#include <stdio.h>
#include <string.h>

main()
{
char p[100], c, invertida;
int tam ,i;

printf ("\n Digite uma palavra: ");
gets (p);
tam = strlen(p);

for (i=tam -1 ; i>=0; i--)
{
    c = p[i];
    strcat (c,p[i]);
}
printf("\n %s", c);
}

Comment: Essa linha, `p[i] = p[i]`, não parece muito certa ou fazer sentido. Poderia rever o código que postou na pergunta?
Answer: Um método simples de você fazer isso é assim:
#include <stdio.h>
#include <string.h>

main()
{
    char p[100], c, invertida[100];
    int tam, i;

    printf ("\n Digite uma palavra: ");
    gets (p);
    tam = strlen(p);

    int count = 0;
    for (i=tam -1 ; i>=0; i--)
    {
        invertida[count] = p[i];
        count += 1;
    }
    // Finaliza String
    invertida[count] = '\0';
    printf("\n %s", invertida);
}

Enquanto percorre a string ao contrario você soma um contador para colocar o valor na string invertida.
Answer: Você pode user uma função em C responsável por inverter os caracteres, chamada strrev().
strrev
char *strrev(char *str);


Guice module provides singleton with two bindings?

Question: I'm very new to Guice (and I'm much more proficient in languages other than Java), but essentially what I want to do is edit some code to convert something like this:
public class AutomobileModule extends AbstractModule {
   @Provides
   @Singleton
   Automobile getCar(final AutomobileFactory automobileFactory) {
      return automobileFactory.createAutomobile("Car");
   }

   @Provides
   @Singleton
   AutomobileFactory getAutomobileFactory(final AutomobileConfiguration automobileConfiguration) {
      return new AutomobileFactory(automobileConfiguration);
   }

   @Provides
   @Singleton
   AutomobileConfiguration getAutomobileConfiguration() {
      return new AutomobileConfiguration();
   }
}

by adding
public class AutomobileModule extends AbstractModule {
   <...SNIP...>

   @Provides
   @Singleton
   Automobile getTruck(final AutomobileFactory automobileFactory) {
      return automobileFactory.createAutomobile("Truck");
   }
}

However, if I try this, I get "A binding to... was already configured at" error. So what's the correct way to share dependencies this way? Or do people usually just create multiple factories, etc, in cases like this.
Answer: As you configured it, Guice can only decide by the type which object to inject and you have two methods that provide Automobile. The methods name is irrelevant.
You will have to specify which method provides which kind of Automobile, you could do this by adding annotations @Named("Car") and @Named("Truck") to your methods.
To get exactly the right kind of Automobile injected, you have to specify that same annotation (@Named...) also at the place where you get it injected.
Your module would then look something like this:
public class AutomobileModule extends AbstractModule {
   @Provides
   @Singleton
   @Named("Car")
   Automobile getCar(final AutomobileFactory automobileFactory) {
      return automobileFactory.createAutomobile("Car");
   }

   @Provides
   @Singleton
   AutomobileFactory getAutomobileFactory(final AutomobileConfiguration automobileConfiguration) {
      return new AutomobileFactory(automobileConfiguration);
   }

   @Provides
   @Singleton
   AutomobileConfiguration getAutomobileConfiguration() {
      return new AutomobileConfiguration();
   }

   @Provides
   @Singleton
   @Named("Truck")
   Automobile getTruck(final AutomobileFactory automobileFactory) {
      return automobileFactory.createAutomobile("Truck");
   }
}

See the official user guide  for more information and this accepted SO answer (together with the question) for a better example than in the user guide.
Comment: Perfect. Simple enough, thanks so much for the explanation!


pod spec lint fails

Question: I made a Swift framework I want to make a CocoaPods for it.
I've followed all the instructions:

created podspec file, added version tag, pushed it to github
When I run pod lib lint it passes but when I run pod spec lint it fails.

Here is my podspec file
Pod::Spec.new do |s|

  s.name         = "Seru"
  s.version      = "0.0.3"
  s.summary      = "Seru is Simple Core Data stack"
  s.description  = <<-DESC
                   Seru is Swift framework for working wit Core Data. It setup your core data stack and
                   gives you nica actions to work with it
                   DESC

  s.homepage     = "https://github.com/kostiakoval/Seru"
  s.license      = { :type => "MIT", :file => "LICENSE" }
  s.author             = { "Kostiantyn Koval" => "email@example.com" }
  s.social_media_url   = "http://twitter.com/kostiakoval"

  s.platform     = :ios, "8.0"
  s.source       = { :git => "https://github.com/kostiakoval/Seru.git", :tag => s.version }

  s.source_files  = "Seru/Source", "Seru/Source/**/*.{swift}"
  s.requires_arc = true
  s.ios.vendored_frameworks = 'Carthage/Build/iOS/Sweet.framework'

end

It has external framework dependency. I'm guessing this is a problem.
When I do pod speck lint, it says that I can't find that external framework
Answer: The problem was that CocoaPods don't include vendored_frameworks folder.
To fix it is to specify that this folder should be included to a CocoaPod by using preserve_paths.
s.preserve_paths = 'Carthage/Build/iOS/Sweet.framework'

pod spec lint fails


Sistema de login com sessoes

Question: EM UM SISTEMA DE LOGIN COM PHP QUAL VARIÁVEIS DEVO ARMAZENAR NAS SESSÕES? email e senha ou só o id do usuário?
Answer: O coreto é armazenar o email/username e id, ou apenas o "id" já que com o "id" podes obter outros dados do utilizador. Não é uma boa ideia armazenar password na sessão, 1º por questão de segurança, 2ª porque não vais precisar do password para efetuar outras operações alem do login.

Sistema de login com sessoes


Maclaurin's series for $\tan(x+x^2)$

Question: I would like to find the Maclaurin's series for $\tan(x+x^2)$ stopped at $x_0^3$.
I tried with:
$$\tan(x+x^2)=1+\frac{1+2x_0}{\cos^2(x_0+x_0^2)}x+....,$$ but it seems like the derivation gets more complicated. I was wondering if there was a simpler way to solve the Maclaurin series. I was thinking about putting $t=x+x^2$, but it looks like wrong (why?).
Update:
I know that MacLaurin's expansion for tan(x): $$T(x) = x + \frac {1}{3}x^{3} + \frac { 2 } { 15 } x ^ { 5 } + \frac { 17 } { 315 } x ^ { 7 } + \ldots$$ But according to Mathematica, there should be  a $x^2$ for the MacLaurin series for $tan(x+x^2)$, which I couldn't understand.
Comment: Setting $t=x+x^2$ in the series for $\tan{t}$ will work fine.  Why wouldn't it?
Comment: If all you care about is the series and not its derivation, why not use Mathematica? I doubt there is any special trick for this.
Comment: Could you show me an example? Do you mean substituting $x_0$ with 0 and solving the derivatives?
Comment: @Hamed Because it is part of a question of my past exams, and we are not allowed to use Mathematica.
Comment: Apparently, the expansion is around an arbitrary point $x_0$ not zero.
Comment: @saulspatz Can you show me an example? I have updated my answer accordingly.
Answer: Just substitute $x+x^2$ for $x$ in your formula of $T(x):$
$$T(x+x^2)=(x+x^2)+\frac13(x+x^2)^3+\cdots$$
Now you just have to expand and rearrange the terms.  Since you only need powers up through $x^3$, there no need to be concerned with the higher-degree terms in $T(x)$
Comment: Now I get it. Apparently, I had a lot of confusion in my mind. Thank you!

Maclaurin's series for $\tan(x+x^2)$


Inferring the number of topics for gensim's LDA - perplexity, CM, AIC, and BIC

Question: I am confused as to how to interpret the LDA's perplexity fluctuations with different numbers of topics, in the endeavour of determining the best number of topics. Additionally, I would like to know how to implement AIC/BIC with gensim LDA models.
I am importing the 20 newsgroups dataset from sklearn:
from sklearn.datasets import fetch_20newsgroups;

Metadata were removed as per sklearn recommendation, and the data were split to test and train using sklearn also (subset parameter).
I trained 35 LDA models with different values for k,  the number of topics, ranging from 1 to 100, using the train subset of the data. Afterwards, I estimated the per-word perplexity of the models using gensim's multicore LDA log_perplexity function, using the test held-out corpus::
DLM_testCorpusBoW = [DLM_fullDict.doc2bow(tstD) for tstD in testData];
PerWordPP = modelLDA.log_perplexity(DLM_testCorpusBoW);

Eventually, keeping in mind that true k is 20 for the used dataset, perplexity figures were startling negative ones:

Additionally, I implemented Topic Coherence Models, and the results weren't very informative, with a lot of fluctuation:

Having negative perplexity apparently is due to infinitesimal probabilities being converted to the log scale automatically by Gensim, but even though a lower perplexity is desired, the lower bound value denotes deterioration (according to this), so the lower bound value of perplexity is deteriorating with a larger number of topics in my figures, yet we expect the perplexity to improve with a bigger k (here).
So, do the figures seem logical?
And I would like to implement AIC and BIC as well, but for that I need the SSE of the models, how can I get it using gensim? or are these measures implemented somehow?
Answer: Counter intuitively, it appears that the log_perplexity function doesn't output a $perplexity$ after all (the documentation of the function wasn't clear enough for me personally), but a likelihood $bound$ which must be utilised in the perplexity's lower bound equation thus (Taken from this paper - Online Learning for Latent Dirichlet Allocation by Hoffman, Blei and Bach):
$$
perplexity (n^{test}, \lambda, \alpha) \leq exp\{
-(\sum_i{
\mathbb{E}_q [log_p(n_i^{test}, \theta_i, z_i | \alpha, \beta)]
-
\mathbb{E}_q[log_q(\theta_i, z_i)])
/
(\sum_{i,w}{n_{iw}^{test}})
}
\}
$$
Viz.,
$$
perplexity (n^{test}, \lambda, \alpha) \leq e^{- bound}
$$
Some people like to use $2$ instead of $e$ in the equation above.
For calculating $AIC$ and $BIC$, one usually needs the Bayesian likelihood of the model, not necessarily the $SSE$, especially in a topic modelling environment.
Finally, as for the $U Mass$ coherence measure, to the best of my knowledge, it hasn't been used in a model selection scenario with LDA yet, but the sharp dip I got at $k=20$ (the proper number of topics according to the 20 newsgroups dataset) is encouraging. However, topic coherence measures should be close to zero optimally, so that sharp dip isn't an improvement, rather a deterioration in the coherence (the meaningfulness or interpretability) of topics.


Ansible - can't refer to module parameter value

Question: This is my playbook
---
- hosts: mytestserver
  become: true
  become_method: sudo
  gather_facts: true

  vars:
  # To get vgname and lvname from ansible_mounts's device
    mt: "{{ MT }}" #Extravariable
    disp_pth: "{{ item['device'] }}"
    disp_tmp: "{{ disp_pth | basename }}"
    DISP: "{{ disp_tmp.split('-') }}"
    VGname: "{{ DISP.0 }}"
    LVname1: "{{ DISP.1 }}"
    DISPP2: "{{ DISP.3|default('') }}"
    LVname2: "{{ DISP.1 }}-{{ DISPP2 }}"
    LVname: "{{ LVname2 if (disp_tmp | regex_search('--')) else LVname1 }}"

  tasks:
    - name: Get filesystem values
      lvol:
        vg: "{{ VGname }}"
        lv: "{{ LVname }}"
      with_items: "{{ ansible_mounts }}"
      when: item.mount == MT
      register: myfs

    - debug:
        var: myfs

When I excecute it:
$ ansible-playbook -i proyects/Inventory/awx_hosts -l mytestserver getlvmfacts.yml -e MT=/DATA

I get the values:
PLAY [mytestserver] ******************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************************
ok: [mytestserver]

TASK [Get filesystem values] ************************************************************************************************************************************************************************************************************
ok: [mytestserver] => (item={'block_used': 21620, 'uuid': '7fef92b8-8157-43d1-92b4-525a56fa33f8', 'size_total': 1056858112, 'block_total': 258022, 'mount': '/DATA', 'block_available': 236402, 'size_available': 968302592, 'fstype': 'ext4', 'inode_total': 65536, 'options': 'rw', 'device': '/dev/mapper/vgAPP-DATA', 'inode_used': 11, 'block_size': 4096, 'inode_available': 65525})

TASK [debug] ****************************************************************************************************************************************************************************************************************************
ok: [mytestserver] => {
    "myfs": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": false,
                "item": {
                    "block_available": 414770,
                    "block_size": 4096,
                    "block_total": 516052,
                    "block_used": 101282,
                    "device": "/dev/mapper/vg00-lvol01",
                    "fstype": "ext3",
                    "inode_available": 124211,
                    "inode_total": 131072,
                    "inode_used": 6861,
                    "mount": "/",
                    "options": "rw",
                    "size_available": 1698897920,
                    "size_total": 2113748992,
                    "uuid": "7df9171b-c31f-434f-94c5-344d02775e89"
                },
                "skip_reason": "Conditional result was False",
                "skipped": true
            },
            {
                "ansible_loop_var": "item",
                "changed": false,
                "item": {
                    "block_available": 1037688,
                    "block_size": 4096,
                    "block_total": 1046016,
                    "block_used": 8328,
                    "device": "/dev/mapper/vgDATA-BASET--DATA1",
                    "fstype": "xfs",
                    "inode_available": 4194301,
                    "inode_total": 4194304,
                    "inode_used": 3,
                    "mount": "/BASET/DATA1",
                    "options": "rw",
                    "size_available": 4250370048,
                    "size_total": 4284481536,
                    "uuid": "91689e9b-552c-4f0e-b0ec-0d3d25154a72"
                },
                "skip_reason": "Conditional result was False",
                "skipped": true
            },
            {
                "ansible_loop_var": "item",
                "changed": false,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "active": true,
                        "force": false,
                        "lv": "DATA",
                        "opts": null,
                        "pvs": null,
                        "resizefs": false,
                        "shrink": true,
                        "size": null,
                        "snapshot": null,
                        "state": "present",
                        "thinpool": null,
                        "vg": "vgAPP"
                    }
                },
                "item": {
                    "block_available": 236402,
                    "block_size": 4096,
                    "block_total": 258022,
                    "block_used": 21620,
                    "device": "/dev/mapper/vgAPP-DATA",
                    "fstype": "ext4",
                    "inode_available": 65525,
                    "inode_total": 65536,
                    "inode_used": 11,
                    "mount": "/DATA",
                    "options": "rw",
                    "size_available": 968302592,
                    "size_total": 1056858112,
                    "uuid": "7fef92b8-8157-43d1-92b4-525a56fa33f8"
                },
                "lv": "DATA",
                "size": 1024.0,
                "vg": "vgAPP"
            },
            {
                "ansible_loop_var": "item",
                "changed": false,
                "item": {
                    "block_available": 472667,
                    "block_size": 4096,
                    "block_total": 516052,
                    "block_used": 43385,
                    "device": "/dev/mapper/vg00-lvol07",
                    "fstype": "ext3",
                    "inode_available": 131061,
                    "inode_total": 131072,
                    "inode_used": 11,
                    "mount": "/tivoli",
                    "options": "rw",
                    "size_available": 1936044032,
                    "size_total": 2113748992,
                    "uuid": "2310d046-eaad-4419-a94b-197c2c56502c"
                },
                "skip_reason": "Conditional result was False",
                "skipped": true
            }
        ]
    }
}

To the end of the matched mount point (/DATA) there are three filesystems parameters:
"lv": "DATA",
"size": 1024.0,
"vg": "vgAPP"

The question is: How can I refer to this parameters?
I have tried using myfs.lv but don't work and varius more ways.
I think this is because those aren't inside 'item'
Desired:
using somthing like "myfs.lv" and get "DATA"
hope you can help.
Thanks in advance!
Answer: If you refer to the structure that debug outputs you can see that myfs.lv is clearly wrong, because the only keys at the top level are msg, changed, and results.
When you run a task in a loop, the results are stored as a list under the results key of the registered variable. To access that particular result, you would do something like myfs.results.2.lv.
Hardcoding an index like this is generally not what you want, though, so you should instead do something to select the result you want. (myfs.results | reject('skipped') | list | first).lv would retrieve lv for the first non-skipped result.
Or, of course, you could make this easier on yourself by not looping in the first task:
  tasks:
    - name: Get filesystem values
      lvol:
        vg: "{{ mount_dev_split.0 }}"
        lv: "{{ mount_dev_split.1 ~ lv_name_suffix }}"
      vars:
        mount_dev: "{{ (ansible_facts.mounts | selectattr('mount', 'equalto', MT) | list).0.device }}"
        mount_dev_split: "{{ (mount_dev | basename).split('-') }}"
        lv_name_suffix: "{{ ('-' ~ mount_dev_split.3 | default('')) if '--' in mount_dev else '' }}"
      register: myfs

    - debug:
        msg: "{{ myfs.lv }}"

Comment: Well. First of all thank you very much!
Comment: Well. First of all thank you very much! You made it much easier this way. I'm new to Ansible and there're elements I don't handle. I appreciate your help. Thanks again!


Differentiate $\sqrt{x}^{\sqrt{x}e^\sqrt{x}}$

Question: Differentiate $$\ln (\sqrt{x}^{\sqrt{x}e^\sqrt{x}})$$
Answer: Let,
$$y = \sqrt{x}^{\sqrt{x}e^\sqrt{x}}$$
Taking log on both sides,
$$\log y = \log \sqrt{x}^{\sqrt{x}e^\sqrt{x}}$$
$$\log y = \sqrt{x}e^\sqrt{x} \log \sqrt{x}$$
Now differentiate using product rule.
Comment: Derivative of (1.2.3) = 1.2.derivative of 3 + 1.3.derivative of 2 + 2.3.derivative of 1
Answer: hopefully this will help:
<code>http://www.wolframalpha.com/input/?i=D%5Bsqrt(x)%5E(sqrt(x)*e%5E(sqrt(x))),x%5D
</code>
calculated solution: Solution from Wolfram Alpha
Comment: This should be a comment (unless posted by Wolfram Alpha itself).
Answer: In the same spirit as Kanwaljit Singh's answer, let $$y = \sqrt{x}^{\sqrt{x}\,e^\sqrt{x}}$$ and first change variable $x=t^2$ to get $$y = t^{t\,e^t}$$ Take logarithms $$\log(y)=t\,e^t \log(t)\implies \frac{y'}y=\left(t\,e^t \log(t)\right)'$$ Differentiate with respect to $t$ and, later, use $$\frac{dy}{dx}=\frac{dy}{dt}\times\frac{dt}{dx}$$


Trouble understanding elementary embedding proofs

Question: Here are two pretty standard results about elementary embeddings that I don't understand.
(1) Let $\pi:V \to M$ be a non-trivial elementary embedding with $M$ a transitive class. Let $crit(\pi)=\kappa$. Let $C \subset \kappa$ be a club in $\kappa$. Then, we know $\pi(C)$ is a club in $\pi(\kappa)$ by elementarity of $\pi$. Also, since $\pi(\alpha)=\alpha$ for all $\alpha < \kappa$, $\pi(C) \cap \kappa = C$. So, $\pi(C) \cap \kappa$ is unbounded in $\kappa$, so $\kappa \in \pi (C)$ since it is closed.
My problem is understanding what's going on when $\kappa \in \pi (C)$. If this is the case doesn't there have to exist some $\alpha \in C$ such that $\pi(\alpha)=\kappa$, which there isn't? Something similar happens in (2):
(2) The following is an initial part of a proof of Kunen's theorem that there is no non-trivial elementary embedding $\pi:V \to V$. Let $\kappa_0 = crit(\pi)$. Recursively define $\kappa_{n+1}=\pi(\kappa_{n})$. Set $\lambda = \sup_{n<\omega}\kappa_n$. Let $S=\{\alpha < \lambda^+: cf(\alpha)=\omega\}$. S is stationary, so take it apart into $\kappa_0$ disjoint stationary subsets $S_i , i<\kappa_0$. Then, the proof goes, set $(T_i: i<\kappa_1)=\pi((S_i: i<\kappa_0))$. I don't see how this last part is possible. Where does, for example, $T_{\kappa_0}$ come from if it's not in the range of $\pi$? I'm not even sure what $T_{\kappa_0}$ is.
Answer: For the first question, the elementary embedding is "jumping" at $\kappa$. Namely, the universe of set theory is the same all the way below $\kappa$, and then it get stretched up, somehow. This is the meaning that $\pi(\kappa)>\kappa$.
But at the same time, $M$ is a transitive class. So if $\pi(\kappa)>\kappa$, then $\kappa\in M$.
The key, I think, for understanding this (and it took me several years to grasp that fine point), is that the elements of the ultrapowers are really functions from $\kappa$ to $V$. The embedding just maps $x$ to a constant function $c_x$. To say that $\kappa$ is not in $\pi(\alpha)$ is to say that it is not represented by a constant function.
So, what does that have to do with anything? Well, $\kappa$ is a club in $\kappa$. So the question why $\kappa\in\pi(C)$ is a generalization for why $\kappa<\pi(\kappa)$. Since $\pi''\kappa\neq\pi(\kappa)$, it is natural that $\pi''C\neq\pi(C)$. $C$ gets "stretched" up.
For the second question, Think about $\vec S$ as a function from $\kappa_0$ to stationary subsets of $\lambda$, then $\pi(\vec S)$ is a function from $\pi(\kappa_0)=\kappa_1$ to stationary subsets of $\pi(\lambda)=\lambda$.
This is again the same issue, the function does not operate pointwise, it moves things around, and if need be, it gives us new information. It's just something to get used to, I suppose.
Comment: Is there a problem with the answer that is merits a downvote?
Comment: I upvoted, the answer helped. It is just so strange to me that functions don't operate pointwise... I guess it's something to get used to. Can anything concrete be said of $T_{\kappa_0}$, or in general $T_\alpha$ where $\alpha$ is not in the range of $\pi$? I don't even know what they are. If I wanted to know what elements in M are elements of $T_\alpha$, what would I do?
Comment: Mmm... that's a great question. I'm not sure what to tell you.


how is it beneficial to Derive a formula for the maximum likelihood and apply it to a dataset

Question: What is the benefit of applying the following on the data set?
If I have a data set that is distributed as follows:

after calculating the Maximum of logarithm of the likelihood function and applying it to the data according to the equation:

The distribution is as follows:
Comment: That gives you a *probability density*, not a dataset!
Comment: Please explain how you computed the "New Values of X."
Comment: I calculated labmda as the reciprocal of the mean of the original dataset. Then I applied the f(x) rule shown above to every element of the dataset.
Answer: Well, the OP hit by accident on one more special property of the Exponential distribution.
The OP's second diagram is the empirical frequency function  of the random variable
$$Y = f_X(X),\;\;\; X \sim \text{Exp}(\lambda)$$
And it does look like the empirical frequency from a Uniform distribution, right? But, we get the Uniform if we consider the random variable $Z = F_X(X)$, where $F_X$ is the distribution function, not the density...
Well, this is the special property of the Exponential distribution. Consider the random variable $Y= f_X(X)$. To apply the change-of-variable rule, we have $X = f^{-1}(Y)$ and
$$f_Y(y) = \left|\frac{df^{-1}(y)}{dy}\right|\cdot f_X(f_X^{-1}(y))$$
Now by the inverse function theorem,
$$\left|\frac{df^{-1}(y)}{dy}\right| = \frac 1 {\left|f'_X(f^{-1}(y))\right|}$$
while also $$f_X(f_X^{-1}(y)) = y$$ so
$$f_Y(y) = \frac {y}{\left|f'_X(f^{-1}(y))\right|}$$
Now, whenever $|f'| = f$ we get
$$f_Y(y) = \frac {y}{y} = 1,\;\;\; \implies Y \sim U(0,1)$$
i.e. $Y$ is a Uniform $(0,1)$, as if we have considered the $Z = F_X(X)$ rv. And when do we get $|f'| = f$? When $f(x) = e^{-x}$, i.e. when the $X$ variable follows an Exponential distribution with rate/scale parameter equal to unity.
When $X \sim \text{Exp}(\lambda),\;\; \lambda \neq 1$we get $|f'| = \lambda f$, and the result generalizes to
$$f_Y(y) = \frac {y}{\lambda y} = \frac 1 {\lambda},\;\;\; \implies Y \sim U(0,\lambda)$$


How to show that $A :=\{(x,y) \in S^2 \times S^2 \mid \langle x,y\rangle =0\}$ is homeomorphic to $SO(3)$

Question: How to show that $A :=\{(x,y) \in S^2 \times S^2 \mid \langle x,y\rangle=0\}$ is homeomorphic to $\operatorname{SO}(3)$? Does proving this require that I know the specific form of the matrices in $\operatorname{SO}(3)$?
Comment: Or maybe you really mean $\{(x,y)\in S^2\times S^2: \langle x,y\rangle = 0\}$. This will have dimension $3$ (as does $SO(3)$), whereas, however we interpret your set, it has dimension $2$.
Comment: I may be missing something, but what does it mean to take the dot product of an element of $\mathbb{S}^1\subseteq\mathbb{R}^2$ and an element of $\mathbb{S}^2\subseteq\mathbb{R}^3$? What does $\langle\cdot,\cdot\rangle$ stand for?
Comment: What does $\langle x,y \rangle=0$ mean? Should we think of $S^1$ and $S^2$ as being embedded in $\Bbb R^3$?
Comment: @PedroTamaroff That makes sense!
Comment: I am so sorry, it should be $S^2 \times S^2$
Answer: Hint: Take $e_1,e_2,e_3$ to be standard basis of ${\bf R}^3$. If $A\in \operatorname{SO}(3)$, then $A(e_1)$ can be any unit vector, $A(e_2)$ can be any unit vector orthogonal to $A(e_1)$, and $A(e_3)$ is uniquely determined by $A(e_1)$ and $A(e_2)$.
All you really need is the definition of the special orthogonal group and elementary facts about inner product spaces. There is no need to use matrices at all.
Comment: How is this related to $S^2 \times S^2$
Comment: @Adam: $S^2$ is the space of unit vectors in ${\bf R}^3$.
Comment: I see. One more question, suppose that I have two orthogonal vectors $a,b$ such that $|a|=|b| = 1$ and $a,b$ are orthogonal. How would I show that there is a unique unit vector $c$ such that is orthogoal to both $a$ and $b$ and the determinant of the matrix formed by $a,b,c$ as row vectors is 1. Is it possible to write $c$ in terms of $a$ and $b$?
Comment: @Adam: There are two unit vectors $c$ (in a three dimensional space) orthogonal to $a$ and $b$ simultaneously, and they are opposite to one another. The difference between them is the orientation of the  triple $(a,b,c)$ (flipping the sign of one vector flips the orientation). But is you use the *special* orthogonal group, the orientation is fixed. So in terms of $a$ and $b$, $c$ is the vector orthogonal to $a$ and $b$ such that $(a,b,c)$ has the same orientation as $(e_1,e_2,e_3)$.
Comment: Yes, but in order to prove that it is a homeomorphism, I need to write down $c$ explicitly. Is there an explicit formula for $c$?
Comment: @Adam: You could write it in terms of determinants/cross products, but you really don't need it. There is no need to use any coordinates whatsoever.


Jenkinsfile one type of parameter instead of two type, convert choice into string or string into choice

Question: I'm using two parameters one is choice (ID) and other one string (NID) but values are same. Requirement is to use only parameter either choice or string. Is it possible to convert choice parameter into string or string to choice parameter?
so that i can use one parameter and one deploy function.
def deploy1(env) {
step([$class: 'UCDeployPublisher',
siteName: siteName,
deploy: [
$class: 'com.urbancode.jenkins.plugins.ucdeploy.DeployHelper$DeployBlock',
deployApp: appName,
deployEnv: 'DEV',
deployVersions: "${compName}:${version}",
deployProc: simpleDeploy,
deployOnlyChanged: false,
deployReqProps: "ID=${params.ID}" ===> string paramater
]])

def deploy2(env) {
step([$class: 'UCDeployPublisher',
siteName: siteName,
deploy: [
$class: 'com.urbancode.jenkins.plugins.ucdeploy.DeployHelper$DeployBlock',
deployApp: appName,
deployEnv: 'DEV',
deployVersions: "${compName}:${version}",
deployProc: simpleDeploy,
deployOnlyChanged: false,
deployReqProps: "ID=${params.NID}"  ===> Needs choice paramater
]])

parameters {
choice(
name: 'ID',
choices: [ '8922', '9292', '3220' ]
 )

string(
name: 'NID',
defaultvalue: '8922,9292,3220'
)

stage (DEV') {
steps {
    script {
     if (params.ENVIRONMENT == "dev"){
         deploy1('devl') ===> this will call my deploy function
      }
     }
    }
  }

Answer: Yes you can convert the string parameter to an array by just using split:
Below is an example :
// Define list which would contain all servers in an array
def ID= []
pipeline {
    agent none
     parameters
    {
        // Adding below as example string which is passed from paramters . this can be changed based on your need
        // Example: Pass NID list as , separated string in your project. This can be changed
        string(name: 'NID', defaultValue:'8922,9292,3220', description: 'Enter , separated NID values in your project e.g. 8922,9292,3220')
    }
    stages {
        stage('DEV') {
            agent any
            steps {

                script
                {
                    // Update ID list
                    ID= params.NID.split(",")
                    // You can loop thorugh the ID list
                    for (myid in ID)
                    {
                        println ("ID is : ${myid}")
                    }
                }
            }
        }
    }
}