Weird number appearing on Header image in IE and edge browser works fine on other browsers

Question: WP site header has a weird number over header image when accessed in Internet explorer and Edge, the same page works fine in other browsers. tried resizing, and also using static image, same issue.
Screenshot taken from IE and chrome
Answer: That appears to be a place where you can place a banner. 728x90 is a standard banner size.
Comment: I tried without header image and I still get the 728x90 when accessing the page using IE or Edge
Comment: It's probably a widget in your theme, or it is built into your template.
Comment: Hold on. If you are on free hosting, that banner may be a banner inserted by your free hosting provider.
Comment: it's a premium hosting, and the issue is limited to IE and Edge.


Calculating the Confidence Interval

Question:
It is found that in a random sample of 100 Science students, there are 48 studying statistics . To test whether the true proportion of students in statistics is 50% or not, suitable null and alternative hypotheses are:
(a) H0 :p=0.48;H1 :p̸=0.48 (b) H0 :p=0.5;H1 :p>0.5 (c) H0 :p=0.5;H1 :p<0.5 (d) H0 :p=0.5;H1 :p=0.48 (e) H0 :p=0.5;H1 :p̸=0.5
Find a 95% Confidence Interval for p in Q1.

I have determined the answer to Q 1), which I believe is e).
For question 2), I have been told the CI= estimator +/- (table value)(Standard error). The estimator is 0.48, and I have found the SE to be 0.05. However, I am unsure about how to calculate the "table value".
Thank you.
Answer: You are correct to use $H_0: p = .5$ versus $H_1: p \ne .5.$ for
your hypothesis testing.
In the US until several years ago, the traditional 95% ci for $p$ is to use the point estimate $\hat p = X/n = 48/100$. The standard error of $\hat p$ is $\sqrt{p(1-p)/n},$ but
because you don't know $p$, the traditional method is to estimate it
by plugging in $\hat p$ for $p$. Thus the traditional formula
for the 95% CI is
$$\hat p \pm 1.96\sqrt{\frac{\hat p(1-\hat p)}{n}},$$
which computes to $(0.382, 0.578)$. This method uses the
normal approximation to the binomial distribution, so 1.96
is the 'table value' you're looking for.
However, this method has two sources of error: (a) using the
normal approximation to the binomial distribution, and
(b) estimating the standard error. Computational evidence
is that the traditional method often does not actually
have the 'promised' 95% coverage.
Much of the error due to (b) can be eliminated by
using $\tilde n = n+2$ instead of $n$, and $\tilde p = (X+2)/\tilde n = 50/104$ instead of $\hat p.$ The resulting adjusted interval, due to Agresti, is $(0.385, 0.577)$. (In your particular
example, the adjustment is small.)
The Wilson interval is also more accurate than the traditional one.
You can google that. For the 95% confidence level, it is not
much different from the more easily computed Agresti interval.
The Wilson interval has been standard for many years in parts
of Europe.
All three intervals cover $p = .5$, so there is no reason to
doubt that the true percentage of statistics majors is near 50%.

Calculating the Confidence Interval


Apache Reverse Proxy IIS Streaming File

Question: We recently setup an apache reverse proxy with IIS sitting behind it. All of our apps work fine except for one.
In one app we will prepare and stream a PDF file to the user with the follow example code:
Response.Clear();
Response.ContentType = "binary/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length);
Response.OutputStream.Write(downloadBytes, 0, downloadBytes.Length);
Response.End();

The app will seem to hang and never stream the PDF. The app works fine with no proxy. And also if I take a pdf of the same size and store it on the server's file systems and then download from that directory it works fine. It seems to only have a problem when we try to stream using Response.
I suspected the connection wasn't being kept alive while the PDF generated (it takes about 5 to 7 seconds) but I have adjust the timeout and had no luck.
Here is my apache proxy config.
<VirtualHost *:443>

<Proxy *>

Order deny,allow
Allow from all

SSLEngine on
SSLCertificateFile C:/certs/example.crt
SSLCertificateKeyFile c:/certs/example.key
ServerName www.example.com

ProxyVia On
ProxyPass / http://127.0.0.1:5000/ timeout=360
ProxyPassReverse / http://127.0.0.1:5000/
ProxyPreserveHost On
LogLevel debug

Answer: So I solved my problem.
There was an internal process in the application that would use self referencing URLs to generate the PDF.
I had proxypreservehost on which was causing the PDF process to timeout because of some bad URLs it was generating.
I disabled proxypreservehost and it works like a charm!
Comment: +1 for coming back and answering your own question. Good etiquette!
Answer: What about excluding the pdf file using the following '!' directive from mod_proxy manual?

The ! directive is useful in
  situations where you don't want to
  reverse-proxy a subdirectory, e.g.
ProxyPass /mirror/foo/i ! ProxyPass
  /mirror/foo http://backend.example.com
will proxy all requests to /mirror/foo
  to backend.example.com except requests
  made to /mirror/foo/i.

Apache Reverse Proxy IIS Streaming File


Inform user with account creation email, for existing users to

Question: Is there a way(It doesn't matter if passwords need to be recreated/generated) to send all the users an email about there account being added to the website after they are already added?
Comment: does this help? http://drupal.stackexchange.com/questions/15779/how-can-i-email-all-registered-users
Answer: I'd be really interested in this idea too.  I'm making a website to contain and extend an existing registry and it would be great to set the whole thing up with all the members' details and then just send out a mass email containing each user's username and generated password when everything's put together...
I haven't tested it yet, but it could potentially be done:

Set up your users, ensuring 'Notify User' is unchecked and Status is 'Blocked'.  If you already have active users, block them (make sure no email goes out, check admin/config/people/accounts)
When you're ready to notify the users, go to admin/people and check all the blocked users, then user Bulk Options to Activate them (if there's a huge amount of users you might want to do a group at a time to save the server a bit...)
Individual emails should be sent out containing a 'one-time login', see admin/config/people/accounts and scroll down to E-mails and choose 'Account Activation' for the email which goes out.

I will give it a shot and let you know if it worked.
Comment: Just tested it, and it seems you're solution worked perfectly.
Comment: I have also now used it to successful effect!  Worth noting that you can also Block and then re-Activate a user to resend the email and one-time-login link.
Answer: The Account Reminder module could probably handle this requirement. Available for D6 and D7. Offers the ability to schedule the email to a given number of days after the account was set up and, as you might guess from the name it is designed to remind users who have not logged in to their account to log in. Can also be configured to send several reminders every X days.
Answer: Maybe there is a module for that but I don't know it.
But I would use hook_user_insert in a custom module and intercept each user creation.
In this hook_user_insert I would invoke drupal_mail
Comment: Looks promising, going to take a look and see if i can do fix something myself. Thanx for pointing to the drupal_mail hook.
Answer: Mass Messaging will allow you to do that.

This module allows you to send mass messages to users. To compose and
  select recipients the Views module is used. This allows complex
  selection queries setup by a administrator. The mapping of the view
  fields and the subject, recipient, message body and the attachments is
  done in the view. To send a message the view plus the arguments of the
  view are put into a queue. The cron does then send the messages in the
  background.


Sending Data Structures over Named Pipes

Question: I found this StackOverflow question:

Create Named Pipe C++ Windows

And created this class:
#pragma once

#define PIPE_FD TEXT("\\\\.\\pipe\\somepipe")

#define BUFFER_SIZE 1024

// CPipe Class
class CPipe
{

private:

    //
    // Variables
    //

    HANDLE hPipe;
    char buffer[BUFFER_SIZE];
    DWORD dwRead;
    DWORD dwWritten;

public:

    bool CreatePipe()
    {
        hPipe = CreateNamedPipe(PIPE_FD, PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, PIPE_WAIT, 1, BUFFER_SIZE * 16, BUFFER_SIZE * 16, NMPWAIT_USE_DEFAULT_WAIT, NULL);

        return (hPipe == NULL) ? false : true;
    }

