Como testar meu web service feito sob o spring boot usando um profile específico?

Question: Estou desenvolvendo um web service RESTFul usando o Spring Boot e gostaria de saber como executar os testes unitários com requisições direcionadas ao web services sem que eu precise antes levantar o servidor manualmente. Gostaria que os testes já levantassem o servidor automaticamente. Além disso, gostaria que a aplicação usasse um profile específico chamado test com as configurações em application-test.properties que contem o endereço de um banco local e uma porta específica. Isso é possível?
Answer: É sim. Primeiramente, vamos pensar em levantar os seus serviços automaticamente. Para isso, usaremos duas annotations, uma informando o "executor" do Spring, que é @RunWith(SpringRunner.class), e outra informando que nossa porta é definida pelo arquivo de configuração e não randômica,além de informar nossa class com o método main que publica o web service, que é @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = RestfulApplication.class). Então, supondo que vamos testar o resource pessoa do seu web service RESTFul:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
        classes = RestfulApplication.class)
public class PessoaResourceTest {

//...

}

Mas isso não soluciona tudo. As configurações que serão usadas para lançar o serviço serão a default, no arquivo application.properties e o desejado é o profile test. Para isso usaremos a tag @ActiveProfiles("test"):
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
            classes = RestfulApplication.class)
    @ActiveProfiles("test")
    public class PessoaResourceTest {

    //...

    }

Agora o serviço será lançado automaticamente usando o profile test antes dos testes serem executados.


T-distribution versus normal distribution (sample means and linear inference)

Question: From course notes, I see that when working with a quantitative variable, we can standardize the sample mean to have a normal distribution (as per the central limit theorem) as long as the sample size is "large". As a result, the distribution of the sample means is normally distribution (whether we are working with $\sigma$ or s) as long as the sample size is "large":
$$\frac{\overline{X} - \mu}{\frac{\sigma}{\sqrt{n}}} \sim N(0,1),$$
$$\frac{\overline{X} - \mu}{\frac{s}{\sqrt{n}}} \sim N(0,1),$$
If the sample size is "small", then we will have a t-distribution:
$$\frac{\overline{X} - \mu}{\frac{s}{\sqrt{n}}} \sim t_{n-1}.$$
However, we recently started looking at inference for linear regression, and I see the following two equations:
$$\frac{\hat{\mu}_{y|x} - {\mu}_{y|x}} {\sigma{\sqrt{\frac{1}{n}+\frac{(x-\overline{x})^2}{\sum_i(x_i-\overline{x})^2  }}}} \sim N(0,1),$$
$$\frac{\hat{\mu}_{y|x} - {\mu}_{y|x}} {s{\sqrt{\frac{1}{n}+\frac{(x-\overline{x})^2}{\sum_i(x_i-\overline{x})^2  }}}} \sim t_{n-2}.$$
I am wondering if the second equation can be normally distributed if its sample size is "large". In other words, if we have a large sample size, then can we still use the central limit theorem and show that:
$$\frac{\hat{\mu}_{y|x} - {\mu}_{y|x}} {s{\sqrt{\frac{1}{n}+\frac{(x-\overline{x})^2}{\sum_i(x_i-\overline{x})^2  }}}} \sim N(0,1).$$
The course notes make it seem as though when working with $\hat{\mu}_{y|x}$ (a sample mean) we cannot use the central limit theorem like we can for $\overline{x}$ (a sample mean). In the case of linear regression, it seems that only $\sigma$ and s determine whether we have a normal distribution or t-distribution respectively.
Is this correct, and if so, why can't we apply the central limit theorem in the linear regression case?
Comment: Note that there is a nuance in your first two formula.

In the case of large sample size you have **equality** $$\frac{\bar{X}-\mu}{\frac{\sigma}{\sqrt{n}}} \sim N(0,1)$$ and **approximation** $$\frac{\bar{X}-\mu}{\frac{s}{\sqrt{n}}} \sim t_{n-2} \underset{{n \to \infty}}{\sim} N(0,1)$$

You can do the same for the linear regression.
Answer: The difference is 'type of test' and not 'sample size'
The difference between the two formula, $\sigma$ vs $s$, is not in the difference of sample size.
The difference is whether $\sigma$ is known or estimated. The first formula uses a normalization with a "known" standard deviation, and the second formula uses a normalization with the sample estimate of the standard deviation. The first, $\sigma$, is a constant, the second, $s$, is a random variable (with chi-square distribution).
So the difference is:

you use the t-distribution $\mathcal{N}(0,1)/\sqrt{\chi_{n-1}/(n-1)}$ to describe the distribution of the difference between a 'sample mean' and 'the population mean', if this difference is normalized based on the sample estimate of the standard deviation
and you use the normal distribution $\mathcal{N}(0,1)$ to describe the distribution of the difference between a 'sample mean' and 'the population mean', if this difference is normalized based on the standard deviation of the population.

Note:
for large sample sizes you do get that the distribution of this chi-square denominator becomes closer to a peak around 1
$$\lim_{n \to \infty} \sigma_{\left(\frac{\chi_{n-1}}{n-1}\right)} = \sqrt{\frac{2}{n-1}}= 0 \qquad \mathrm{and} \qquad \mu_{\left(\frac{\chi_{n-1}}{n-1}\right)} = 1 $$
or in other words the sample estimate of the standard deviation is less variable
$$ \lim_{n \to \infty} s = \sigma$$
and the t-distribution becomes approximately a normal distribution
$$ \lim_{n \to \infty} t_n = \mathcal{N}(0,1)$$
So you could say that: for large sample sizes the formula that are used with sample estimated standard deviation approximate the formula that are used with known standard deviation.
This is a different thing than the central limit theorem in which a mean of sample of variables from a non-normal distribution becomes a normal distribution for large $n$.

Note:
The standard deviation is often not 'really' known. But it can be 'hypothetically' known. For instance in testing a hypothesis or in Bayesian inference you 'assume' a certain deviation.
(in the same way as $\mu$ is not known but you can still use it in the formula and use it hypothetically, for instance in determining confidence intervals)


Saving a file with a custom extension

