Lentidão em arquivo arquivo restrito

Question: Tenho um arquivo em php processo.php que recebe informações em looping via jquery e faz uma requisição a outra pagina com curl, esse arquivo faz algo em torno de 4 á 5 mil requisições uma por uma, tudo funcionava bem mais depois que restringi o acesso ao arquivo usando sessões por meio do código:

ob_start();
session_start();

if(isset($_SESSION["numlogin"])){
    $n1 = $_GET["id"];
    $n2 = $_SESSION["numlogin"];
    if($n1 != $n2) { }

}else{
    header("location:index.html");
}

O retorno dos dados ficou lentíssimo antes retornava na tela 2 até 3 json arrays por segundo mais agora a cada 8 segundos retorna uma array somente, creio que é porque ele executa a verificação do session a cada requisição como posso melhorar isso ?
meu processo.php

<?php
error_reporting(0);

ob_start();
session_start();

if(isset($_SESSION["numlogin"])){
    $n1 = $_GET["id"];
    $n2 = $_SESSION["numlogin"];
    if($n1 != $n2) { }

}else{
    header("location:../../../index.html");
}

$dados = $_POST["entrada"];
$nome = explode("|", $dados)[0];
$data = explode("|", $dados)[1];

function GetStr($string, $start, $end){
$str = explode($start, $string);
$str = explode($end, $str[1]);
return $str[0];
}

$ch = curl_init();
$url = "";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "nome=$nome&data=$data");
$resultado = curl_exec($ch);
curl_close($ch);

$valor = GetStr($resultado, '',"");

if ($valor == "Sair") {
$dds = array("consulta 1" => $nome, "data" => $data, "resultado" => "existe");
} else {
$dds = array("consulta 4" => $nome, "data" => $data, "resultado" => "nao existe");
}

echo json_encode($dds);

ob_end_flush();

?>
Comment: Se é o tratamento de sessão que tornou o processamento mais lento, por que não tratar mais de uma requisição ao mesmo tempo? O seu jquery nao pode juntar tudo e mandar num POST só, para o PHP fazer o curl em loop?
Comment: O problema é que isso lagaria muito o servidor por isso mesmo o jquery ja envia linha por linha do lado do cliente, assim fica tudo equilibrado
Answer: Isso possivelmente está ocorrendo porque o session_start trava a leitura simultânea. Dois processos não podem ler o mesmo arquivo, sendo assim um mesmo usuário não pode carregar duas páginas ao mesmo tempo enquanto o cURL da primeira não for finalizado.

Altere:
session_start();

Para:
session_start();
session_write_close();

Isso deve ser suficiente para que outros processos possam ler o mesmo arquivo. Usar o write_close apenas diz que não irá gravar nada, mas ainda pode ler a sessão normalmente.
Comment: Obrigado funcionou perfeitamente como o esperado

Lentidão em arquivo arquivo restrito


Como não mostrar tela de erro para Usuário - LARAVEL

Question: Bom dia galera, como eu faço para não mostrar o erro igual a imagem para o Usuário?
Essa imagem é só um exemplo
Comment: Qualquer no codigo que presente uma inconcistência  sempre tem que apresentar o ocorreu. O que você pode fazer e tratar os erros assim assim apresentando de forma coesa em uma tela amigavel  os possiveis erros.
Answer: basta editar o .env e setar APP_DEBUG=false
Comment: nossa perfeitooooooooooooooo... obrigado
Comment: marca concluído aki ^^
Comment: O meu nao fucnionou. php 7.4 Laravel 4.2
Comment: Deu certo pra mim, valeu!


Is the conditional probability fallacy exising in the case of an individual with full control

Question: Hello I had a very interesting discussion and I need your help in clarifying the correct answer.
TLDR: Problem statement for a layman: Given I am a woman and I want to become professor, and given that $75\%$ of the professors are male - would it help if I fully control and change my gender by surgery, etc. to become a male because then the chances of becoming a professor would be higher (pretending the process was truly only influenced by the gender and there were no other influencing variables like publication success). Please forgive the placative example but this is the catchiest I could imagine to make this an interesting, more or less real life question.
More formal description:
Given two discrete, binary random variables $X$ (gender, is male) and $Y$ (is professor), which have some joint probability $P(X,Y)$ which is unknown.
Let us have a conditional dataset with random samples where people $(x_i,y_i=1)$ with $i = 1,...,N,$ a big number.
Let's say I can estimate the conditonal probability almost perfectly (so I will not differentiate between estimated probabilities and true probabilities in the following).
This means from the dataset I infer $P(X\mid Y=1)$.
Now I also know Bayes theorem:
$$P(Y\mid X) =\frac{P(X\mid Y)P(Y)}{P(X)}$$
Now I want to know for an individual with full control over $X$ (i.e. not the population or a bigger sample) how to increase the individual probability $P(Y=1\mid X)$.
$$P(Y=1|X) =\frac{P(X\mid Y=1)P(Y=1)}{P(X)}$$
What to look at?
Update
I should look at the relative risk https://en.m.wikipedia.org/wiki/Relative_risk which is not possible since P(X) is unknown in the dataset!
Ignoring the base rate P(X) while computing the relative risk is a form of base rate fallacy.
PS: A) I know that the dataset needs to be representative and may not suffer from selection bias. B) there may not be any confounders which would affect the outcome of $Y.$ C) if you ask how to interpret the probability of becoming a professor for an individual, the answer is parallel universes :)
Comment: I am not sure I understand your argument.  Let's change the structure: suppose I had a ticket-based lottery and said that I have four equivalent prizes, but would award one prize by drawing from the green tickets sold and three by drawing from the red tickets sold, and everybody knows this.  You can buy one ticket: would you buy a red or a green ticket? If you knew that so far $80\%$ of tickets sold have been red, would that affect your choice? $75\%$?
Comment: I am not sure your problem is equivalent. I feel the constraint to a fixed number of prizes and the involvement of other people's decisions makes it harder and non-equivalent
Answer: I hope I understand the setup right but to me yes it does increase or decrease your chances of success on $Y$. I always like to think of Conditional Probabilities as simply just changing/shrinking the sample space. Consider the figure below of the binary events $X$ and $Y$ after fixing $X=1$, then surely your new sample space or the area you're thinking about will change and depending on the available information and you will be able to leverage the fixing of X to increase your chances. Although not the same problem but kinda reminds me of the Monte Hall problem.

Comment: I was wrong. I should have read https://en.m.wikipedia.org/wiki/Relative_risk in general we are interested in P(Y=1|X=0)/P(Y=1|X=1)=[P(X=0|Y=1)P(Y=1)/P(X=0)]/[P(X=1|Y=1)P(Y=1)/P(X=1)] which involves the marginal frequency P(X). As soon as P(X) has a big imbalance, this starts to matter.


Github STAR button on repository page