    bool CreatePipeFile()
    {
        hPipe = CreateFile(PIPE_FD, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        return (hPipe == NULL) ? false : true;
    }

    void Destroy()
    {
        DisconnectNamedPipe(hPipe);
    }

    bool IsPipe()
    {
        return (hPipe == NULL) ? false : true;
    }

    bool IsConnected()
    {
        return (ConnectNamedPipe(hPipe, NULL) != FALSE) ? true : false;
    }

    void Read()
    {
        while (ReadFile(hPipe, buffer, sizeof(buffer), &dwRead, NULL) != FALSE)
        {
            /* do something with data in buffer */
            printf("%s", buffer);
        }
    }

    void Write()
    {
        WriteFile(hPipe, "Hello Pipe\n", 12, &dwWritten, NULL);

        CloseHandle(hPipe);
    }
};

extern CPipe gPipe;

Main Process:
    gPipe.CreatePipe();
    while (gPipe.IsPipe())
    {
        if (gPipe.IsConnected())
        {
            gPipe.Read();
        }

        gPipe.Destroy();
    }

Remote:
    gPipe.CreatePipeFile();
    if (gPipe.IsPipe())
    {
        gPipe.Write();
    }

Which works great. I can send "Hello Pipe\n" between two applications. However, I am trying to modify it to send data structures rather than strings.
For example, this structure:
struct Test_t
{
    int x;
    int y;
    float J[3];
    bool Yes;
};

That way, the client can send the structure over the pipe, and the server can read the structure off the pipe and update local server structs accordingly.
I have tried:

reinterpret_cast<char*>(&test);

But I haven't been able to get it to work. Any ideas?
Any help is appreciated.
Comment: Just to warn you, if you change that struct to non-POD, your method of just passing the entire struct will not work.
Answer: The reinterpret cast should probably look like this:
reinterpret_cast<void*>(&test);

You also need to make sure you get the amount of data to transfer right (sizeof is your friend here).
Note that sending structs like that can get risky.

The objects sent need to be plain old data objects or they will not serialize properly. See What are POD types in C++? for more information about plain old data. Pointer members, virtual functions etc. will not work.
If the two processes talking to each other have different ideas about structure packing things will come out wrong on the other side. As long as you have full control over the build environment this should be fine, but when things starts breaking you can get some really nasty bugs to fix.

Unless you have extreme performance considerations you should look into some more organized way of serializing the data you send over the pipe such as google protocol buffers or boost::serialize that will make sure the wire format is a little bit less fragile. protocol buffers (and many other technologies) have the advantage of not being c++ specific so you can talk between processes created in different programming languages.


Show that $\frac{\pi}{\sin\pi z}=\lim_{m\to\infty}\sum_{n=-m}^m(-1)^n\frac{1}{z-n}$

Question: Question: Show that $\frac{\pi}{\sin\pi z}=\lim_{m\to\infty}\sum_{n=-m}^m(-1)^n\frac{1}{z-n}$.
Specifically.....: Ahlfors derives this on page 189/190 of his "Complex Analysis" book.  In it, he uses his derivations for $\pi\cot\pi z$, specifically, $$\pi\cot\pi z=\lim_{m\rightarrow\infty}\sum_{n=-m}^m\frac{1}{z-n}=\frac{1}{z}+\sum_{n=1}^\infty\frac{2z}{z^2-n^2}$$  I suppose I am wondering if there is maybe a way to derive the question above without the use of $\pi\cot\pi z$?  Maybe using the Laurent Series expansion of $\frac{\pi}{\sin\pi z}$, but I wasn't getting anything to come out cleanly (maybe I just made a mistake).
Comment: I'm not surprised Laurent series doesn't work, this function has poles everywhere! The maximum radius of convergence for any such series would be $\pi$ (the distance between neighboring poles). The beauty of the expression on the right is that it is not a power series, so notions like "center" and "radius" don't make sense.
Comment: Looks like an application of the [Mittag-Leffler theorem](https://en.wikipedia.org/wiki/Mittag-Leffler%27s_theorem) to me.
Comment: @BastienTourand Of course, the Mittag-Leffler theorem should only be used if it's already proven; otherwise using the cotagent series is the go-to as there is a derivation, known as *Herglotz Trick*, which (IIRC) doesn't need any heavy machinery at all.
Comment: There might be a way to use whichever technique was used to prove the other identity, since the two identities don't differ too much. (For example, the Herglotz trick works in this case.)
Comment: It's just, as @mrtaurho highlights an application of [Mittag-Lefflet theorem][1] (I was writing this while you posted the comment so I finish) but the proof of this theorem might be heavy
Answer: As already noted in the comments this is a typical usage of the Mittag-Leffler theorem. As the same theorem also can be used for deriving the cited cotangent series this is not a fundamentally different approach.
Note, however, that the cotangent series can be derived completely different using the so-called Herglotz Trick, which is an elementary approach using no heavy machinery from complex analysis. The linked PDF only proves the series representation in case of real arguments but if I am not mistaken the result can be easily extended to whole complex plane by continuation as usual. This might be of particular interest if you have not covered Mittag-Leffler yet.
The Laurent series approach fails due to the many singularities of the given function (as noted by Ninad Munshi). I am not aware of a different approach than using Mittag-Leffler directly or the Herglotz Trick.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\bbox[5px,#ffd]{{\pi \over \sin\pars{\pi z}} =
\lim_{m \to \infty}\sum_{n = -m}^{m}{\pars{-1}^{n} \over z - n}}:\
{\Large ?}}$.

With $\ds{m \in \mathbb{N}_{\ \geq\ 1}}$:
\begin{align}
&\bbox[5px,#ffd]{\pi \over \sin\pars{\pi z}} =
{1 \over z} + {1 \over z}\bracks{{\pi z \over \sin\pars{\pi z}} - 1}
\\[5mm] = &\
{1 \over z} + {1 \over z}\bracks{%
\lim_{m \to \ \infty}\sum_{{\Large n\ =\ -m} \atop {\Large n\ \not=\ 0}}^{m}
a_{n}\pars{{1 \over z - n} + {1 \over n}}}
\end{align}
where $\ds{a_{n} \equiv
\mrm{Res}\pars{{\pi z \over \sin\pars{\pi z}} - 1, z = n} =
\lim_{z \to n}
\braces{\pars{z - n}\bracks{{\pi z \over \sin\pars{\pi z}} - 1}} = \pars{-1}^{n}\, n}$.
See Mittag-Leffler Expansion.
Then,
\begin{align}
&\bbox[5px,#ffd]{\pi \over \sin\pars{\pi z}} =
{1 \over z} + {1 \over z}\bracks{%
\lim_{m \to \ \infty}\sum_{{\Large n\ =\ -m} \atop {\Large n\ \not=\ 0}}^{m}
{\pars{-1}^{n}\,z \over z - n}} =
{1 \over z} +
\lim_{m \to \ \infty}\sum_{{\Large n\ =\ -m} \atop {\Large n\ \not=\ 0}}^{m}
{\pars{-1}^{n} \over z - n}
\\[5mm] = &\
\bbx{\large\lim_{m \to \ \infty}\sum_{n\ =\ -m}^{m}
{\pars{-1}^{n} \over z - n}} \\ &
\end{align}


Prove the unit sphere of $\Bbb R^n$ is closed.

Question: The title is pretty almost self explanatory, but I will leave my precise question below.
Question. Consider the normed space $(\Bbb R^n,\|\cdot\|_\infty)$, where the infinite norm is the usual one. Show that the unit sphere defined by
$$ S = \{\alpha \in \Bbb R^n \colon \|\alpha\|_\infty = 1\}$$
is closed and bounded.
My attempt. $S$ is obviously bounded (each element of $S$ satisfies the property $\|\alpha\|_\infty = 1$ which implies that each element of $S$ also satisfies the property $\|\alpha\|_\infty \leqslant 1).$
Now, I was trying to prove $S$ is closed (directly) but I am having some troubles. To see $S$ is closed, it suffices to prove that $\overline{S} \subset S.$ Let $\alpha \in \overline{S}$ be an arbitrary point. Then, there exists a sequence $(\alpha_k)_{k \in \Bbb N}$ s.t. $\alpha_k \rightarrow \alpha$ as $k \rightarrow \infty.$ By definition of a convergent sequence,
$$\forall \epsilon > 0, \exists N = N(\epsilon) \colon \forall n \in \Bbb N, n > N \Rightarrow \|\alpha_n-\alpha\|_\infty < \epsilon. $$
But
$$\|\alpha\|_\infty = \|(\alpha-\alpha_n) + \alpha_n\|_\infty \leqslant \|\alpha-\alpha_k\|_\infty + \|\alpha_n\|_\infty < \epsilon +1. $$
From here I don't know how to proceed. Any help would be apreciated.
Comment: The final step is to let $\varepsilon \rightarrow 0^+$ in the last inequality, since it holds for each $\varepsilon > 0$ (and don't forget to change the strict inequality to non-strict one!).
Comment: Of course, but the more elementary way was not obvious to you and your question was about it. Glad that the comments helped you to solve your issue. Also, you could shorten your title and text to "Prove that the unit sphere of $\Bbb R^n$ is closed" (since the unit sphere of $\Bbb C^n$ is nothing but the unit sphere of $\Bbb R^{2n}$).
Comment: This answered your question [Showing the the unit sphere is closed using sequences](https://math.stackexchange.com/questions/1590700/showing-the-the-unit-sphere-is-closed-using-sequences). Note that you should similarily bound $\|\alpha\|_\infty$ from below
Comment: @AnneBauval Well, every norm is bounded below by $0$...
Comment: Oh, I see what you mean now. I would have to find something like $\|\alpha\|_\infty > 1 - \epsilon$. Is this it?
Comment: Thank you for your help. I think I will stick with @SomeCallMeTim answer though, much more clean and quick
Answer: The essential property you are missing is that the norm is continuous (basically by definition). This means that your proof gets even simpler: Take $(a_n)_n$ so $a_n\to a$, with $a_n\in S$. Then, as the norm is continuous and therefore commutes with limits, $1=\lim_{n\to\infty}||a_n||_\infty =||\lim_{n\to\infty}a_n||_\infty=||a||_\infty $.
Another way to see it is that since $||\cdot||_\infty:\mathbb{K}^n\to\mathbb{R}_{\geq 0}$ is continuous, the preimage of closed sets are closed. And $S$ is exactly the preimage of $\lbrace 1\rbrace$.
Comment: Oh wow. This makes a lot more sense than working with the $\epsilon$ definition of convergence. Thanks for you help.
Comment: @SomeCallMeTim I would have proved closedness the same way as you did. But Zero's comment is a tighter answer to Fire's question. (S)he has to practise calculus before diving into topology.


If com variável do select do banco de dados

Question: Bom dia pessoal!
Estou começando e com uma dúvida básica... preciso realizar um if com uma informação do banco de dados. Faço a conexão e o select, em seguida preciso da variável pra utilizar no if.
<code>$idusuario  = $_SESSION['idusuario'];
$categorias = "SELECT * FROM categorias WHERE idusuario = '$idusuario'";
$resultado  = mysqli_query($con, $categorias);
</code>
Aqui, preciso comparar o valor da coluna "confirmado" do banco de dados para o usuário que está logado, algo como:
<code>if $confirmado == 0

{

echo "XXXXX";

}
</code>
Podem me ajudar com essa dúvida?
Obrigado!
Comment: aqui no site está cheio de exemplos, como esses: https://pt.stackoverflow.com/q/209975/57220 e https://pt.stackoverflow.com/q/133463/57220
Comment: É só trocar o while por if. A diferença é que o while percorre todas as linhas e if só vai pegar a primeira (se a query só retorna uma linha, não fará diferença)
Comment: Esses exemplos estão utilizando while, exemplos assim realmente têm um monte. Mas essa é a única forma? Porque pensei existir uma mais simples!
Comment: um select sempre retorna uma lista de resultados, é preciso fazer o fetch, mesmo que seja só pra pegar o primeiro resultado
Answer: Se a relação for de 1 pra 1 na tabela categoria, pode se escrever assim:
<code>$confirmado = $mysqli->query("SELECT confirmado FROM categorias WHERE idusuario = '$idusuario'")->fetch_object()->confirmado ;
if($confirmado == "<valor desejado>") {
// seu código aqui
}
</code>
Lembrando que esse exemplo só serve se seu retorno corresponder a 1 resultado somente, caso contrário você deve seguir o exemplo do comentário do nosso colega Ricardo Pontual, e resolver usando while.
Select Sum em tabela com PHP/Mysql
Comment: É isso que preciso e que eu quis dizer, é apenas 1 registro, aquele do usuário que está logado! Obrigado. Vou fazer o teste!


Concatenate multiple digits in different rows into one integer

Question: I have a data frame of a single column made of 30000 rows each housing an individual integer like 1, 2, 4, 7, 9, etc.
I want to concatenate the digits of every 50 rows into one single digit. So the number of rows will change from 30000 to 30000/50 = 600 rows each housing a single integer made of concatenating 50 rows.
So digits like 1, 2, 4, 7, 9, ... 3 (50 of them) will turn into one integer 12479...3 occupying one cell or row and so on for the rest.
Thanks
Answer: So, if your input dataframe looks something like this:
df = pd.DataFrame({'col': np.random.randint(10, size=30000)})

       col
0        1
1        1
2        1
3        8
4        4
...    ...
29995    0
29996    2
29997    4
29998    2
29999    7

[30000 rows x 1 columns]

Then you can do this:
print(df.groupby(df.index // 50)['col'].agg(lambda x: ''.join(map(str, x))))

to print:
0      1118461343314944251078615718342449112249161558...
1      1747004710953641680211733510264626747570866618...
2      8121414590539954240646159491668057874649372193...
3      6752166006104257704233198888085209307579966492...
4      6894789891094181188516974222021527062663673212...
                             ...
595    9134173565553669597038089981125300730142452161...
596    4673218339922521922263861144391586968793317405...
597    3274562300781449881296937717538762105128040998...
598    4158802127883136581682677478655313834281219294...
599    6963604643343712867804357553402388236789039680...
Name: col, Length: 600, dtype: object


Little equivalence-relation problem

Question: If $U=\{1,2,\ldots,1000\}$ and $A = \mathbb P(U) - \{ \emptyset \}$, the following relation $R$ is defined in $A$
$$XRY \Leftrightarrow (\min X = \min Y) \wedge (\max X = \max Y)$$
Calculate $\#[\{101,201\}]$
(The number of elements in the equivalence class of $\{101,201\}$)
What I did was simply use that:
$$\sum_{i=0}^{100} {100\choose i}=2^{100}$$
Is this right?
Answer: Every set in the equivalence class contains $101$ and $201$ as members, and may or may not contain others in the set $\{102,\ldots,200\}$.  So you're just counting subsets of $\{102,\ldots,200\}$.
The number of members of the set $\{102,\ldots,200\}$ is $99$, so it would just be the number of subsets of a set of size $99$, i.e. it's $2^{99}$.

Little equivalence-relation problem


Ao tentar definir coluna como Unique, erro é gerado falando de 767 bytes

Question: Quando tento executar uma migration no Laravel, o seguinte erro é gerado:

[Illuminate\Database\QueryException]   SQLSTATE[HY000]: General
  error: 1709 Index column size too large. The maximum column size is
  767 bytes. (SQ   L: alter table usuarios add unique
  usuarios_email_unique(email))
[PDOException]   SQLSTATE[HY000]: General error: 1709 Index column
  size too large. The maximum column size is 767 bytes.

A sql que está sendo executada é essa:
create table `usuarios` (
  `id` int unsigned not null auto_increment primary key,
  `nome` varchar(255) not null,
  `email` varchar(255) not null,
  `password` varchar(255) not null,
  `nivel_id` int unsigned not null,
  `empresa_id` int unsigned not null,
  `departamento_id` int unsigned null,
  `cargo_id` int unsigned null,
  `status` tinyint(1) not null default '1',
  `created_at` timestamp null,
  `updated_at` timestamp null)
default character set utf8mb4 collate utf8mb4_unicode_ci

alter table `usuarios` add unique `usuarios_email_unique`(`email`)

alter table `usuarios` add index `usuarios_password_index`(`password`)

O que pode estar gerando isso?
Comment: São as configurações do MySQL, eu também estava com esse problema e resolvi através desse link, veja se te ajuda: https://stackoverflow.com/questions/42043205/how-to-fix-mysql-index-column-size-too-large-laravel-migrate
Comment: Isso acontece porque o email esta com o tamanho muito grande não aceitando criar o índice.unico. Solução diminiu o tamanho de 255 para 100 vai funcionar acho também um exagero 255
Comment: @arllondias assim funcionou kkkkk, eu só troquei o charset da conexão e funcionou corretamente
Answer: Resumindo as colunas do tipo string do Laravel vem com default 255 o que faz com que o tamanho exceda ao tamnho maxímo para o indíce, vá até sua migration e troque o lenght do campo com chave unique para 191 ou para o tamanho que preferir, por exemplo:
$table->string('email', ['length' => 191])->unique();
Você pode adicionar no seu arquivo AppServiceProvider.php dentro do método boot() a seguinte instrução para seu campo string ficar default e não precisar declarar em toda migration o tamanho do campo string:
Schema::defaultStringLength(191);
Comment: Não é uma boa ideia, na minha opinião. O campo "password" também está dando esse mesmo problema, e creio que o hash gerado pode passar esse tamanho...
Comment: Não passa de 191, tenho algumas aplicações em Laravel e definimos o default de string para esse tamanho justamente para não dar brecha para erros futros
Comment: @WallaceMaxters pra que.colocar índice no password e outra não vai estourar a hash é bem menor
Comment: @WallaceMaxters editei a resposta, e foi a maneira que solucionamos aqui, para não precisar toda hora ficar alterando o tamanho do campo string.
Comment: @arllondias eu resolvi o problema mudando de `utf8mb4` para um `utf8_*_ci` da vida.
Answer: Eu resolvi esse problema trocando o charset e o collation nas configurações do bando de dados, em config/database.php:
//'charset' => 'utf8mb4',
//'collation' => 'utf8mb4_unicode_ci',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',

Outra solução, já apresentada na outra pergunta, mas  pode ser feita globalmente ao invés de individualmente, é definir o tamanho máximo da string para 191. Isso deverá ser feito no AppServiceProvider::boot.
Schema::defaultStringLength(191);

Nota: Não acho uma boa ideia usar a segunda opção, eu preferi trocar o charset e o collation.


To what degree would learning music notation help improve singing

Question: I sometimes sing from a song book that contains the lyrics between two staff lines that show the notation for a piano.
What I do is to try to listen only to the sound of the music so as to stay at the right location but this does not always work that well.
I have also tried to determine the current location within the song by looking at the notation and matching this with the song at the current point. This has not worked very well, partially because the music at times seems to move faster than than my interpretation and partially because some notation is not really clear to me.
What I wanted to ask is whether learning the notation would help in singing, or if this is more of a matter of me getting used to particular songs?
If learning notation can help in this, are there some particular aspects that would be especially beneficial to focus on (like maybe chords)?
Comment: Singers who are comfortable with note reading, and who are able to write down a melody that is in their head, are at a huge advantage.  One excellent way to learn what will help you would be to take up a musical instrument.  Recorder, clarinet, trumpet and trombone are instruments that will give you a sound quickly.  You would do best with a teacher.
Comment: As to the location aspect: Professional singers who are reading music, tend to be looking ahead. In other words they are rarely looking at where they are, but they are quickly memorizing small chunks of the music just before they need to sing them. Of course that aspect of sight singing is useless without any other.
Answer: There is a musical discipline called sight singing. Do a search for that and you will find a lifetime's worth of knowledge worthy of study that will assist you in your goal of reading music as a singer.
Consider sub categories such as solfège, Interval Training, and Rhythm Training.
Note that there are some computer applications that can assist you in practicing your skill in certain aspects of sight singing. These might accelerate your progress. I have not personally tried any of these tools.
To answer the specific question "Is it useful". Yes, further it is a skill that needs constant practice and improvement throughout a musical career. Of course that does not mean that it is easy.


Is there any way to change variables or functions defined outer in a function

Question: Assuming that I have foo.py like below.
This file is not created by me, so I want neither to modify nor copy this.
In other words, foo.py is in some extra package I installed.
# foo.py

def bar():
  print('This is bar')

def foo():
  print('something')
  bar()
  print('something')

Then, I want to implement foo_as_baz() behaving as comments.
# baz.py

from foo import foo

def baz():
  print('This is baz')

def foo_as_baz():
"""
This function is expected to behave as below
  print('something')
  baz()
  print('something')
"""
  pass

I tried below one but it does not work since the namescope differs.
def foo_as_baz():
  bar = baz # I expect this `baz` affects `bar` function in `foo`
  foo()

Comment: Possible duplicate of [Changes made to variable not reflected in console](https://stackoverflow.com/questions/56615309/changes-made-to-variable-not-reflected-in-console)
Comment: look at my another answer a few days ago. look different, but same issue in fact.
Comment: The underlying issue is the same as in that question, but I think there's some possible nuance here about mocking and how module attributes work.
Comment: @JoshKarpel I think understand the underlying issue is key. After that, you can do whatever you want by any possible trick.
Comment: @LiuXiMin
Thanks.
 if `a` shows zeros, this issue is the same as yours.

```
In [5]: a = np.zeros(shape=(4, 2))

In [6]: func()
[666.   1.]
[1. 1.]
[1. 1.]
[1. 1.]
```
Comment: @Hironori Yes, it does. `a` is rebound to zeros, but `func` can not see it unless you redefine a new `func`.
Answer: You can pass the function itself as an argument to foo by slightly modifying how foo works
def foo(func=bar):
   print('something')
   func()
   print('something')

def foo_as_baz():
   foo(baz)

By adding bar as the default argument to foo you retain the original behaviour
Comment: Yes, but `foo()` has no argument and I do not want to modify `foo`, if possible. I know this question is much odd.
Comment: But `foo` when called without any arguments still exhibits the same behaviour. So what would be the issue?
Comment: @Hironori rebind an object to bar in your file can not affect the bar in `foo`, it is the scope rule of Python.
Answer: For the record: don't do the thing below the horizontal rule in normal code. It's confusing and largely pointless.
If you're doing this kind of thing to test your code, I recommend the standard library unittest.mock package, which provides a systematic way to replace Python objects with fake Python objects for testing purposes.
If you think you have some real non-testing use case, please elaborate...

# foo.py

def bar():
    print("This is bar")

def foo():
    print("something")
    bar()
    print("something")

And then then in another file:
import foo

def baz():
    print("This is baz")

def foo_as_baz():
    original = foo.bar  # save a copy of the original bar()

    foo.bar = baz       # make foo.bar point to baz()

    foo.foo()

    foo.bar = original  # cleanup by restoring bar()

foo_as_baz()

The key difference from your attempt is that I did import foo, which lets me look into the actual module namespace foo. I swap foo.bar for baz, then call foo.foo(), then switch foo.bar back to the original bar function.
This works because functions are effectively attributes of modules. Therefore, we can reassign those attributes as if they were attributes of any other object (because, in Python, everything, including modules, are objects).
Comment: As you said, this is a very dangerous code. Do you think which is better to copy all the `foo` function or your implementation shown in the above? @JoshKarpel
Comment: @Hironori Could you clarify what you mean by "copy all of the `foo` function"?
Comment: When I wrote this, I meant copy all the source of `foo` to another file. But now, I realize that there is another way based on  `new_foo = foo.copy()`. I think this better than the others. Thanks.


How to understand the "id" attribute of flex skin?

Question: I'm reading some source of flex skin, and found there are some id attributes, which seems important. Take a "button" skin for example:
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
             minWidth="21" minHeight="21"
             alpha.disabled="0.5">

    <fx:Metadata>
        <![CDATA[
        /**
        * @copy spark.skins.spark.ApplicationSkin#hostComponent
        */
        [HostComponent("spark.components.Button")]
        ]]>
    </fx:Metadata>

    <s:Group id="textGroup" verticalCenter="1" left="25">
        <s:filters>
            <s:DropShadowFilter alpha="0.5" blurX="0" blurY="0" distance="1" />
        </s:filters>
        <s:Label id="labelDisplay"
                 textAlign="center"
                 verticalAlign="middle"
                 maxDisplayedLines="1">
        </s:Label>
    </s:Group>

</s:SparkSkin>

You can see there are ids of textGroup and labelDisplay. They are important since if I use other ids, the styles won't be applied to button.
But how don I know what ids should I use? Why it's textGroup and labelDisplay? Where can I find the declarations?
I tried to search them in the source of spark.components.Button.as, but not found anything related.
Answer: The IDs textGroup and labelDisplay are part of the skinning contract.
If you check the source for ButtonBase the class extended by the Button class you will notice:
[SkinPart(required="false")]

/**
 *  A skin part that defines the label of the button.
 *
 *  @langversion 3.0
 *  @playerversion Flash 10
 *  @playerversion AIR 1.5
 *  @productversion Flex 4
 */

public var labelDisplay:TextBase;

Here as you can see the declaration tells you that labelDisplay is a TextBase in the skin and that the labelDisplay skin part is technically not required (required="false"), but without it, Flex would not draw a label on the Button control. The default value for the required property is false. The contract between the Button class and its skin dictates that when you set the label property on a button, the value is pushed down into the skin and modifies the value of the labelDisplay skin part's text, if the labelDisplay skin part exists.
So essentially this means that these IDs will be used in the ButtonBase class. Usually no need to change the Ids unless of course your requirement needs you to do so. In which case you need to change the skinning contract appropriately too.
Answer: Check http://help.adobe.com/en_US/flex/using/WSC8DB0C28-F7A6-48ff-9899-7957415A0A49.html
section Skinning contract.
id is used to bind skin part instance in skin and logic in host component.


using resolution rule, check if the following is a tautology

Question: i understand how to use resolution but i get to an answer and i dont know if its ok. I need to check if the following is a tautology only using resolution rules.
(p∨q)→(q→(p∨(p∧q))
i get to the following clauses:
p∨q, q, ¬p, ¬p∨¬q
I dont know how to procede past that.
Also i have a second question about resolution:
i want to know, what happens if i get a clause with (¬p∨p)
Comment: You might do best to reread what the resolution rule of inference says, and look for pairs of clauses where $\phi$ and $\lnot$$\phi$ both appear within the formula.  In your example $\lnot$p appears in one formula, and p appears in another.  Thus, you can infer the rest of the clause without p, or $\lnot$p according to the resolution rule of inference.  There's only so many clauses that you can infer here, and no clause that you can infer is the empty set here. Thus, you might list all of the clauses that can get inferred and then indicate that the empty set is not one of them.
Comment: So, i get no empty set, that means is not a tautology? Also if i get an empty set it is a tautology ? (not this case)
Comment: If you get an empty set, then it's a tautology.  If you've deduced *all* possible formulas that can get deduced and there is no empty set, then it's not a tautology.
Comment: Thanks!! this is very helpfull
Answer: First, a clause with an atomic proposition and its negation both in it is called a tautologous clause. That makes sense, since the statement it represents is a tautology.  In practice, you can ignore any tautologous clauses, since they don't do anything to the outcome of the resolution process.
Now back to your problem. You are actually quite right in that you're basically stuck: the only new clauses you can get from the ones you have are $p \lor \neg p$ and $q \lor \neg q$. Both being tautologous clauses, that does not get you anywhere.  And given that you can;t get anything else, that tells you you won;t get to a contradiction. Moreover, the $q$ and $\neg p$ clauses tells you exactly the model that will make the statement False: if you set $q$ to True and $p$ to False, then you'll find that the original statement evaluates to False, and thus is not a tautology.
Finally, form the clauses that you have, you can remove the clauses $p \lor q$, since it is subsumed by the clause $q$. Likewise, you can remove the $\neg p \lor \neg q$ clauses since it is subsumed by $\neg p$. So, you are left with $q$ and $\neg p$ ... and now it is obvious that you won't get a contradiction from that!
Comment: Thanks!! so seeing this from the other side, if i get an empty clause, then it means that the original sentence is a tautology?
Comment: @Cipher Correct. The empty clause corresponds to a contradiction, so being able to resolve to an empty clause means that you are able to derive a contradiction from if the negation of the original statement, and that means that the original statement apparently cannot be false, and is therefore indeed a tautology.
Comment: @Cipher *not* getting an empty set would suggest it is not a tautology ... but you have to be careful: You have to make sure that you have tried all possible resolutions and that there are indeed no more new clauses to be obtained. So for this to become a demonstration, you need to systematically demonstrate that there are no new clauses to be obtained. Saying "Well, I couldn;t get to en empty clause" is really not enough: maybe you weren't trying hard enough to find new clauses! :) But in this case it's clear, especially after removing the subsumed clauses and ending up with $q$ and $\neg p$.


Inverse Mills ratio in system of equations

Question: I have been stuck on the following selection/endogeneity problem for a while:
I have a panel dataset with 1.000 products becoming fair trade products, all at very different times between 2010 and 2014. For each product, I have weekly sales data for 6 months before they become fair trade up to 1 year after they become fair trade.
In step 1, I estimated the effect of becoming fair trade using a (step) dummy variable that becomes 1 from the week onwards they become fair trade using OLS for each product individually. In step 2, I regress the coefficients from the step dummy on about 12 variables (moderaters). I use a 2 step procedure, because 12 interaction effects are not possible to estimate in the same equation due to multicollinearity.
The problem, however, is that brands self-select into joining fair trade or not. I do have data on all products, including those who did not become fair trade.
In short, my question is:
Can I estimate 1 (panel?) selection equation across time across products, and include the same single inverse Mills ratio in each product equation seperately?
Or are there other, better approaches to my problem?
Comment: Edited to Mills ratio (named for John P. Mills).
Answer: To answer your question: No, you cannot use the IMR from a pooled selection equation in the regression in an outcome equation with just a subset of the pooled observations. The outcome equation has to contain all observations, except for those cases that do not fulfill your selection criterion.
However, I think might be a much simpler resolution to your situation:
If the multicollinearity you are concerned about his multicollinearity between the interaction term and its components, you could try standardizing your variables, as suggested here.
Hope that helps.


Rudin's Functional Analysis Theorem 1.41

Question: While I was reading the proof of Theorem 1.41 in Rudin's Functional Analysis, I was stuck in the equation
\begin{equation*}
\pi(\{x:d(x,0)<r\}) = \{u:\rho(u,0)<r\}
\end{equation*}
where $N$ is a closed subspace of a topological vector space $X$, $\pi$ is the quotient map of $X$ onto $X/N$, $d$ is a complete translation-invariant metric on $X$, and $\rho(\pi(x),\pi(y)) = \inf\{d(x-y,z):z\in N\}$.
Specifically, I cannot prove $\{u:\rho(u,0)<r\}\subset \pi(\{x:d(x,0)<r\})$.
I guess that it seems necessary to show that for every $x\in X$ there exists $y\in N$ satisfying $d(x,y) = \inf\{d(x,z):z\in N\}$, but not sure.
Would you give me any hint?
Answer: Fix $u$ with $\rho(u,0)<r$, say $u=\pi(y)$. Since
$$
\inf \{d(y,z):z\in N\}<r
$$
there is some $z\in N$ with $d(y,z)<r$. Then $d(y-z,0)<r$ and
$$\pi (y-z)=\pi(y)-\pi(z)=\pi(y)=u,$$ so  taking $x=y-z$ does the trick.
Comment: Why there is some $z\in N$ with $d(y,z)<r$? This is the point I cannot prove.
Comment: @flyingwith Given any bounded non-empty set $A\subset  \mathbb{R}$, if $\inf A <r$, then $r$ is not a lower bound of $A$ (because $\inf A$ is the largest lower bound), which means that there exists some $a\in A$ with $a<r$.
Comment: Could you also say the infimum is attained in $N$ because it is closed?
Comment: @Connor_Tracy No, it false for general Banach spaces (it holds in Hilbert spaces though, by taking orthogonal projections). Here's a counterexample: Let $X:=\{f\in C([0,1]): f(0)=0$. Let $\phi(f):=\int_0^1 f$ (wrt to Lebesgue measure), $N=\ker \phi$ (you can check that $\phi$ is continuous). Assuming you have a function $f\in X$ with $d(f, N)=1=\|f\|$, you can argue that $|\phi(f)|\|g\|\ge |\phi(g)|$ for every $g\in X$. If you consider $f_n(t)=t^\frac{1}{n}$, then $f_n\in X\setminus N$, and you can show using the previous fact that $|\phi(f)|\ge 1$. But $f\in M$, so $f(0)=0$.
Comment: @Connor_Tracy Therefore, using that $\|f\|_\infty =1$, $\phi(f) \le \int _0^1 |f| <1$, contradiction.
Comment: Thank you for taking the time to explain and provide the counter example @Reveillark


onClickListener not working on navigation drawer

Question: I am trying to set an OnClickListener on the navigation drawer item , but I can't seem to get around.On clicking an item from the drawer a new intent should open.
I even tried to follow this video step by step still the problem is there.
https://www.youtube.com/watch?v=M_4Oh2FeRYs
I am new to android so I can't seem to find the bug.
Here is my java code:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    private ActionBarDrawerToggle mToggle;
    private DrawerLayout mDrawerLayout;
    private NavigationView navView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gv = findViewById(R.id.gridView);
        //Drawer
        DrawerLayout mDrawerLayout = findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.drawer_open,R.string.drawer_close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        navView = findViewById(R.id.navView);
        navView.setNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    }

    @Override
    public void onBackPressed() {
        if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
        else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.nav2:
                Toast.makeText(MainActivity.this, "nav1 selected", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(MainActivity.this, new.class);
                startActivity(i);
                break;

            case R.id.nav1:
                Toast.makeText(MainActivity.this, "nav2 selected", Toast.LENGTH_SHORT).show();
                Intent j = new Intent(MainActivity.this, new.class);
                startActivity(j);
                break;
        }
            mDrawerLayout.closeDrawer(GravityCompat.START);
            return true;

    }

}

here is the navigation_menu layout file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav1"
        android:title="@string/nav1"
        android:icon="@mipmap/nav2"
        />
    <item
        android:id="@+id/nav2"
        android:title="@string/nav2"
        android:icon="@mipmap/nav1"/>
</menu>

here is the mainactivity.xml:

   <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:nestedScrollingEnabled="true"
    tools:context="com.example.xxx.xxx.MainActivity"
    app:layout_behavior="android.support.design.widget.AppBarLayout.ScrollingViewBehaviour">
<LinearLayout
    android:orientation="vertical"
    android:background="#ffff"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent"
    tools:context="com.example.xxx.xxx.MainActivity"
    android:isScrollContainer="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:background="#ff77"
        android:layout_marginTop="5dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/banner1"
            android:src="@drawable/banner1"
            android:scaleType="fitXY"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"/>
    </LinearLayout
        <GridView
            android:id="@+id/gridView"
            android:nestedScrollingEnabled="false"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffff"
            android:numColumns="3"
            android:padding="2dp"
            android:gravity="center"
            android:horizontalSpacing="2dp"
            android:stretchMode="columnWidth"
            android:verticalSpacing="2dp">
        </GridView>
</LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/navView"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start"
        android:alpha="0.4"
        android:fitsSystemWindows="true"/>
</android.support.v4.widget.DrawerLayout>
Answer: Try this
public class Main extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    private ActionBarDrawerToggle mToggle;
    private DrawerLayout mDrawerLayout;
    private NavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Drawer
    mDrawerLayout = findViewById(R.id.drawer_layout);
    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    navView = findViewById(R.id.nav_view);
    navView.setNavigationItemSelectedListener(this);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mToggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }
    else {
        super.onBackPressed();
    }
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case R.id.nav_camera:
            Toast.makeText(Main.this, "nav1 selected", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(Main.this, test.class);
            startActivity(i);
            break;

        case R.id.nav_gallery:
          /*  Toast.makeText(Main.this, "nav2 selected", Toast.LENGTH_SHORT).show();
            Intent j = new Intent(Main.this, new.class);
            startActivity(j);*/
            break;
    }
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;

}

}

working for me
or
GO to File > new > Activity(last part) > Navigation Drawer Activity
which will add a navigation drawer class to your project
Answer: The problem was that I needed to put rest of the layout in a FrameLayout , this link helped.
https://developer.android.com/training/implementing-navigation/nav-drawer
So just needed to change the code of mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:nestedScrollingEnabled="true"
    tools:context="com.example.xxx.xxx.MainActivity"
    app:layout_behavior="android.support.design.widget.AppBarLayout.ScrollingViewBehaviour">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frameLayout">
<LinearLayout
    android:orientation="vertical"
    android:background="#ffff"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent"
    tools:context="com.example.xxx.xxx.MainActivity"
    android:isScrollContainer="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:background="#ff77"
        android:layout_marginTop="5dp">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/banner1"
            android:src="@drawable/banner1"
            android:scaleType="fitXY"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="0dp"/>
    </LinearLayout
        <GridView
            android:id="@+id/gridView"
            android:nestedScrollingEnabled="false"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffff"
            android:numColumns="3"
            android:padding="2dp"
            android:gravity="center"
            android:horizontalSpacing="2dp"
            android:stretchMode="columnWidth"
            android:verticalSpacing="2dp">
        </GridView>
</LinearLayout>
    </FrameLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/navView"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start"
        android:alpha="0.4"
        android:fitsSystemWindows="true"/>
</android.support.v4.widget.DrawerLayout>


confusion on legendre symbol

Question: i know that $\left(\frac{1}{2}\right)=1$ since $1^2\equiv 1 \pmod2$ now since
$3\equiv 1\pmod2$ we should have $\left(\frac{3}{2}\right)=\left(\frac{1}{2}\right)=1$ but on Maple i get that $\left(\frac{3}{2}\right)=-1$ why?
Comment: The command `\pmod` produces the appropriate spacing and font for this.
Answer: The Legendre symbol, the Jacobi symbol and the Kronecker symbol are successive generalizations that all share the same notation. The first two are usually only defined for odd lower arguments (primes in the first case), whereas the Kronecker symbol is also defined for even lower arguments.
Since the distinction is merely historic, I guess it makes sense for math software to treat them all the same; Wolfram|Alpha returns $-1$ for JacobiSymbol(3,2). See the Wikipedia article for the definition for even lower arguments; the interpretation that a value of $-1$ indicates a quadratic non-residue is no longer valid in this case.

confusion on legendre symbol


Centos mailx sending body as attachment

Question: I've got a script I'm trying to send emails through.  I'm trying to send a string variable as the body, but mailx is adding it as an attachment 'ATT00001.bin'.
Here's a snip of my script:
RESULT=''
for i in "${ARRAY[@]}"
do
    FILE=($(ls /tmp/backup/*$i*.xml -Art | tail -n 1))
    BACKUP_NAME=$(grep 'label' $FILE)
    BACKUP_NAME=${BACKUP_NAME//}
    BACKUP_NAME=${BACKUP_NAME/<\/label>/}
    RESULT="$RESULT"$'\n'"INFO: $i - $BACKUP_NAME"
done
echo "$RESULT" | mailx -r "email@example.com" -s "Script Report" email@example.com

I think it's to do with the way I'm building the variable, as sending other single-line variables or files works as expected.  I've also attempted to output the variable to a file and cat that to mailx with the same results.
How do I get the contents of the $RESULT variable into the body of the mail message?  Installing and using a different utility is not an option in this case.
Answer: I resolved my own issue.  I found that ^M carriage return characters were being added to the string and either windows/exchange/outlook didn't like it.  I found this by sending RESULT to file and editing with vim.
I removed the unwanted characters by outputting to file, running sed against the file and removing via regex, then then sending the email via that file.  See adjusted code below:
RESULT=''
for i in "${ARRAY[@]}"
do
    FILE=($(ls /tmp/backup/*$i*.xml -Art | tail -n 1))
    BACKUP_NAME=$(grep 'label' $FILE)
    BACKUP_NAME=${BACKUP_NAME//}
    BACKUP_NAME=${BACKUP_NAME/<\/label>/}
    RESULT="$RESULT"$'\n'"INFO: $i - $BACKUP_NAME"
done

echo "$RESULT" > /tmp/result.txt
sed -i "s/\r//g" /tmp/result.txt

cat /tmp/result.txt | mailx -r "email@example.com" -s "Script Report" email@example.com

Comment: Depending on how you're using this, you may find it easier to simply print from the for loop, and pipe that to mailx.
for i in ; do ; ; echo ; done | sed  | mailx
Comment: Regardless my last comment, if this answers your question, you may consider marking your answer as the solution.
Answer: Similar aproach but without a file:
RESULT=''
for i in "${ARRAY[@]}"
do
    FILE=($(ls /tmp/backup/*$i*.xml -Art | tail -n 1))
    BACKUP_NAME=$(grep 'label' $FILE)
    BACKUP_NAME=${BACKUP_NAME//}
    BACKUP_NAME=${BACKUP_NAME/<\/label>/}
    RESULT="$RESULT"$'\n'"INFO: $i - $BACKUP_NAME"
done

RESULT=$(echo "$RESULT" | sed -e 's/\r//g')

# If you have problem with format, try: echo -e
echo "$RESULT" | mailx -r "firstname.lastname@example.com" -s "Script Report" firstname.lastname@example.com

Centos mailx sending body as attachment


Facilitar contagem entre colunas - Python

Question: Estou iniciando no python e tenho dificuldades para automatizar alguns cálculos. Possuo um DataFrame com 8 colunas [A, B, C, D, E, F, G, H] e 150 linhas.
Preciso contabilizar quantas vezes 2 colunas são iguais entre si, por exemplo: A==B, A==C, A==D... B==C, B==D... Depois preciso dividir a quantidade de igualdades pelo número total de linhas (150) e armazenar esse resultado em outra tabela. Até o momento consegui isso:
condicao = (df['A']==df['B'])
sum(condicao)

x = sum(condicao)/150
print(x)

Com esse código já consigo o resultado que preciso, porém, seria necessário criar 28 condições. Alguma ideia de como resumir isso?
Abraços.
Comment: As colunas precisam ser iguais em todas as entradas ou você quer contabilizar o número de entradas em comum entre duas colunas?
Answer: (no caso em que você queira contabilizar o número de entradas iguais para cada possível par de colunas)
import pandas as pd
import numpy as np

Colunas = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

Duplas = [Colunas[i]+Colunas[j] for i in range(8) for j in range(i+1, 8)]
Duplas = np.array(Duplas)

@np.vectorize
def ContaDuplas(Dupla):

    return np.sum(df[Dupla[0]] == df[Dupla[1]])

NovaTabela = pd.DataFrame({'Contagem': ContaDuplas(Duplas)/150}, index=Duplas)

Comment: Era exatamente o que eu estava precisando, com essa nova tabela eu consigo montar uma matriz. Muito obrigado.


databinding DataGrid to a List

Question: I have a List<object[]> MyCollection which is a result of a SELECT SQL query.
Each object[] represents a row in the query result, and the length of the array will vary for different queries.
I have the name of the column headers in a separate List<string> MyHeaders.
I want to databind MyCollection to a DataGrid with the header of the columns from MyHeaders, and autogenerate the columns.
The reason I want to use AutoGenerateColumns is because I want the Datagrid to reconize the DataTypes of each object, and use the appropriate Column Templates for each DataType.
Thanks!
Comment: I think DataGrid would make a better tag than dynamic. I'm curious about the solution too :)
Answer: If you're stuck and need to get on: use a dataset/ datatable. Ancient but they still work fine! If you want to know if it can be done, i don't know. Most examples of binding to an IList I've seen manually loop and create columns.
Regards GJ
Comment: I felt somewhat gulity using Datatable, but decided to use it. it seems to be the simplest solution.
Comment: LOL yeah I know, they don't feel MVVMy/Linqy, but I do think they're not getting enough love lately ;-)
Answer: Don't use a list for the headers, use a dictionary and use the property names as the keys and put the description as the values.  Do a normal blah.DataSource = List and DataBind().  In your itemdatabound event replace the headers with your description by searching the dictionary with something like this:
foreach col in grid.Columns
{
    col.Name = dic[col.Name].Value;
}

databinding DataGrid to a List


Fechar windowsForm atual ao abrir o proximo

Question: O meu form atual se chama FrmVender (O que está aberto) ao clicar em um botao dentro do FrmVender, quero que ele (FrmVender) feche e abra o form que eu chamar que no caso é FrmVendaImprimir.
<code>FrmVendaImprimir frmVendaImprimir = new FrmVendaImprimir()
this.Close();
frmVendaImprimir.Show();
frmVendaImprimir.Focus();
</code>
Com esse código, o atual (FrmVender) fecha e o frmVendaImprimir abre, porem o frmVendaImprimir vai para trás da janela principal do meu sistema, ele não fica com o foco nele. Como resolvo isso?
Comment: (ignorando o conteúdo) deveria fazer isso no form que abre o "vender"... levando em consideração, que é uma venda e uma impressão, a impressão deve estar dentro da venda... não faz sentido fechar a tela da venda pra depois imprimi-la
Answer: Você pode usar dois comandos pra trazer pra frente:
<code> frmVendaImprimir.BringToFront();
</code>
Ou
<code> frmVendaImprimir.Activate();
</code>


Tag the 6 first wording days of the month

Question: I am trying to find a way to tag the 6 first wording days (Monday to Friday) of the month.
For example, for November I want:

Date
FlagDate

11/01/2021
True

11/02/2021
True

11/03/2021
True

11/04/2021
True

11/05/2021
True

11/06/2021
False

11/07/2021
False

11/08/2021
True

11/09/2021
False

11/10/2021
False

11/11/2021
False

11/12/2021
False

11/13/2021
False

11/14/2021
False

11/15/2021
False

11/16/2021
False

11/17/2021
False

11/18/2021
False

11/19/2021
False

11/20/2021
False

11/21/2021
False

and so on.
Comment: Do you want this in DAX or M?  And do you want to exclude holidays also?
Comment: Both are fine with me, if possible to exclude french bank holiday ?
Answer: You can create a custom column with DAX with the following formula
= CONTAINS(TOPN(6,FILTER('Table',WEEKDAY('Table'[Date],2)<6)),'Table'[Date],'Table'[Date])

You can update TopN(6 to accordingly update the number of first working days
Comment: Hello, not working, i only want working days
Comment: Add a filter to it for saturdays and sundays?
Comment: I updated the formula. It should work now
Comment: not sure what you mean by buffered list. But if you already have a date table called "Table" with a column named "Date", then you can simply use the above formula directly to create a new DAX column.
Comment: change the table name (`Table`) and Column name(`Date`) respectively in the formula
Answer: Here is M code that adds a column to your existing table.
It assumes that the column Name in your table is Date
It also assumes you have a List of the relevant holiday dates spanning at least the relevant time frame.  I obtained the list from https://publicholidays.fr and buffered it to keep it from continuously downloading
See the comments in the M-Code to understand the algorithm

Note that there is no requirement that the Date column encompasses a full month.  But if it starts on, for example, the 15th, there will be nothing in that month marked TRUE since the first6 are not there.

Assumption: Date column spans less than 1 year
If that is not the case, will need a different algorithm to create the first6 list.
M Code
//Before adding the "Flag" column enter this code to create a buffered list of working days in the months in the Date column
    workingDays =
        let

    //generate list of all dates from beginning of first month to the last date listed
        dts = List.Transform(
                {Number.From(Date.StartOfMonth(#"Previous Step"[Date]{0}))..
                 Number.From(List.Max(#"Previous Step"[Date]))},each Date.From(_)),

    //Using List.Generate, create a list of working days from the preceding list
    //working days will be days that are Monday-Friday and NOT found in the list of Holiday dates
        wdys = List.Generate(
            ()=>[wd=if Date.DayOfWeek(dts{0})>= Day.Monday
                        and Date.DayOfWeek(dts{0})<=Day.Friday
                        and not List.Contains(#"FR Holidays",dts{0}) then dts{0} else null,
                        idx = 0],
            each [idx] < List.Count(dts),
            each [wd=if Date.DayOfWeek(dts{[idx]+1})>= Day.Monday
                        and Date.DayOfWeek(dts{[idx]+1})<=Day.Friday
                        and not List.Contains(#"FR Holidays",dts{[idx]+1}) then dts{[idx]+1} else null,
                        idx = [idx]+1],
            each [wd]),

    //clean the wdys List by removing the Nulls
        cleanList = List.RemoveNulls(wdys),

    //create a list of the Months within the workday list
        monthsInList= List.Distinct(List.Transform(cleanList, each Date.Month(_))),

    //Use List.Accumulate to create lists of the first 6 working days in each month
        first6 = List.Accumulate(monthsInList,{},
            (state, current)=> state &
                List.FirstN(List.Select(cleanList,each Date.Month(_)=current),6))
        in List.Buffer(first6),

//Now add a column and set the flag if a Date in the date column is found in the first6 list
    flagged = Table.AddColumn(#"Previous Step","FlagDate", each List.Contains(workingDays,[Date]), type logical)
in
    flagged

filtered to show only dates marked True

M Code Edited to handle spans of more than one year
Change MonthsInList to include the year, and also Test for that in the List.Accumulate step
//Before adding the "Flag" column enter this code to create a buffered list of working days in the months in the Date column
    workingDays =
        let

    //generate list of all dates from beginning of first month to the last date listed
        dts = List.Transform(
                {Number.From(Date.StartOfMonth(#"Previous Step"[Date]{0}))..
                 Number.From(List.Max(#"Previous Step"[Date]))},each Date.From(_)),

    //Using List.Generate, create a list of working days from the preceding list
    //working days will be days that are Monday-Friday and NOT found in the list of Holiday dates
        wdys = List.Generate(
            ()=>[wd=if Date.DayOfWeek(dts{0})>= Day.Monday
                        and Date.DayOfWeek(dts{0})<=Day.Friday
                        and not List.Contains(#"FR Holidays",dts{0}) then dts{0} else null,
                        idx = 0],
            each [idx] < List.Count(dts),
            each [wd=if Date.DayOfWeek(dts{[idx]+1})>= Day.Monday
                        and Date.DayOfWeek(dts{[idx]+1})<=Day.Friday
                        and not List.Contains(#"FR Holidays",dts{[idx]+1}) then dts{[idx]+1} else null,
                        idx = [idx]+1],
            each [wd]),

    //clean the wdys List by removing the Nulls
        cleanList = List.RemoveNulls(wdys),

    //create a list of the Months within the workday list
        monthsInList= List.Distinct(List.Transform(cleanList, each Date.ToText(_,"yyyy-MM"))),

    //Use List.Accumulate to create lists of the first 6 working days in each month
        first6 = List.Accumulate(monthsInList,{},
            (state, current)=> state &
                List.FirstN(List.Select(cleanList,each Date.ToText(_,"yyyy-MM")=current),6))
        in List.Buffer(first6),

//Now add a column and set the flag if a Date in the date column is found in the first6 list
    flagged = Table.AddColumn(#"Previous Step","FlagDate", each List.Contains(workingDays,[Date]), type logical)
in
    flagged

Comment: @Kair0  Minor change in the algorithm to handle that.  See Edit
Comment: Hello, amazing job, but Date column spans more than 1 year
Comment: i'm trying your solution, what is the exact process to make it work ? first creating a date table with a column date then create a blanck query for the buffered list then add the flag column ?
Comment: @Kair0 Briefly: `1:` Create a **List** of the relevant holidays in a separate query which you named **FR Holidays** . `2:` Create your **Date** table with the single column. `3:` Paste the M-Code into your query after the last relevant step (perhaps a `#"Changed Type"`? `4:` Change the name in the code from `#"Previous Step"` to whatever the actual name is.


How can I force a cell to stop editing in Excel interop?

Question: I have an Excel 2007 add-in with a ribbon. One of the buttons in the ribbon triggers heavy manipulations of the current worksheet and I set various Excel.Application properties like Interactive and EnableEvents to false during the manipulations for speed and UX reasons.
My problem is that the ribbon doesn't steal focus so if the user was editing a cell when he clicks my ribbon button, an exception is thrown when setting Application.Interactive = false because Excel considers the user is still editing the cell.
Is there a way to stop the edition either by saving or discarding the changes made to the cell?
It appears that Range.DiscardChanges() would probably solve my problem but it isn't available in the 2007 API.
EDIT: It seems that Range.DiscardChanges() is for ranges based on OLAP data sources so it wouldn't solve my problem anyway.
EDIT: I have tried calling Range.Activate() on another cell. While I do see the cell focus changing in the GUI, the exception is thrown anyway. Range.Select() doesn't do anything.
Comment: There is a solution near the bottom of this link which may help http://www.autoitscript.com/forum/topic/109032-excel-bug-comsolved/
Comment: @kevchadders This solution uses a third party scripting library in Excel and I'd like a .NET solution. Though it seems like it all boils down to sending and ESC and that didn't work for me with `Application.SendKeys()`. I feel like the Ribbon has the focus at that point in time and the ESC doesn't affect the cell that is in edition.
Comment: In fact, the reason `SendKeys` didn't work is that the ESC takes effect only when the execution is done and the GUI takes control.
Comment: In case you still need a solution, I have found a simple solution using interop event handler in your .NET code.
Answer: You can not stop editing but you can check if editing is enabled and afterwards tell the user to stop it:
private bool IsEditing(Microsoft.Office.Interop.Excel.Application excelApp)
{
    if (excelApp.Interactive)
    {
        try
        {
            excelApp.Interactive = false;
            excelApp.Interactive = true;
        }
        catch (Exception)
        {
            MessageBox.Show("Please stop cell editing before you continue.");
            return true;
        }
    }
    return false;
}

I found the answer at this page and changed it from VBA to C#:
https://www.add-in-express.com/creating-addins-blog/2011/03/23/excel-check-user-edit-cell/
Answer: So after looking around for a few days and asking on MSDN, the final answer is that there is simply nothing in the API for this and that it isn't possible without using hacky solutions1.
The way Excel itself handles this kind of thing is simply to gray out its menus while the user is editing so I've done that instead for the sake of consistency with the host application.
1: Hacky, because techniques like using SendKeys require going back to the GUI to make sure the action is processed and then calling the method that required the cells to not be in edition. This is fine in one place, but doing that for every method call to the Excel Interop is madness.
Comment: This is not true at present. There is now a simple solution using Interop event handler in .NET code. Please check my answer.
Answer: It may be too late to answer to it. But thinking someone use this trick when they look for a solution.
For some reason, the sendkeys and Cells/Range activate command didn't workout.
The only workaround to get rid of this issue would be change the focus to another worksheet and come back to current worksheet to cheat the excel. :-)
ExcelUtil.ActivateWorksheet("Sheet1");
currentWorksheet.Activate();

public static void ActivateWorksheet(string strWorksheetName)
    {
        bool found = false;

        foreach (Excel.Worksheet sheet in Globals.ThisAddIn.Application.Worksheets)
        {
            if (sheet.Name.ToLower() == strWorksheetName.ToLower())
            {
                found = true;
                break;
            }
        }

        if (!found)
            Globals.ThisAddIn.AddNewWorksheet(strWorksheetName);

        ((Excel.Worksheet)Globals.ThisAddIn.Application.Worksheets[strWorksheetName]).Activate();
    }

Hope this helps.
Ram
Comment: Except if the cell is being actively edited, the application will not respond to *any* method calls. This needs to be handled with a `try/except`.
Answer: None of the other proposed solutions worked for me, then I learned that we can use excel Events in the VB.NET application and made a solution using the "BeforeClose" event that forces Excel to exit cell edit mode.
VB.NET code:
'Declare Excel object'
Public WithEvents Excel As New Microsoft.Office.Interop.Excel.Application
public Fake_close as boolean

Public Function Is_in_edit_mode() As Boolean
    Try
        Excel.Interactive = Excel.Interactive
    Catch Ex As Exception
        Return True
    End Try
    Return False
End Function

'Wb = handle to your workbook in Excel'
Public Sub Exit_cell_edit_mode(Wb as Workbook)
    If Not Is_in_edit_mode() Then Exit Sub

    'initiates closing the worksheet, which forces cancellation of cell edit mode.'
    Fake_close = True  'Signal that the closing event is fake'
    Wb.Close()  'This command will trigger the WorkbookBeforeClose event below'
End Sub

'This event will be triggered in the VB.NET app before the workbook is closed on Excel'
Private Sub WorkbookBeforeClose(Wb As Workbook, ByRef Cancel As Boolean) Handles Excel.WorkbookBeforeClose
    If Fake_close Then
        Cancel = True  'Cancel the closing of the workbook'
        Fake_close = False
    End if
End Sub

Comment: This does not work. Excel.ActiveWorkbook.Close() can not be executed because excel is in edit mode.
Comment: Did you test it? I have been using this code for 1 year and it is still working. The Excel.ActiveWorkbook.Close() can indeed be executed and it will trigger the WorkbookBeforeClose event that will cancel the closing of the workbook and this exits edit mode. Try it and see
Comment: Yes, I tried it. While in cell edit mode (user types into a cell -> all buttons in the ribbon get disabled --> user clicks out of the excel window and leaves it in cell edit mode), all interop calls will fail. Even Excel.ActiveWorkbook.Close(). Actually even Excel.ActiveWorkbook.
Comment: Only thing that worked so far was to keep track of all opened window handles and do a User32.PostMessage to the excel windows and send "Enter". Excel will leave the cell edit mode on enter.
Comment: OK I just checked my code and there were some changes that I didn´t update here. You should save the Workbook to a Workbook variable, then use Workbook.Close() instead of Excel.ActiveWorkbook.close(), this should work. I will edit the answer
Answer: If you select another cell or all cells, does the error disappear?
private void myFunction()
     {
         xlSheet.Cells.Select();
         //the rest of the work
     }

Comment: It doesn't work. `Range.Activate` looked a bit more promising but the exception is thrown anyway. I have added that information to the question.
Comment: Well, an ugly method would be `Application.SendKeys("{ESC}")`. This will send to the application escape key which discards the changes. But I don't think it is a reliable solution.
Comment: Yeah I have already tried that but it didn't work as noted in the question's comments.
Answer: I detected the problem and displayed a message to tell user:
         If excelHelper.ExcelIsEditing() Then
            System.Media.SystemSounds.Beep.Play()
            MsgBox("Please finish editing the sheet!" & vbCrLf & vbCrLf & "Move cursor out of current cell and try button again.")
            Exit Function
         End If
Function ExcelIsEditing() As Boolean
      ExcelIsEditing = False
  If ExcelApp.Interactive = False Then Return False
  Try
     ExcelApp.Interactive = False
     ExcelApp.Interactive = True
  Catch
     Return True
  End Try

End Function
its the best I could come up with :_(


mocking Phaser with Jest

Question: I've been trying to set up jest as a test framework for a project I'm working on that uses Phaser, and I am getting stuck trying to mock out Phaser itself. I first ran into this issue with the missing canvas, which I was able to resolve from the link. But now I am getting another error "Cannot read property 'postion' of undefined".
jest.config.js:
module.exports = {
  verbose: true,
  roots: ['./src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '\\.(css|less|scss)$': 'identity-obj-proxy'
  },
  setupFiles: ['jest-canvas-mock']
}

__mocks__/phaser.js:
const phaser = jest.genMockFromModule('phaser');

module.exports = phaser;

error message:
TypeError: Cannot read property 'position' of undefined

      1 |
    > 2 | const phaser = jest.genMockFromModule('phaser');
        |                     ^
      3 |
      4 | module.exports = phaser;

      at Image.get [as x] (node_modules/phaser/src/physics/matter-js/components/Transform.js:36:30)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
          at Array.forEach (<anonymous>)
      at Object.<anonymous> (src/__mocks__/phaser.js:2:21)
      at Object.<anonymous> (src/main.ts:3:1)
      at Object.<anonymous> (src/main.spec.ts:3:1)

I'm looking at that Transform file and its blowing up on a getter because this.body is undefined:
get: function ()
{
  return this.body.position.x;
},

Has anyone else had this problem? I'm hoping I just have some configuration wrong.
Answer: I wanted to thank you for sharing your configuration to run Jest with Phaser 3.
Regarding your issue, it appears that the Phaser.Physics.Matter.Commponents.Trasnform component is not really compatible with the way jest.genMockFromModule() works.
You can hack it simply by creating a default value for the body property of the Transform instance in phaser/src/physics/matter-js/components/Trasnform.js:
var Transform = {

    body: Body.create({}),

    // ...

Although I don't know how it might affect the production code.
If you don't use the Matter.js physics engine in your game, maybe you could create a custom Phaser 3 build instead.

mocking Phaser with Jest


Finding $E[\overline{X}^3]$ where $X_1,\ldots,X_n$ are i.i.d $N(\mu,1)$

Question: Suppose $X_1, X_2, \ldots, X_n$ are  i.i.d. Normal$(\mu , 1)$ random variables with $μ \in$ $\mathbb{R}$.
How can we calculate   $E\left[\overline X^3\right]$?
Comment: Think moment generating functions.
Comment: How do you think $E(\bar{X}^3)$ with $X\sim N(\mu,1)$ relates to $E((X-\mu)^3)$ where $X-\mu \sim N(0,1)$ ?
Answer: Let $Z=\bar X - \mu$ so that $Z$ has mean $0$.
Since $(a+b)^3 = a^3+3a^2b + 3ab^2 +b^3$ you obtain
$$
E[\bar X^3] = E[(Z+\mu)^3] = E[Z^3] + 3 E[Z^2]\mu + 3 E[Z] \mu^2 + \mu^3.
$$
Because $Z$ is normal with mean 0, it is symmetric about 0 so that $E[Z^3]=0$ and $E[Z]=0$. We are left with
$$E[\bar X^3] = 3 E[Z^2]\mu +\mu^3.$$
If remains to compute $E[Z^2]$ which is also the variance of $\bar X$, equal to $1/n$. The final answer is
$$
E[\bar X^3] = 3\mu/n +\mu^3.
$$
Comment: You may as well divide by sqrt(n) but it's not needed. The scaling you mention appears at the end, where I wrote that $E[Z^2] =1/n$. The final answer $3+3/n$ is correct, see https://www.wolframalpha.com/input/?i=E%5BX%5E3%5D+where+X+is+N(1,1%2Fn) for instance
Comment: I think when you start $Z= (\bar X - \mu ) $ you should divide with the Sd of $ \bar X $ which is equal to 1/ (root of n)
Comment: (My previous comment treats the case mu=1, the answer now handles any mu).
Answer: There is a much more general solution to this problem that holds for any distribution whose moments exist. It is a problem known as finding moments of moments. The modus operandi for solving such problems is to work with power sum notation $s_r$, namely: $s_r = \sum_{i=1}^n X_i^r$.
We seek $\mathbb{E}[ (\frac{s_1}{n})^3]$ ... which is just the $1^\text{st}$ raw moment of $(\frac{s_1}{n})^3$:

where:

$\mu_r$ denotes the $r^{th}$ central moment of $X$ i.e. $\mu_r = E[(X-\mu)^r]$
${\hat\mu}_1$ denotes the 1st raw moment (i.e. the population mean), and
RawMomentToCentral is a function from the mathStatica package for Mathematica.

In the special case of $X \sim N(\mu, 1)$, the third central moment $\mu_3$ is zero (by symmetry), and the variance $\mu_2 = 1$, and so the solution simplifies to: $\frac{3 \mu}{n} + \mu^3$


mongodb aggregation cast to int

Question: I have the following problem with mongo using the aggregation framework.
Suppose and item with time in seconds, t, and an event id occurring, e, like:
item:{t:11433, e:some_id}
what I want is to aggregate according to t and e. It means counting the number of id 'e' in a time t.
This is easy to do using the aggregation with $group.
However, I would like to have a different time course. For example, I want to count number of same event id in a time slot of eg. 5 seconds. I could do this progammatically, in js or python . I was just wondering if it could work using just mongo, using a cascade of group.
I tried to project using $divide[t,10]. For 11433, this would give,  1143.3 But it seems that I can't remove the 0.3 in Mongo (Otherwise I could group in this other scale).
Any hint?
thanks
Comment: Not in aggregation as far as I know.
Answer: To get an integer group key for a 5-second interval, you could use the formula
t = t - (t % 5)  // % is the modula operator

In the aggregation framework this would look like this:
db.xx.aggregate([
     // you need two projections, as they can not be nested
     // this does not work:
     // { $project: { _id: 0, e: 1, t: 1, tk: { $subtract: [ "$t", $mod: [ "$t", 5 ] ] } } },
     //
     // get modula 5 of time in seconds:
     { $project: { _id: 0, e: 1, t: 1, tm5: { $mod: [ "$t", 5 ] } } },
     // subtract it from time:
     { $project: { _id: 0, e: 1, ti: { $subtract: [ "$t", "$tm5" ] } } },
     // now group on e and interval,
     { $group: { _id: { e: "$e", interval: "$ti" }, count: { $sum: 1 } } },
])

For this example collection:
> db.xx.find()
{ "_id" : ObjectId("515e5a7157a0887a97cc8d1d"), "t" : 11433, "e" : "some_id" }
{ "_id" : ObjectId("515e60d457a0887a97cc8d1e"), "t" : 11434, "e" : "some_id" }
{ "_id" : ObjectId("515e60d857a0887a97cc8d1f"), "t" : 11438, "e" : "some_id" }

the result is:
{
    "result" : [
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11435
            },
            "count" : 1
        },
        {
            "_id" : {
                "e" : "some_id",
                "interval" : 11430
            },
            "count" : 2
        }
    ],
    "ok" : 1
}

mongodb aggregation cast to int


Android calculator crash

Question: I just started learning Android today, and my program is crashing when I run it. Sorry for my incompetence, help would be greatly appreciated. I have been trying to figure this out. I have been following youtube tutorials, but the teacher's eclipse is an older version, making it very difficult to learn. Here is the code:
package com.audiack.newproj;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity
{
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton,derp;
TextView answer;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    layout1 = new LinearLayout(this);
    number1Text = new EditText(this);
    number2Text = new EditText(this);
    calcButton = new Button(this);
    answer = new TextView(this);

    layout1.setOrientation(LinearLayout.VERTICAL);

    answer.setText("0");
    calcButton.setText("you suck at math bro");

    calcButton.setOnClickListener((android.view.View.OnClickListener) multiplyClicked);

    layout1.addView(number1Text);
    layout1.addView(number2Text);
    layout1.addView(calcButton);
    layout1.addView(answer);

    setContentView(layout1);
}
    private OnClickListener multiplyClicked = new OnClickListener()
    {

        @Override
        public void onClick(DialogInterface arg0, int arg1)
        {
            String firstString = number1Text.getText().toString();
            String secondString = number2Text.getText().toString();
            double firstNum = Double.parseDouble(firstString);
            double secondNum = Double.parseDouble(secondString);
            double result = firstNum * secondNum;
            String resultString = String.valueOf(result);
            answer.setText(resultString);
        }

    };

}
Comment: Please update the title of your question. Saying *my application crashes* means nothing, is like going to a doctor and saying *I have a headache, heal me now*.
Comment: What is the stack trace? Like what is the reason it is crashing? Leave a stack trace if you could.
Comment: I have no idea how to get the stack trace...so sorry
Comment: Check the Logcat stacktrace or the Consolve view output. There it will say what problem your application had (lot of *caused by* clauses, we need you to copy/paste it here [yes, all of it]).
Comment: When your application has failed. Go to eclipse and look for Logcat and copy the code that should be in read. Should say "threw an exception at ...." and "caused by ....." with a lot more text which helps us find where the error happened within the code.
Comment: 06-01 15:37:57.439: E/AndroidRuntime(21957): Caused by: java.lang.ClassCastException: com.audiack.newproj.MainActivity$1 cannot be cast to android.view.View$OnClickListener
Comment: Is that what you are looking for?
Comment: That is what caused the error. you have an invalid cast
Comment: Sorry i know so little, care to elaborate? I know what a cast is, but I am not sure where in the program the issue is.
Answer: You were using the wrong import for the onClickListener you want to use the android.view.View OnClickHander
private OnClickListener multiplyClicked = new OnClickListener()
{

    @Override
    public void onClick(View v)
    {

and change your import to this
import android.view.View;

You have imported a differnt EventHandler which was throughing the error since you were calling it like this
calcButton.setOnClickListener((android.view.View.OnClickListener) multiplyClicked);

But in your imports you were using a different OnClickHandler so it used that and was giving a InvalidCastException since they are two differnt EventHandlers.
So if you remove the
import android.content.DialogInterface.OnClickListener;

and change the
calcButton.setOnClickListener(multiplyClicked);

you should solve that invalid cast.
Comment: it is giving me this error now: 06-01 15:37:57.439: E/AndroidRuntime(21957): Caused by: java.lang.ClassCastException: com.audiack.newproj.MainActivity$1 cannot be cast to android.view.View$OnClickListener
Comment: sorry wrong error XD here is the right one: The method onClick(View) of type new DialogInterface.OnClickListener(){} must override
 or implement a supertype method
Comment: This is because you need to call it `new View.OnClickListener` or do a static import: `import static android.view.View.*`. IMO I would prefer the former.

Android calculator crash


Throw exception, but json response get status SUCCESS

Question: I have this part of code in Controller, but when i make this action and IF works fine and the error message appears in console log.
But it looks like 'success' has status true. And it shouldn't
Try {
    if ($last['date']) {
        if ($last['date']->format('d-m-Y') == $par['date']) {
                throw new \Exception('error', 500);
            }
    }

    return new JsonResponse([
        'success' => true,
        'data'    => $content,
        'message' => 'success'
    ]);
} catch (\Exception $exception) {

    return new JsonResponse([
        'success' => false,
        'code'    => $exception->getCode(),
        'message' => $exception->getMessage(),
    ]);
}

JQuery
$.ajax({
    type: "POST",
    url: "/app/url",
    data: TableData,
    dataType: "json",
    success: function(response){
        console.log(response.message);
        $('#message').html('
' + response.message + '
');
    },
    error: function (response) {
        console.log(response.message);
        $('#message').html('
' + response.message + '
');
    }
});

Comment: To report an error, you would have to return a HTTP response in the 400 or 500 range. In your current implementation you made a request with a successful response. That response contains a piece of Json which happens to have a property `success` with the value `false`, but your Ajax call doesn't know that that indicates an error. You could implement that in JavaScript by parsing the response, but the better and more 'pure' way would be to make PHP return a proper error response code. See [HTTP status codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
Comment: But shouldn't CATCH block work when i throw exception?
Comment: Ok, so instead of throwing exception i should resturn response with success: false
Comment: No the other way around. Returning a response with `success: false` is what you currently do.
Answer: Your AJAX code is receiving the response as success every time, regardless of the JSON content, because you're always sending a 200 response (which is success). To tell AJAX to process the response as an error (and go to the error method instead of success method in your AJAX response handler), you need to send an error code in the response, i.e. 400, like this:
return new JsonResponse([
        'success' => false,
        'code'    => 400,
        'message' => $exception->getMessage(),
    ], 400);

So, if you're throwing your custom Exceptions, you need to set the code property for each according to their real HTTP meaning.
Now, the success and error handlers in AJAX have different parameters. In success, the first parameter is data, simply the data returned from the server. On the other hand, in error, the first parameter is an jqXHR object. To access the data in this object, you have a handful of different parameters, but what you need now, since you have JSON, is jqXHR.responseJSON. So, now your error message will be in response.responseJSON.message, not in response.message. See more about this here.
Comment: Your data in the `error` method is now in `response.responseJSON`, so get it with `response.responseJSON.message`. To further debug this, put `console.log(response);` in the error handler, so you can see all the response object has.
Comment: Could you tell me how i can get error message, from jsonRespone with your  answer?

the old way gives me UNDEFINED (my love)


cronbach's alpha negative value for dichotomous answers

Question: Mine is multiple choice science questionnaire. The correct answer is marked '1' and wrong '0'. The aim of the test was to find out what they know and what they don't know (pre test). The alpha is negative.  How to interpret?  Should I give easy questions that 60% of the students can answer? In that case how to identify the weak spots where intervention will be focussed?
Comment: First thing is to look at the inter-item correlations. If many are negative you know where to look next.
Comment: I'd also check the between-student variance. If this is too low, then high correlations will not be possible. By the way, Cronbach's alpha for dichotomous data is the same as Kuder-Richardson Formula 20 (KR-20).
Answer: Cronbach's alpha isn't really about the difficulty of the items, although it will be low if all the questions are so hard that the answers are random. So, if you asked questions about calculus to 1st grade students, you'd get a very low alpha - maybe even negative by chance.  The same happens if the questions are all ridiculously hard.
A very low alpha is saying that the interitem correlations are low.  There are a couple reasons this could happen.  If you are asking about different areas of science, then you would expect that.  If some of the answers were coded incorrectly, you can fix that.
So, look at the inter-item correlations and, especially, look at correlations that are negative and think about whether that could be expected.


Using environment.ts value in proxy.config.mjs file + Angular

Question: At work we are trying to use proxy.config.mjs (located in src folder) as per Angular Docs to talk to back-end API in Dev mode but we want to set target value in this proxy conf using environment.ts file.
Have followed all default configurations to set-up proxy.config.mjs, environment files but getting below error when doing ng serve :
An unhandled exception occurred: Cannot find module '/proxy-test/src/environments/environment' imported from proxy-test/src/proxy.config.mjs

Other files :
src/environments/environment.ts :
export const environment = {
    production: false,
    apiUrl: 'http://localhost:3000'
  };

src/proxy.config.mjs :
import { environment } from './environments/environment';

export default [
  {
    context: [
      '/api'
    ],
    target: environment.apiUrl, <- Trying to use env value here
    secure: false
  }
];

angular.json :
"serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "proxy-test:build",
        "proxyConfig": "./src/proxy.config.mjs" <- Using proxy conf here
      },
      "configurations": {
        "production": {
          "browserTarget": "proxy-test:build:production"
        },
        "development": {
          "browserTarget": "proxy-test:build:development"
        }
      },
      "defaultConfiguration": "development"
    }

Comment: maybe yoou can use this https://stackoverflow.com/questions/53479209/angular-cli-proxy-with-env-variables ?
Answer: Since the environment is most likely a TypeScript file, you're running a Node Javascript Module (.mjs) and not TypeScript.
Now, there is an experimental feature in the works from Node (and as of Node 21 it's at stage 3) which will allow you to import .json into your mjs.
For example:
import jsonObj from "./some/file.json" with { type: "json" };

You'll get a warning, but feel free to use this or not. You can track it at: https://github.com/tc39/proposal-import-attributes
So let's go over what you'll need:

In the resolveJsonModule flag in your tsconfig.json:

{
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

Have a json dev file (say, src/environments/environment-data-dev.json):

{
  "dev": true,
  "apiUrl": "http://localhost:3000"
}

Then in src/environments/environment.ts:

// Just import the Json Object as a Javascript Object //
import devData from "./environment-data-dev.json";

// Expand it in your environment const. //
export const environment = { ...devData };

For the production you can make a separate src/environments/environment-data-prod.json:

{
  "dev": false,
  "apiUrl": "http://localhost:3000"
}

In the src/environments/environment-prod.ts:

import prodData from "./environment-data-prod.json";

export const environment = { ...prodData };

Finally, in your mjs file, you can use:

import environment from "./src/environments/environment-data-dev.json" with { type: "json" };

export default [{
  context: ["/api"],
  target: environment.apiUrl
}];

Answer: You could try to update the import statement to use the full path of the environment.ts file.
Change this :
import { environment } from './environments/environment';

To this :
import { environment } from '../environments/environment';

Comment: Have tried it but no luck. Thanks @Baki.