Question: I have a program I wrote in Windows with this piece of code that works on Windows, but when compiled in linux, the saved file doesn't have the .l2p extension.
void MainWindow::on_saveButton_clicked()
 {
     QString fileName = QFileDialog::getSaveFileName(this,
         tr("Salvesta Projekt"), "",
         tr("Latid Pindalaks (*.l2p)"));

     if (fileName.isEmpty())
         return;
     ...

What should I do?
Comment: The behaviour you want to force is exactly what I hate(d) about windows applications. File name extensions should be up to the user to use or not (they are part of the file name, which is chosen by the user). You could let the user choose between "Latid Pindalaks (\*.l2p)" and "All files (\*)" and only force the extension if he selected the first one. But I'm not sure if Qt provides you the info about which one has been selected in the combo box of the dialog.
Comment: What is the final result that you get ?
Comment: It shows the saving dialog and it all seems fine, but the file it has saved has no extension.
Answer: If the file name doesn't have the extension you need, just add it:
QString fileName = QFileDialog::getSaveFileName(this,
    tr("Salvesta Projekt"), "",
    tr("Latid Pindalaks (*.l2p)"));

if (fileName.isEmpty())
    return;

if (!fileName.endsWith(".l2p"))
    fileName += ".l2p";

Saving a file with a custom extension


In Win32, how can a text file be successfully read into memory?

Question: I am trying to get simple file IO working in Win32. So far the writing is working fine, but the reading is not: although it successfully reads the contents, additional "garbage" is appended to the string. The code I have so far is below. The program has UNICODE defined.
For writing:
DWORD dwTextSize = GetWindowTextLength(hWndTextBox);
WCHAR *lpszText = new WCHAR[dwTextSize];
GetWindowText(hWndTextBox, lpszText, dwTextSize + 1);
hTextFile = CreateFile(lpszTextFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWritten;
WriteFile(hTextFile, lpszText, 2 * dwTextSize, &dwBytesWritten, NULL);  // x2 for 2 bytes per Unicode character
CloseHandle(hTextFile);
DeleteObject(hTextFile);

For this example, Hello, World! is saved successfully as Hello, World!.
For reading:
lpszTextFileName = L"text.txt";        // LPCTSTR Variable
hTextFile = CreateFile(lpszTextFileName, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwFileSize = GetFileSize(hTextFile, &dwFileSize);
DWORD dwBytesRead;
WCHAR *lpszText = new WCHAR[dwFileSize / 2];
ReadFile(hTextFile, lpszText, dwFileSize, &dwBytesRead, NULL);
CloseHandle(hTextFile);

The string is then used to set the text of an EDIT control:
SendMessage(hWndTextBox, WM_SETTEXT, NULL, (LPARAM)lpszText);    // SetWindowText() also possible

When Hello, World! is read back in, it reads back in as Hello, World!﷽﷽ꮫꮫꮫꮫﻮ or a visual variation upon this, but basically "garbage"!
I have probably missed something rather obvious, but I cannot see where! Is there a solution to this problem and if so, what is it?
Comment: Null-terminate the string (and make sure to allocate space for that terminator) before sending it to `SendMessage()`. (And in case it wasn't obvious, delete the buffer when you're done with it). Also, `GetWindowText(hWndTextBox, lpszText, dwTextSize + 1)` into a buffer that is allocated on the previous line to be `dwTextSize` probably isn't a wise idea.
Comment: How do I go about null-terminating a string in Win32? Is it simply something like `lpszText[sizeof(lpszText) - 1] = (WCHAR)0; // or '\0'`?
Comment: That will set the 3rd (or 7th, if compiling 64bit) wchar in your string to 0, which is not what you want. `sizeof(pointer-type-var)` is not the same as `sizeof(array-type-var)`. See the post below for how to terminate your string.
Answer: Ok I started this with a comment, but its getting out of control.
For Writing
This:
WCHAR *lpszText = new WCHAR[dwTextSize];

should be:
WCHAR *lpszText = new WCHAR[dwTextSize+1];

This:
DeleteObject(hTextFile);

should not be there at all.. Get rid of it.
I'm assuming you delete [] lpszText; somewhere when you're done with it. if not, do so.

For Reading
The second parameter to GetFileSize() should not be the same variable as your return value. It is the HIGH 32bit of a 64-bit value for large file sizes. If you know you're file size is smaller than 4gB, you can leave it NULL, so change this:
DWORD dwFileSize = GetFileSize(hTextFile, &dwFileSize);

to this:
DWORD dwFileSize = GetFileSize(hTextFile, NULL);

You must account for the null terminator of your file buffer, so this:
WCHAR *lpszText = new WCHAR[dwFileSize / 2];

should be changed to this:
WCHAR *lpszText = new WCHAR[dwFileSize / 2 + 1];
lpszText[dwFileSize / 2] = 0;

and the rest should work as you're hoping it would. No error checking, which is not good, but I've seen worse. And as before, I'm assuming you delete [] lpszText; somewhere when you're done with it. if not, do so.
Comment: Excellent post. It's amazing how 8 lines of code had so many mistakes/issues... I don't know that I would use `lpszText[dwFileSize/2] = 0` personally; I much prefer to `memset` the buffer to all zeroes directly, but that's a style thing.
Comment: @NikBougalis most of it is common for people new to both Windows and C/C++. The only one that made me go "wtf???" was the `DeleteObject()`. Lord knows where *that* came from. And regarding `memset`, its a performance thing. No need to fill memory with a bunch of zeros only to have all-but-one of them overwritten immediately after. Comes from platforms where doing that can get expensive. But whatever works and lets you sleep at night =P
Comment: Yeah, the DeleteObject was peculiar. As for `memset`, I get where you're coming from - I'm a big performance-squeezing geek too, alas it's a requirement we have at my workplace...
Comment: Perfect - many thanks for your help! Yes - the `lpszText` variables were deleted, but I left the code out. I am primarily a .NET developer but decided to try out some Win32 for an experiment/learning exercise, hence the rather large number of mistakes, but I'm gradually getting there!
Comment: @BWHazel you're doing fine. Just tread carefully and *thoroughly* understand an API call (i.e. read its docs) before coding with it. Unlike .NET, C/C++ WIN32 API programming is somewhat unforgiving. In a "That which does not make you stronger kills you." 'sorta way =P
Comment: @WhozCraig Thanks! I'm gradually getting used to it - coming from .NET it was indeed quite an eye-opener!


Domain mapping subdirectory to external domain

Question: I'm running a Wordpress multisite install where the blogs are created in subdirectories - e.g. www.mydomain.com/blog1, www.mydomain.com/blog2
I need to clarify what I think is and isn't possible with domain mapping so that clients can use their own domain (and therefore improve their SEO) for the blog.
What I want in an ideal world is for www.clientdomain.com/blog to serve the respective Wordpress blog (e.g. www.mydomain.com/blog6) BUT as far as the user is concerned, they are looking at www.clientdomain.com/blog.
I know this is possible with subdomain mapping (e.g. I can serve www.mydomain.com/blog6 as blog.clientdomain.com) but is there any solution for making a subdirectory of one domain serve a website on another domain?
I don't think this is possible without using 301 redirects in .htaccess but just need someone to confirm this for me.
In summary, I believe my options are:

User types www.clientdomain.com/blog and browser loads www.mydomain.com/blog6 (address bar also shows www.mydomain.com/blog6) using .htaccess redirect 301.
User types blog.clientdomain.com and browser loads www.mydomain.com/blog6 (address bar remains blog.clientdomain.com) using domain mapping DNS.

For more information, hosting for wordpress multisite and client website is completely different and client website will have a "normal" site plus email in addition to their blog.
Thanks for your help.
Answer: You need need to add an vserver with the document root set to the root of the blog (say for example /var/www/blog6) and the vserver name to blog.clientdomain.com. That should do what you want.

Edit
What you are really looking for is a reverse proxy. With reverse Proxying you can let the server resolve a path (for example /blog) from another server.
+--------+   Request   +--------------------+   Request    +--------------------+
| Client |-----------> | Server domain1.com |------------->| Server domain2.com |
+--------+    /blog    +--------------------+   /blog6     +--------------------+

Comment: why this answer is not accepted, or no-one upvoted?
Comment: Thanks for the quick reply. I need the client domain URL to be clientdomain.com/blog rather than blog.clientdomain.com. I don't think there's any way to map a subdirectory onto a domain without doing a 301 redirect?
Comment: Sure there is. It's called reverse proxy. Let me revise my post.
Comment: Now I have added new info


Is this the right equation for this 3D surface?

Question: Is $\frac{\sin \sqrt{x^2+y^2+z^2}}{\sqrt{x^2+y^2+z^2}}$ the right equation for this surface? I am confused what $z$ is doing in there (unless this is an implicit equation). I get something fairly similar looking if I omit it in Wolfram Alpha, though it's hard to compare.
Also, does it have a proper name?
Comment: Its proper name is [$\operatorname{sinc}(r)$](https://en.wikipedia.org/wiki/Sinc_function) where $r=\sqrt{x^2+y^2+z^2}$.
Answer: Yes, but it is not the (four-dimensional) graph of the function $f:\mathbb{R}^3\to\mathbb{R}$ defined by
$$f(x,y,z)=\frac{\sin(\sqrt{x^2+y^2+z^2})}{\sqrt{x^2+y^2+z^2}},$$
but rather a slice of it; that is, choose some value $z=c$, and this graph is the graph of the function $g:\mathbb{R}^2\to\mathbb{R}$ defined by
$$g(x,y)=\frac{\sin(\sqrt{x^2+y^2+c^2})}{\sqrt{x^2+y^2+c^2}}.$$
Choosing different values of $c$ varies the graph; here is an animation of the graph of $g$ as $c$ goes from $0$ to $8$:

listofplots = {}; For[c = 0, c <= 40, c++, AppendTo[listofplots,
  Plot3D[Sin[Sqrt[x^2 + y^2 + (c/5)^2]]/ Sqrt[x^2 + y^2 + (c/5)^2],
    {x, -15, 15}, {y, -15, 15}, PlotPoints -> 40, PlotRange -> {-0.2, 0.2}]]]

Export["animation.gif", listofplots, "DisplayDurations" -> {0.25}]
Comment: Makes perfect sense!
Comment: Go U of C math!
Comment: Haha thanks, glad I could help :)


How come that if Ax = W is consistent than a vector w is part of the Im A.

Question: If I have a matrix A and a vector w and I want to verify that w is included in the Im A, Why is solving [ A | w ] and it giving a solution (being consistent) prove that w is include in Im A?  I am also not sure what consistent even means.
Comment: How do you define the image/column space of a matrix? Also, consistency of a linear system of equations is covered in [this Wikipedia article](https://en.wikipedia.org/wiki/Consistent_and_inconsistent_equations).
Comment: "$Ax = w$ is consistent" is _defined_ as "$Ax = w$ has a solution", i.e., "There is a vector $x$ such that $Ax = w$", that is, $w \in \operatorname{Im} A$.
Answer: A matrix equation $Ax = w$ is consistent if it has at least one solution $x$.  If any solutions $x$ exist, then $w$ is in the image, or range of the matrix $A$.  Think of the matrix $A$ as a function that maps a vector $x$ to another vector $w$.  The output $w$ must be in the image of $A$.


fluxxor add more than 1 set of actions to a flux instance

Question: I have set up a React application using Fluxxor, I am trying to use a controller view which gets multiple stores and actions, similar to this carousel example.
However in the fluxxor example it uses multiple stores but only the one set of actions. I wanted to know how to pass in multple actions.
var React = require('react/addons'),
    Fluxxor = require("fluxxor"),
    authorActions = require("../actions/author-actions"),
    authorStore = require("../stores/author-store"),
    productActions = require("../actions/product-actions"),
    productStore = require("../stores/product-store");

var stores = { ProductStore: new productStore(), AuthorStore: new authorStore()  };
// how do I combine my actions here?
var flux = new Fluxxor.Flux(stores, actions);

Answer: Fluxxor supports adding actions dynamically:
var flux = new Fluxxor.Flux(stores);
flux.addActions(authorActions);
flux.addActions(productActions);

If the namespaces don't conflict, you can also merge them together with something like Underscore's extend:
var actions = _.extend({}, authorActions, productActions);

or Object.assign (or a polyfill):
var actions = Object.assign({}, authorActions, productActions);

Answer: To add to @BinaryMuse answer. I like to namespace my actions so there'll be no clashes on any generically named actions.
Just initiate an object with a key for each namespace:
...
var actions = { author: authorActions, product: productActions  };
var flux = new Fluxxor.Flux(stores, actions);

Then call them with their namespace:
this.getFlux().actions.author.add("Aldus", "Huxley", ...);


ReactJS - TypeError: Cannot convert undefined or null to object

Question: Boa tarde,
Tenho um componente onde consumo dados de uma API, até ai tudo bem!
Estou tentando adicionar um modal do reactstrap e estou enfrentando o seguinte erro:
TypeError: Cannot convert undefined or null to object
O código completo do meu componente é:
import React from 'react';
import styled from 'styled-components';
import { Container, Row, Col, Card } from 'reactstrap';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

// api
import api from '../../servicos/Api';

const BoxPalestrantes = styled.div`
            .card{ background-color: transparent !important; border: 0; }
            .palestrantes{ background: #27ae60; width: 100%; padding: 5rem 0 5rem 0; }
            .palestrante-item{ margin-bottom: 1rem; }
            .foto-palestrante{ border-radius: 1rem;}
            .titulo{font-family: 'Oswald', sans-serif; font-size: 2rem; text-transform: uppercase; font-weight: bold; padding: 2rem 0 2rem 0; color:#fff;  }
            .subtitulo{font-family: 'Oswald', sans-serif; font-size: 2rem; font-weight: 500;  }
            .palestrante-info{ position: absolute;  opacity: 0; transition: visibility 0s 0.1s, opacity 0.1s linear; height: 100%; width: 100%; align-items: center; flex-direction: column; justify-content: flex-end; display: flex; }
            .palestrante-info p{text-align: center; margin: 0; color: #fff; font-family: 'Oswald', sans-serif; font-size: 1rem; text-transform: uppercase; font-weight: bold;}
            .palestrante-info:hover{background: rgba(44, 62, 80, 0.90); padding: 10px; max-width: 100%; height: 100%;  opacity: 1; transition: opacity 0.1s linear; cursor: default; border-radius: 1rem;}
            .palestrante-item{ margin: 1rem 0 1rem 0; }
        `

export default class Palestrantes extends React.Component {

    // metodo construtor - modal
    constructor(props) {
        super(props);
        this.state = {
            modal: false
        };
        this.toggle = this.toggle.bind(this);
    }

    toggle() {
        this.setState(prevState => ({
            modal: prevState.modal
        }));
    }

    // armeza o estado do objeto contendo os palestrantes
    state = { palestrantes: {} }

    // metodo executado assim que o componente é exibido em tela
    componentDidMount() {
        this.carregarPalestrantes();
    }

    carregarPalestrantes = async () => {
        //caminho da requiscao na api
        const response = await api.get("palestrante/todos/5a34a185-bbd8-461e-6ffd-08d6cccadba7");

        // atualiza o estado dos patrocinadores com base no retorno da api
        this.setState({ palestrantes: response.data })
    };

    render() {

        // armeza o estado do objeto para uso
        const { palestrantes } = this.state;

        // url de caminho das imagens
        const caminho = "https://localhost:44332/api/palestrante/Imagem/";

        return (
            <BoxPalestrantes>

                    <Row>
                        <Container>
                            <Col md={{ size: 12 }} xs={{ size: 12 }}>

Palestrantes

                            </Col>
                        </Container>
                    </Row>
                    <Row>
                        <Container>
                            <Col md={{ size: 12 }}>
                                <Row>
                                    {
                                        Object.keys(palestrantes).map((item) => {
                                            return (
                                                <Col xs={{ size: 12 }} md={{ size: 3 }} sm={{ size: 6 }} className="palestrante-item" key={palestrantes[item].id}>
                                                    <Card>

{palestrantes[item].nome}

{palestrantes[item].descricaoCurta}

                                                    </Card>
                                                </Col>
                                            )
                                        })
                                    }
                                </Row>
                            </Col>
                        </Container>
                    </Row>

                    <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
                    <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
                        <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
                        <ModalBody>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                            </ModalBody>
                        <ModalFooter>
                            <Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
                            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
                        </ModalFooter>
                    </Modal>

            </BoxPalestrantes>
        )
    }
}

Alguém pode me ajudar? Sou iniciante em ReactJs e desde já agradeço pela atenção!
Answer: Resolvido!
Eu estava setando duas vezes o state de meu componente. Agora setei no meu método construtor da seguinte forma:
constructor(props) {
        super(props);
        this.state = {
            modal: false,
            palestrantes: {}
        };

Comment: Isso. Eu já ia perguntar o que era aquele ` state = { palestrantes: {} }` solto no meio da classe.


Division of metatable

Question: got some problem with metatable. This is my simple metatable:
local mt = {}
function mt:add(n)
  return setmetatable({n = n}, {__index = mt})
end

function mt:get() return self.n end

Now I want to add some division like:
mt.math
mt.effect

Which each one has some own methods like:
mt.math:floor() return math.floor(self:get()) end
mt.effect:show(args) onMapShowEffect(self:get(), {x = x + (args[1] ~= nil or 0), ...) end
mt.effect:get() return getCurrentPos() end

Any ideas?
OK, trying make all details to share my problem.
Player = {}
function Player:add(this)
  return setmetatable({this = this}, {__index = Player})
end

Player:get() return self.this end

Above code works perfectly on this example
function enterToGame(player1, player2)
  local p1 = Player:add(player1)
  local p2 = Player:add(player2)
  print(p1:get()) -- ID1
  print(p2:get()) -- ID2

Now I want to create some helpfully methods(functions) for table Player. I want to make it more flexible, so I want divide it for classes. Example:
Player.info = {
  id = function() return Player:get() end,
}
Player.pos = {
  get = function() return getPosition(Player:get()) end,
  set = function(args) setPosition(Player:get(), args) end,
}
Player.speed = {
  get = function() return getSpeed(Player:get()) end,
  set = function(value) setSpeed(value) end,
  improve = function(value) setSpeed(Player.speed.get() + value) end,
}

But its not work exactly what I want:
function enterToGame(player1, player2)
  local p1 = Player:add(player1)
  local p2 = Player:add(player2)
  print(p1:get()) -- ID1
  print(p2:get()) -- ID2
  print(p1.info.id()) -- ID2 instead of ID1
  print(p2.info.id()) -- ID2

When I put Player:get() in my methods its return last object declaration.
Comment: I'm not sure I understand the question exactly but `self` in those inner functions is going to be the `mt.math`/`mt.effect` tables and not the top-level `mt` table in case that wasn't clear to you.
Comment: Is there any way to call mt?
Comment: If you give your mt table a `__call` metamethod it can be called. I'm not sure how that's relevant to your question though.
Answer: Based on what you state, if you do
mt.math = mt:add(123)

You don't need themt:get() because mt is the metatable for mt.math. Then
mt.math.floor = function(self) return math.floor(self.n) end

will work as expected. For example,
print(mt.math:floor())

prints 123.
EDIT 1: So now that I have a better understanding of what you are trying to do: normally you would do
p1:id()
p1:getPos()
p1:setPos()
p1:getSpeed()
p1:improveSpeed()

Note the colon, this is important, so that each method gets a "self" as first parameter, thereby given them the table instance to operate on (p1, in the above example). Instead you want to group methods so
p1.info:id()
p1.pos:get()
p1.pos:set()
p1.speed:improve()
p1.speed:get()

These methods will get a self that points to p1.info, p1.pos, etc. But those sub-tables have no knowledge of the container table (p1). The info and pos tables are in the Player class: they are shared by all instances of Player (p1, p2 etc). You have to make the info and pos tables non-shared:
function Player:add(player)
    local pN= setmetatable( {n = player, info={}, pos={}}, {__index = Player})
    pN.info.id = function() return pN.n end
    pN.pos.set = function(x) return setPosition(pN, x) end
    return pN
end

Then you get
> p1=mt:add(player1)
> p2=mt:add(player2)
> print(player1)
table: 0024D390
> print(p1.info.id())
table: 0024D390
> print(player2)
table: 0024D250
> print(p2.info.id())
table: 0024D250

All that said, I don't really like the idea of having to use closures like this, perhaps there are gotchas since not everything will be in Player.
Comment: Not exactly that. I want create functions before use it. In your case I need first assign `mt:add()` into `mt.math` then create function `mt.math.floor`. Edited my problem for more details.
Comment: @user3225882  OK I extended answer based on your new info I think I understand what you are trying to do now

Division of metatable


Retrieve data from two tables in mysql. There is only one common column between the two tables

Question: I have a table "ttquestion" which has columns 'qId', 'question', 'option1', 'option2', 'option3', 'difficulty'. The primary key is 'qId'.
I have another table "level" which has columns 'userId' and 'qId'. There is no primary key in this table.
I have to retrieve data from "ttquestion" and the below query is working fine. Now the query has to be modified such that I should get 12 records from "ttquestion" and should exclude 'qId' present in the table "level" for a specfic user.
SELECT * FROM (
    (SELECT * FROM ttquestion WHERE difficulty='1' ORDER BY RAND() LIMIT 4)
    UNION ALL
    (SELECT * FROM ttquestion WHERE difficulty='2' ORDER BY RAND() LIMIT 4)
    UNION ALL
    (SELECT * FROM ttquestion WHERE difficulty='3' ORDER BY RAND() LIMIT 4)
)
ttquestion ORDER BY difficulty;

Kindly suggest as I am not good at SQL queries.
Comment: See [Tips for asking a good Structured Query Language (SQL) question](https://meta.stackoverflow.com/questions/271055), #5 and #3.
Answer: Try adding a NOT EXISTS clause in each subquery to filter out the 'qId' values that exist in the "level" table for a specific user.
SELECT * FROM (
   (SELECT * FROM ttquestion
   WHERE difficulty='1' AND NOT EXISTS (SELECT 1 FROM level WHERE level.qId = ttquestion.qId AND level.userId = 'exampleID')
   ORDER BY RAND() LIMIT 4)
   UNION ALL
   (SELECT * FROM ttquestion
   WHERE difficulty='2' AND NOT EXISTS (SELECT 1 FROM level WHERE level.qId = ttquestion.qId AND level.userId = 'exampleID')
   ORDER BY RAND() LIMIT 4)
   UNION ALL
   (SELECT * FROM ttquestion
   WHERE difficulty='3' AND NOT EXISTS (SELECT 1 FROM level WHERE level.qId = ttquestion.qId AND level.userId = 'exampleID')
   ORDER BY RAND() LIMIT 4)
) ttquestion ORDER BY difficulty;

replace 'exampleID'' with the actual user ID . this modified query ensures that the selected 'qId' values do not exist in the "level" table for the specified user.


Eliminate code on Client-side in React Js

Question: I need help in one of my project. (React based)
scenario : In my project file A has code in which some portion of code utilise on SSR and some on CSR.
Problem facing : when bundling the project(app-shell), in CSR also i am seeing the SSR code.
Goal: Eliminate SSR code when render on CSR. (react based solution)
similar behaviour  like vercel nextjs:  https://next-code-elimination.vercel.app/
please do let me know how to achieve or any reference link would be helpful.
Answer:
used a flag isServer in webpack config and set it to false as default.

determine on the basis of proess.isServer

Tried AST approach to eliminate the server side code


Change workflow state with particular payment method

Question: Right now i have a payment method called "Transferência Bancária" and I need it to change to the workflow state "Awaiting Transferencia" automatically when that payment method is selected.
Is it possible to do programmatically?
I'm stuck at:
 $order = $event->getEntity(); if(($order->getPaymentGateway()) == ('transferencia')) { $order->set('state', 'aguardando_transferencia'); }
on my /modules/workflowtkn/src/EventSubscriber/WorkflowTknProcessSubscriber.php
Error: Call to undefined method Drupal\commerce_order\Entity\Order::getPaymentGateway()

EDIT: I'm having troubles calling the function "getPaymentGateway()" because is in another module, can somebody help, please :) It has to be corresponded to the order.
I've tried $gateway = \Drupal::service('plugin.manager.commerce_payment_method_type'); but it says can't convert to string...
This:
$payment = $order->get('payment_gateway')->first()->entity
Gives me:

Warning: htmlspecialchars() expects parameter 1 to be string, object given in Drupal\Component\Utility\Html::escape() .

I've looked at How do I get information about the payment method from the order object programmatically?
but can't figure it out.
I guess i'm failing to convert to string?
EDIT: When I use json_encode: json_encode($order->get('payment_gateway')->first()->entity) it only returns "{}"
Comment: Welcome to Drupal Answers :) As mentioned asking for links is off topic here, this is a Q+A site so we need the question and answer to be here, not somewhere else, or the site stagnates when the external links go down. For the remaining question the answer is definitely "yes", but again, for this format you'll need to be more specific about the problem. Add details of what you've tried, error messages, and so on. If you haven't started yet, or haven't found the commerce documentation, you're probably a bit early on to ask a question here just yet
Comment: At a minimum, you need to read the docs yourself before asking here.  Asking for a link to the docs is off-topic for this site.
Comment: I asked for the docs because i didn't find one for my specific issue, if there is one.
Comment: Thank you Clive. I've been researching this for the last couple of days, but since there is no support for my issue im realy strugling. As for more information, I created a module for a custom workflow and different states. I have a manual payment method that gives the IBAN of my business for the client to transfer the money, has soon as he/her chooses it, my colegues want the order to pass to a chosen state, which is "Awaiting Transfer" in my custom workflow.
Answer: After much head bashing and pure luck i found out the solution.
In order.php:
function getPay()
{
    return $this->get('payment_gateway')->entity->get('label');
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to prove a quotient space is again compact and Hausdorff

Question: I'm struggling with a topology question and I'm having a hard time proving the following:
If I know that $X$ is a compact Hausdorff space, $A$ is a closed subspace and $X/A$ denotes the quotient space of $X$ which identifies $A$ to a single point.
Then I'd like to show, that $X/A$ is a compact Hausdorff space.
So far I have that since $A$ is a closed subspace of a compact space $X$ then $A$ is compact as well.
Since $A$ is a subspace of a Hausdorff space then $A$ is a Hausdorff space as well.
Since $X/A$ is the quotient space of $X$, which identifies $A$ to a single point, then by the definition of a quotient space (Munkres p. 137) then $X/A$ is a partition of $X$ into disjoint subsets whose union is $X$. Also there exist a surjective map $p:X \to X/A$  that carries each point of $X$ to the the element of $X/A$ containing it. Since $p$ is a quotient map this is equivalent to saying that $p$ is continuous.
And now I can't seem to get any further. How do I prove that $X/A$ is compact and Hausdorff?
Comment: Have you tried writing down the definition of Hausdorffness, then taking two distinct points in $X/A$ and the _continuous_ map $p$?
Comment: BTW this was listed among related questions: [Prove that $Y$ is Hausdorff iff $X$ is Hausdorff and $A$ is a closed subset of $X$](https://math.stackexchange.com/q/346009).
Answer: Let the quotient map be $q:X \rightarrow X/A$. $X/A$ is compact because if $\{U_\alpha\}$ is any open cover of $X/A$ then $\{q^{-1}(U_\alpha)\}$ is an open cover of $X$. Since $X$ is compact then there is a finite subcover $\{q^{-1}(U_{\alpha_i})| i = 1,...,n\}$. But then $\{U_{\alpha_i}|i=1,..,n\}$ is a finite subcover of $X/A$ because $q(q^{-1}(U_\alpha)) = U_\alpha$. Therefore, $X/A$ is compact.
To show that $X/A$ is Hausdorff we pick two points $x,y\in X/A$. If $x,y\neq q(A)$ then pick open subsets $U, V \subset X$ such that $q^{-1}(x) \in U$, $q^{-1}(y) \in V, U\cap V = \emptyset, U\cap A = \emptyset, V\cap A = \emptyset$. Then $x\in q(U), y\in q(V)$ and both $q(U)$ and $q(V)$ are open in $X/A$ such that $q(U) \cap q(V) = \emptyset$. If $x \neq y = q(A)$ then you can use the fact that $A$ is compact and Hausdorff to show that there is are open subsets $U, V \subset X$ such that $q^{-1}(x)\in U, q^{-1}(y)\in A\subset V$ and $U\cap V = \emptyset$.
Answer: Notice that $X$ is normal.
Assume distinct $x',y'$ in the quotient space.

Case $x',y' \neq a$, the point to which $A$ identifies:
$x,$y the points in $X$ that quotient map maps to $x',y'$ can be separated by open sets.  Use those sets to separated $x',y'$ by open sets.  Note $x,y$ are not in $A$.
Case $x' \neq a, y' = a$:
the quotient map maps $x$ to $x'$, $A$ to $y'$. Since $x\notin A$, $x$ and $A$ can be separated by open sets.  As before use those sets to separate $x',y'$ by open sets.


Index of child views in custom RelativeLayout

Question: I would like to know how the child views in my custom RelativeLayout is drawn so that I can use getChildAt() (the childviews are defined in xml).
In particular, my layout contains 5 of these custom layout each containing a number of child views. Most solution I seen seem to be using findViewById() and indexOfChild(), however, since each child view with the same id would appear 5 times I am unsure if this method can be implemented. As a side note I would also like to know if how the index is determined so that when I make modification to the custom layout I would know how to adjust the index. Thanks!
Answer: RelativeLayout does not override getChildAt, so the order is the one defined in ViewGroup. The code of getChildAt is
2914    public View getChildAt(int index) {
2915        try {
2916            return mChildren[index];
2917        } catch (IndexOutOfBoundsException ex) {
2918            return null;
2919        }
2920    }


Kendo UI TabStrip not able to select default tab

Question: I am trying to add Kendo-UI tabstrip dynamically in my page.
I am able to add it, but after that i am not able to open it as default one.
Code which I have used is as follow.
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
     <kendo-tabstrip [ngStyle]="{'width': '400px'}">
        <kendo-tabstrip-tab
          *ngFor="let item of items let i=index"
          [title]="item.city"
          [height]="height"
          [selected]="i == selected"
          [disabled]="item.disabled"
        >

{{item.temp}}ºC

Rainy weather in {{item.city}}.

        </kendo-tabstrip-tab>
      </kendo-tabstrip>
    `
})

export class AppComponent {
  public selected: number = 0;
  public height: string = "300px";
  public items: any = [{
            disabled: false,
            city: "Paris",
            temp: 17
      }, {
            disabled: false,
            city: "New York",
            temp: 29
      }, {
            disabled: false,
            city: "Sofia",
            temp: 23
      }]

  constructor(){

    let a={
            city: "New Paris",
            temp: 20
      };

     setTimeout(() => {
      this.items.splice(0, 0, a);
      console.log(this.items);

      }, 100);

  }

}

Answer: You can load dynamic tabs and select default tab like this-
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
     <kendo-tabstrip [ngStyle]="{'width': '400px'}">
        <kendo-tabstrip-tab
          *ngFor="let item of items let i=index"
          [title]="item.city"
          [height]="height"
          [selected]="i == selected"
          [disabled]="item.disabled"
        >

{{item.temp}}ºC

Rainy weather in {{item.city}}.

        </kendo-tabstrip-tab>
      </kendo-tabstrip>
    `
})

export class AppComponent {
  public selected: number = 1;
  public height: string = "300px";
  public items: any = [{
            disabled: true,
            city: "Paris",
            temp: 17
      }, {
            disabled: false,
            city: "New York",
            temp: 29
      }, {
            disabled: false,
            city: "Sofia",
            temp: 23
      }]
}

Refer sample Plunker
See if this helps.
Comment: Please refer this plunker , it show two tab selected at same time and because of that behaviour is not as accepted, i wants to select first tab all time. Plunker : http://plnkr.co/edit/nPzIDHrlgVGkH783dVWx?p=preview


What piano chords should I memorize?

Question: Seems that there were similar questions, probably clear to most of forum folks, but still not to me as a piano beginner.
I found chords theory rather straightforward, however practicing seems a bit confusing. To be more specific, I found few recommendations to memorize (and play automatically) all major and all minor triads. Knowing that there exist Sus chords, seventh chords, ... as well as many inversions it becomes senseless to memorize them all.
So the question is if there exists some "reasonable" measure of what to memorize, if any ?
Comment: I'd say you need to memorize how to form chords rather than chords themselves
Comment: I'm not sure I understand what you're trying to do. Are you having problems playing some actual pieces, songs or something? Or are you trying to first acquire all possible skills, so that you're prepared for anything?
Comment: What's the purpose behind it? If you're reading music, the chords will be there as clusters of dots. Very different from trying to play pieces which are on lead sheets.
Comment: Maybe it's wrong, but I didn't play some piece. I simply red theory and then watch few videos explaining practical matters of playing chords.
Comment: All of them, the list is finite.  There are also useful, logical, formulas for building chords.  If you know these it makes the task easier.
Comment: Of course, Lou Reed famously said "One chord is fine. Two chords is pushing it. Three chords and you're into jazz." & wrote many songs based on that premise. He did however write a whole lot of stuff he'd have definitely called 'jazz' ;))
Comment: Funny that _Sweet Jane_ is one of Lou Reed's most popular songs. It has way more than three chords.
Answer: Understand how chords are built.  Then don't bother with rote-learning.  Learn the chords as they occur in the music you're playing.
Comment: Good point but terrible analogy!
Comment: yep, that's what I was thinking.  rather than learning individual chords learn how they're built is the answer.  it'd be like saying "which programming language should I learn" .. completely depends learn the fundamentals then you can use all of them
Answer: 1.start with the triads of the primary chords in root
position, major and minor scales
2.the 7th chords in root position.

chord progressions like cadence and 5th fall sequences with inversions.

dim.7 and +5 chords, N6 (neapolitanian)

aug. 6th chords (german, french, italian

Edit:
opposite to other answers I propose to elaborate the accompaniment of a new piece first with block chords and simple harmony and establish in a second step the extended chords. This kind of reduction and analysis may help as approach to develop the understanding of more complex harmonisation.
Add:
for a beginner it might be sufficient to know and understand the basic chords in C major and a-minor. (This can work like the moveable do or the R.N. Once learnt you can later transpose them  in other keys and often it will be helpful to transpose other keys back to C and am.
Comment: Never come across the need to read aug. 6th chords. Wouldn't they be written out in notes?
Comment: 6th chords are 1st inversion of root chords. It's like Laurence Payne says: their image in the note staff respectively the pattern of the keyboard must be memorized respectively recognized: a third and a fourth.
Answer: I'll reiterate what others have said: first learn triads, major, minor and diminished. Then move on to the diatonic seventh chords: major, minor, dominant, half-diminished, and fully diminished. Extending the seventh chord set with ninth chords and the French augmented sixth (dominant seventh flat five chord) would be the next logical step.
Starting with a base of triads, it should be noted on piano there are only 6 chord "shapes" for major/minor triads. Several shapes repeat like D, A, and E major.
When moving on to the other chords it's good to think in terms of modifications and additions to major and minor chords and learning a few principles about the black/white piano keys for specific intervals. For example, minor and dominant seventh chords are formed simply by adding a minor seventh to either a minor or major triad. All minor seventh will be same key color except those involving BC or EF. You can look for key color patterns in the same way for other intervals.
The point is to start with a relatively small base of triads where you think of the chord as a single unit. But when that base is established you should start to think in terms of intervals. The base triads are practical, but limited. Learning all intervals in all positions on the keyboard provides for the full range of chords.
All intervals in all positions is basically 12 intervals times 12 roots, or 144 specific intervals. That brings us back to a large number of things to learn. I think the way to deal with this effectively is to learn chord movements rather than discrete chords. Two chord progressions like V6/5 I or three chord progressions like ii7 bII7 I sequenced up/down by step covers practical chord changes and technical coverage of the whole keyboard. It's also a good way to learn chord inversions by putting them in their usual musical context. You can systematically "rotate" through inversions, like this V65 I, V4/3, V4/2 I6, V I6/4.
If you play cadential progressions, things like the classical cadences and the jazz progressions ii V I in major and minor, and also with the alternative tritone substitutions, which is somewhere around a dozen progressions, and then sequence them up/down by steps, you will develop the basis for playing automatically lots and lots of chords and the flexibility to move beyond rote memorization of everything.
Comment: Since the OP accepted this, I'd like to note that based on the OP's comments, the actual question is: "What piano chords should I memorize _before trying to play any pieces_." If this is the answer to THAT question, how is it possible that anyone has ever got to the point of being ready to play any music at all. The same comment applies to most of the answers.
Comment: OP said "Maybe it's wrong, but I didn't play some piece. I simply red theory and then watch few videos explaining practical matters of playing chords." To me it seems that the idea is to memorize everything first. I am very happy if I got it wrong and the OP doesn't have this nonsensical idea. At least @Laurence seems to have understood it the same way as I. (right?)
Comment: @piiperiReinstateMonica this wording "before trying to play any music pieces" was _not_ asked by the OP. It's not even implied. You made that up yourself.
Comment: In what way does that preclude practicing chord while also practicing specific pieces? _You_ are making up some scenario where the OP isn't going to learn any pieces until memorizing a set of chords. The OP didn't say that. I didn't say that. But clearly you are worried they plan to do that. So, write an answer with _your_ recommendations and warnings.
Comment: I asked that from the OP. You assume that you understood correctly. Never assume that. Hello @Zoran can you help us out here.
Comment: But, to get to your point. I would recommend someone practices chords and scales at the outset. That's very common. You start with something like Czerny's _Recreations_ and do daily practice of scales and chords. It's _ridiculous_ to think I'm suggesting a beginner should _not_ start learning pieces until they finished drilling ninth chords, etc. My first  paragraph lays things out in _progressive stages_.
Comment: That was not my point. Again you assumed you understood. Never assume that. My point was to make you and other people here consider that the OP may be asking about something impractical.
Comment: I didn't assume anything. The question was straight forward. I answered about what they asked, not about what _you_ assumed they were planning to do.
Answer: Perhaps extending Laurence's answer, I agree that the best way to memorize is to learn them in music context. Play many songs, figure out good voicings and practice them. This way you not only practice the chords themselves, but learn practical associations. As on piano transposition is not trivial, make sure to practice in all 12 keys.
Answer: As a fellow beginner, I think it's important to recognize that knowledge and memorization are different from the muscle memory associated with learning an instrument.  Learning how to construct a chord in theory can allow you to figure out how your fingers should be arranged for any particular chord you read about, but that's not what you'll do when you're actually playing.
To go from understanding chords in theory to actually playing chords as part of playing music requires developing a muscle memory for the relationships between the piano's keys and how you can move your hands between them.  As you encounter chords in your practice, they will become implicitly encoded into the part of your mind that transforms musical intention into motion and, via an instrument, into the sounds that contribute to music.  You can choose to focus on particular chords of interest in the genres you like to play and deliberately practice those progressions, which will help to strengthen that portion of the encoding, but you don't necessarily need to systematically practice every arbitrary chord.  This means that some rarely encountered chords will feel 'weirder' than others to play, but they'll be related to things you already know and you'll be able to adapt.
For me, personally, following a self-learning process, I've found that a combination of practicing scales and learning/practicing simple songs has helped a lot with developing that muscle memory.  I'm still just sticking to C/Am for the most part, but that suits my initial goals anyway, since my primary hobby is music production and I can always use the DAW to 'cheat' my recording in C into any other scale.  If you're still at the point of poking at the piano and want to actually get into playing, leave the theory for a bit and try looking for those basic exercises.  A lot of them are targeted at young kids, but that's fine, gotta start somewhere, right?
Answer: All of them.
What would happen if halfway through a piece you suddenly had to stop to work out what an E♭ minor 11 was as a first inversion, or how to voice it wide, with both hands without the bass sitting awkwardly on the third?
You learn these as patterns, not as absolutes. You're a human, not a computer ;)
Comment: Yikes, stuff like this is why I'm currently a lot better at playing piano from sheet music than lead sheets.
Answer: Most chords start out as triads. So learning the major and minor triads is essential.
Then they become more complex, with extensions, like 7, 9 11, 13. These simply add on to the triads in most cases, so knowing which are the m7 and 9 of E♭ major are, for example, you can play the whole chord -E♭9 - or an inversion thereof.
Understanding what difference say, a ♭5 of ♯9 makes in changing specific notes is good to know as well. So if you can play Cm, you can work out Cm7♭5 from there.
So, it's not such a daunting task as 'there are 1000 chords, learn them all'.
And, the more you get used to playing the basic triads as a start point, then adding extensions and/or changes, the more automatic it becomes to find your fingers getting there before your brain tells them to.

What piano chords should I memorize?


Using ajax with pager in ctools modal window

Question: Continuing my work from here, I have a modal window that displays a text field and submit button.  When the form is submitted, a Solr search is run using ajax, and the first ten results are displayed in a table with a pager.
/**
 * Implementation of hook_menu.
 */
function nb_alters_menu() {
  $items = array();

  $items['imgsearch/%ctools_js/%node'] = array(
    'page callback' => 'imgsearch_page',
    'page arguments' => array(1, 2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['imgsearch/%ctools_js/imgadd/%/%'] = array(
    'title' => 'Add Image',
    'page callback' => 'nb_alters_add_image',
    'page arguments' => array(1, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Page callback for imgsearch modal popup window.
 */
function imgsearch_page($ajax, $node) {
  if ($ajax) {
  // Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Image Search Form'),
    'base_node' => $node,
  );

  // Add custom settings for form size.
  drupal_add_js(array(
    'imgsearch-modal-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 750,
        'height' => 750,
      ),
    ),
  ), 'setting');

  // Use ctools to generate ajax instructions for the browser to create
  // a form in a modal popup.
  $output = ctools_modal_form_wrapper('imgsearch_form', $form_state);

  // If the form has been submitted, there may be additional instructions
  // such as dismissing the modal popup.
  if (!empty($form_state['ajax_commands'])) {
    $output = $form_state['ajax_commands'];
  }

  // Return the ajax instructions to the browser via ajax_render().
  print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('imgsearch_form', $node);
  }
}

/**
 * Drupal form to be put in a modal.
 */
function imgsearch_form($form, $form_state, $node) {
  $form = array();

  $form['search_terms'] = array(
    '#type' => 'textfield',
    '#title' => t('Search text'),
    '#description' => t('Enter the search terms'),
  );

  $form['replace_div'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#weight' => 6,
  );

  $form['node'] = array(
    '#type' => 'value',
    '#value' => $node,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Drupal form submit handler.
 */
function imgsearch_form_submit(&$form, &$form_state) {
  // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
  $return = nb_alters_search($form_state['values']['search_terms']);

  if (is_array($return['images']) && count($return['images'] > 0)) {
    // Create object to store file and target field info. To be stored in ctools cache.
    $file_info = new stdClass();
    // Calculate the field name.  It is a multivalue field, so we just need the next available option
    // in the $field_images['und'] array.
    $field_images = $form_state['base_node']->field_images['und'];
    $next_value = count($field_images);

    $file_info->fieldname = '#edit-field-images-und-' . $next_value . '-imgsearch-file-url';
    $file_info->fids = array();

    // Theme the results as a table.
    $header = array(t('Image'), t('File Name'), t('Add to field'));
    $rows = array();
    foreach ($return['images'] as $image) {
    // Create image style derivative for each image.
      $imagestyle = array(
        'style_name' => 'thumbnail',
        'path' => $image['filepath'] . $image['filename'],
        'width' => '',
        'height' => '',
        'alt' => '',
        'title' => $image['filename'],
      );
      $styled_image = theme('image_style', $imagestyle);
      $fid = $image['fid'];

      $rows[] = array(
        'image' => $styled_image,
        'name' => $image['filename'],
        'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $form_state['base_node']->nid, t('Select')),
      );

      $file_info->fids[$fid] = $image['filename'];
    }
    //Cache image name in ctools object cache so it can be used later in nb_alters_image_add()
    ctools_include('object-cache');
    ctools_object_cache_set('imgsearch', $form_state['base_node']->nid, $file_info);

    //$output = theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('imgsearch-table'))));

    // Create a render array ($build) which will be themed as a table with a
    // pager.
    $build['imgsearch_table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => t('There were no matching results found'),
    );

    // Attach the pager theme.
    pager_default_initialize($return['total_found'], $return['rows']);
    $build['imgsearch_pager'] = array('#theme' => 'pager');

    $output = drupal_render($build);
  }
  else {
    $output = '
No images found
';
  }

  // Tell the browser to replace add the table with returned images to the form.
  $form_state['ajax_commands'][] = ajax_command_replace('#imgsearch-replace-div', $output);
}

My problem is getting the pager to work so that when the pager link is clicked, the search is run again via ajax, and the results are written to the appropriate div (imgsearch-replace-div) on the page. Currently, the pager link is to imgsearch/nojs/$nid?page=x, which is just to the page function that displays the modal, but it's the form submit function that runs the search again and replaces the div with the output.  What do I need to do to get the form submission function to be run and the new set of results displayed, all via ajax?
Thanks.
Comment: It seems no one has answer to this ctools forms issue. Were you able to solve it?
Comment: Nope, no answer yet. However, I'm trying a new approach (see [this question](http://drupal.stackexchange.com/questions/173633/table-not-rendered-using-ajax-render-in-ctools-modal-window)).
Answer: I was able to get this working, but not without substantial re-working of my page callback and getting rid of the submit function. Details are in a blog post series I'm working on starting here, but the gist of it is that you can't use a submit function to start the search. This is because the links generated by the pager code always link back to the original page url, so you have to call the actual search from within the page callback, and then pass the page number param to your search function to get the correct results.


Getting the latest entry per day / SQL Optimizing

Question: Given the following database table, which records events (status) for different objects (id) with its timestamp:
ID | Date       | Time | Status
-------------------------------
 7 | 2016-10-10 | 8:23 | Passed
 7 | 2016-10-10 | 8:29 | Failed
 7 | 2016-10-13 | 5:23 | Passed
 8 | 2016-10-09 | 5:43 | Passed

I want to get a result table using plain SQL (MS SQL) like this:
ID | Date       | Status
------------------------
 7 | 2016-10-10 | Failed
 7 | 2016-10-13 | Passed
 8 | 2016-10-09 | Passed

where the "status" is the latest entry on a day, given that at least one event for this object has been recorded.
My current solution is using "Outer Apply" and "TOP(1)" like this:
SELECT DISTINCT rn.id,
                tmp.date,
                tmp.status

FROM run rn OUTER apply
  (SELECT rn2.date, tmp2.status AS 'status'
   FROM run rn2 OUTER apply
     (SELECT top(1) rn3.id, rn3.date, rn3.time, rn3.status
      FROM run rn3
      WHERE rn3.id = rn.id
        AND rn3.date = rn2.date
      ORDER BY rn3.id ASC, rn3.date + rn3.time DESC) tmp2
   WHERE tmp2.status <> '' ) tmp

As far as I understand this outer apply command works like:
For every id
  For every recorded day for this id
     Select the newest status for this day and this id

But I'm facing performance issues, therefore I think that this solution is not adequate. Any suggestions how to solve this problem or how to optimize the sql?
Answer: Your code seems too complicated.  Why not just do this?
SELECT r.id, r.date, r2.status
FROM run r OUTER APPLY
     (SELECT TOP 1 r2.*
      FROM run r2
      WHERE r2.id = r.id AND r2.date = r.date AND r2.status <> ''
      ORDER BY r2.time DESC
     ) r2;

For performance, I would suggest an index on run(id, date, status, time).
Comment: Great, this little change - which I was too blind to see - made the code running 8 times faster. Thanks a lot!
Answer: Using a CTE will probably be the fastest:
with cte as
(
    select ID, Date, Status, row_number() over (partition by ID, Date order by Time desc) rn
    from run
)
select ID, Date, Status
from cte
where rn = 1

Answer: Do not SELECT from a log table, instead, write a trigger that updates a latest_run table like:
CREATE TRIGGER tr_run_insert ON run FOR INSERT AS
BEGIN
    UPDATE latest_run SET Status=INSERTED.Status WHERE ID=INSERTED.ID AND Date=INSERTED.Date
    IF @@ROWCOUNT = 0
        INSERT INTO latest_run (ID,Date,Status) SELECT (ID,Date,Status) FROM INSERTED
END

Then perform reads from the much shorter lastest_run table.
This will add a performance penalty on writes because you'll need two writes instead of one. But will give you much more stable response times on read. And if you do not need to SELECT from "run" table you can avoid indexing it, therefore the performance penalty of two writes is partly compensated by less indexes maintenance.
Comment: Thank you for this suggestion, but it's a commercial application which I'm not allowed to change.


Regarding the theory of real addition with a nonzero constant

Question: Let us consider the theory of the structure $(\mathbb{R}, +, r)$, where $r$ is a nonzero constant. Does it matter which $r$ it is? In other words, is any theory of that form the same as any other theory of that form? This is different from a previous question, because that one was a universal algebra question, while this is a model theory question.
Comment: Does $(\mathbb{R}, +, r)$ come equipped with an ordering? Or can you construct a total ordering from the theory of the structure?
Answer: For any $c\in\mathbb{R}\setminus\{0\}$, the map $$x\mapsto cx$$ is an automorphism of $(\mathbb{R}, +)$; this means $(\mathbb{R}; +,r)\cong(\mathbb{R}; +, 1)$ for any $r\not=0$, so the answer to your question is "no" in the strongest way possible.


How does jQuery $(this) on Clicked element or class work?

Question: I have a simple html snippet.

Click Symptom

Click Remedy

Now for the click action...
$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom"))
    alert("Symptom Clicked");
if($(this).parents(".remedy"))
    alert("Remedy Clicked");
});

$(this) is supposed to refer only the element that I have clicked. Why does it alert both the alert statements even if the if conditions do not satisfy?
Comment: `parents` returns an object and objects are truthy values in JavaScript.  Use `parents(...).length` instead.
Answer: Change your code as following
$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom").length>0)
    alert("Symptom Clicked");
if($(this).parents(".remedy").length>0)
    alert("Remedy Clicked");
});

https://jsfiddle.net/1mz8s73b/
Comment: Strange! What does length indicate here?
Comment: @Jay, https://stackoverflow.com/questions/2877654/determining-whether-jquery-has-not-found-any-element/2877672


How do I use run_once with CallbackQueryHandlers in a telegram bot written in Python?

Question: I have written a telegram bot in python. In particular, I am working on this flow:
"recheck2" has an inlinekeyboardbutton that links to "timer", and "timer" will wait for an hour before activating "recheck3". "recheck3" runs a database query and sends a message to the telegram user.
The purpose of the bot is to allow the user to have an option to re-run the same query after an hour (or any predefined duration).
I receive an error on the line "context.job_queue.run_once...." saying that "ValueError: The following arguments have not been supplied: context".
I've based on code on timerbot.py and inlinekeyboard2.py avail at https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/README.md.... I've scanned thru many forums and QnAs, but unable to find any solution. I'm trying to avoid using sleep() as it suspends/blocks the code. Also, I tried asyncio.sleep but it doesn't work with bots with CallbackQueryHandlers.
Could a kind soul please point me in the right direction please? Thanks!
<code>def timer(update: Update,context: CallbackContext)-> None:
    chat_id=CallbackContext.chat_id
    due = int(3600) #to run recheck3 after one hour
    ****context.job_queue.run_once(recheck3, due, context=chat_id, name=str(chat_id))****

def recheck3(update: Update, context: CallbackContext) -> int:
    """Stores the info about the user and ends the conversation."""
    #user = update.message.from_user
    logger.info("%s: rechecked  for %s with timed delay", CallbackContext.firstname, CallbackContext.tag)
    update.callback_query.message.edit_text('Sure, will send you a message again in xxmins.')

    connection = cx_Oracle.connect(dsn="XXXXXX") ## ,encoding="UTF-8"

    cur = connection.cursor()
    tag=CallbackContext.tag #recall the user input
    cur.execute("SELECT * \
........ code truncated.....
</code>
Answer: Solved! Each job can only have ONE argument / can only take context as argument. Eg: My "timer" calls for "recheck3" and recheck3 must only take one argument (cannot have both update and context as arguments). Thanks to a kind Telegram user on https://t.me/pythontelegrambotgroup for the assistance!
Comment: Sure you can pass both or any count of arguments with context=(tuple)


Differential function as a linear map.

Question:
Consider the Linear Map $T\colon P_{3}(\mathbb{R}) \rightarrow P_{3}(\mathbb{R})$
  given by the
  set of infintely differentiable functions
  1) $T(f)\colon x \mapsto xf'(x)$ , Prove that $T$ is linear.
  2) What is $\ker T$ ?.

For 1) i think I make I have made this sort of error before, I think
of an input like
$ax^{3}+bx^{2}+cx+1$ so the derivative would be $3ax^{2}+2bx+c$
then then $T(x)$ would be $3ax^{3}+2bx^{2}+cx$ and similarly
$T(y) = 3ay^{3}+2by^{2}+cy$ but $T(x+y) = (x+y)f'(x+y) =(x+y)[f'(x)+f'(y)]
=xf'(x)+xf'(y) +yf'(x)+yf'(y)$ which is clearly
not equal to $T(x)+T(y)$ and similarly $T(cx) = cxf'(cx) \neq cT(x)=
cxf'(x)$, where am i going wrong here ?
For 2) would the kernal be $x: \{0\} \cup c$ where $c$ is a constant
since $x =0$ will output zero, and the differentiation of any constant
is zero.
Comment: Don't you mean $(T(f))(x):=xf'(x)$?
Comment: yes that is what is mean
Comment: So this is the answer to your question. Instead of dealing with $x$ and $y$, deal with $ax^3+bx^2+\ldots$ and $a'x^3+b'x^2+\ldots$ and show that $T$ takes the sum to the sum of images.
Comment: This is in many ways the root of your problem; you need to check that $T(f)$ is linear in $f$, so if $f$ and $g$ are two differentiable functions, then $T(f+g)=T(f)+T(g)$ (and something similar for scalars). You shouldn't try to check linearity in the arguments of the functions $f$ and $g$, because it won't hold, as you point out. Said differently, you want to check that $T(f+g)(x)=T(f)(x)+T(g)(x)$, *not* that $T(f)(x+y)=T(f)(x)+T(f)(y)$ - this second statement says that $T(f)$ is linear, rather than that $T$ is linear, and this won't be true for general $f$.
Comment: For part 2), you've described the set slightly inefficiently, because $0$ is itself a constant, so it isn't a special case. You have proved that this set is contained in the kernel; why is it the whole thing?
Answer: First of all, the notation should be $T(f)$ instead of the confusing $T(x)$, because the symbol $f$ would othewise remain undefined.
In any reasonable way, $T(f+g)=x(f(x)+g(x))'=xf'(x)+xg'(x)$ by the linearity of the derivative.
Assume that $xf'(x)=0$, the null polynomial of degree (at most) three. Then $xf'(x)$ is a polynomial of degree (at most) three without constant term. Its coefficients must vanish, and we remain with $f(x)=a_0$, a constant polynomial.
It is trivial now to conclude that $\ker T$ is exactly the set of constant polynomials.

Differential function as a linear map.


Residue for quotient of functions

Question: Let $f, g$ be holomorphic functions on a disk $\mathbb{D}(z_0,r)$ centered at $z_0$ and of radius $r>0$. Suppose $f$ has a simple zero at $z_0$. I want to find an expression for $Res(g/f, z_0)$. But I'm not sure what this expression should look like.
Here's my guess:
Since $f$ has a simple zero at $z_0$, $\exists h(z)$ holomorphic on $\mathbb{D}(z_0,r)$ such that $f(z)=(z-z_0)h(z)$ and $h(z_0)\ne 0$. So that we can represent $g/f = \frac{g(z)}{(z-z_0)h(z)}$, where we observe that $z_0$ is a pole of order 1 of $g/f$. This implies that we can express $$g/f=\frac{a_{-1}}{z-z_0}+\sum\limits_{n=0}^\infty a_n(z-z_0)^n$$
Hence, $$a_{-1}=\frac{g(z)}{f(z)}(z-z_0)-\sum\limits_{n=0}^\infty a_n(z-z_0)^{n+1}$$
Does this look like a correct approach? I think that this expression is too general because of the infinite series on the right-hand side. Is there a clue I'm missing?
Update:
Another approach might be this:
$$g/f = \frac{g(z)}{(z-z_0)h(z)}=\frac{c_0+c_1(z-z_0)+\dots}{d_1(z-z_0)+\dots}=\frac{c_0}{d_1(z-z_0)+\dots}\\
+\frac{c_1(z-z_0)+\dots}{d_1(z-z_0)+\dots}=\frac{a_{-1}}{z-z_0}+\sum a_n(z-z_0)^n$$
But what next?
Comment: $Res(g/f, x_0) = g/f'$. The proof of it is in most textbooks and is very straightforward. Think differentiation.
Answer: Suppose that $z_0$ is a simple zero of the fraction
$$\mathrm {Res}(g/f,z_0) = \lim_{z\to z_0}(z-z_0) \frac {g(z)}{f(z)}=\frac {g(z_0)}{f'(z_0)} \tag{1}$$

Alternatively
Since $f$ has a simple zero at $z_0$
$$\frac{1}{f} = \frac{a_{-1}}{(z-z_0)}+\sum_{k=0}^\infty a_k (z-z_0)^k$$
Suppose that $g$ is analytic in a nbhd of $z_0$
$$g(z) = \sum_{k=0}^\infty b_k(z-z_0)^k$$
Then
$$G(z)=\frac{g(z)}{f(z)} = \left( \sum_{k=0}^\infty b_k(z-z_0)^k \right)\left( \frac{a_{-1}}{(z-z_0)}+\sum_{k=0}^\infty a_k (z-z_0)^k\right)$$
Finally we have the residue at $z_0$
$$\mathrm {Res}(G(z),z_0) = a_{-1}b_0 \tag{2}$$
Comment: @sequence, to evaluate the residue at $z_0$ you need the coefficient of $(z-z_0)^{-1}$ which is in that case $a_{-1}b_0$.
Comment: @sequence, (+1) glad that hepled you.
Comment: I can't use this definition. I need to expose the constant $c_{-1}$. That is, I can only use the definition that $Res(f, z_0)=c_{-1}$ in the Laurent series.
Comment: @sequence, see my edit. I am not sure if this what you want.
Comment: How do you determine that $a_{-1}b_0$ is the needed constant in the series of $G(z)$? There doesn't appear to be the constant with the index $-1$ there.
Comment: Yes, this makes sense. Even though this doesn't the give answer more explicitly, in terms of the functions and their derivatives. We only know that $b_0=g(z_0)$, but we don't know what $a_{-1}$ is.
Comment: @sequence, that seems impossible. You have to have some information about $f(z)$.
Comment: Please see my answer. @ZaidAlyafeai
Answer: Here's what I've finally come up with, with credit to the answer by Zaid Alyafeai.
Since $f$ has a simple zero at $z_0$, we can express it as $f(z)=(z-z_0)h(z)$, where $h(z)$ is holomorphic on $\mathbb{D}(z_0, r)$ and $h(z)\ne 0$ on this set, so that $1/h(z)$ is holomorphic on $\mathbb{D}$ and has Taylor series $1/h(z)=\sum\limits_{k=0}^\infty a_k(z-z_0)^k$. Thus $\frac{1}{f}= \frac{1/h(z)}{z-z_0}=\sum\limits_{k=0}^\infty a_k(z-z_0)^{k-1}=\frac{a_0}{z-z_0}+O(1)$. $g(z)$ is holomorphic on $\mathbb{D}$, so it has Taylor series $g(z)=\sum\limits_{k=0}^\infty b_k (z-z_0)^k=b_0+O[(z-z_0)^2]$. So that $$\frac{g}{f}=\frac{b_0a_0}{z-z_0}+O(1)$$
where $b_0=g(z_0)$. Now, $f'(z)=h'(z)(z-z_0)+h(z)$, and $1/f'(z_0)=1/h(z_0)=a_0$. Hence,
$$Res(\frac{g}{f}, z_0)=\frac{g(z_0)}{f'(z_0)}$$

Residue for quotient of functions


How much does it matter if my Masters is in stats or math (in a stats track)

Question: I have a choice of Master's programs in statistics, one of which is formally a program in applied statistics, the other is formally in math with an applied statistics "track".
The courses in the 2 programs are about the same, so I am wondering how much the label of the degree really matters (I most likely will not work in academia unless I am doing contract work).
Comment: Related: [Things to consider about masters programs in statistics](http://stats.stackexchange.com/q/25713/2970).
Comment: Are you aware of the [academia](http://academia.stackexchange.com/) site? This question half-belongs there, except that there may be three people cross-active on both sites... all of whom have probably replied already :)
Comment: This thread is CW, & has upvoted answers. I think it has stood the test of time. It can stay open.
Comment: I think that math curriculum can change greatly in three years.  Someone up on academia might be able to give an informed answer but it doesn't seem fair to reevaluate old answers and the question is no longer relevant to the OP.
Comment: It might be of interest to the OP :)
Answer: It is my understanding that most employers focus on skills, not necessarily degree titles.  As long as you will obtain expertise with the same/similar techniques and list them on your resume, it should really not matter to the prospective employer.
Comment: My two cents - your comment is culture specific. In places like France, the name of the degree matters much more than in the US, where experience is more important.
Comment: @Scortchi, the diploma follows you for many years after graduation regardless of the private/public split. This often means that you are denied accesss to the best positions in a company (say, the lead of a team of statisticians) because of the school you graduated from. Of course, there are some SMEs that are taking the style of "English companies," where they say they care less about your diploma. However, even there you often see people coming from top programs. Side note - I'm an American doing a stats masters in France.
Comment: I agree with you! Skills are more important than degrees.
Comment: Get computer science and programming courses, or at least check which programs has better SAS/R/Stata courses. Software is the most important generalizable skill you can get while still in school. (Workflow and project management are some of the others, but nobody really teaches them well enough.)
Comment: @StasK: Computer Science? What 'Computer Science' courses consist of doubtless varies from country to country, but I understand it as being all about big O's, white-box testing, cyclomatic complexity, & the like: important stuff for software engineers, but tangential for statisticians, most of whom have to be only moderately competent programmers.
Comment: @Drew75: That's interesting (as well as being a good general point). Does it matter as much for employment with a private company as for public service?
Answer: Surely no-one cares what the degree's called, even in academia. (At least I can't remember ever coming across anyone who cared.†) You say the courses are "about the same", so focus on the differences & think about (1) what would be useful for what kinds of job; & (2) what's going to be easy to pick up later if you want to, & what you'd do better to get under your belt now. These two can sometimes conflict rather.
† I live & work in England—see @Drew's comment.
Comment: Not strongly disagreeing. When I put on my layman's hat, my connotation is that a "mathematician" is theoretical, while a "statistician" is applied. Not true, of course, but between that and an HR person being told that they need a "statistician", I think there could be a small point in favor of having "Statistics" in the title. As I said, I'd consider the quality of restaurants near the school before this factor, but I don't think absolutely no one cares about how something's named.
Comment: "Surely no-one cares"... If an HR drone is told to look for a "statistician", I'm not sure that a Math degree (with some kind of note that it's a Statistics "concentration" or "track") will be as obvious of a fit. That said, you'd never want to compromise your education on that off-chance, so I'd only consider this if I otherwise couldn't decide which program to choose. After I'd decided which institution was located near better restaurants.
Comment: @Wayne: The drones don't parse sentences; they just search for key-words. And a lot of companies do look for Math/Stats graduates.


What are the option for a post-hoc test after running a multinomial model?

Question: Currently, I am trying to run the multinomial model Age = Gender to investigate the effect of Gender on the probability that my study animal belongs to a particular age class. I am not necessarily interested in the model parameters, but more in the model fit estimates. More precise I am interested in whether:
Estimates significantly differ from 0.25 (no bias towards a particular age class)
Estimates significantly differ between males and females.
Until now, I tried to answer these questions by running the model, calculating the emmeans and using the contrast function to see if there are differences between both genders.
My main question is: Is this a statistically correct way (I know it from "normal" linear modelling , but as I use multinomial models, I don't know whether this is a good way )
WHAT I TRIED
a <- multinom(`Age class` ~ Sex , data = goodyears_hunting)
emmeans = emmeans(a,~ `Age class`  | Sex, mode = "prob")
x = as.data.frame(emmeans)
gt(x, rownames_to_stub = TRUE)
z =contrast(emmeans, "pairwise",  simple = "each", combine = TRUE, adjust = "mvt")
z = as.data.frame(z)
gt(z, rownames_to_stub = TRUE)

This resulted in the following emmeans output
Age Sex        prob         SE      df  lower.CL    upper.CL
0   female  0.2198662   0.01383598  6   0.1860108   0.2537216
1   female  0.3169641   0.01554436  6   0.2789284   0.3549998
2   female  0.1439735   0.01172819  6   0.1152757   0.1726714
3+  female  0.3191962   0.01557349  6   0.2810892   0.3573031
0   male    0.2067437   0.01206316  6   0.1772262   0.2362612
1   male    0.2954747   0.01359085  6   0.2622191   0.3287303
2   male    0.2413486   0.01274622  6   0.2101597   0.2725375
3+  male    0.2564329   0.01300724  6   0.2246054   0.2882605

For example: May I conclude that 2y female's are underrepresented in the population as 0.25 is not part from the confidence interval?
In case for the contrasts I get the following results (selected only the relevant part)
Age    contrast      estimate    SE         df  t.ratio       p.value
0   female - male   0.013122464 0.01835631  6   0.71487502  0.982821954
1   female - male   0.021489382 0.02064796  6   1.04075092  0.911929460
2   female - male   -0.097375074 0.01732099  6   -5.62179680 0.010827774**
3+  female - male   0.062763228 0.02029093  6   3.09316739  0.140517335

Is it correct to conclude that the ratio of 2y old indivduals is signficant different between males and females?
I am mainly confused as I have little experience with discrete data and have not used these types of models much. Hopefully some of you can approve my way of thinking, or help me on the right way :D
Comment: How biologically plausible in the null hypothesis that the four age groups (0yo, 1yo, 2yo and 3+yo) are equal in size?
Comment: rather unlikely
Comment: That's what I thought too but wasn't sure I understand how the null is specified. So why test and reject a null hypothesis that you know is wrong? There is little knowledge to gain from this. See for example [1](https://www.fharrell.com/post/nhst-never/), [2](https://statmodeling.stat.columbia.edu/2016/02/04/the-notorious-n-h-s-t-presents-mo-p-values-mo-problems/).
Answer: If you truly want to test the proportions against 0.25, that is possible; you should do
# as you have...
emmeans = emmeans(a,~ `Age class`  | Sex, mode = "prob")

test(emmeans, null = 0.25)

That said, I think I like your contrast comparisons better, because (a) that is a more conventional approach, and (b) when you test females against 0.25 and males against 0.25, you have two tests instead of one; what will you say if the conclusions are different?
Comment: Hi                                                                                Thanks for the answer. I am actually interested if the prob to be in a certain age class differs from 0.25. So I thinks it works with your piece of code. I use the contrast to more quantify the difference (if there is some) between two classes.          Does this clarifies my question a bit?


Display contact address in ios using xamarin

Question: absolute beginner with xamarin.
Followed the following tutorial to try and simply click a button to display the contact list, select a contact, and then to display firstname, surname, and address on the screen.
https://github.com/xamarin/recipes/tree/master/Recipes/ios/shared_resources/contacts/choose_a_contact
Managed to get the firstname and surname to be displayed,  but cannot get the address. Constantly getting the error
Foundation.MonoTouchException: Objective-C exception thrown.  Name: CNPropertyNotFetchedException Reason: A property was not requested when contact was fetched.

On the
contanct.PostalAddresses

This is the snippet of code:-
partial void UIButton197_TouchUpInside(UIButton sender)
    {

        // Create a new picker
        var picker = new CNContactPickerViewController();

        // Select property to pick
        picker.DisplayedPropertyKeys = new NSString[] { CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PostalAddresses };

        // Respond to selection
        var pickerDelegate = new ContactPickerDelegate();
        picker.Delegate = pickerDelegate;

        pickerDelegate.SelectionCanceled += () => {
             SelectedContact1.Text = "";
        };

        pickerDelegate.ContactSelected += (contact) => {
            SelectedContact1.Text = contact.GivenName;
            SelectedContact2.Text = contact.FamilyName;
            SelectedContact3.Text = contact.PostalAddresses
        };

        pickerDelegate.ContactPropertySelected += (property) => {
            SelectedContact1.Text = property.Value.ToString();
        };

        // Display picker
        PresentViewController(picker, true, null);
    }

Am i missing something?
Answer: Seem to have resolved this if anyone else is having a similar issue.
The solution was to completely close down visual studio on the mac and re-open it.
Originally, i was stopping the project, and re-building. Possibly a bug, but non of my changes where being picked up.
A simple re-start kicked it back in


title in page.html.twig

Question: I find out title is not exists in page.html.twig, and there is a file page-title.html.twig to theme title, then in block section we should use block title. ( ** I don't want use this strange structure for title,really I  didn't find out why Drupal do this  !!!).
any way
I want to provide it by myself, maybe hook_preprocess_page is solution,any body know how can I add title variable to page variables ?
Comment: You can find the reasons why this was done here: https://www.drupal.org/node/2568563 and https://www.drupal.org/node/2476947
Comment: @4k4 thanks. but if I don't want use any region and block system then ? I think  beside block title, title variable have to exists in page templates.
Answer: This is my solution for adding title to page templates.
in yourthemename.theme add
function hook_preprocess_page(&$vars) {
    if(isset($vars['node'])) {
        $vars['title'] = $vars['node']->title->value;
    }
    else{
       $vars['title'] =$vars['page']['#title'];
    }
 }

then title exist in page templates.
Answer: You can get it with:
{% if node.label %}
  {{ node.label }}
{% else %}
  {{ page['#title'] }}
{% endif %}

Comment: it's about page title, not just node title ;-)
Comment: True, edited answer.
Comment: I prefer the previous answer. because it handled in PHP side and FrontEnd developer shouldn't care about the logic.

title in page.html.twig


Unexpected matlab behaviour when using vectorised assignment

Question: I've come across some unexpected behaviour in matlab that I can't make sense of when performing vectorised assignment:
>> q=4;

>> q(q==[1,3,4,5,7,8])
The logical indices contain a true value outside of the array bounds.

>> q(q==[1,3,4,5,7,8])=1

q =

     4     0     1

Why does the command q(q==[1,3,4,5,7,8]) result in an error, but the command q(q==[1,3,4,5,7,8])=1 work? And how does it arrive at 4  0  1 being the output?
Comment: Let's see a simpler example `a = 4;` then `a(2)` will give you that error and `a(2)=1` will be okay.
Comment: Assigning to an out-of-bounds index will expand the array and write to that index. Reading an out-of-bounds index is an error.
Answer: The difference between q(i) and q(i)=a is that the former must produce the value of an array element; if i is out of bounds, MATLAB chooses to give an error rather than invent a value (good choice IMO). And the latter must write a value to an array element; if i is out of bounds, MATLAB chooses to extend the array so that it is large enough to be able to write to that location (this has also proven to be a good choice, it is useful and used extensively in code). Numeric arrays are extended by adding zeros.
In your specific case, q==[1,3,4,5,7,8] is the logical array [0,0,1,0,0,0]. This means that you are trying to index i=3. Since q has a single value, reading at index 3 is out of bounds, but we can write there. q is padded to size 3 by adding zeros, and then the value 1 is written to the third element.
Comment: Thank you for the really clear explanation. I make use of that feature quite a bit, not sure why it was such a mystery here!


Url Rewriting not working on server

Question: I am using Context.RewritePath in Application_BeginRequest to make my url user friendly, everything works fine on my local machine but on the server(shared) i get 404 errors. do you have any idea how can i fix this problem?
thanks
Answer: Which IIS version are you running? 6?
As far as I know the URL that you want to map, must be physical existing in order to make this work.
Example: /Page/Television/default.aspx should map to /page?id?=5
You need to create the Folder Page/Televsion and the default.aspx in your solution.
The default.aspx must not contain more than "<% Page %>
Answer: Under Cassini, Application_BeginRequest runs for all files.  Under IIS, it only runs for files with managed handlers, such as *.aspx files.
For the general case, you will need to create your own HttpModule.  Here's an example (based off of a similar one from my book: Ultra-Fast ASP.NET):
using System;
using System.Web;

namespace Samples
{
    public class RewriteExample : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
        }

        void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            // re-write URL here...
        }

        public void Dispose()
        {
        }
    }
}

Then register it in web.config (this is for IIS; using Cassini is slightly different):
<system.webServer>
  <modules>
    . . .
    <add name="RewriteExample" type="Samples.RewriteExample" />
  </modules>
</system.webServer>

Comment: How do I create an HttpModule? Could you provide an example please?

thanks

Url Rewriting not working on server


Deriving $E[g(X)h(Y)]$

Question: My attempt:
$\sum_x \sum_y g(x)h(y)f_x(x)f_y(y)$?
Is this the correct way?

Problem: Let $X$ take one of two values ${x_1, x_2}$ with $p_1 = P(X = x_1)$ and let $Y$ take one of two values ${y_1, y_2}$ with $q_1 = P(Y = y_1)$. Let these two discrete random variables be independent. Derive $E[g(X)h(Y )]$ and compare this to $E[g(X)] × E[h(Y )]$.
Comment: Because $X$ and $Y$ are two independent random variables, your attempt is correct.
Comment: Awesome. Thanks @HasanHeydari
Answer: Yes, ${{\mathsf E[g(X)\,h(Y)] ~}{= \sum_x\sum_y g(x)\,h(y)\,f_X(x)\,f_Y(y) \\ = {p_1q_1g(x_1)h(y_1) +p_1(1-q_1)g(x_1)h(y_2)\\+(1-p_1)q_1 g(x_2)h(y_1)+ (1-p_1)(1-q_1)g(x_2)h(y_2) }}}$
Similarly $\mathsf E[g(X)]\;\mathsf E[h(Y)] ~{= (\sum_x g(x)\,f_X(x))(\sum_y h(y)\,\,f_Y(y))\\ =}$
How do they compare.

Deriving $E[g(X)h(Y)]$


File Watcher console application closes after one execution

Question: I have a console application that watches for directory, It runs only once, I need the application to keep running and watching the directory for files.
The code also check if the files are already, if it is then it moves it, it there is none it should wait and watch, but the wait and watch is not happening.
Here is the code
class Program
    {
        public static String stagepath = @"C:\Users\a\Desktop\.NET Data Loader\stage\";
        public static String archivePath = @"C:\Users\a\Desktop\.NET Data Loader\archive\";
        static void Main(string[] args)
        {
            DirectoryInfo dirinfo = new DirectoryInfo(stagepath);
            FileInfo[] file = dirinfo.GetFiles();
            if (file.Length > 0)
            {
                MoveFile(stagepath);
            }
            else
            {

                MonitorDirectory(stagepath);
            }

        }

        public static void MonitorDirectory(string path)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
           watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Changed += FileCreated;
            watcher.EnableRaisingEvents = true;

        }

        private static void FileCreated(object sender, FileSystemEventArgs e)
        {
            if (!FileIsReady(stagepath+e.Name)) return;
            System.Threading.Thread.Sleep(1000);

            MoveFile(stagepath);

        }

        private static  bool FileIsReady(string path)
        {
            try
            {
                using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    return true;
                }
            }
            catch (IOException)
            {
                return false;
            }
        }

        private static void MoveFile(string path)
        {

            string[] fileNames = Directory.GetFiles(path);
            var sort = from fn in fileNames
                       orderby new FileInfo(fn).Name ascending
                       orderby new FileInfo(fn).LastWriteTime ascending
                       select new FileInfo(fn).Name;
            foreach (string fi in sort)
            {

                System.IO.File.Move(stagepath +fi, archivePath+fi);
                Console.WriteLine($"File {fi} has been sucessfully moved ");
            }
        }
    }

Comment: Of course it does. Your Main() and the methods it calls have no looping in it, so it runs once and is done.
Comment: I completely understand that, but i am not sure how to effectively loop..
Comment: This egg has to go before the chicken.  *First* decide what the user should do to make your program stop running.  *Then* it becomes easy to decide what code you need.  For possible inspiration, consider [the Any Key](https://en.wikipedia.org/wiki/Any_key).
Comment: Well this application is going to be running in the background processing files as they arrive. The only way the application would stop, is if the service is stopped manually, otherwise consider this as an infinite loop, unless service stopped
Answer: Put your code that moves files in a loop, like a while loop. Be sure to put a Thread.Sleep after each cycle.
MSDN - Thread.Sleep
Hook up your events for the FileSystemWatcher just once upon initialize.
Probably, going to want a way to exit the loop, unless killing the process is sufficient.

Update
I revamped it so no loop was needed. You're going to have to modify this a bit to get it exactly how you want it, but at least now you have a working example. In the future use the Visual Studio/IDE debugger there was a number of things wrong with the original example.
Your issue specifically was that your file paths were jamming the path and the file name together so for example a file located C:\temp\foo.txt would become C:\tempfoo.txt. Then you were checking if the file could be opened before moving it, which it cannot because the malformed path doesn't exist. Additionally, the console just needs to be kept open, looping is not necessary. The event was still being triggered properly just the code to move files had a bug. You may want to remove the sleep from the FileCreatedInMonitoredDirectory event handler I don't think it is needed, but I left it in there because that's how it was originally.
using System;
using System.IO;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        private static string _monitoringPath = @"C:\temp";
        private static string _destinationPath = @"C:\dest";
        static void Main(string[] args)
        {
            MonitorDirectory(_monitoringPath);
            Console.ReadKey();
        }

        public static void MonitorDirectory(string path)
        {
            var watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Changed += FileCreatedInMonitoredDirectory;
            watcher.EnableRaisingEvents = true;
        }

        private static void FileCreatedInMonitoredDirectory(object sender, FileSystemEventArgs e)
        {
            MoveFilesInDirectory(_monitoringPath);

            System.Threading.Thread.Sleep(1000);
        }

        private static bool CanFileBeOpened(string path)
        {
            try
            {
                using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
                    return true;
            }
            catch (IOException ioEx)
            {
                Console.WriteLine($"Warning: File could not be opened, it will not be moved. {ioEx}" );
                return false;
            }
        }

        private static void MoveFilesInDirectory(string dirPath)
        {
            string[] fileNames = Directory.GetFiles(dirPath);
            var sortedFileNames = from fn in fileNames
                                  orderby new FileInfo(fn).Name ascending
                                  orderby new FileInfo(fn).LastWriteTime ascending
                                  select new FileInfo(fn).Name;

            foreach (string fileName in sortedFileNames)
            {
                string filePath = Path.Combine(_monitoringPath, fileName);

                if (!CanFileBeOpened(filePath))
                    continue;

                var fileInfo = new FileInfo(filePath);
                if (fileInfo.Length > 0)
                {
                    File.Move(Path.Combine(_monitoringPath, fileName), Path.Combine(_destinationPath, fileName));
                    Console.WriteLine($"File {fileName} has been moved successfully.");
                }
            }
        }
    }
}

Comment: Do you mind giving me a example  on how do i go about doing this?
Answer: Hi just change your code as below:
    static void Main(string[] args)
    {
        DirectoryInfo dirinfo = new DirectoryInfo(stagepath);
        FileInfo[] file = dirinfo.GetFiles();
        if (file.Length > 0)
        {
            MoveFile(stagepath);
        }
        else
        {

            MonitorDirectory(stagepath);
        }
        Console.ReadKey();

    }

When you are using file watcher, another thread is made that it is live till your application is run. so you need just  keep your application run with any strategy.
Comment: Use debugger and see what happens when you create a new file
Comment: Well it keep the window active, but when a new file comes in it doest execute anything


Copy a content type from another site

Question: I am the owner of 2 sites that are running Drupal 8. In Site[X] I have news nodes.
In Site[Y], I want to automatically get all the news nodes that are posted on Site[X] (title, body, images etc.).
Scenario:

Site[X] making new content (news) article
Site[Y] checking for new nodes, copying them, and saving them in the database to show them on Site[Y]

How can I do this the best/easiest/safest way in Drupal 8, with what methods, languages and how do I start?
Comment: content type(and fields) are config so that is easy but content itself has to be migrated, so you will have to write a migration plugin with site X DB being the source and run it via cron or something).
Answer: Although not yet a full release for D8, Feeds is perfect for this type of thing.
That said if you have the know-how, when saving a node, you could post to the second site, and consume the data using the built-in REST API.

Copy a content type from another site