Question: Is there any way to add star button to the promotional page of the repository just like there is facebook like and Google Plus' +1 button?
Comment: Not easily. Using the API you'd have to make this call `https://developer.github.com/v3/activity/starring/#star-a-repository` but it requires authentication so first you'd have to get an oath token (`https://developer.github.com/v3/oauth_authorizations`)
Comment: Have a look at [this](http://ghbtns.com/)
Comment: @KamranAhmed: Great, posted as an answer so others can find it easily
Answer: I use GitHub buttons, which you can find here
Comment: The problem with ghbtns.com is that when you click on the star button it doesn't actually star the project.  It just takes you to the GitHub page.  Then you have to click the button again.  This will be confusing for many users.
Comment: But there used to be official buttons where you had to click only once to star a project, right? Were they discontinued?
Answer: You can also use the unofficial buttons provided by:
https://buttons.github.io (more customization options).

You can find the source code here: https://github.com/ntkme/github-buttons

Github STAR button on repository page


Find electric potential at a point at the edge of a charged disc of uniform surface charge density

Question: If I've made any mistakes, please point them out in the comments

Find electric potential at a point at the edge of a charged disc of uniform surface charge density

I started by setting up a curved charge element(an Arc), and took the point about which I want to find the potential as Origin
Let the angle the point at which the arc touches either end of the disc be $\theta$ and the distance between the point and the ends of each element vary from $r$ to $R$
First to find the area  of the element $dQ=r \sigma dr d({\theta})$
where r varies from r to R and the angle varies from $0$ to $\theta $
that gives $\sigma \frac{(R^2-r^2)}{2}\theta $ as the charge on a given charge element
now  $dV =\frac{kQ}{r}$
so here $$dV=\sigma \frac{(R^2-r^2)}{2}\theta $$
so
not too sure how to proceed from here
Alternatively, starting by finding the Potential due to an arc at a distance $x$ from its midpoint
so that would be
$dV=\frac{\sigma xdxd\theta}{x}$
which would mean the potential  would be
$$dV=\int_0^\theta \int_r^R\sigma dxd theta  $$
which simply  is $\sigma (R-r)\theta $
Edit:- If possible, I would like to stick to Cartesian coordinates and single integrals
Comment: Your expression for $dQ$ is the charge from $r$ to $r+dr$ and from $\theta$ to $\theta + d\theta$.  Now from one given point on the perimeter you have to integrate $\frac {dQ}\rho$ over the disc, where $\rho$ is the distance from your given point to another point on the disc.
Comment: What are the co-ordinates at which you want to find $V$? If they are $(R,\phi)$ then the problem will require evaluating some nasty integrals, resulting finally in $V=\sigma R/\pi \epsilon_0$. To set up the integrals you need to carefully draw a diagram that indicates the co-ordinate $r$ and the different $r'=$distance from $dq$ to the point you're evaluating $V$ at
Comment: @Sal a point on the edge of the disc
Answer: Let's take your first approach. The problem is we need to know the distance between the point $r \times \theta$ (where $r \in [0, R]$ and $\theta \in [0, 2 \pi)$) and the location of the test charge, $R \times 0$. To find the distance, let's convert into Cartesian coordinates: the first point becomes $r \cos \theta \times r \sin \theta$, and the test charge becomes $R \times 0$. The (Euclidean) distance is therefore $d (r) = ((R - r \cos \theta)^2 + (r \sin \theta)^2)^\frac{1}{2}$.
You are correct that the differential charge is $dQ = \sigma r dr d\theta$. The contribution of the charge to the potential is $dV = k \frac{dQ}{d}$. Therefore, your desired potential is
$$V = k \sigma \int_0^R \int_0^{2 \pi} \frac{r}{(R^2 - 2 r R \cos \theta + r^2)^\frac{1}{2}} d\theta dr$$
You could non-dimensionalize a bit with $\hat{r} = \frac{r}{R}$ to get
$$V = [k \sigma R] \underbrace{\int_0^1 \int_0^{2 \pi} \hat{r} (1 - 2 \hat{r} \cos \theta + \hat{r}^2)^{-\frac{1}{2}} d\theta d\hat{r}}_I$$
At this point it just becomes a matter of evaluating integrals. The integral over $\theta$ gives
$$I = \int_0^1 \left( \frac{4 \hat{r}}{1 - \hat{r}} \right) K \left(- \frac{4 \hat{r}}{(1 - \hat{r})^2} \right) d\hat{r}$$
where $K(x)$ is an elliptic integral of the first kind. The result turns out to be $I = 4$. So your answer is
$$V = 4 k \sigma R$$
EDIT
The really simple answer suggests there might be a simpler approach. There is indeed for this problem. Consider arcs centered $R \times 0$. These arcs will intersect the disc at two points; let the separation angle be $2 \theta$. Note that $\theta$ ranges from $\frac{\pi}{2}$ (when the arc has $0$ radius) down to $0$ (when the arc has a radius of $2 R$). Through simple trigonometry, you can see that the relationship between the radius of the arc and $\theta$ is given by $r = 2 R \cos \theta$. The differential charge on an arc is $dQ = 2 \sigma r \theta dr$, so the contribution to the potential is $dV = k \frac{dQ}{r} = 2 k \sigma \theta dr = -4 k \sigma R \sin \theta d\theta$. Then
$$V = \int_{\frac{\pi}{2}}^0 -4 k \sigma R \sin \theta d\theta = 4 k \sigma R \underbrace{\int_0^{\frac{\pi}{2}} \sin \theta d\theta}_{1} = 4 k \sigma R$$
just the same as with the more complicated method.


What is the best way to make some content only available to authenticated users?

Question: I'm currently trying out Drupal 8, but I'm wondering what is the best way to make some content (content types and some specific nodes) only available to authenticated users?
I'm using 2 content types, private and public, with both using the same taxonomy, but I would like one type to be published public and one private.
Comment: See https://drupal.stackexchange.com/questions/231420/is-there-a-way-to-avoid-anonymous-user-can-see-a-node-of-a-specific-content-type for more recent answers
Comment: Possible duplicate of [Is there a way to avoid anonymous user can see a node of a specific content type?](https://drupal.stackexchange.com/questions/231420/is-there-a-way-to-avoid-anonymous-user-can-see-a-node-of-a-specific-content-type)
Answer: You can use the combination of ACL and Content access modules to achieve this. ACL + Content access give you better control over access to content: You can make certain types accessible to certain roles, or even specific nodes accessible to specific users.
Now here comes the tricky part:
Both the Acl and Content Access modules have no D8 release yet and have patches in their issue queues, which convert them to D8. For some reason the maintainers have not created D8 branches yet, but I'm using the patched versions of both the modules on my company site - they work perfectly.
ACL patch can be found here.
Content access patch can be found here.
Answer: Use the Content Access Drupal module, it allows per content type and per node access rights.

This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


Is there a name for the matrix $X(X^tX)^{-1}X^{t}$?

Question: In my work, I have repeatedly stumbled across the matrix (with a generic matrix $X$ of dimensions $m\times n$ with $m>n$ given) $\Lambda=X(X^tX)^{-1}X^{t}$. It can be characterized by the following:
(1) If $v$ is in the span of the column vectors of $X$, then $\Lambda v=v$.
(2) If $v$ is orthogonal to the span of the column vectors of $X$, then $\Lambda v = 0$.
(we assume that $X$ has full rank).
I find this matrix neat, but for my work (in statistics) I need more intuition behind it. What does it mean in a probability context? We are deriving properties of linear regressions, where each row in $X$ is an observation.
Is this matrix known, and if so in what context (statistics would be optimal but if it is a celebrated operation in differential geometry, I'd be curious to hear as well)?
Comment: Perhaps you mean $X(X^TX)^{-1}X^T$? Otherwise the sizes don't match.
Comment: If so, I think the properties you have listed are a perfectly good interpretation: the matrix $\Lambda$ projects any vector $v$ to the column space of $X$.
Comment: Oh, I actually figured it out now. $(I-\Lambda)$ takes outcomes $Y$, does a regression and spits out the estimated residuals. If anyone else is interested, I'll elaborate more.
Answer: It is also called hat matrix. The idea is that this matrix "gives the hat": transforms the dependent variable to its prediction in linear regression.
The linear regression model is the following:
$$y=X\beta+\varepsilon.$$
The least squares estimate of the $\beta$ is defined as
$$\hat\beta=(X^TX)^{-1}X^Ty.$$
The prediction of the model is then:
$$\hat{y}=X\hat\beta=X(X^TX)^{-1}X^Ty$$
So we get that matrix $X(X^TX)^{-1}X^T$ transforms $y$ to $\hat{y}$, hence the hat matrix.
Comment: Beautiful. This was exactly what I was looking for. I just (well, 35 minutes ago) managed to deduce the relevant properties but knowing that it is called the hat matrix might be very useful! Thanks!
Answer: This should be a comment, but I can't leave comments yet.  As pointed out by Rahul Narain, this is the orthogonal projection onto the column space of $X$


How to optimize this kind of loop?

Question: I'm trying to make this GUi.

I write my own layout because existing layout manager don't meet my requirements
It works but I attempt to optimize the creation of all buttons by using loops.
Test.class
public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        JPanel parent = new JPanel();
        f.add(parent);
        parent.setLayout(new BoxLayout(parent, BoxLayout.X_AXIS));

        JPanel[] children = new JPanel[6];
        for (int i = 1; i < children.length; i++) {
            children[i] = new JPanel();
            children[i].setLayout(new XYLayout());
            children[i].setBorder(new LineBorder(Color.red));
            parent.add(children[i]);
        }

        int x = 0, y = 375, w = 0, h = 50;

        children[1].add(new JButton("8"), new XYConstraints(0, 25, 0, 50));
        children[1].add(new JButton("7"), new XYConstraints(0, 75, 0, 50));
        children[1].add(new JButton("6"), new XYConstraints(0, 125, 0, 50));
        children[1].add(new JButton("5"), new XYConstraints(0, 175, 0, 50));
        children[1].add(new JButton("4"), new XYConstraints(0, 225, 0, 50));
        children[1].add(new JButton("3"), new XYConstraints(0, 275, 0, 50));
        children[1].add(new JButton("2"), new XYConstraints(0, 325, 0, 50));
        children[1].add(new JButton("1"), new XYConstraints(0, 375, 0, 50));

        children[2].add(new JButton("7"), new XYConstraints(240, 25, 0, 100));
        children[2].add(new JButton("6"), new XYConstraints(200, 75, 0, 100));
        children[2].add(new JButton("5"), new XYConstraints(160, 125, 0, 100));
        children[2].add(new JButton("4"), new XYConstraints(120, 175, 0, 100));
        children[2].add(new JButton("3"), new XYConstraints(80, 225, 0, 100));
        children[2].add(new JButton("2"), new XYConstraints(40, 275, 0, 100));
        children[2].add(new JButton("1"), new XYConstraints(0, 325, 0, 100));

        children[3].add(new JButton("6"), new XYConstraints(200, 25, 0, 150));
        children[3].add(new JButton("5"), new XYConstraints(160, 75, 0, 150));
        children[3].add(new JButton("4"), new XYConstraints(120, 125, 0, 150));
        children[3].add(new JButton("3"), new XYConstraints(80, 175, 0, 150));
        children[3].add(new JButton("2"), new XYConstraints(40, 225, 0, 150));
        children[3].add(new JButton("1"), new XYConstraints(0, 275, 0, 150));

        //children[4],//children[5]...

        f.setSize(800, 600);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

    }

The custom layout in one file : XYLayout
 public class XYLayout implements LayoutManager2, Serializable {

    private int width;
    private int height;
    Hashtable<Component, Object> info;
    static final XYConstraints defaultConstraints = new XYConstraints();

    public XYLayout() {
        info = new Hashtable<Component, Object>();
    }

    public XYLayout(int width, int height) {
        info = new Hashtable<Component, Object>();
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("XYLayout [width=").append(width).append(", height=").append(height).append("]");
        return builder.toString();
    }

    public void addLayoutComponent(String s, Component component1) {
    }

    public void removeLayoutComponent(Component component) {
        info.remove(component);
    }

    public Dimension preferredLayoutSize(Container target) {
        return getLayoutSize(target, true);
    }

    public Dimension minimumLayoutSize(Container target) {
        return getLayoutSize(target, false);
    }

    public void layoutContainer(Container target) {
        Insets insets = target.getInsets();
        int count = target.getComponentCount();
        for (int i = 0; i < count; i++) {
            Component component = target.getComponent(i);
            if (component.isVisible()) {
                Rectangle r = getComponentBounds(component, true);
                component.setBounds(insets.left + r.x, insets.top + r.y, r.width, r.height);
            }
        }

    }

    public void addLayoutComponent(Component component, Object constraints) {
        if (constraints instanceof XYConstraints)
            info.put(component, constraints);
    }

    public Dimension maximumLayoutSize(Container target) {
        return new Dimension(0x7fffffff, 0x7fffffff);
    }

    public float getLayoutAlignmentX(Container target) {
        return 0.5F;
    }

    public float getLayoutAlignmentY(Container target) {
        return 0.5F;
    }

    public void invalidateLayout(Container container) {
    }

    public Rectangle getComponentBounds(Component component, boolean doPreferred) {
        XYConstraints constraints = (XYConstraints) info.get(component);
        if (constraints == null)
            constraints = defaultConstraints;
        Rectangle r = new Rectangle(constraints.getX(), constraints.getY(), constraints.getW(), constraints.getH());
        if (r.width <= 0 || r.height <= 0) {
            Dimension d = doPreferred ? component.getPreferredSize() : component.getMinimumSize();
            if (r.width <= 0)
                r.width = d.width;
            if (r.height <= 0)
                r.height = d.height;
        }
        return r;
    }

    public Dimension getLayoutSize(Container target, boolean doPreferred) {
        Dimension dim = new Dimension(0, 0);
        if (width <= 0 || height <= 0) {
            int count = target.getComponentCount();
            for (int i = 0; i < count; i++) {
                Component component = target.getComponent(i);
                if (component.isVisible()) {
                    Rectangle r = getComponentBounds(component, doPreferred);
                    dim.width = Math.max(dim.width, r.x + r.width);
                    dim.height = Math.max(dim.height, r.y + r.height);
                }
            }

        }
        if (width > 0)
            dim.width = width;
        if (height > 0)
            dim.height = height;
        Insets insets = target.getInsets();
        dim.width += insets.left + insets.right;
        dim.height += insets.top + insets.bottom;
        return dim;
    }

}

class XYConstraints implements Cloneable, Serializable {

    private int x;

    private int y;

    private int w;

    private int h;

    public XYConstraints() {
        this(0, 0, 0, 0);
    }

    public XYConstraints(int x, int y, int w, int h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getW() {
        return w;
    }

    public void setW(int w) {
        this.w = w;
    }

    public int getH() {
        return h;
    }

    public void setH(int h) {
        this.h = h;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + h;
        result = prime * result + w;
        result = prime * result + x;
        result = prime * result + y;
        return result;
        // return x ^ y * 37 ^ w * 43 ^ h * 47;
    }

    public boolean equals(Object that) {
        if (that instanceof XYConstraints) {
            XYConstraints other = (XYConstraints) that;
            return other.x == x && other.y == y && other.w == w && other.h == h;
        } else {
            return false;
        }
    }

    public Object clone() {
        return new XYConstraints(x, y, w, h);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("XYConstraints [x=").append(x).append(", y=").append(y).append(", w=").append(w).append(", h=").append(h).append("]");
        return builder.toString();
    }

My first attempt was:
     for (y = 375; y > 0; y = y - 50)
     children[1].add(new JButton("1"), new XYConstraints(x, y, w, h));

     for (y = 325, x = 0; y > 0 && x < 280; y = y - 50, x = x + 40)
     children[2].add(new JButton("2"), new XYConstraints(x, y, w, 2 * h));

     for (y = 275, x = 0; y > 0 && x < 240; y = y - 50, x = x + 40)
     children[3].add(new JButton("3"), new XYConstraints(x, y, w, 3 * h));

but something's missing like a loop for "children[i]".I'm sure there is a better solution to improve the loop Any idea of improvement or suggestion ? Thanks
Comment: Does your first attempt work, and you just want to eliminate further duplication?  Or did your first attempt not work and you want help with that?
Comment: In fact, I'm looking something to deal with children[i]. if I have 10 children, I have to write 10 for loop.
Answer:
I write my own layout because existing layout manager don't meet my requirements

Right idea, but your implementation is incorrect. The fact that you need to provide the x/y values means you are not using a layout manager but just hardcoding some values.
Instead you need to provide information to the layout manager to define the parameters of the layout, maybe something like:
MyLayout layout = new MyLayout(xSize, ySize, xOffset, yOffset);

So for the first panel you would use:
MyLayout layout = new MyLayout(50, 50, 0, 50);

This code would say that each component is (50, 50). As you add components to the panel you change the x offset by 0 and the y offset = -50.
You know you have 8 buttons so you can use math to figure out the width/height of the panel. You can then use a loop inside the layout manager to position each component.
So now you add components to the panel like:
panel.add( new JButton("1") );
panel.add( new JButton("2") );
panel.add( new JButton("3") );

For the second panel you might use:
MyLayout layout = new MyLayout(50, 100, 50, 50);

So this time it means each button know has a size of (50, 100) and each button is placed (50, -50) to the previous button.
This is how layout managers should be created. You should not need complex loops to build the constraints of each component that you add to the panel. That is the job of the layout manager.
Answer: You could try:
for( int i=1; i<=3; i++ ) {
    x = 0;
    for( y=375-((i-1)*50; y>0; y-=50, x+=40 ) {
        children[i].add(new JButton((String)i), new XYConstraints(x, y, w, i*h));
    }
}

Comment: @user3748551 - I know it may answer your question, but it is not a good solution. Now you are writing layout management code outside the layout manager. Take the time to learn how to write a layout manager properly.
Comment: camickr is right that the cleanest separation of concerns here would be to write a self-contained layout manager that lays out each button 50 pixels above and 40 pixels right of the previous one, so that each time you call add() the layout manager can automatically figure out where to place the element.  Is it worth the trouble?  I say no in this limited case, even though that's the cleanest separation of concerns.  But I'd break the inner for loop into a helper method (to which you'd pass children[i]), to make that part of it more modular.
Comment: `Is it worth the trouble? I say no in this limited case,` - I would disagree :) If you go to the trouble to attempt to make a layout manager then do it properly. Learn how to write a layout manager in a simple case and it will make the harder cases easier when you need it in the future.

How to optimize this kind of loop?


Am I stuck like this?

Question: My name is Stavros and I am 16 years old.  My voice changed around 12-13 and my voice stopped breaking around 14. I've always wanted to sing.  My current range is B1-F#5. However, I flip into falsetto around F4-F#4. On a very good day I can hit a chest G4 briefly but most days it will crack. I want to be able to sing songs sung by tenors or high baritones (chest voice going up to B4 and C5).  I want to be able to expand my chest voice.  Am I stuck like this?  Or can I change how I am and make my chest voice register wider so I can do higher belts? BTW I am starting vocal lessons in a week. My lessons will be weekly.
Thanks guys
Answer: No, you are not stuck like this. You're voice is only just beginning to develop. Your voice won't reach full maturity until around your mid-30's, in about 20 more years. That's a long time.
Your voice will change naturally over time. One of the biggest mistakes people make is singing music that doesn't fit their voice. If it doesn't fit your voice, either change the key or change the song. Straining to sing too high or low can damage the voice.
Your range, resonance, and technique will improve with lessons. Belting is a technique specific to musical theater and I highly recommend you DO NOT do it until your voice is more mature, say in 6-10 years.
Remember that at 16, you are QUITE young and that you're voice is just starting to mature.
Answer: You go where your vocal teacher and common sense admits you to go.  Singing higher means stretching your vocal folds across moving parts of your larynx.  With a male voice, your larynx had a significant growth spurt few years ago and will take decades to harden out (think of the growth areas of cartilege as similar to a freshly molted insect).  Putting large strains on it while this hasn't happened completely is a recipe for damage.  In particular as a male with a low voice (B1 is already lower than any Western bass part), the mechanics (long vocal folds and big leverage on the larynx) do not bode well for healthy high singing.
So I strongly recommend educating your musical interests on material you might perform yourself in a manner satisfying to you eventually.

Am I stuck like this?


Cluster point of a sequence and limit point of some subsequence

Question: In a topological space $X$, quoted from Wikipedia:

A point $x ∈ X$ is a cluster point of a sequence $(x_n)_{n ∈ N}$ if,
for every neighbourhood $V$ of $x$, there are infinitely many natural
numbers $n$ such that $x_n ∈ V$. If the space is sequential, this is
equivalent to the assertion that $x$ is a limit of some subsequence of
the sequence $(x_n)_{n ∈ N}$.

I was wondering when a topological space is not necessarily sequential, what is the relation between cluster point of a sequence and limit of some subsequence of the sequence?
When the topological space is sequential space, why are the two equivalent?
Thanks and regards!
Comment: Wikipedia is wrong: we need ($T_1$) Fréchet-Urysohn spaces for this to hold, also for the statement that there is a sequence from $S \setminus \{ p \}$ converging to $p$ if $p$ is a limit point of $S$. See my answer below.
Answer: In general, if $p$ is the limit of a subsequence $(x_{n_k})$ of the sequence $(x_n)$ in $X$ then $p$ is a cluster point of the sequence: let $O$ be a neighbourhood of $p$, then as $(x_{n_k})$ converges to $p$, there is some $K \in \mathbb{N}$ such that for all $k \ge K$ we have that $x_{n_k} \in O$, and $\{ n_k \mid k \ge K \}$ then are infinitely many natural numbers such that $x_{n_k}$ is in $O$.
For sequential spaces it does not to hold that a cluster point of a sequence is the limit of a subsequence of it. This will hold in $T_1$ Fréchet-Urysohn spaces (see below) and certainly in first countable spaces. The Arens space is a counterexample: it consists of all pairs $(n,m)$ in $\mathbb{N}^{+} \times \mathbb{N}^{+}$ (which are all isolated points), all $n \in \mathbb{N}^{+}$, which have basic neighbourhoods of the form $B(n,N) = \{ n \} \cup \{ (n,m) \mid m \ge N \}$, for $N \in \mathbb{N}^{+}$, so that $ ((n,m))_m \rightarrow n$ for all $n$, and the point $0$, which has basic neighbourhoods of the form that contain $0$, all but finitely many $n$ and for each of these $n$ a neighbourhood $B(n, N(n))$. One checks that this space is sequential and normal. Also, no sequence from $\mathbb{N}^{+} \times \mathbb{N}^{+}$ converges to $0$, but $0$ is in the closure of it. So if we index the set of all pairs as a sequence, $0$ is a cluster point of it, but not a subsequential limit.
For Fréchet-Urysohn spaces the set of all subsequential limits from a set $A$ equals the closure of $A$ (this is one of the definitions of being Fréchet-Urysohn), and if we have a sequence $(x_n)$ in a $T_1$ Fréchet-Urysohn space with a cluster point $p$, then either $p$ appears infinitely any times in the sequence, and this gives us a convergent subsequence to $p$, or we can assume $p$ does not appear at all in $A = \{ x_n \mid n \in \mathbb{N} \}$, and $p$ is in the closure of $A$, so is a subsequential limit from $A$, which allows us to define a subsequence from $(x_n)$ that converges to $p$ as well, using $T_1$ to get higher and higher indices from the sequence.
Comment: I'm not sure if there is a non-$T_1$ Fréchet-Urysohn space that has a sequence $(x_n)$ and a cluster point $p$ of that sequence *without* $p$ being a subsequential limit of it. That would show the necessity of $T_1$-ness in my (sketch of) proof that cluster points are subsequential limits in F-U spaces.
Comment: +1, thanks! "This will hold in T1 Fréchet-Urysohn spaces (see below) and certainly in first countable spaces." I was wondering: (1) Is "T1 Fréchet-Urysohn spaces" a sufficient condition, while "first countable spaces" is a necessary condition? (2) Since Urysohn implies Fréchet, and T1 and Fréchet are the same thing, what does "T1 Fréchet-Urysohn spaces" mean?
Comment: A first countable space is Fréchet-Urysohn, and is a sufficient condition. A $T_1$ Fréchet-Urysohn space also has the property (as I sketched in the last paragraph), but for first countable spaces I can prove the property (a cluster point is a subsequential limit) without the $T_1$ assumption. I'm not sure if I can omit it for the more general F-U spaces. A space is called Fréchet-Urysohn iff the sequential closure of any subset equals its closure. A space is sequential if sequentially closed sets are closed, a weaker property. NO relation to the separation axioms Fréchet and Urysohn
Comment: Thanks! From [Wikipedia](http://en.wikipedia.org/wiki/Separation_axiom), "Two points x and y are separated if each of them has a neighbourhood that is not a neighbourhood of the other; that is, neither belongs to the other's closure." "X is T1, or accessible or Fréchet, if any two distinct points in X are separated." "X is T2½, or Urysohn, if any two distinct points in X are separated by closed neighbourhoods." So I think Urysohn implies Fréchet, and Fréchet and $T_1$ are the same thing. Isn't it?
Comment: Sure, Fréchet is another name for $T_1$, and Urysohn implies it, and is sometimes called $T_{2\frac{1}{2}}$. But Fréchet-Urysohn is a sequence related property, also mentioned in the Wikipedia page for sequential spaces. It says that the closure equals the sequential closure.
Comment: Thanks! I didn't know that. Now I know they are different concepts.
Comment: Wait, since they T1 and Fréchet-Urysohn describe different things, what does "(T1) Fréchet-Urysohn space" mean?
Comment: A Fréchet-Urysohn space (in the sense described before) that is also $T_1$ (or Fréchet if you prefer).
Comment: @HennoBrandsma: I think in any Fréchet—Urysohn space for any cluster point of any sequence there is a subsequence such that the cluster point is its limit. See http://math.stackexchange.com/a/497805/87690 .


Default firebase application not initialized

Question: I am trying to integrate FCM in one of my Android App. I have followed the instructions as per documentation and my POC app is working fine. When I follow the same steps, in my final app, which is a multidex app, it is not working. I am getting an Illegal state exception with the message that Default Firebase application has not been initialized. My package name (defined in manifest file) and application ID (as defined in gradle file) are different, and in the google-services.json file, it hase taken the application id in the client info section. I have tried searching in net, gone through several stack overflow discussions, but none of the suggestions did work for me.
Section from Manifest file:
<service
  android:name=".services.JBFirebaseMessagingService">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>

Initialization code in activity:
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w("", "getInstanceId failed", task.getException());
                        return;
                    }
                    // Get new Instance ID token
                    if (task.getResult() != null) {
                        String token = task.getResult().getToken();
                        // Log
                        String msg = getString(R.string.msg_token_fmt, token);
                        Log.d("", msg);
                        LogHelper.writeLog(null,msg);
                    }
                }
            });

Comment: https://stackoverflow.com/a/53645728/2633909 are you sure you have done all these.
Answer: Try this And you have to add the google-services.json file from the firebase console.
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String deviceToken = instanceIdResult.getToken();
        }
    });

Comment: In my case FirebaseInstanceId.getInstance() gives null.
Comment: @NibirChakraborty https://stackoverflow.com/questions/40008076/firebaseinstanceidservice-gettoken-returning-null
Comment: This is happen only coz of your one small mistake you have double check your code with Google doc
Comment: Jaydip, could you please be little more specific to point out the mistake I have made. Thank You.
Comment: Just go through your code and this link https://firebase.google.com/docs/cloud-messaging/android/client
Comment: Thanks Jaydip. All the mentioned steps in the provided links are actually done. Still getting the error.
Comment: All the time, FirebaseInstanceId.getInstance() returns null


Using user_access() on Custom Node Type

Question: How can I check if a user has access to create a new node of a custom node type?
In 'admin/people/permissions' I have an item named "Custom Type: Create new content" and it is enabled for authenticated users.
How can I use user_access() to verify against "Custom Type: Create new content"?
Answer: Perhaps I'm missing something, but noting that using exactly the text 'Custom Type: Create new content' does not work with user_access, at least not for me.
Instead, use the machine value of the permission. One way to get that is to look at the user permission page, and view the checkbox value for the permission.
For example, instead of this:
if (user_access('Basic page: Edit any content'))

use this
if (user_access('edit any page content'))

To find the definition of the machine name, look in the .module file of the module that defines the permission.
Answer: user_access($string, $account = NULL)

if a custom module you can say
 if (user_access('Custom Type: Create new content') {
    // do X
 }

this will check the current logged in user.  To check someone else
 $uid = //get if from somewhere;
 if (user_access('Custom Type: Create new content', $uid) {
    // do X
 }

When you create a node, Drupal checks this by default....so I assume that you are trying to check it somewhere else.   What function you would like to check it in,  I cannot predict, but any function, template file, preprocess, etc will do
Answer: user_access() function did not worked for me.
I used node_access()
like this: node_access('create', 'custom_content_type', $user) and it worked.
Answer: Thought I'd share this.  (Druapl 6.x)
global $user;
$types = node_get_types();
foreach ($types as $type)
{
    print '
' . $type->name . '
';
    if (node_access('create',$type->type,$user)) {
        $output = l(t('Add new '.$type->name), '/node/add/'.str_replace('_','-',$type->type));
        print $output;
    }
}

Using user_access() on Custom Node Type


Validity of Automatic Portmanteau test for serial correlation vs Ljung-Box Test

Question: I would like to model the Value-at-Risk of U.S. sector indices and the U.S. Broad Dollar Index using the variance-covariance method. To achieve this, I model the conditional means and variances of the returns using ARMA-GARCH models. Here is the issue: I first need to determine whether ARMA orders are necessary to eliminate whatever autocorrelation may be present in the returns series. Convention indicates that Ljung-Box tests are in order, however, having researched the topic more, I came across the automatic Portmanteau test for serial correlation as seen here, which supposedly addresses some of the shortcomings of the Ljung-Box test, namely the issues of the selection of a superficial lag order, low power, and lack of robustness to heteroskedasticity. The equivalent R package is vrtest, and more specifically, the Auto.Q command.
My anxieties with this statistic lie in the fact that I get vastly different results using it as opposed to the Ljung-Box test through the Box.test command. This is true almost across the board with my sector indices, but for instance, the CRSP Real Estate Index yields the following results:
> Auto.Q(ts_realestate_is, lags=20)
$Stat
[1] 1.159207

$Pvalue
[1] 0.28163

> Box.test(ts_realestate_is, lag = 10, type = "Ljung")

    Box-Ljung test

data:  ts_realestate_is
X-squared = 187.59, df = 10, p-value < 2.2e-16

If you follow the results of the Ljung-Box test, then you would come to the conclusion that there is likely serious autocorrelation you need to address with possibly some ARMA model before applying a GARCH-type model, but the Automatic Portmanteau test indicates that the returns series is likely some sort of white noise, or at least that there might not be a reason to apply an ARMA model to address serial correlation. This naturally raises a question: should I trust the automatic portmanteau test over the Ljung-box despite these large disparities? I would greatly appreciate any help on this matter.
If it is of relevance, after detecting autocorrelation through the Automatic test, I used auto.afirma to determine optimal ARMA orders by minimizing AIC, and then tested the standardised residuals again with the Automatic test to ensure that no autocorrelation remains. When done exclusively through the Ljung-Box test, I almost always found that none of the optimal models of auto.arfima had white noise for the residuals as evaluated by a 10-lag Ljung-Box test. This was another reason why I wanted to use another method; it did not make sense for there to be significant remaining autocorrelation for the residuals of such returns series after fitting ARMA models.
Yes, I do understand that ARMA-GARCH orders should ideally be determined in parallel, but I do not currently have a good way of doing so. This is why I am opting to address autocorrelation separately. However, from what I understand from the authors of the test, it should also work for the residuals of some ARMA-GARCH model as well.
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. A helpful answer can also be upvoted by clicking on the upward-pointing arrow. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: Some points:

The results of Auto.Q and Box.test may differ not only due to the peculiarities of the test statistics, but also because of the different lag lengths that are used. For a direct comparison between the test results, specify the same lag length in Box.test as you get in Auto.Q.

Ljung-Box test might not be appropriate for diagnostic testing of ARMA models; see "Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey". I have no idea whether the same applies to the Automatic Portmanteau test as well.

When choosing an ARMA model by AIC, you aim for a model that is best at prediction. That need not be the model that has white noise residuals. The additional complexity of the model needed to make the residuals white noise may not be justified from the forecasting perspective. This is about the bias-variance trade-off. AIC-based trade-off will be different than obtained by seeking white noise residuals.
Comment: 1: I cannot specify exactly which lag to use, as one of the main features is the automatic selection of lags. Across a wide range of lags, I see that the Ljung-Box Q only ever increases, and at no point reaches anything near what Auto.Q outputs.

2:  I cannot use Breusch-Godfrey because the R command doesn't support ARMA(P,Q) models. I opted for Auto.Q as a compromise for the inconsistencies of Ljung.

3: I understand that AIC has a different goal. Would it not be fair to argue that white noise is needed to ensure that the ARMA-GARCH models hold in terms of assumptions?
Comment: @WebSurfer, 1: You can specify the same lag in Ljung-Box as in Auto.Q, since for Ljung-Box the lag is chosen by the user rather than automatically. 2: Are there indications that make Auto.Q immune to the problem of Ljung-Box in the context of ARMA residual diagnostics? 3: Yes. If you care about the statistical adequacy of the model more than about its predictive ability, you may give up AIC for something else.
Comment: 1: I may not be understanding the command correctly, but it doesn't appear to show me the chosen lag, so I cannot match them. 2: I do not claim to understand the authors' paper very well, but as I understand, they claim that their test is suitable for dynamic models, as opposed to Ljung-Box, at least conceptually. 3: I think for VaR modelling, a mix of both may be necessary, as in a high-AIC-ranking model with sufficiently uncorrelated errors. Though, I understand the necessity of compromise here.

Still, I do not quite understand the discrepancy between these statistics.
Comment: @WebSurfer, 1: Oh, I see. Well, that is unfortunate (unless there actually is a way to extract the lag order from the output). 2: Sounds reasonable. 3: Sounds reasonable, though why would you be puzzled by the discrepancy? Thinking about all possible models, there is a curve in terms of bias-variance trade-off. AIC-optimal model occupies one point on it while a model selected by seeking white noise residuals occupies another point. There is no reason for them to coincide.
Comment: Sorry, in my last statement, I meant that I'm still rather unsure about why there is such a large difference between my Ljung-Box Q statistic and this Automatic Q statistic, not between AIC-chosen and no-autocorrelation models.
Comment: @WebSurfer, try LB test with different numbers of lags, and you will see how great the differences may be. Add to that the difference between LB and Auto.Q for any given lag, and then it should not be surprising anymore.


Multi-upload in PHP

Question: I am trying to upload 2 files, the first one is a flash (.swf) file and the second a .png.
At the moment, I would have no problem making 2 different php upload file, with 2 different forms, but Im sure there can be a way to make that all together.
I am not really experimented with PHP, but Im trying to learn.
At the moment I have this:
<?php
      $allowed_filetypes = array('.swf','.png');
      $max_filesize = 10524288;
      $upload_path = 'swf/';

   $filename = $_FILES['userfile']['name'];
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');

   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');

   if(move_uploaded_file($_FILES['swf']['tmp_name'],$upload_path . $filename))
         echo 'Your file upload was successful, view the file here';
      else
         echo 'An unknown error occured, try again.';

?>

Ok so this is part of the code I found online, with that Im using a simple upload form.
How could I go and put 2 forms on the same page, and the 2 forms upload separately to 2 different folders, in example .png goes to icons/ folder and .swf goes to swf/ folder?
All that with only one button, that will also post other stuff.
Answer: the userfile in $_FILES['userfile'] is set by the value of the name attribute of the <form> in your html file.
so:
<form (.....)>
    <input type="file" name="userfile0"/>
    <input type="file" name="userfile1"/>
</form>

would result in
$_FILES['userfile0']
$_FILES['userfile1']

Please note:
Accepting files from the internet can be dangerous in many ways. make sure you do proper input sanitation and do not store the uploaded files in a web-accessible folder.
Comment: My html file is:

Select a file:
Select a file:
Upload File

So where would I add the $_FILES['swf'] and $_FILES['png']?

Here? if(move_uploaded_file($_FILES['swf']['tmp_name'],$upload_path . $filename))

If yea, how can I do so?
Comment: You are on the right track. start experimenting and you will eventually get there. just take it one step at the time.

Multi-upload in PHP


Training a binary classifier acting on n-class data

Question: Given a classifier, that was trained on a data having two classes e.g. class red and class blue. The training samples are hand picked and only contains those two classes.
After training the classifier should classify some samples, but it turns out that those samples contain the classes red, blue and a third one magenta (red+blue) e.g a class that contains features of both classes. The classifier will correctly identify red and blue but will degrade to a random guesser for magenta.
I try to give an example here (of course this is much simpler than in real life...):
assume that a sample has the features A and B, which are binary fields (either 0 or 1).
The training data looks like this:
A   B   Label
-------------
1   0   red
1   0   red
0   1   blue
0   1   blue

One possibility for the classifier (e.g. a tree) would be to have the following output:
If A == 1: red
If A == 0: blue

Well, obviously this model is too general (but for this example I hope this makes no difference).
Now the classifier is tested on some samples:
A   B   Output
--------------
1   0   red
0   1   blue
1   1   red

Here is the problem.
The classifier will just output some "random" label for the third sample, depending on the training. If this oversimplified classifier would have looked at label B, it would outputted blue.
From other knowledge (e.g. a Gold-Standard) we can see that the third sample is actually neither red or blue but our magenta class.
The classifier is just too general (?) or not well-trained (?). Is this a Sampling Error, because the third class was not identified as such during training (because the data was not available in the training set)?
How is this problem called exactly? I'm searching for the term but can not find one...
What could be a countermeasure? Of course, one could add samples of class magenta into the training set. Are there other possibilities?
Comment: You turned a binary classifier into a classifier that has 3 possible outputs, how did you change the algorithm?
Comment: @dimpol No, the classifier will obviously have two outputs, either `red` or `blue`. The problem is, that the data I'm testing on has actually three classes, where the third (previously unknown) class `magenta` is exactly a mix of both classes the classifier was trained with. So if the classifier tries to classify such a sample, it will output either `red` or `blue`, depending where the threshold is set.
Comment: Then you need a way to determine what inputs correspond to "magenta". If that is obvious, you can manually identify "magenta" inputs and put the rest through your original algorithm. If it isn't obvious and you want to train a model to identify "magenta", you indeed need to add "magenta" training examples. I don't think there is a term for this problem or a special solution.
Comment: @dimpol I added an example in the question. Yes, adding such samples to the training set and learing the classifier three classes would help.
For the term: Is it maybe some kind of sampling error? I think there should be a term for it but I really can not find something to search for...
Answer: When you train a classifier $f$ using a set of $m$ training classes $C=\{1,2,...,m\}$, it is possible that your classifier will encounter some class $c\notin C$ after it has already been trained. For instance, in object recognition, it may not be possible to obtain a training example for every type of object your sensor will encounter in practice. As you pointed out, if $f$ is not trained to recognize $c$, then it's impossible to make a correct decision! The classifier has been trained under the closed set assumption: the only classes we will encounter in the field are in $C$.
Depending on the problem at hand, this can occur quite frequently, and classification errors can really pile up. Researchers have been trying to deal with this problem since the 1970s or earlier under a number of names. In the past, these approaches were usually called something like "classification with reject option," but lately the term open set recognition has been popping up.
Whatever the case, many of these approaches boil down to picking some score threshold $\tau$ below which we forgo a decision on the input and simply call it "unknown." They typically deal with rejection at the classifier output, rather than the feature level (the decision is based on $f(x)$ rather than $x$).
In your example, we might build a classifier that returns probabilities that the example is red or blue:
$$
\begin{split}
p_1 &= f(y=\texttt{red} | x)\\
p_2 &= f(y=\texttt{blue} | x)
\end{split}
$$
Then, we can define a decision function
$$
\delta_\tau(p_1,p_2) =
\begin{cases}
\operatorname{argmax}(p_1,p_2) & \text{if } p_1>\tau \text{ or } p_2>\tau\\
\text{unknown} & \text{otherwise}
\end{cases}
$$
or some incarnation thereof. In that case, the output would hopefully look something like
A   B   Output
--------------
1   0   red
0   1   blue
1   1   unknown

Now, this doesn't directly address the problem of getting the magenta label into the classifier. In fact, this is an open topic of research—check into open world recognition.


How to use eigenvectors to identify which variables are involved in collinearity?

Question: The question involves a regression of $Y$ on $11$ predictor variables $X_1$ through $X_{11}$.
The problem asks me to identify the variables involved in the collinearity using the eigenvectors that correspond to small eigenvalues.
Using R, I have calculated the $11$ eigenvalues and eigenvectors, but I am not sure how to use an eigenvector to see which predictor variables are involved in the collinearity.
<code> [1] 7.702574847 1.403077880 0.773435643 0.577055424 0.211498935 0.141941470 0.095142049
 [8] 0.050092536 0.033266309 0.008417705 0.003497202

$vectors
            [,1]         [,2]        [,3]         [,4]         [,5]        [,6]        [,7]
 [1,] -0.3529639 -0.112431387  0.03114403 -0.006932422  0.026272973 -0.09512815  0.26787382
 [2,] -0.3299718 -0.260762001  0.07836539 -0.194970349 -0.142783457 -0.23889898  0.34910433
 [3,] -0.3510109 -0.139829772  0.04294522 -0.004153543 -0.084990459 -0.18488343  0.35518667
 [4,]  0.1610427 -0.552726480  0.11863260  0.785849610  0.096920435  0.09122188  0.09287761
 [5,]  0.2663779 -0.346997347 -0.43309789 -0.352178691  0.516283052  0.07200995  0.06450059
 [6,] -0.2047881 -0.548146807  0.41844801 -0.380746710 -0.007176897  0.38287792 -0.37681067
 [7,]  0.3040550 -0.352222407 -0.22122179 -0.134117215 -0.050372348 -0.57691563 -0.02079064
 [8,] -0.3232988 -0.078466513 -0.36961713  0.180329365 -0.200485930 -0.20407455 -0.67496023
 [9,] -0.3026624  0.006019985 -0.54645511  0.094905101  0.106514020  0.51959464  0.19659254
[10,] -0.3446125 -0.100475266 -0.26679114  0.040652506 -0.028959499 -0.14008874 -0.06284718
[11,] -0.3117090  0.181885175  0.24279993  0.119155548  0.800493659 -0.27479473 -0.16382124
             [,8]        [,9]        [,10]        [,11]
 [1,] -0.25888638  0.49677393 -0.290946296  0.617904045
 [2,]  0.05057424 -0.65243209  0.290811120  0.258528596
 [3,] -0.06800437  0.03290868 -0.466442937 -0.681570251
 [4,] -0.06188507 -0.06292276  0.051311641  0.012735988
 [5,] -0.43886854 -0.13804308 -0.086127357 -0.045372936
 [6,]  0.16574908  0.13359309 -0.004651702 -0.059626414
 [7,]  0.55944398  0.24949398 -0.055978181  0.049028663
 [8,] -0.15486222 -0.25287357 -0.294111256  0.091346835
 [9,]  0.52415223 -0.01482782 -0.055178229  0.052597726
[10,] -0.20261712  0.39402290  0.714256660 -0.259679096
[11,]  0.22167146 -0.06274209  0.017189710 -0.009773591 </code>
Above are the $11$ eigenvalues and then their corresponding eigenvectors.
Any help would be greatly appreciated.
Comment: Not identical question, but a related topic: https://stats.stackexchange.com/q/16327/3277
Answer: I don't believe there is a magical statistical test to say these four variables are villans and those seven are upstanding citizens. The territory is all shades of grey, not black and white.  However, we can find some dark grey pretty easily.  Your first eigenvalue is 7.7 with a CI of 1 (obviously)  Looking at the corresponding eigenvector [,1] (i think),  you can see the vector components are more or less of the same magnitude (though different signs). Now examining the eigenvector for 0.003497202: [,11]  you find components ranging in abs from .009 to .68.  The larger components will point to the variables which are still clinging together within the orthonormal basis of eigenvector.  Looks like 1 & 3 and to a lesser extent 2 & 10. Moving up to the eigenvector associated with eigenvalue 0.008417705 we again see 10 and 3 ugly with 1,2 and now 8 homely.  Proceed in this fashion until depression sets in.  You really want to go back to the actual variable definitions and verify that the correlations revealed make intuitive sense.  Presumably, addressing the problem by dropping redundant variables, clustering them, or finding a good instrument to replace the entangled collinear variables.


Anyone know how to allow query string parameters in a wordpress page?

Question: Anyone know how to allow query string parameters in a wordpress page? it's running a muffin theme (betheme)
e.g. localhost/mypage/?name=bill
redirects to the 404 page (but it keeps the url intact).
I want it to not do the redirect and keep the querystring as is.
Thanks
Comment: Seems like a htaccess / rewrite thing. WordPress tries to translate `mypage/?name=bill`  or rewrite that into a page or post, and it does not exists.
Answer: Try flushing your permalinks. Navigate to Settings->Permalinks. Then all you have to do is click "Save Changes", and it will reconfigure your permalinks.

If that still doesn't fix it, you may have an issue in your Apache or NGINX configuration involving some odd URL rewrite rules. But simply flushing permalinks usually does the trick for any issue involving URLs.


Return users who follow me and I follow

Question: Hi I'm trying to do this function, my problem is that inside the function in the console.log it does return, but in the return it returns as undefined
async function followThisUser(identify_user_id, user_id) {
var following = await Follow.findOne({ "user": identify_user_id, "followed": user_id }).exec((err, follow) => {
    if (err) return handleError(err);
    console.log(follow)
    return follow;
});

var followed = await Follow.findOne({ "user": user_id, "followed": identify_user_id }).exec((err, follow) => {
    if (err) return handleError(err);
    console.log(follow)
    return follow;
});

return {
    following: following,
    followed: followed
}

}
Comment: ah, then its most likely a scope error. put your final return inside the async function, or declare your variables as a global initially.
Comment: in your final return put your key value in quotes "" , e.g. "following" : following
Comment: Thanks for responding, this didn't work for me. My problem is that the return doesn't put a value on the variable. Thank you
Answer: Well if the console.log is showing correct value, then you can try something like this:
async function followThisUser(identify_user_id, user_id) {
let obj = {}
await Follow.findOne({ "user": identify_user_id, "followed": user_id }).exec((err, follow) => {
    if (err) return handleError(err);
    console.log(follow)
    obj['following'] = follow; //setting the required object value
});

await Follow.findOne({ "user": user_id, "followed": identify_user_id }).exec((err, follow) => {
    if (err) return handleError(err);
    console.log(follow)
    obj['followed'] = follow; //set the required value
});

console.log(obj); // see if the obj has actual value
return obj;
}

As a friendly suggestion try to keep variable names so that they are differentiable from each other. This really helps in the long run!
Hope that helps! Happy coding!

Return users who follow me and I follow


Difficulty Accessing UITableViewCell Created in Interface Builder .xib File

Question: In my UITableView, for the last row of the last section of the table, I load a special UITableViewCell that is different from all the others on the table.  I created the cell in my .xib file and gave it the reuse identifier "endCell."  I would think that I could just do the following to access my cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

if ((indexPath.section == [sections count] - 1) && indexPath.row == [[sections objectAtIndex:indexPath.section] count])) {

    return [tableView dequeueReusableCellWithIdentifier:@"endCell"];

} //more code for other cells...

I have set the cell identifier in the interface builder. However, running this code causes a crash with an error:
"Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:],..."

After researching this error, the only solution I could find was to get a pointer to the .xib cell by accessing it through an array that holds the objects contained inside the .xib. So I tried the following:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

if ((indexPath.section == [sections count] - 1) && (indexPath.row == [[sections objectAtIndex:indexPath.section] count]) ) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"endCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]init];
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PLNewConversationViewController" owner:self options:nil];
            for (id xibItem in topLevelObjects) {
                if ([xibItem isKindOfClass:[UITableViewCell class]]){
                    UITableViewCell *tableViewCell = (UITableViewCell *)xibItem;
                    if ([tableViewCell.reuseIdentifier isEqualToString:@"endCell"]) {
                        cell = xibItem;
                    }
                }
            }
        }

    return  cell;
} //more code for other cells...

This results in very strange behavior - it's not even obvious to me what it is doing - the last cell is never shown, and it appears to be scrolling endlessly because when it gets to the bottom of the table, it automatically jumps back up to the top of the table.  Sometimes there is a crash with varying errors.
I have managed to work around this by hooking up my cell to the necessary class as an outlet and just returning the cell as "return self.endCell..." but I feel like I should be able to access the cell without doing this.
Can anyone see what I am doing wrong?
Comment: Do you have normalCell and endCell in the same nib file?
Comment: no but I have other objects in the same nib file with the endCell
Answer: The easiest way to load custom table view cells from a nib file is to create them in a
separate xib file (containing only that cell) and registering the generated nib file with
[self.tableView registerNib:[UINib nibWithNibName:@"YourNibFile" bundle:nil] forCellReuseIdentifier:@"YourReuseIdentifier"];

for example in viewDidLoad of the table view controller.
[tableView dequeueReusableCellWithIdentifier:@"YourReuseIdentifier"]

will then instantiate cells from that nib file if necessary.
Comment: Small correction, the function is [self.tableView registerNib:[UINib nibWithNibName:@"EventCell" bundle:nil] forCellReuseIdentifier:@"EventCell"];
Comment: @CedricSoubrie: You are right, thanks for fixing it!


Gauge Taiko: given selector list/count encountered itens

Question: I'm using Gauge/Taiko to automate some scenarios and I'm struggling with some basic stuff.
Given a selector that match N elements: is there a way to list/count those elements?
Today even I provide a selector that matchs N elements, it returns only the 1st match.
example:
$('.input')

returns only the first element with the class input
Answer: To just find the number of matching elements (await $('#id').get()).length can be used,  to access element by index there is an open issue for the same https://github.com/getgauge/taiko/issues/288
Update:
get() is now deprecated in taiko. And taiko supports accessing elements by index. Do use (await $('#id').elements()).length
Comment: Upvote this answer and adding that for anyone that is trying to assert on count, you need to use direct node `assert`: `assert.equal((await text(`MY LABEL`).elements()).length, 2)`.  See: https://nodejs.org/api/assert.html#assert_assert_equal_actual_expected_message


How to use Green's theorem if the divergence is $0$

Question: I'm trying to use Green's theorem to calculate the flux of $F$ through some curve. However, is it possible to use Green's theorem if the divergence of $F$ is $0$?
Comment: Why do you think it may not be possible?
Answer: Of course. That means you're integrating $0$ over some area, the result of that is $0$, so the flux through the curve is $0$. Be careful that the divergence is defined at each point inside the curve.
Comment: To use Green's theorem, I closed the given curve by drawing a line segment between the two endpoints. To calculate the flux of the original curve, would I just subtract the flux of the line segment from 0, which is the flux of the original curve + the line segment?
Comment: @Math3983 If the divergence of a field is $0$ everywhere, then the flux through any curve between two given end points is the same. So the flux through your complicated curve is equal to the flux through the straight line. This is the same as saying that the flux through the curve, minus the flux through the straight line (which amounts to the fluz into or out of the enclosed area) is $0$.
Comment: Makes sense, thank you.


Webpack ERROR in node:crypto Module build failed: UnhandledSchemeError: Reading from "node:crypto"

Question: I am attempting to update some older code to eliminate warnings. I have upgraded some code that uses the 'crypto' module. However, webpack 5.88.2 does not recognize the new syntax. My new import looks like this:
const crypto = await import('node:crypto');

The complete error looks like this. It suggests that I may need another plugin, but I can't find one.
ERROR in node:crypto
Module build failed: UnhandledSchemeError: Reading from "node:crypto" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
    at C:\xxxxx\functions\auth-check\node_modules\webpack\lib\NormalModule.js:838:25
    at Hook.eval [as callAsync] (eval at create (C:\xxxxx\functions\auth-check\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\xxxxx\functions\auth-check\node_modules\tapable\lib\Hook.js:18:14)
    at Object.processResource (C:\xxxxx\functions\auth-check\node_modules\webpack\lib\NormalModule.js:835:8)
    at processResource (C:\xxxxx\node_modules\loader-runner\lib\LoaderRunner.js:220:11)
    at iteratePitchingLoaders (C:\xxxxx\functions\auth-check\node_modules\loader-runner\lib\LoaderRunner.js:171:10)
    at runLoaders (C:\xxxxx\node_modules\loader-runner\lib\LoaderRunner.js:398:2)
    at NormalModule._doBuild (C:\xxxxx\auth-check\node_modules\webpack\lib\NormalModule.js:825:3)
    at NormalModule.build (C:\xxxxx\functions\auth-check\node_modules\webpack\lib\NormalModule.js:969:15)
    at C:\xxxxx\functions\auth-check\node_modules\webpack\lib\Compilation.js:1377:12
 @ ./src/index.ts 6:21-42

webpack 5.88.2 compiled with 1 error in 2790 ms

Answer: You should change node:crypto to node/crypto
Comment: Thanks for the answer, but that doesn't work. Typescript can't find the module, and ignoring that, it just gives a different error message in webpack.
Comment: Did you find a solution to this? Thanks
Answer: I came across the above error on my project and this is the command to fix the error.
npm install stream-browserify crypto-browserify process
In case you are working on a web5 using next project this is the link for more support.
https://developer.tbd.website/docs/web5/build/frameworks/next/
Comment: FYI the URL has been updated to: https://developer.tbd.website/docs/web5/troubleshooting/common-errors
Answer: Install the packages first
npm i stream-browserify crypto-browserify
and then make the following changes to your next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,

  webpack: (config, { isServer, buildId, dev, webpack }) => {
    if (!isServer) {
      config.resolve.fallback = {
        ...config.resolve.fallback,
        stream: require.resolve('stream-browserify'),
        crypto: require.resolve('crypto-browserify'),
      };

      config.plugins.push(
        new webpack.ProvidePlugin({
          process: 'process/browser',
        }),
        new webpack.NormalModuleReplacementPlugin(
          /node:crypto/,
          (resource) => {
            resource.request = resource.request.replace(/^node:/, '');
          }
        )
      );
    }
    return config;
  },
};

module.exports = nextConfig;

Answer: The question is, do you want crypto to be included into the client bundle.
If the answer is YES, then the use of *-browserify libs is advised.
If NO, then you can import the module by its normal name crypto, and add this to your package.json file:
{
  ...
  "browser": {
    "crypto": false
  }
  ...
}

The result is, webpack will not even attempt to include this module into any of your client bundles.


C# generated .XML file not including other file class

Question: I am writing a C# winforms application, and I would like to create documentation for my code with XML comments. However, it seems like I am doing something wrong and can't figure out what is it. Currently, for generating HTML documentation I am using DocFX (but i also tried sandcastle , but with the same result). When XML File and HTML documentation is created, it seems to only consists of my main Form1.cs class(which is interesting because in that particular file I dont have any XML comments). Other .cs files(which consist of XML comments) are not included (they were added to the project throughout development via visual studio with right-click on project -> Add -> New item -> C# class). Here is my docfx.json :
{
  "metadata": [
    {
      "src": [
        {
          "files": [
            "*.cs"
          ],
          "cwd": ".",
          "exclude": [
            "**/obj/**",
            "**/bin/**",
            "_site/**"
          ]
        }
      ],
      "dest": "obj/api"
    }
  ],
  "build": {
    "content": [
      {
        "files": [
          "api/**.yml"
        ],
        "cwd": "obj"
      },
      {
        "files": [
          "api/*.md",
          "articles/**.md",
          "toc.yml",
          "*.md"
        ],
        "exclude": [
          "obj/**",
          "_site/**"
        ]
      }
    ],
    "resource": [
      {
        "files": [
          "images/**"
        ],
        "exclude": [
          "obj/**",
          "_site/**"
        ]
      }
    ],
    "overwrite": [
      {
        "files": [
          "apidoc/**.md"
        ],
        "exclude": [
          "obj/**",
          "_site/**"
        ]
      }
    ],
    "dest": "_site",
    "template": [
      "default"
    ]
  }
}

And also, my files hierarchy looks like this :
How do I include other files in XML creation as well ?
Answer: Could the reason be that the classes for which the documentation is not generated are internal classes? I believe that documentation is generated only for public classes by default.


windows 2003 server licence issues

Question:
Possible Duplicate:
Can you help me with my software licensing issue?

I have a 2003 R2 std OEM  English Licence
Can I use it in the same machine, but installing from a spanish  std retail media?
I haven't the original disk.
Thanks in advance
Comment: What did Microsoft say when you asked them?
Answer: Chances are very low unless the media is from the same OEM, even then it may not work. You should contact the OEM, if the media is from the same OEM.

windows 2003 server licence issues


$(X, Y)$ is not Bivariate Normal because $P(X + Y = 0) = P(S = −1) = 1/2$, which implies that $X + Y$ can't be Normal

Question: My textbook, Introduction to Probability by Blitzstein and Hwang, gives the following example:

Example 7.5.2 (Non-example of MVN). Here is an example of two r.v.s whose marginal distributions are Normal but whose joint distribution is not Bivariate Normal. Let $X \sim \text{N}(0, 1)$, and let
$$S = \begin{cases} 1 \ \ \text{with probability} \ \dfrac{1}{2} \\ -1 \ \ \text{with probability} \ \dfrac{1}{2} \end{cases}$$
be a random sign independent of $X$. Then $Y = SX$ is a standard Normal r.v., due to the symmetry of the Normal distribution (see Exercise 32 from Chapter 5). However, $(X, Y)$ is not Bivariate Normal because $P(X + Y = 0) = P(S = −1) = 1/2$, which implies that $X + Y$ can't be Normal (or, for that matter, have any continuous distribution). Since $X + Y$ is a linear combination of $X$ and $Y$ that is not Normally distributed, $(X, Y)$ is not Bivariate Normal.

I understood everything until the claim that what was shown implies that $X + Y$ can't be Normal (or have any continuous distribution). I would greatly appreciate it if someone could please take the time to clarify why this is the case.
Answer: If a random variable $Z$ is continuous, we have for every $c \in \mathbb{R}$
$$P(Z=c)=0.$$
Comment: Oh, of course! Thanks for the clarification.

$(X, Y)$ is not Bivariate Normal because $P(X + Y = 0) = P(S = −1) = 1/2$, which implies that $X + Y$ can’t be Normal


Help with First Order Logic

Question: I am having a hard time understanding how to represent sentences in first order logic. Here is an example I am trying to understand, but I really can't:
enter image description here
enter image description here
There's another slide I cannot upload (don't have enough reputation), which says:

The "all its children can fly" part needs to be read as: "if it's a
child of the elephant, then it can fly"
This will be inside another if-then statement:
"if all the children of an elephant can fly, then the elephant is happy"
Then, we need a third
implication to say that if something is an elephant, then, if all its
children can fly, it is happy.

The original sentence seems to implicitly state that children of an elephant could also not fly, while according to the explanation: if one is a child, then it can fly (as if this was a direct implication). This seems wrong to me.
I would have said that the 4) is the right answer. I can't understand why 1) is correct instead.
Answer: Let's look at the last part of (4):
$$\forall y[(child(y, x)\wedge fly(y))\implies happy(x)].$$ Note that I've changed a pair of curved braces to square braces for improved readability.
The problem is that "$\forall y$" binds too much: the expression above says

$(*)\quad$ For all $y$, if $y$ is a child of $x$ that flies then $x$ is happy.

Now let's imagine an $x$ that has two children $a$ and $b$, and $a$ flies and $b$ doesn't. Then:

Clearly $x$ shouldn't be happy.
BUT, $a$ is a child of $x$ that flies! And $(*)$ says that for any child of $x$, if that child flies then $x$ is happy. So since $a$ flies, $x$ is happy.

This is an instance of the following derivation:

"$\forall y(P(y)\implies Q(x))$" and "$P(a)$" together imply "$Q(x)$".

Basically, "$\forall y(P(y)\implies Q(x))$" means that any $y$ satisfying $P$ triggers the consequent $Q(x)$.
Comment: Thanks Noah, I got the point. But, what about 1)? Is it correct to say that if *a* is a child of *x*, then *a* can fly? It doesn't seem to me that the original sentence *An elephant is happy if all it's children can fly* is saying that.
Comment: @GianlucaJohnMassimiani (1) is saying: "If x is an elephant, then: if (every child of x can fly), then x is happy." Now, "every child of x can fly" is just another way of saying "for all a, if a is a child of x, then a can fly" (this is actually what (1) says directly - what I wrote above was a clearer English interpretation). So (1) is correct.
Comment: Ok thanks, I think I am getting the grasp

Help with First Order Logic


Document classification with Naive Bayes performs worse than other methods

Question: I am doing a document classification challenge on hackerrank.com. The training data is $X$ strings classified into $8$ classes. My approach is to use word frequencies and naive bayes (GaussianNB() from sklearn) instead, since I've read this is good for document classification. Specifically, I found the $Y$ most common words for each class, put this set $Y$ for each class into a large set of all common words. The features were then how many times each word in this large set occurred in the string.
The result of this for naive bayes classifier was a sklearn.metric.accuracy_score (on unseen data) of less than $0.75$ while other methods such as sklearn.svm.SVC and sklearn.tree.DecisionTreeClassifier achieved a $0.8$ to $0.9$. These scores were for choosing $Y$ (number of words from each class to use as features) to around 100. For $Y=10, 4$ etc the score was much lower.
Considering the cutoff accuracy is $0.95$, I am wondering what I have done wrong for two reasons:

Why are svm and decision tree performing better than naive-bayes, for a problem naive bayes is supposedly good at?
Is there something fundamentally wrong with my feature selection or choice of methods preventing me from achieving a higher score, or is it likely due to some error in the code?

Note that I have tried other features, like avg. word length, number of characters, with worse results for all methods.
Answer: Naive Bayes is often given as an example for algorytm that can be used for textual data, but this doesn't mean that it usually performs better. It certainly can be the case that for some dataset. Moreover, it often will be the case that other algorithms work better, because Naive Bayes makes very strong assumptions about conditional independence that are unlikely to hold.


WebView - ClassNotFoundException

Question: Estou criando a seguinte tela no android
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/activities_fundo_cinza"
    android:orientation="vertical" >

<Webview
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Mas estou com o seguinte erro:

04-07 14:55:45.557: E/AndroidRuntime(1693): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.Webview" on path: DexPathList[[zip file "/data/app/br.test.apk"],nativeLibraryDirectories=[/data/app-lib/br.livetouch.synchro-2, /system/lib]]
Answer: Você precisa reescrever Webview para WebView. Assim:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/activities_fundo_cinza"
    android:orientation="vertical" >

<WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

O nome da tag é utilizada para carregar a classe por isso tem que ser exatamente o mesmo nome.
Como descrito na documentação.

Em geral, no vocabulário XML para declarar elementos da interface segue a estrutura e a convenção de nomes das classes e métodos, onde os elementos e o nome do elemento corresponde a classe e os atributos correspondem aos métodos. Na verdade, a correspondência é tão direta que você pode supor qual atributo XML corresponde a qual método de classe, ou supor qual classe corresponde a qual a um elemento XML. Entretanto, note que nem todo vocabulário é idêntico. Em alguns casos existe uma leve diferença de nomeação. Por exemplo, o elemento EditText tem um atributo text que corresponde a EditText.setText()

WebView - ClassNotFoundException


How to replace all the \ which is coming inside the string which also contains a string

Question: I am calling REST api through ADF and storing the data in blob storage. There are few columns which has value like \\name\\":\\"what we do\\",\\"values\\":[\\"food\\"]"
The output should be name:what we do,values:food
How to handle such column values using dataflow visual builder expression before writing into a final csv file.
Appreciate your help.
Answer: I think you just need a regexReplace in a derive Column block.
The expression used is regexReplace(body, '\\[|\\]|\\\\|\"', '')
the regex separate following 4 cases by \, which means or

\\[ : replace open square bracket
\\] : replace close square bracket
\\\\ : replace double slash
\" : replace double quote

output in ADF:


Retrieve Specific Value

Question: I would like to retrieve the value 'productname' inside of a variable named 'Test' by using T-SQL
I do not know how to do it?
Thanks!
http://sqlfiddle.com/#!3/68c2d/1/0
Answer: You need to declare the variable, then initialise it like so:
DECLARE @TEST NVARCHAR(10)

SELECT @TEST = VALUE FROM [TABLE] WHERE NAME = 'productname'

You can then PRINT or SELECT it like so:
PRINT @TEST
SELECT @TEST

Comment: Thank your for your help. How about using top 1?
Comment: You'd simply change it to: `SELECT TOP 1 @TEST = VALUE FROM [TABLE] WHERE NAME = 'productname'`

Retrieve Specific Value


SqlAlchemy many to many data modeling

Question: Please help me model this in SQLAlchemy. A user can create a question. A question can have any number of choices (E.g. YES, NO, LATER, MAY BE, DONT KNOW, NEXT YEAR, NOT APPLICABLE). I have created a mapper between questions and choices. How do I model the responses in SQLAlchemy?
question_choices = Table('question_choices', Base.metadata,
    Column('id', Integer, primary_key=True),
    Column('question_id', Integer, ForeignKey('questions.id')),
    Column('choice_id', Integer, ForeignKey('choices.id'))
    )

class Choice(Base):
    __tablename__ = 'choices'
    id = Column(Integer, primary_key=True)
    value = Column(String(30), nullable=False)

class Question(Base):
    __tablename__ = 'questions'
    id = Column(Integer, primary_key=True)
    title   = Column(String(100))
    created = Column(DateTime)

    choices = relationship('Choice', secondary=question_choices)

class questionResponse(Base):
    """A friend's response to a question"""
    __tablename__ = 'question_responses'
    id = Column(Integer, primary_key=True)
    question_id = Column(Integer, ForeignKey('questions.id'))
    choice_id = Column(Integer, ForeignKey('choices.id'))
    user_id = Column(Integer, ForeignKey('users.id'))
    created = Column(DateTime)

The questionResponse model is not normalized. Question_id and listing_id are repeated. I do not have a relationship in the mapper table. I want to be able to count the responses for a given question.
Answer: Your mapper for QuestionResponse is pretty good already, but it does not restrict an answer of the choice that is not configured: so if LATER is not allowed answer for a question Will you marry me?, the database does not restrict this.
One solution to this would be to also add a two-column foreign key constraint to the QuestionResponse:
class QuestionResponse(Base):
    """A friend's response to a question"""
    __tablename__ = 'question_responses'
    id = Column(Integer, primary_key=True)
    question_id = Column(Integer, ForeignKey('questions.id'))
    choice_id = Column(Integer, ForeignKey('choices.id'))
    # ...
    __table_args__ = (
            ForeignKeyConstraint(['question_id', 'choice_id'], ['question_choices.question_id', 'question_choices.choice_id']),
            )

Alternative (more normalized DB model) is to define the FK only to the question_choices.id:
class QuestionResponse(Base):
    """A friend's response to a question"""
    __tablename__ = 'question_responses'
    id = Column(Integer, primary_key=True)
    question_choice_id = Column(Integer, ForeignKey('question_choices.id'))

edit-1: In this case you can have a relationship between Question and QuestionResponse defined like below, which will provide you with count as well:
class Question(Base):
    # ....
    answers = relationship("QuestionResponse",
        primaryjoin="Question.id==question_choices.c.question_id",
        secondary=question_choices,
        secondaryjoin="question_choices.c.id==QuestionResponse.question_choice_id",
        backref="question",
        )

In any case you might want to add a UniqueConstraint to the question_choices table on columns (question_id, choice_id).

Now, in order to count responses, you either add the relationship between Question and QuestionResponse and return len(answers) or you just create a query-based property on Question:
class Question(Base):
    # ...
    answer_count = column_property(
                select([func.count(QuestionResponse.__table__.c.id)]).
                where(question_choices.c.question_id==id).
                where(question_choices.c.id==QuestionResponse.__table__.c.question_choice_id)
            )

Comment: Thanks a lot for the detailed answer. I learned about column_property. When I chose the second answer, querying turned out to be really difficult, since I needed a join with choice and Listing.
Comment: For example, I can query QuestionReponse by question_choice_id, how do I get choice from here? I am not able to add a relationship to question_choices mapper table.
Comment: I added the `answers` relationship configuration to the answer.

SqlAlchemy many to many data modeling


Regression multi-level meta-analysis with binomial data in R: no existing package?

Question: The question is in the title.
Meta-analysis with binomial distribution
I'm trying to do a meta-analysis on occurence of an event across different studies. For each study $i$ ($i=1,\dots,N$), I have the number of participants $n_i$ and the number of events $k_i$. I don't have individual data. The number of event thus follows a binomial distribution: $k_i\sim Bin(\theta_i,n_i)$, where I assume a random effect: $\theta_i\sim N(\theta,\tau)$.
Regression meta-analysis
Additionally, I'm doing a regression on $\theta$ using the variable $x_i$: $$\theta_i\sim N(\alpha+\beta x_i,\tau).$$
Multi-level regression meta-analysis
Some studies are split into groups. As they have the same baseline characteristics, I thought of using a multi-level model (first formulation):
$$\theta_{i,j}\sim N(\alpha+\beta x_{i,j},\tau+\delta_j).$$
We could alternatively write it like this (although it is a bit different, second formulation):
$$\theta_{i}\sim N(\alpha+\beta x_i,\tau).$$
$$\theta_{i,j}\sim N(\theta_i+\gamma_i x_{ij},\delta_j)$$
Which function to use in R
I thought of doing it with the rma.mv() function from the metareg package, but the issue is that you cannot specify the distribution of the data. As far as I understood, it assumes normally distributed data. I thought of applying a logit transformation to the probability of success $p_i:=k_i/n_i$, but it's not possible to the some zero counts ($y_i=0$ for some studies i). Any other function that could solve that?
Moreover, I'm not sure if such models follow my first or second formulation.
Comment: To be honest, I don't understand why it is off topic. I modified the question now, could anyone tell me if it fits better to CrossValidated or if not, where I should post it?
Answer: It's not clear to me why general purpose GLMM (e.g. lme4 R package) or Bayesian models (e.g. brms, rstanarm, or rstan R packages) would not work. Surely, you can specify the model of interest as a GLMM with a binomial outcome and a trial main effect with whatever random effects you require?


Problem regarding tensor

Question: Prove that the contraction of a tensor $A^l_m$ is a scalar or invariant.
My try:
Mixed tensor of rank 2 formula: $$\bar A^l_m=\frac{\partial \bar x^l}{\partial x^p}\frac{\partial x^q}{\partial \bar x^m}A^p_q$$
Then letting $l=m$ and also $p=q$
$$\bar A^l_l=\frac{\partial \bar x^l}{\partial x^p}\frac{\partial x^p}{\partial \bar x^l}A^p_p$$
Finally $\bar A^l_l=A^p_p$
Am I correct?
Answer: To be more precise, I'd write:
$$
\bar{A}_\ell^\ell =
\frac{\partial \bar{x}^\ell}{\partial x^p}
\frac{\partial x^q}{\partial \bar{x}^\ell}A^p_q
= \delta^q_pA^p_q = A_q^q
$$
It holds in general for tensor contractions (see here).

Problem regarding tensor


Sending keystrokes and mouse clicks using Scala

Question: I've previously used AutoHotkey to send keystrokes and mouse clicks to automate interaction with GUIs and browsers. How do I send keystrokes and mouse clicks this time using Scala?
Comment: Try Java's [robot](http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html ) class
Answer: You can use java.awt.Robot.
val robot = new java.awt.Robot
robot.mouseMove(100,100)    // Cursor will jump to the top left of your screen

Note that you have to enter text keycode by keycode (see java.awt.event.KeyEvent).  This is pretty annoying, but you can write code to automate the pressing and releasing of keys.  (You do need to release every key you press!  It's emulating the keyboard....)
Comment: Thanks, I have been playing with the robot class and it is simple to send keystrokes and mouse commands. You're right that sending text isn't very elegant but using the clipboard makes it easier.
Answer: JNA + Windows API
I had to send input to a background window and it worked really well for me.
Comment: Thanks for the suggestion, I'll try the robot class first to keep the code platform independent but may revert to using a Windows API.


How to disabled style from library css in React

Question: I use the react-slick library to make a slider. I have images inside the tag responsible for the slider. Depending on the size of the screen I would like to hide the images but the property slick.css blocks my css style. How could I turn it off?
Comment: Can you link the library you are using?
Comment: yes, https://react-slick.neostack.com/
Answer: You can try to write a more specific css selector.
I assume your image has a class .cHgPZg.
If yes you can try the selector
<code>.slick-slide img.cHgPZg { dsiplay: none; }
</code>
If this is not working you can always use the !important; but try to avoid it if possible.
<code>.cHgPZg {display: none !important;} // not recomanded
</code>
Answer: The issue is specificity. You have to add a more specific selector in order to overwrite the dominating selector and hide the image. Try walking the selector tree backwards until the selector is specific enough; Something like this:
<code>.slick-slider .slick-list .slick-slide img {
    display: none;
}
</code>


Gerenciar versões bibliotecas android

Question: Atualmente no meu aplicativo possuo os seguintes imports de bibliotecas no meu build.gradle:
compile 'com.google.android.gms:play-services-maps:+'
compile 'com.google.android.gms:play-services-gcm:+'
compile 'com.google.android.gms:play-services-location:+'

O que definitivamente o :+ faz?
Ele traz a última versão disponível no celular que irá rodar o app?
Ou que existe no meu Android Studio no momento da compilação?

Eu tenho tido problemas, por exemplo, com alguns clientes com celulares mais antigos, o qual o serviço de mapas não tem funcionado de forma perfeita, pelo fato do Google Play Services não estar atualizado..
Atualmente o compileSDKVersion do meu App é o 26
Answer: A utilização de versões dinâmicas é uma funcionalidade do Gradle, e está documentada no site deles:

If the dependency is declared as a dynamic version (like 1.+), Gradle
will resolve this to the newest available static version (like 1.2) in
the repository. For Maven repositories, this is done using the
maven-metadata.xml file, while for Ivy repositories this is done by
directory listing.
[...]
Once each repository has been inspected for the module, Gradle will choose the 'best' one to use. This is done using the following criteria:
For a dynamic version, a 'higher' static version is preferred over a 'lower' version.

Em tempo de compilação do projeto o Gradle irá traduzir o + para a última versão que ele encontrar nos repositórios acessíveis.
Então quando você instala o app está versão já foi definida.

A forma que acontece a interação entre a biblioteca cliente e o APK instalado nos smartphones está descrita no site do Play Services.

The client library contains the interfaces to the individual Google services and allows you to obtain authorization from users to gain access to these services with their credentials. It also contains APIs that allow you to resolve any issues at runtime, such as a missing, disabled, or out-of-date Google Play services APK. The client library has a light footprint if you use ProGuard as part of your build process, so it won't have an adverse impact on your app's file size.
[...]
The Google Play services APK contains the individual Google services and runs as a background service in the Android OS. You interact with the background service through the client library and the service carries out the actions on your behalf. An easy-to-use authorization flow is also provided to gain access to the each Google service, which provides consistency for both you and your users.

Utilizar a última versão do Play Services oferece a vantagem de sempre ter disponíveis as novas funcionalidades e atualizações de segurança.
Mas, como você percebeu isso tem um preço. A biblioteca cliente precisa rodar em conjunto com uma versão compatível do Google Services APK.

Resumindo
Da forma que você descreveu, sempre que você compilar seu app e o Gradle encontrar uma nova versão do Play Services, ele a utilizará. Seu usuário então deverá ter uma versão compatível do Google Services APK instalado no smartphone dele.
A pergunta que você deve se fazer é: É absolutamente necessário pro meu aplicativo sempre utilizar a última versão do Google Play Services?
A resposta é quase sempre não. Usar a última versão é quase sempre desnecessário, exceto em caso de atualizações de segurança ou novas funcionalidades indispensáveis.
Minha recomendação é que você escolha uma versão fixa e utilize-a, atualizando somente conforme necessário.

Nota: no geral, qualquer tipo de dependência dinâmica pode trazer problemas, não somente a do Play Services. Evite-as sempre que possível.

Gerenciar versões bibliotecas android


XOR with three constants in First Order Logic

Question: I have a problem where S(X) is true for either (only one of) X=a, X=i, or X=k
I've expressed it like so:
$$
(S(a)\land ¬S(i)\land ¬S(k))\lor(¬S(a)\land S(i)\land ¬S(k))\lor (¬S(a)\land ¬S(i)\land S(k))
$$
If I reduce this to CNF I get a very long set of clauses after distributing ands over ors. Is there a 'nicer' way of writing this?
Thanks!
Answer: If you are okay with using XOR then your expression can be seen as XOR of all the cases, excluding the one with all true:
$$(S(a) \oplus S(i) \oplus S(k)) \land \lnot (S(a) \land S(i) \land S(k))$$
In general taking the XOR of some inputs will be true if an odd number of inputs are true, that is XOR acts like addition mod 2.
Note that I interpret your first sentence as "$S(X)$ is true for exactly one of $X=a, X=i, X=k$". The "either" case is trivial OR.