Is sampled absolutely integrable function absolutely summable?

Question: Suppose I have function $f:\mathbb{R}\rightarrow\mathbb{R}$ such that it's absolutely integrable: $\int_{\mathbb{R}}|f(x)|dx<\infty$.
I am sampling function $f(x)$ with some period $T_s$.  I am interested whether
$$\sum_{k=-\infty}^{k=\infty}|f(kT_s)|<\infty$$
It seems to me that it's true, but I can't figure out how to prove that.
The reason I ask is that I know that if $f(x)$ is absolutely integrable, then its Fourier transform exists, and  I am wondering if the sampled version is guaranteed to have a discrete Fourier transform.  Sorry if this is a silly question.
Answer: No, that is not true in general.
Let us consider, for example, $$f=\sum_{k\in\mathbb{Z}}g_k\in C^\infty(\mathbb{R})$$ obtained by taking $g_k=g(2^k(x-k)),\ \forall x\in\mathbb{R},k\in\mathbb{Z},$ for some $g\in C_c^\infty(]-1/2,1/2[),$ with $g(0)>0.$
Now taking $T_s=1,$ we get $\sum_{k\in\mathbb{Z}}f(kT_s)=\sum_{k\in\mathbb{Z}}g(0)=+\infty.$
Comment: Thank you, @Giuseppe!  However, I am sort of lost in your notation: what is the set $C_c^{\infty}(]-1/2,1/2[)$?
Comment: $g$ is a smooth (indefinitely differentiable with continuity) function which vanishes outside $]-1/2,1/2[$. An example is $\exp[1/(x^2-1/4)]$
Answer: Not true, as Giuseppe said. However, if you put $$g(x)=\sum_{k=-\infty}^\infty f(kT_s+x)$$ then the sum defining $g$ will be absolutely convergent for almost every $x$, and $g$ will be periodic with period $T_s$. Also, $$\int_0^{T_s}g(x)\,dx=\int_{-\infty}^\infty f(x)\,dx.$$ This might be of some use, depending on your application.


Factoring 3 Dimensional Polynomials?

Question: How do you factor a system of polynomials into their roots the way one can factor a single dimensional polynomial into its roots.
Example
$$x^2 + y^2 = 14$$
$$xy = 1$$
We note that we can find the 4 solutions via quadratic formula and substitution such that the solutions can be separated into $2$ groups of $2$ such that each group lies on either $(x + y + 4)$ and $(x + y - 4)$. Note that:
$$(x + y + 4)(x + y - 4) = 0$$
$$xy = 1$$
Is also an equivalent system.
How do I factor the bottom half?
Ideally if $g$ is a linear expression then my system should be
$$g_1 * g_2 = 0$$
$$g_3 * g_4 = 0$$
Such that the solutions to
Any of the subsystems of this system is a solution to system itself (note there are $4$ viable subsystems).
Help?
Comment: So I have worked a bit more on the system and found that:
Comment: x = 2 + sqrt(3), x = 2 - sqrt(3), x = -2 + sqrt(3), x = -2 - sqrt(3), are the four x solutions with corresponding y. The system is equivalent to:
Comment: (x + y + 4)(x + y - 4) = 0 & (x - y - 2sqrt(3))(x - y + 2sqrt(3)) = 0
Answer: Generally, if you have a bunch of equations in several variables and want to solve them simultaneously, you should not think of factoring as the basic method but rather elimination of variables, one by one. For a different example, take the circle $x^2+y^2=2$ and the ellipse $x^2-xy+y^2=1$. You expect four intersections, if you count them properly anyway. Subtract the equations and get the third relation $xy=1$, and substitute $y=1/x$ into (for instance) the first equation, which becomes $x^4-2x^2+1=0$ after clearing the fractions. This is $(x^2-1)^2=0$, as you see, and now, in the last step, you factor, to see that the points $(1,1)$ and $(-1,-1)$ are the only intersection points, but that they occur with multiplicity two.
Answer: For the "example" you list, here are some suggestions: Given
$$x^2 + y^2 = 14\tag{1}$$
$$xy = 1 \iff y = \frac 1x\tag{2}$$

Substitute $y = \dfrac{1}{x}\tag{*}$ into equation $(1)$. Then solve for roots of the resulting equation in one variable.

$$x^2 + y^2 = 14\tag{a}$$
$$\iff x^2 + \left(\frac 1x\right)^2 = 14\tag{b}$$
$$\implies x^4 - 14x^2 + 1 = 0\tag{c}$$
Try letting $z = x^2$ and solve the resulting quadratic:
$$z^2 - 14z + 1 = 0\tag{d}$$ Then for each root $z_1, z_2,\;$ there will be two repeated roots solving $(c)$: $2 \times 2$ repeated roots
Notice that by incorporating the equation (2) into equation  step $(b)$, we effectively end up finding all solutions that satisfy both equations $(1), (2)$: solutions for which the two given equations coincide.
See Lubin's post for some additional "generalizations": ways to approach problems such as this.
Comment: This is the method I had used earlier. I didn't find it appealing at the time since the problem becomes exponentially more difficult to solve as equation degree and variable count is increased...
Comment: Do you suppose there is some way to divide out the roots the way one does when factoring a normal 1-dimensional polynomial?
Comment: The best way, with this given example, is to use the quadratic formula to find the roots of the equation in $z$: there are two real roots, but they will involve a radical (square root sign): $z = 7 \pm \dfrac{\sqrt{285}}{2}$, so those will be the roots for $(c)$, but each will be repeated.
Comment: Does this make sense? In this case, the "fourth degree" polynomial can be treated as a quadratic equation, which greatly simplifies the factoring/solution-finding!
Answer: If you have equations of the form $p(x, y) = 0$ where $p$ is a polynomial, factoring that one is certainly worthwhile, It will give you more equations, but simpler ones. So, if you have:
$$
\begin{align*}
(x + y) (x^2 - y^2) &= 0 \\
(x - y) (x^2 + y^2) &= 0
\end{align*}
$$
you end up with $2 \times 2 = 4$ (pick one from each) systems of equations.
But if factoring polynomials in one variable isn't a walk in the park, with more variables it just gets worse.

Factoring 3 Dimensional Polynomials?


What are the security implications of the "Allow DNS Suffix Appending to Unqualified Multi-Label Name Queries" setting?

Question: The Allow DNS Suffix Appending to Unqualified Multi-Label Name Queries group policy was introduced in Windows Vista, and blocks the behaviour of child subdomains being tested against domain suffix, for example:
ping example will check example, but also example.mydnssuffix.local, however ping example.tld will check example.tld, but not example.tld.mydnssuffix.local.
Because this is disabled by default, I assume there are security implications involved in enabling this.  Does anyone know what those security implications would be?
Comment: Closely related, the headaches that the new TLDs are causing on search suffix resolution: [DNS just started resolving my server.prod addresses to 127.0.53.53](http://serverfault.com/questions/626612/dns-just-started-resolving-my-server-prod-addresses-to-127-0-53-53)
Answer: DNS clients that spend more time appending suffixes to ambiguous names and retrying their searches will take longer before giving up. This can cause significant slowdowns in applications that perform a lot of DNS queries.
It can also create a security concern if DNS clients erroneously resolve a name that is under the control of an external, malicious entity. Appending DNS suffixes is basically the opposite of devolution, which can present similar concerns.  I'll copy the example from the Windows IT Pro website (which is primarily about devolution, but also applies somewhat to appending suffixes) :

A domain-joined computer's primary domain suffix is mycompany.fl.us
  (mycompany is located in Florida, hence the extension fl.us) and tries
  to connect to mailserver1. In this example, the DNS client will try to
  resolve mailserver1.mycompany.fl.us and mailserver1.fl.us. The last
  name in this list, mailserver1.fl.us, is outside of the control of my
  company. If a malicious person has registered mailserver1.fl.us in the
  DNS, the name resolution will succeed, the domain-joined computer will
  try to connect to it, and the malicious user could spoof an internal
  server.

So why would you want to turn it on? You might want to give DNS clients the added flexibility of hopefully being able to resolve ambiguous names. But it could theoretically lead to a security concern. So it's up to the administrator to decide what is more appropriate for his or her environment.
Further reading:
http://blogs.technet.com/b/networking/archive/2009/04/16/dns-client-name-resolution-behavior-in-windows-vista-vs-windows-xp.aspx
And:
http://windowsitpro.com/networking/whats-dns-name-devolution
Comment: Your example explains side-effects of devolution, but does not apply to multi-label suffixing at all. The worst thing that can happen is that a non-existent domain (such as a typo, I don't know, `goodle.com`) ends up being checked as `goodle.com.company.org`, which should not be a problem if you trust your company (which you should if you use their domain as a DNS suffix). Of course, setting up `.com` as a DNS suffix would be an issue if you want to go to `google.com`, type `google.comm` and someone registered `comm.com` - but that is an issue regardless of multilabel-suffix application.
Comment: The example you quote has a single label name.  As such the Windows setting doesn't apply to it; any configured suffixes will always be attempted.  A more apt example would be trying to connect to mailserver1.mycompany.fl.us and ending up at a fake server mailserver1.mycompany.fl.us.fl.us, assuming that fl.us is in your search list.


Search API Usage

Question: I'm new to search api. Can anyone please make me understand about the usage of "Search API" on my opinion below.
As far my understanding, it can index from multiple source like solr, mongodb or any other source that defined in service (as it allowed me to configure multiple server) and can serve search result by combining all the data.
OR
It provide a mechanism to index existing data through configured server?
Answer: Search API is a module the creates index where are indexed nodes or other entities.
If you want to use it you have to have a "server" (by default the index is the same db of the drupal installation). There are modules that implements connection between search api and server (Solr, Elastic Search, for example).
After you have configured the index you can use Views to build view with data from the search api index and also use facet integration.
Comment: can you explain more please. so can I gather as many source as i like together combined? for example i have three sister site there are using different server. can i combine all of their search result into my site? if they share search data in xml format or json format?

Search API Usage


Como utilizar IValidatableObject?

Question: Como utilizar o IValidatableObject para não validar a uma propriedade de chave estrangeira durante um cadastro? Quero validar apenas a chave estrangeira na edição.
Answer: IValidatableObject pede para implementar Validate, que é um método que recebe como argumento um ValidationContext.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    /* Aqui entra a validação em si */
}

Para o seu caso, como você apenas quer validar na edição, isto quer dizer que a chave primária está preenchida. Então a lógica ficaria assim:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.EntidadeId != null && this.EntidadeId > 0) {
        if (this.EntidadeEstrangeiraId == null || this.EntidadeEstrangeiraId <= 0) {
            yield return new ValidationResult("É necessário definir um valor de EntidadeEstrangeira", new [] { "EntidadeEstrangeiraId" });
        }
    }
}

Comment: Legal, é semelhante ao FluentValidation, vou utilizar nesse projeto. Valeu demais!!

Como utilizar IValidatableObject?


Erro de configuração na conexão JPA e PostgreSQL

Question: Estou com problemas ao conectar o JPA com PostgreSQL. Acredito que o problema seja na configuração da aplicação.
Estou usando a versão do Java 8, e meu arquivo pom.xml é:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fsma</groupId>
<artifactId>ControleVenda</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.14</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.14</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.faces</artifactId>
        <version>2.1.21</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-java8</artifactId>
        <version>5.1.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4.1208.jre7</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>5.1.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.weld.servlet</groupId>
        <artifactId>weld-servlet</artifactId>
        <version>2.3.3.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.spec.javax.servlet.jstl</groupId>
        <artifactId>jboss-jstl-api_1.2_spec</artifactId>
        <version>1.1.2.Final</version>
    </dependency>

</dependencies>

Em meu arquivo persistence.xml, uso as seguites configurações:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="ControleVenda">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <class>com.fsma.controleVenda.models.Cliente</class>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://172.18.0.2:5432/sis_venda" />
            <property name="javax.persistence.jdbc.user" value="postgres" />
            <property name="javax.persistence.jdbc.password" value="postgres" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.default_schema" value="sis_venda" />
            <property name="hibernate.max_fetch_depth" value="3" />

            <property name="hibernate.c3p0.min_size" value="5" />
            <property name="hibernate.c3p0.max_size" value="25" />
            <property name="hibernate.c3p0.timeout" value="120" />
            <property name="hibernate.c3p0.acquire_increment" value="2" />
            <property name="hibernate.c3p0.max_statements"  value="30" />
            <property name="hibernate.c3p0.idle_test_period"  value="150" />
            <property name="hibernate.c3p0.preferredTestQuery"  value="select 1" />

        </properties>

    </persistence-unit>
</persistence>

Criei um JPAUtil.java para complementar a configuração:
package com.fsma.controleVenda.dao;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtil {

    /**
     * Atributo que pega o nome da conexão do persistence.xml
     */
    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("ControleVenda");

    @Produces
    @RequestScoped
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void close(@Disposes EntityManager em) {
        em.close();
    }

}

A StackTrace Retorna os seguintes erros:
Cliente [id=null, nome=Yure Menezes, endereco=Rua das Pacas]
nov 25, 2018 6:56:42 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{clienteBean.gravar()}: java.lang.NullPointerException
javax.faces.FacesException: #{clienteBean.gravar()}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:117)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1139)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    ... 27 more
Caused by: java.lang.NullPointerException
    at com.fsma.controleVenda.dao.ClienteDao.gravar(ClienteDao.java:33)
    at com.fsma.controleVenda.controllers.ClienteBean.gravar(ClienteBean.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:279)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 28 more

nov 25, 2018 6:56:42 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/ControleVenda] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at com.fsma.controleVenda.dao.ClienteDao.gravar(ClienteDao.java:33)
    at com.fsma.controleVenda.controllers.ClienteBean.gravar(ClienteBean.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:279)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1139)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

A minha classe Cliente e Controle ClienteBean, seguem abaixo:
package com.fsma.controleVenda.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "cliente")
public class Cliente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "nome", length = 100, nullable = false)
    private String nome;

    @Column(name = "endereco", length = 150, nullable = false)
    private String endereco;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((endereco == null) ? 0 : endereco.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((nome == null) ? 0 : nome.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Cliente other = (Cliente) obj;
        if (endereco == null) {
            if (other.endereco != null)
                return false;
        } else if (!endereco.equals(other.endereco))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (nome == null) {
            if (other.nome != null)
                return false;
        } else if (!nome.equals(other.nome))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Cliente [id=" + id + ", nome=" + nome + ", endereco=" + endereco + "]";
    }

}

ClienteBean.java
package com.fsma.controleVenda.controllers;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;

import com.fsma.controleVenda.dao.ClienteDao;
import com.fsma.controleVenda.models.Cliente;

@SessionScoped
@ManagedBean
public class ClienteBean implements Serializable {

    @Inject
    private ClienteDao clienteDao;

    private Cliente cliente;

    private Boolean alterando;

    /**
     * Esse método será executado no momento de instanciação da classe dentro da View
     */
    @PostConstruct
    public void init() {
        System.out.println("Cliente.init();");

        if (cliente == null) {
            cliente = new Cliente();
        }
    }

    public Cliente getCliente() {
        return cliente;
    }

    public String cadastraCliente() {
        return "CadastraCliente";
    }

    public String voltar() {
        return "cliente";
    }

    public String gravar() {
        this.clienteDao = new ClienteDao();
        System.out.println(cliente.toString());
        clienteDao.gravar(cliente);
        return "index";
    }

}

Comment: Poste o código de `ClienteDao`; em especial, a instrução na  linha 33 dentro do método `gravar`.
Answer: O problema está aqui:
#{clienteBean.gravar()}: java.lang.NullPointerException

Ele está detectando algum valor nulo! Não vai conseguir cadastrar no banco! Pelo que vi você colocou o id com autoincremento. Então você não pode setar valor para essa variável!
Recomendo criar uma classe principal, criar um objeto cliente e tentar cadastrar assim para ver se retorna algum erro!
Tem que ver esse erro também:

Servlet.service() for servlet [Faces Servlet] in context with path [/ControleVenda] threw exception [java.lang.NullPointerException] with root cause
  java.lang.NullPointerException

Se você estiver tentando cadastrar o cliente e juntamente com chave estrangeira no controle de vendas, nunca vai funcionar. Pois o cliente nem possui id ainda!


How to estimate logit model

Question: I am trying to understand how to fit a logit model using maximum likelihood described in a paper:
$$p_{it}=\frac{exp(\alpha+\beta q_{it})}{1+exp(\alpha+\beta q_{it})} $$
where
$$q_{it}=\frac{q_0d^{t-1}+x_{i1}d^{t-2}+...+x_{it-2}d+x_{it-1}}{d^{t-1}+d^{t-2}+...+1}$$
My question is how to estimate $\alpha$, $\beta$, $q_0$ and $d$ and also their standard errors.
I am thinking to write out the expressions:
$$q_{it}=a+b_1x_{i1}+b_2x_{i2}+...+b_{t-1}x_{it-1}$$ such that
$$a=\alpha+\frac{\beta q_0d^{t-1}}{d^{t-1}+...+1}$$
$$b_1=\frac{\beta}{d^{t-1}+...+1}d^{t-2}$$
$$...$$
$$b_{t-1}=\frac{\beta}{d^{t-1}+...+1}$$
I kind of know how to solve the equations to get $\beta$ and $d$, but I don't know how to get $\alpha$ and $q_0$. And the model is over parameterized ($t=75$), so I do not know how to get the standard errors. So far I think of it in terms of regressions, and perhaps it is not a right way to get the parameters, but I have no clue how to do it.
Answer: It is unlikely that there is a closed form solution for the ML-estimators of the parameters. You must thus find the values numerically with an optimization (minimization/maximization) algorithm.
The outline is as follows

Define the log-likelihood function as $$l = \sum_{i,t} \log p_{it}$$

Use a software library routine, e.g. optim in standard R, to find the parameters that maximize l. Caveat: if the function minimizes the given function (like optim does), you must replace $l$ with $-l$.

To estimate standard errors for the parameters, there is a complicated method based on the inverse Hessian matrix (which I occasionally observe to be numerically unstable). A more robust and very simple method is instead to use the jacknife method, which I have described in section 5.2 of this article:

Dalitz: "Construction of confidence intervals." Technical Report No. 2017-01, pp. 15-28, Hochschule Niederrhein, Fachbereich Elektrotechnik und Informatik, 2017
Answer: If you are open to a Bayesian approach and willing to specify at least weakly informative proper prior distributions for the model parameters, then using the brms R package should make this relatively straightforward. This is basically a logistic regression - I assume this is what you meant by a logit-model, if you are modeling logit-transformed probabilities that you observe instead of Bernoulli trials, not much changes below except that you'd e.g. use beta-regression - with a non-linear function of the predictors, which is a feature that package implements easily.
Taking a Bayesian approach also helps with over-parameterized models: if you specify not-too-weak priors, these will to some extent resolve issues with model parameters being not identified or only poorly identified.
Something along the lines below should let you fit this model with a bit of experimentation. I've put in some placeholder prior distributions, but I have no idea whether those make any sense in your context (who knows, maybe some model parameters should even have joint priors).
library(brms)

brmfit1 = brm( family="bernoulli",
     bf( y ~ alpha + beta * ( q0 * d^(t-1) + ...  ) / ( d^(t-1) + d^(t-2) + ... + 1 ),
         nl = TRUE,
         alpha ~ 1, beta ~ 1, q0 ~ 1, d ~ 1), # assumes the t and x_it are observed covariates
     prior=c(prior(normal(0,1), nlpar="alpha"),
             prior(normal(0,1), nlpar="beta"),
             prior(normal(0,1), nlpar="q0"),
             prior(lognormal(0,1), nlpar="d")),
     control=list(adapt_delta=0.99))
prior_summary(brmfit1
summary(brmfit1)
stancode(brmfit1) # if you want to see the Stan code generated by brms, that way you could modify it yourself and then use it with rstan

Comment: Thank you! I did not know anything about bayesian logit, but definitely will look at it.

How to estimate logit model


Heatmaps in ggplot using multiple variables (formatted as individual columns)

Question: I'm looking to make a Heatmap from some protein signature data in ggplot, but haven't been able to figure out how to wrangle the dataframe so I can visualize properly. Here is an example of the data format:
CellLine, Protein1, Protein2, Protein3, Protein 4
Cancer1, 0.22, 1.15, 0.68, 0.44
Cancer2, 0.95, 1.54, 0.55, 0.02
Cancer3, 1.20, 0.85, 0.99, 0.89

Ideally, I'd like to show the cell line on the y-axis and the proteins on the x-axis, with the respective expression values filling in the color scale. Please let me know if you have any suggestions, would greatly appreciate the help!
CtrlsMatrixed <- DF from above
CtrlsMatrixed <- ControlsDF %>% pivot_longer(cols = 3:45, cols_vary = "fastest", names_to =   "GeneSignature")

Code came back with error in pivot_longer()--> couldn't combine CellLine <character> and Protein1 <double>
***** EDIT for Allan:
structure(list(`PI3K-p110-a-R-C` = c(1, 1, 1, 1, 1, 1), `PI3K-p85-R-C` = c(1,
1, 1, 1, 1, 1), `EGFR-R-V` = c(1, 1, 1, 1, 1, 1), `EGFR_pY1173-R-V` = c(1,
1, 1, 1, 1, 1), `FGF-basic-R-C` = c(1, 1, 1, 1, 1, 1), `c-Kit-R-V` = c(1,
1, 1, 1, 1, 1), `c-Met_pY1234_Y1235-R-V` = c(1, 1, 1, 1, 1, 1
), `PDK1-R-V` = c(1, 1, 1, 1, 1, 1), `PDK1_pS241-R-V` = c(1,
1, 1, 1, 1, 1), `PTEN-R-V` = c(1, 1, 1, 1, 1, 1), `Akt-R-V` = c(1,
1, 1, 1, 1, 1), `Akt1-R-V` = c(1, 1, 1, 1, 1, 1), `Akt1_pS473-R-V` = c(1,
1, 1, 1, 1, 1), `Akt2-R-V` = c(1, 1, 1, 1, 1, 1), `Akt2_pS474-R-C` = c(1,
1, 1, 1, 1, 1), `Akt_pS473-R-V` = c(1, 1, 1, 1, 1, 1), `Akt_pT308-R-V` = c(1,
1, 1, 1, 1, 1), `FOXO3-R-V` = c(1, 1, 1, 1, 1, 1), `FoxO3a_pS318_S321-R-C` = c(1,
1, 1, 1, 1, 1), `PKCa-R-V` = c(1, 1, 1, 1, 1, 1), `PKC-a-b-II_pT638_T641-R-V` = c(1,
1, 1, 1, 1, 1), `TSC1-R-C` = c(1, 1, 1, 1, 1, 1), `mTOR-R-V` = c(1,
1, 1, 1, 1, 1), `mTOR_pS2448-R-C` = c(1, 1, 1, 1, 1, 1), `Rictor-R-C...28` = c(1,
1, 1, 1, 1, 1), `Rictor_pT1135-R-V` = c(1, 1, 1, 1, 1, 1), `Raptor-R-V` = c(1,
1, 1, 1, 1, 1), `PRAS40_pT246-R-V` = c(1, 1, 1, 1, 1, 1), `p70-S6K_pT389-R-V` = c(1,
1, 1, 1, 1, 1), `S6_pS235_S236-R-V` = c(1, 1, 1, 1, 1, 1), `S6_pS240_S244-R-V` = c(1,
1, 1, 1, 1, 1), `4E-BP1-R-V` = c(1, 1, 1, 1, 1, 1), `4E-BP1_pS65-R-V` = c(1,
1, 1, 1, 1, 1), `4E-BP1_pT37_T46-R-V` = c(1, 1, 1, 1, 1, 1),
    `eIF4E-R-V` = c(1, 1, 1, 1, 1, 1), `eIF4E_pS209-R-V` = c(1,
    1, 1, 1, 1, 1), `p38-MAPK-R-V` = c(1, 1, 1, 1, 1, 1), `p38-MAPK-_pT180_Y182-R-V` = c(1,
    1, 1, 1, 1, 1), `p44-42-MAPK-R-V` = c(1, 1, 1, 1, 1, 1),
    `MEK1_pS217_S221-R-V` = c(1, 1, 1, 1, 1, 1), `p90RSK_pT573-R-C` = c(1,
    1, 1, 1, 1, 1), `Rictor-R-C...45` = c(1, 1, 1, 1, 1, 1),
    CellLines = c("Cancer A", "Cancer E", "Cancer C", "Cancer F",
    "Cancer D", "Cancer B")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

Answer: You could do this in ggplot quite easily with geom_tile
library(tidyverse)

ControlsDF %>%
  pivot_longer(-CellLine, names_to = 'Protein', values_to = 'Expression') %>%
  ggplot(aes(Protein, CellLine, fill = Expression)) +
  geom_tile(color = 'black') +
  scale_fill_viridis_c() +
  coord_equal(expand = FALSE)

Created on 2023-09-12 with reprex v2.0.2

Data from question in reproducible format
ControlsDF <-  structure(list(CellLine = c("Cancer1", "Cancer2", "Cancer3"),
               Protein1 = c(0.22, 0.95, 1.2), Protein2 = c(1.15, 1.54, 0.85
               ), Protein3 = c(0.68, 0.55, 0.99), Protein4 = c(0.44, 0.02,
                0.89)), class = "data.frame", row.names = c(NA, -3L))

EDIT
Using the data in the dput output above, we can use essentially the same code:
ControlsDF %>%
  pivot_longer(-CellLines, names_to = 'Protein', values_to = 'Expression') %>%
  ggplot(aes(Protein, CellLines, fill = Expression)) +
  geom_tile(color = 'black') +
  scale_fill_viridis_c() +
  coord_equal(expand = FALSE) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

Comment: Thank you for your speedy reply Allan. I tried your code with my original data frame and received the following error

`Error: Discrete value supplied to continuous scale`

It seems to be referring to the x-value for the visualization-- the CellLine equivalent. Do you think there is some reformatting to do here? i.e. transforming the 'Cell Line' variable? How would you go about handling this error
Comment: @Jeremybravo I can't say without seeing your actual data. Are you able to edit your question to include the output of `dput(ControlsDF)`?  I can only show how to work with the data you provide in your question. Alternatively a DropBox or Google Sheet  or Gist link would work.
Comment: Hey Allan, I added the output of the `dput()` function into the question. Thanks again for all your expertise.
Comment: @Jeremybravo that's great - thanks, but I don't get any error with essentially the same code using that data either - you will see the output I'm getting in my edit above.
Comment: I found some errors in the syntax I was using, but your code worked great! Thank you so much :)


Android Croperino - Crop in copy instead of original

Question: I'm using Croperino with Android to pick a picture from the gallery and then run a crop.
But, when the crop is done the original file is modified and I don't want that, I only need the cropped image inside my app.
I have the following code:
CroperinoFileUtil.newGalleryFile(data, getActivity());
Croperino.runCropImage(CroperinoFileUtil.getmFileTemp(), getActivity(), true, 1, 1, 0, 0);

I also tried:
 File dest = new File(CroperinoFileUtil.getPath(getActivity(), data.getData()), "IMG_" + System.currentTimeMillis() + ".jpg");

                try {
                    FileInputStream inStream = new FileInputStream(CroperinoFileUtil.getmFileTemp());
                    FileOutputStream outStream = new FileOutputStream(dest);
                    FileChannel inChannel = inStream.getChannel();
                    FileChannel outChannel = outStream.getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                    inStream.close();
                    outStream.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

After CroperinoFileUtils.newGalleryFile... and before Croperino.runCropImage...
Anybody know how to do that?
Comment: Hey I am also facing this issue. Any way to fix this?
Answer: That problem made me download the source code and inspect the error
The solution is very easy but as I said it made me download the source code then integrate it with my project
in CropImage.java: find
mSaveUri = getImageUri(mImagePath);

and replace it with
mSaveUri = Uri.fromFile(new File(CroperinoConfig.getsRawDirectory()+CroperinoConfig.getsImageName()));

That's all


a divide b mod m when mod inverse doesn't exist

Question: I am trying to compute [(2 ^ (2*n-1) + 1) / 3] mod m.  The value for n can be very large, so computations are performed mod m.
The computed value is always an integer, and hence the computation is valid for all m.
When m is not divisible by 3, we can use mod power to compute the power of 2, add 1, then multiply by the mod inverse of 3.
However, I am stuck when m is divisible by 3.  How do we perform the computation when m is divisible by 3?
Comment: Hello David welcome ,try to use Mathjax while writing the question. This would help others to understand easily.
Comment: If $\,3\mid a\,$ then $\ \bbox[5px,border:1px solid #c00]{a/3 \bmod m = (a\bmod 3m)/3}\ $ by the [mod Distributive Law](https://math.stackexchange.com/a/2059937/242).
Comment: Thank you - this is the solution!
Answer: The point is that $3^{-1}$ is only defined if $\text{gcd}(3,m) = 1$; otherwise you get non-sensical results. In other words
If $\text{gcd}(3,m) \neq 1$ then division by 3 is the same thing as division by zero (in an abstract sense)
The point is the following:
if \begin{equation}
x y = 1
\end{equation}
and
\begin{equation}
 y \neq 0
\end{equation}
 and there exists some
\begin{equation}
 z \neq 0
\end{equation}
such that
\begin{equation}
 yz = 0
\end{equation}
then we have that
\begin{equation}
x y = 1 \implies xyz = z \implies z = 0
\end{equation}
which is a contradiction.
How does that happen here? Well suppose that there is a $3^{-1} \not\equiv 0 $ mod 6 for example, then
\begin{equation}
3 (3^{-1}) \equiv 1 \ (\text{mod} 6)
\end{equation}
but
\begin{equation}
 3 \not\equiv 0  \ (\text{mod} 6)
\end{equation}
 and
\begin{equation}
2 \not\equiv 0  \ (\text{mod} 6)
\end{equation}
and
\begin{equation}
2 \cdot 3 \equiv 0  \ (\text{mod} 6)
\end{equation}
then we have that
\begin{equation}
3 (3^{-1}) \equiv 1 \ (\text{mod} 6) \implies 2 \cdot 3 \cdot (3^{-1}) \equiv 2 \ (\text{mod} 6)\implies 2 \equiv 0  \ (\text{mod} 6)
\end{equation}
which is a contradiction.
Answer: Hint: $ $ if $\,3\mid a\,$ then $\ \bbox[5px,border:1px solid #c00]{a/3 \bmod m = (a\bmod 3m)/3}\ $ by the mod Distributive Law
Comment: See [here](https://math.stackexchange.com/a/3273923/242) for elaboration. $\ \ $


help with absolute value question $||x-3|-2|\leq 1$

Question: could anyone help in validating this absolute value question that my son is working on?
$|(|x-3|-2)|\leq 1$
$-1\leq|x-3|-2\leq 1$
$1\leq|x-3|\leq 3$
$1\leq x-3\leq 3$
$4\leq x\leq 6$
or
$-3\leq x-3\leq -1$
$0\leq x\leq 2$
thus
$x\in [4,6]\cup [0,2]$
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: Looks fine to me.
Comment: The calculation looks correct and sensibly laid out.
Comment: Thank you, for some reason his online math program isn't accepting the answer, I just wanted to make sure he did it correctly.  I can take up the formatting/input issues with his teacher.
Comment: The way you present it, it looks like you intended to say step 3 implies step 4.  Somehow you should put an "either step 4 or step 6" statement in there.  Other wise.... Um... Yeah.  Correct.
Comment: right, should have included that.
Answer: It looks okay to me. ${}{}{}{}{}{}$


String interpolation tem uma performance melhor que string.Format?

Question: Eu uso Resharper e há poucos dias eu comecei a usar alguns recursos do C# 6.
Em várias partes do código uso string.Format() e percebi que o Resharper sugere que esses trechos sejam substituídos por string interpolation.
A dúvida é: por que o Resharper sugere essa troca?
String interpolation tem uma performance melhor que string.Format() ou essa sugestão é apenas para tornar o código mais legível?
Answer: Não existe diferença nenhuma. O compilador vai chamar string.Format() sempre que você usar a notação $.
Em outras palavras, o IL gerado vai ser o mesmo. Portanto, não existe diferença de performance.
Fonte: https://roslyn.codeplex.com/discussions/570614
Answer: A melhor forma de descobrir, é testando. Fiz um teste simples:
using static System.Console;
using System.Diagnostics;

public class Program {
    public static void Main() {
        var x = "";
        var sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < 10000; i++) x = string.Format("teste de string formatada com resultado: {0}", i + 5);
        sw.Stop();
        WriteLine(sw.ElapsedTicks);
        sw.Restart();
        for (var i = 0; i < 10000; i++) x = $"teste de string formatada com resultado: {i + 5}";
        sw.Stop();
        WriteLine(sw.ElapsedTicks);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
O melhor teste será feito em um ambiente controlado e não em um servidor compartilhado onde não se sabe o que está rodando. Executei algumas vezes. E no geral o resultado foi quase o mesmo.
Mas é importante notar que em outros padrões este resultado pode ser diferente. Este tipo de teste só diz sobre esta situação específica, mas se pode generalizar. Pode ser que montando o teste de outra forma dê um resultado diferente, mesmo que ele execute a mesma coisa. Para testar adequadamente é necessário entender profundamente as implementações para tentar achar os pontos onde cada um se destaca e ondem falham. Se a implementação mudar, o teste não serve mais.
Coloquei no SharpLab para ver o código gerado e ambos usam o Format().
Mais informações na documentação. Como não está na documentação é detalhe de implementação e um dia pode mudar.
A grande vantagem não está na velocidade, mas na simplificação e comodidade. E O Resharper sugere porque é mais elegante, não porque é mais rápido.
Em C# 10 tem a string interpolada constante que faz uma diferença de performance. Veja mais.


PHP link on submit button

Question: Boas,
Preciso de uma funcao em PHP, ja que em HTML não consigo, para listar os ficheiros com uma determinada extensao,(html) e mosta-los numa combo box, ou dropbox. Depois necessito que ao seleccionar um ficheiro e premir o botao, abra o ficheiro corespondente. neste momento, funciona tudo com excepcao de que ao premir o botao aparece o link que tenho de premir para abrir o ficheiro. como faer para abrir logo assim que se prime o botao ?
Obrigado!

<form action="#" method="post">
<?php
$files = glob('*.html');
echo "<select name='datas'>";
foreach ($files as $file) {
echo "<option>".$file."</option>"; }
echo "</select>";
?>
<input type="submit" name="submit" value="Seleccione a Data" />
</form>

<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['datas'];
echo "$selected_val";
}
?>

Comment: Jovem aqui é o PT.StackOverflow, por favor edite sua pergunta escrevendo em português.
Comment: Traduzido. Obrigado pela chamada de atenção,
Answer: Somente com PHP você poderia utilizar a função header('Location:' . $endereco).
Ficaria assim em PHP:
<?php
    if(isset($_POST['submit'])){
        $selected_val = $_POST['datas'];
        header('Location: ' . $selected_val);
    }
?>

Outra alternativa é utilizar um simples JavaScript.
Uma pequena mudança no corpo do HTML

    <form>
        <?php
            $files = glob('*.html');
            echo "<select id='idcombobox' name='datas'>";
            foreach ($files as $file) {
                echo "<option>".$file."</option>";
            }
            echo "</select>";
        ?>

        <input type="button" name="submit" onclick="abrirPagina()" value="Seleccione a Data" />
    </form>

JavaScript

PHP link on submit button


In what situation would Wilcoxon's Signed-Rank Test be preferable to either t-Test or Sign Test?

Question: After some discussion (below), I now have a clearer picture of a focused question, so here is a revised question, though some of the comments might now seem unconnected with the original question.
It seems that t-tests converge quickly for symmetric distributions, that the signed-rank test assumes symmetry, and that, for a symmetric distribution, there is no difference between means/pseudomedians/medians.  If so, under what circumstances would a relatively inexperienced statistician find the signed-rank test useful, when s/he has both the t-test and sign test available?  If one of my (e.g. social science) students is trying to test whether one treatment performs better than another (by some relatively easily interpreted measure, e.g. some notion of "average" difference), I am struggling to find a place for the signed-rank test, even though it seems to generally be taught, and the sign-test ignored, at my university.
Comment: It depends on *whose* conventional wisdom you're looking at; my experience of it is very different from yours. Certainly it's easy to find resources that clearly state that symmetry of difference scores is assumed under the null (and that it matters). But note that this is *under the null* -- as a result, finding lack of symmetry in difference scores in a sample isn't necessarily relevant -- you're not required to have symmetry under the alternative. If you're highly confident that if the null were true the symmetry would hold -- and in many cases it's a highly plausible assumption --  ... ctd
Comment: Looking your second comment first: (on top of what you already mentioned), note that 1. normal assumptions don't exhaust parametric tests. 2. The signed rank test isn't actually a test of medians but of one-sample Hodges-Lehmann statistics / pseudomedians (though if you add the assumption of symmetry to the alternative, it will also test for medians, and where means exist, also for means, among many other things). Similarly the rank sum test is not a test of medians but of median pairwise differences. You're right that the level of the signed rank test can be quite sensitive to asymmetry.
Comment: On your earlier comment: 1 Symmetry isn't generally seen as part of the null, but as part of the assumptions you need in order that the permutations be exchangeable under the null. 2. as previously mentioned, it's not actually a test of medians, but of pseudomedians, and this holds true even under an asymmetric alternative. It's true that interpretation is sometimes easier if you make some restrictive assumptions, but the restrictions required to make it a reasonable test for medians needn't be as strict as assuming symmetry under the alternative.
Comment: @justme The null hypothesis I articulated **is not a null assuming median equality** and rejecting it **does not test for median difference *without the additional assumptions that (1) the distributions have the same shape, and (2) have the same variance.*** The basic null for both sign-rank says a randomly selected paired difference between group A and group B is equally likely to be positive as negative.
Comment: @justme the $>$ as opposed to $\ge$ is because, since these tests assume continuous distributions true equality has a zero probability. Either because of precision issues, or because the data are not actually continuous, data with *ties* require special adjustments to the test statistics (for the rank sum test).
Comment: Justme: of course, I didn't think about that.
Comment: ctd... then there's no issue. The problem is, if you're not prepared to assume it beforehand you don't know if a rejection was caused by assumption failure; the obvious thing to do then is simply *not* assume it.
Comment: I think the OP is still misunderstanding "symmetry." $H_{0}: P(X_{A} = X_{B}) = 0.5$ is a symmetric **probability** under the null, but implies nothing about a **symmetric distribution**, since both (a) asymmetric distributions can exist under the null, and (b) symmetric distributions can exist under a set of alternative hypotheses.
Comment: Thanks @Alexis!  I'm really trying to wrap my head around this, but struggling to piece together all the nuances I'm getting from people's comments and my own simulations.  Am I right in saying that that should be a ">", i.e. $H_0: P(X_A>X_B)=0.5$ ?  I can see how this could solve our problems with a **rank-sum** test, but I still struggle to see how it changes anything for a **signed-rank** test, because presumably this is equivalent to $H_0: P(X_A-X_B>0) = 0.5$, i.e. that the median of differences is 0?  But, both my simulation in the original post (will copy that below) and examination...
Comment: ...of the formula used for the signed-rank test both seem to point towards that not being robust to asymmetry in terms of false positives.  Glen_b's comments about pseudomedians seemed to make sense as a possible way out of this, but I haven't managed to make the simulation much better using pseudomedians instead of medians, and I'm still struggling to wrap my head around where the pseudomedians would fit in.  So I'm still (as you say) confused as to what our real null and assumptions are and what kind of reinterpretation of the test allows me to ignore symmetry in the distn of differences...
Comment: This is the simulation:

    `data = replicate(1000,rlnorm(50))-exp(0)`
    `is.false.positive = function(x)wilcox.test(x)$p.value<0.05`
    `false.positives = apply(data,2,is.false.positive)`
    `false.positive.rate = mean(false.positives)`
    `print(sprintf("%d runs gives false positive rate %f", length(false.positives), false.positive.rate))`
Comment: Thanks @Alexis!  But in your comment you used a $=$ rather than a $>$ or $\geq$, which is where that confusion lay (rather than between the two latter).  Regardless, in my simulation, $P(X_A \geq X_B) = 0.5$ by design, but when I crank up the asymmetry in the distribution of $X_A-X_B$, the false positives go through the roof.  So it must either be an assumption, or incorporated into the null?  This is also what I see on [Wikipedia](https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test#Test_procedure) where it is incorporated into the null.
Comment: @justme Whoops! You are right... I totally did. Properly: $H_{0}:P\left(X_{A} > X_{B}) = 0.5\right)$ and $H_{a}:P\left(X_{A} > X_{B}) \ne 0.5\right)$ I would be happy to see the deets on your simulation and discuss. My email is firstname.lastname@example.com (minus the quadruped-ish bits).
Comment: The t.test performs much worse in this situation (around 70% false positives). But the high rate of false positives with the Wilcoxon signed-rank test is disturbing..
Comment: Thanks for the comment @JonB!  However, I think the reason you are getting such bad false positives for the t-test is that you are not adjusting for the change in null hypothesis.  For the t-test, we should change the first line to `data = replicate(1000,rlnorm(50))-exp(1/2)` so that we have a _mean_ of zero.  If I do that, I get a false positive rate closer to 10%.  (Still not great, but much better than the Wilcoxon).
Comment: The rank sum test does not assume symmetry. The point of such nonparametric tests (e.g. signed rank, Kruskal-Wallis, etc.) is that the only distributional assumption they make is i.i.d.
Comment: @Alexis -- thank you for commenting!  Though I'm talking about the signed-rank test, not the rank sum test.  Though, what you are saying about nonparametric tests is the prevailing teaching from everyone I know.  But yet, looking at the simulation above, at the way the statistic is calculated, and at the fact that it is mentioned as an assumption in passing in many places (e.g. assumption #3 at [Laerd](https://statistics.laerd.com/spss-tutorials/wilcoxon-signed-rank-test-using-spss-statistics.php)), make me suspect that the conventional wisdom might not be all it's cracked up to be?
Comment: @JonB it's a sneaky blighter hiding in the code waiting to trip you up!!
Comment: @Glen_b -- thank you, this is very helpful, but I'm struggling to wrap my head around a few details, if I may ask? If understand you correctly (which I might not), symmetry is (part of) an often sensible null, and assymetry allows us to reject that? But if we do not assume symmetry in the alternative, how do we judge whether our "changed distribution" represent an improvement or a degradation, since the differences could still have zero median? Also, when you say the obvious thing is not to assume it -- do you mean to use a different test (e.g. sign test) instead? Thank you!
Comment: @Glen_b -- to give you some context -- I work for very young university that has no statistics department, and only recently started a maths department.  The standard approach taught to the students is that they should normality test their data, and if that fails to show "normality" then they should use the "equivalent" nonparametric test and compare medians.  I'm very aware of the nonsensicalness of normality testing in this context, but it seems to me that in the one-/paired-samples context it is even more dangerous, because it seems to scoop off the worst performance from both tests...
Comment: I'd like to turn this into an answer but I don't know that I really address everything necessary.
Comment: @Glen_b -- apologies for the slow reply, I needed time to digest and experiment!  But this is SO helpful, thank you!  Especially the pseudomedian comment, which I had missed.  But, does this mean that my simulation above should achieve lower false positives if I gave my distribution zero pseudomedian rather than zero median?  I have tried to estimate the pseudomedian using simulation, but I'm not seeing much improvement in the simulation; I'm not sure if that is because my estimate is too noisy, or because we still require symmetry somewhere, even when we are looking at pseudomedians?
Comment: @Glen_b I also rephrased the question in case that makes it focused enough for a proper answer!  -- Though it is possible that my rephrasing misunderstands something of what you have said...
Answer: Consider a distribution of pair-differences that is somewhat heavier tailed than normal, but not especially "peaky"; then often the signed rank test will tend to be more powerful than the t-test, but also more powerful than the sign test.
For example, at the logistic distribution, the asymptotic relative efficiency of the signed rank test relative to the t-test is 1.097 so the signed rank test should be more powerful than the t (at least in larger samples), but the asymptotic relative efficiency  of the sign test relative to the t-test is 0.822, so the sign test would be less powerful than the t (again, at least in larger samples).
As we move to heavier-tailed distributions (while still avoiding overly-peaky ones), the t will tend to perform relatively worse, while the sign-test should improve somewhat, and both sign and signed-rank will outperform the t in detecting small effects by substantial margins (i.e. will require much smaller sample sizes to detect an effect). There will be a large class of distributions for which the signed-rank test is the best of the three.
Here's one example -- the $t_3$ distribution. Power was simulated at n=100 for the three tests, for a 5% significance level. The power for the $t$ test is marked in black, that for the Wilcoxon signed rank in red and the sign test is marked in green. The sign test's available significance levels didn't include any especially near 5% so in that case a randomized test was used to get close to the right significance level. The x-axis is the $\delta$ parameter which represents the shift from the null case (the tests were all two-sided, so the actual power curve would be symmetric about 0).

As we see in the plot, the signed rank test has more power than the sign test, which in turn has more power than the t-test.
Comment: Thanks a lot for this @Glen_b !  I'm still struggling to work out where it fits in our syllabus, when we have students for whom even the concept of power is beyond the scope of their studies, and why we teach Wilcoxon as the main alternative to the paired t.  But this does give some useful motivations.  Thank you!
Comment: Incidentally after considering what distributional feature impacts the asymptotic variance of the median (and hence the power of the sign test), an example occurred to me where the relative positions of the t and sign test are reversed; as a result I think there's a good possibility of constructing a case where the signed rank test may do considerably better than either of the two other tests. I'll play with it some more when I can and maybe write something on it.
Comment: As far as your syllabus goes, it's clear there are definitely cases where the signed rank outperforms both other tests (as I outlined in my answers -  distributions that are somewhat heavier tailed than normal, but not especially peaked); the t is better at the normal or lighter, and the sign test is better  when the distribution has a strong peak (which often tends to go along with very heavy tails, but doesn't have to). [Beware, however, confusing these ideas with mere changes in spread, which doesn't alter their relative properties.] ... I'm sure you could squeeze a few such sentences in
Comment: Thanks a lot @Glen_b !  The trouble is I'm not teaching the syllabus, just supporting it!  The syllabus in most departments seems to be: (i) use a hypothesis test of normality (kill me now) and based on that (ii) either use Wilcoxon or t-Test.  So the finer details of the shoulders of the distribution etc are never even touched, and nor is power, just whether assumptions are met (in a slightly rubbish way).  But your thoughts are very helpful for me personally, at least!
Comment: Great post @Glen_b! So in terms of selecting from the two tests, can I conclude that we should always compute power first? Rather than following the assumption that always uses Sign Test if the difference distribution is not normal? Thanks!
Comment: @Kay You can only compute power if you know the distribution you're sampling from, which in practice you don't (if you did, you could do better than these tests). If you've seen other samples from this or closely related populations you may be able to garner enough information about distributional characteristics to make a reasonable choice of test. The present sample should not form the basis of that choice, because if you use the sample itself to choose between tests the test will no longer have its nominal properties (both significance level and power will be impacted from what you expect).
Comment: I would not always choose the sign test; in a range of situations that could reasonably occur in practice the signed rank test would be better. On the other hand if we were dealing with *light tailed* symmetric non-normality (like a beta(2,2) distribution, say), the t-test will beat the other two. On the gripping hand, depending on the precise nature of the alternatives of interest, I might choose something different from all three.


Perform Rose Method, then Logistic Regression and do k -fold cross validation

Question: I have unbalanced data so I want to oversample obs from the minority class and then apply Logistic regression to the training set. After that, I would like to perform cross-validation. My question is: When should I separate the data into training and test? After oversampling? Any help will be appreciated.
Comment: How large is the dataset?  If you have sufficient data, it is possible that this is the optimal behaviour from the perspective of accuracy, see my question here: https://stats.stackexchange.com/questions/539638/how-do-you-know-that-your-classifier-is-suffering-from-class-imbalance .  It is unlikely that resampling will make the accuracy of a logistic regression model better.  If the data is small enough for maximum likelihood to be significantly biased, there is unlikely to be enough data to estimate how much resampling is required.
Comment: BTW if you perform resampling it must be done in the training set for each fold of the cross-validation, but not the test partition.  Otherwise the test partition is not representative of operational conditions.
Comment: Note I also asked a question whether there were reproducible examples where rebalancing improves accuracy.  There were no answers, even though a modest bonus was on offer.  https://stats.stackexchange.com/questions/559294/are-there-imbalanced-learning-problems-where-re-balancing-re-weighting-demonstra That is some evidence that class imbalance does not justify resampling on that basis.
Comment: Welcome to Cross Validated! Statisticians do not see class imbalance as such a problem, and there is no need to solve a non-problem. It might be helpful if you say why you find the imbalance problematic.
https://stats.stackexchange.com/questions/357466
https://www.fharrell.com/post/class-damage/
https://www.fharrell.com/post/classification/
https://stats.stackexchange.com/a/359936/247274
https://stats.stackexchange.com/questions/464636/
https://stats.stackexchange.com/questions/558942/
https://twitter.com/f2harrell/status/1062424969366462473?lang=en
Comment: Thank you, Dave. The problem is that even if my model has a good accuracy score the sensitivity is 0u%. That is why I would like to use an oversampling method.
Comment: The links I posted discuss in detail why accuracy is a highly problematic metric.
Comment: Yes but my question is when should I use the Rose method. For example, if I use Logistic regression then my code would look like:library(caret)
crossValSettings <- trainControl(method = "repeatedcv", number = 10,
                                 savePredictions = TRUE)
crossVal <- train(as.factor(admit) ~ gpa + gre + rank, data = myData, family = "binomial",
                  method = "glm", trControl = crossValSettings, tuneLength = 2)
pred <- predict(crossVal, newdata = myData)
confusionMatrix(data = pred, myData$admit). How can I it the ROSE method there?
Comment: Proper statistical methods say that you probably shouldn't. Please read the links. The Twitter post by Frank Harrell is the most concise. // It's really hard to say what the best practice is for applying something that's generally a poor practice.
Answer: As some links I posted discuss, class imbalance usually is not a problem. Therefore, attempts to solve a non-problem are somewhere between superfluous and damaging. Consequently, it is difficult to suggest where you would apply such a technique.
However, I have applied poor practices in regression models specifically to show how they fail, so there is a place for knowing where in the workflow such a practice would occur.
Any messing with the data would come after you have set aside out-of-sample data, since out-of-sample data are there to mimic the real-world application of your model on data that might not even exist (such as Siri or Alexa being expected to be able to do speech recognition on words spoken by people who have yet to speak their first words). This is what Dikran Marsupial means in the comment about doing resampling in the training folds of a cross-validation but not the test partition.
I don't know where exactly that is in your particular package. It might be that you will have to code the splitting and cross-validation yourself (probably not, but maybe). However, it would be cheating to do ROSE on data that are supposed to be hidden.


Can't print $base_root in headers view

Question: I have a View and inside it I have and Attachment display. In this attachment I set a Header with the value you can see in the image below.
I'm sure I have register_globals = 1;
But nothing is printed...
Comment: This is more a PHP question than a Drupal question; using a global variable in code executed from `eval()` or a function always require to define the variable as global, or using `$GLOBALS`.
Answer: Well, you need to say that what you want to display is global as well:
<code><?php
global $base_root;
print $base_root;
?>
</code>
Comment: Thanks, this is my first project with Drupal and the first time I use globals vars.
Comment: As alternative, use `$GLOBALS['base_root']`.

Can't print $base_root in headers view


In a bass guitar, how do I mute the strings that I am not playing?

Question: I am learning Bass Guitar on my own and muting looks challenging. For eg, when I am playing the A string, I find the G string sympathetically humming at times and vice versa. Such humming produces an unpleasant clash in the harmony. I know either hand can be used for muting, but I am not able to decide which is best for a given situation, and this seems particularly hard when playing fast.
Is there a standard method or a popularly accepted approach to doing this? It would be great if someone can list down the commonly used techniques and some guidelines on what can work when.
Answer: On the one hand...  Often the plucking hand thumb will look after the E string, and some players use the extra fingers on that hand to damp the upper strings. Or use the side of the palm/pinky to damp other strings. An acquired idea, but it leaves the gap where your finger joins your palm with a gap for the played note to ring.
On the other hand...  Use the underside of any spare fingers to damp the other strings. Be aware that you may touch a harmonic node, and so set off a different sympathetic vibration though. This can be used in some songs for an extra bit of fun.
Know a session player who plays 5 string, who developed a technique whereby when one string is played, the other four digits (R.H.) will be muting the other four strings. Looked complex, but what a clean player!
Use all of the above ideas - that's belt and braces, and will soon become second nature.
Answer: When playing a fretted note on the A string, the fingers of your left hand have to pass over the D and G strings anyway.  If you want to mute the strings you aren't playing, you can use this to your advantage.  Allow your fingers to gently touch these strings, not enough to fret, simply to rest there.
Also, if you're playing an open note on the A string, you may wish to have the fingers of your left hand rest over the D and G strings (since they aren't up to much at that time anyway).
I often do this instinctually, and have seen many other bass players do the same.
(This will depend specifically on what you're playing, and in certain situations the right hand may well come into it.  Also, as with many things, I wouldn't be surprised in another player comes in here with another technique that works for them.  This is a good rule in general though imo)

My comment got too long, so in light of your further question:
Generally, muting the string below (as in closer to the E string) is achieved in the right hand.
E.g. if I was playing this https://youtu.be/pcawnRIyeok?t=180 , when plucking that first open A string, my fingers would land on the E string (and just sit there, not pluck it).
When playing with rest strokes, I personally tend to pretty much always have one finger on the string below the one I'm currently playing, and I alternate between my fingers for each note.  If that makes sense.  So if I was playing a bunch of notes on the D string in quick succession then I would alternate between my plucking with my first finger and second.  The finger not currently being used would be resting on the A string, and the finger that just plucked the D string would immediately land on the A string to join its finger bro.
Play, and tell me if this makes sense.  You'll be surprised how quickly things like this become second-nature after a while.  See which techniques feel natural to you, experiment and eventually you'll get into a groove with it.  And even if you get into that pattern, never be afraid to switch up and try something new if you want to  :)
Comment: preface to my answer, there are two types of finger strokes.  "rest strokes" and "free strokes".  Rest strokes are much much much more common when playing bass.  It's where the finger lands on the next string down after playing (and "rests").     Also "down" and "below" in this context I mean pitch-wise. (you might think of this as up because, well,  it's further from the floor haha)
Comment: Agreed with this.  You can also use your left palm in the event where you need your other fingers.
Comment: Thanks @Some_Guy, but what if it is the other way round, ie playing the G string but want to mute the D string, can the same approach work?
Comment: @gigahari this make sense to you?
Answer: I've found that my left and right hand postures, without consciously thinking about it, arrange so that no matter what note I play on what fret with what finger, there's a "spare" finger touching each of the other three strings, preventing it from ringing. The finger might be a left or right hand finger.


Refazer array com um limite maximo de posições

Question: Estou trabalhando com Laravel e estava olhando um template bootstrap para personalizar a aplicação e me deparei com este formato de exibir os followers:

Minha dúvida é como poderia tratar o array que trás meus usuários apenas com a foto e caso o array seja maior que 3 como no exemplo trazer a contagem dos demais usuários.
Edit:
$network_users = User::select('photo')->where('parent', Auth::user()->id)->get()->toArray();

$network_images = array();
foreach ($network_users as $user) {
    if (count($network_users) >= 4) {
        $count = count($network_users) - 4;
        array_push($network_images, $user);
    } else {
        $count = count($network_users);
        array_push($network_images, $user);
    }
}
$data = array(
    'count' => $count,
    'network_images' => $network_images
);
dd($data);

Montei nesse formato seguido a ideia de utilizar o count, essa seria a forma mais correta de trazer os dados ou teria alguma forma melhor?
Comment: Utilize o método count
Answer: Basta usar a matemática, veja:
Suponha que você tenha uma lista com 15 usuários e você mostrou 3 deles. O restante de usuários pode ser obtido através da subtração de 15 (o comprimento total da lista) e 3 (o número de usuários mostrados por padrão).
Você pode fazer isso de modo bastante simples, utilizando a função count para determinar o comprimento da lista.
Algo assim:
<?php

// [...]

$usuarios_restantes = count($lista_de_usuarios) - 3;

// [...]


Conjecture about the minimum of the Gamma function

Question: Problem/Conjecture:
Let the function :
$$f(x)=\frac{((x+x_{\min})!-(x_{\min})!)^{\frac{1}{x}}}{x^{\frac{1}{x^2}}}$$
Where $x_\min$ denotes the minimum abscissa of the Gamma function near by $0.4616$
Then do we have :
$$f'(1-x_{\min})<^?0$$
An computation show it could be true.
And what is :
$$\lim_{x\to \infty}(f(x)-f(x-1))=?$$
Is it true? If yes is it trivial or well-know ?
Comment: This is for $\Gamma(x+1)$
Comment: What is the motivation behind this problem?
Comment: @Gary Find an approximative way to evaluate the minimum of the Gamma function
Comment: Euler is back !
Comment: @ClaudeLeibovici Leonard Bean I presume.
Answer: Using for an approximation of $x_{\text{min}}$ the rational values
$$\left\{\frac{343}{743},\frac{379}{821},\frac{2691
   5}{58304},\frac{47381}{102638},\frac{51171}{110848},\frac{102721}{222517},\frac{256992}{556703},\frac{1439231}{3117701}\right\}$$ what is obtained
$$\left(
\begin{array}{cc}
n & f'(1-x_{\text{min}}) \\
 1 & -0.00011212968 \\
 2 & -0.00001826854 \\
 3 & -0.00001806921 \\
 4 & -0.00001815531 \\
 5 & -0.00001816370 \\
 6 & -0.00001816408 \\
 7 & -0.00001816416 \\
 8 & -0.00001816417 \\
\end{array}
\right)$$
For the second question, using $x=10^{12}$ to avoid overflows, it is quite impressive
$$\left(
\begin{array}{cc}
 n & f(10^{12})-f(10^{12}-1) \\
 1 & 0.367879441171796089914000535729 \\
 2 & 0.367879441171796086295532027426 \\
 3 & 0.367879441171796086287846671071 \\
 4 & 0.367879441171796086291166324500 \\
 5 & 0.367879441171796086291489671976 \\
 6 & 0.367879441171796086291504586674 \\
 7 & 0.367879441171796086291507556416 \\
 8 & 0.367879441171796086291507768373 \\
\end{array}
\right)$$
which is
$$\huge \frac 1 e$$
Edit
For the behavior of the difference, assuming that we can neglect $s_{\text{min}}$ and that
$$f(x)-f(x-1) \sim f'(x)$$ using
$$f(x)= \frac{\Gamma (x+1)^{\frac{1}{x}}}{x^{\frac{1}{x^2}} }$$
$$f'(x)= \frac{\Gamma (x+1)^{\frac{1}{x}}}{x^{3+\frac{1}{x^2}} } \left(x^2 \psi
   ^{(0)}(x+1)+2 \log (x)-x \log (\Gamma (x+1))-1\right)$$
$$\log(f'(x))=-1+\frac 1 {2x}+O\left(\left(\frac{\log (x)}{x}\right)^2\right)$$
Comment: See my update  Claude
Comment: You can prove $1/\mathrm{e}$ using Stirling's formula.
Comment: @Gary. Be sure that I tried and ... gave up ! I would enjoy to see an asymptotic of the diffrence. Cheers :-)
Comment: @Gary Can you offer a proof ?
Comment: @ErikSatie Done.
Answer: This is an answer to the second question. We have
$$
((x + x_{\min } )! - (x_{\min } )!)^{1/x}  = (x + x_{\min } )!^{1/x} \left( {1 - \frac{{(x_{\min } )!}}{{(x + x_{\min } )!}}} \right)^{1/x}  \\= (x + x_{\min } )!^{1/x}  + \mathcal{O}\!\left( {\frac{1}{x}} \right),
$$
and
$$
x^{ - 1/x^2 }  = 1 + \mathcal{O}\!\left( {\frac{{\log x}}{{x^2 }}} \right),
$$
and
$$
(x + x_{\min } )!^{1/x}  \sim \frac{x}{\mathrm{e}},
$$
as $x\to +\infty$. Thus
$$\tag{1}
f(x) = (x + x_{\min } )!^{1/x}  + \mathcal{O}\!\left( {\frac{{\log x}}{x}} \right)
$$
Now, for any fixed $a$,
$$
\Gamma (z + a) = z^{z + a - 1/2} \mathrm{e}^{ - z} \sqrt {2\pi } \left( {1 + \mathcal{O}\!\left( {\frac{1}{z}} \right)} \right)
$$
as $z\to +\infty$. Consequently,
\begin{align*}
(\Gamma (z + a))^{1/z} & = z^{1 + a/z - 1/(2z)} {\rm e}^{ - 1} (2\pi )^{1/z} \left( {1 + \mathcal{O}\!\left( {\frac{1}{{z^2 }}} \right)} \right) \\ & = \frac{z}{{\rm e}} + \frac{{a - 1/2}}{{\rm e}}\log z + \frac{{\log (2\pi )}}{{\rm e}} + \mathcal{O}\!\left( {\frac{{\log z}}{z}} \right)
\end{align*}
as $z\to +\infty$. Hence,
$$\tag{2}
(\Gamma (z + a))^{1/z}  - (\Gamma (z - 1 + a))^{1/(z - 1)}  = \frac{1}{{\rm e}} + \mathcal{O}\!\left( {\frac{1}{z}} \right)
$$
as $z\to +\infty$. From $(1)$ and $(2)$ it follows that $f(x)-f(x-1) \to 1/{\rm e}$.
Comment: Great (once more) ! Thanks for posting it.
Comment: Very cool it's nice
Comment: @ClaudeLeibovici see the limit at $x\to 0^-$ of  the last difference with $a$ it answers one of your own question with inverse Gamma function.
Comment: @ErikSatie You mean $(2)$? That is valid only for large $z$. It does not describe the behaviour of the difference near $0$.
Comment: @Gary not your result just the difference at limit which is equal to $-1/\Gamma(a)$


Return objects with duplicate properties to a new array

Question: I've seen a lot of examples that show how to filter/remove duplicate values from array, but I want to get the duplicates and use them in a new array. So for
array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

I want a new array returned that only contains items with matching Id's like so
[
  { id: '1', description: 'foo'},
  { id: '1', description: 'bleep'}
]

I feel like this should be easier than I'm making it
Edit: The suggestions do not do what I'm asking for. They are either creating lookup tables or removing the items from the original array.
Comment: Checked this? - https://stackoverflow.com/questions/53212020/get-list-of-duplicate-objects-in-an-array-of-objects/53212154
Comment: Id equation is enough for you?
Comment: Neither of these solutions do what I am asking
Comment: @ChristopherMellor you claim that your question is substantially different from the suggested duplicate.  (i.e. the accepted answer just creates a "lookup table.")  However, the answer you have accepted here is functionally identical to the answer accepted over there.
Answer:

array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

const duplicates = array.reduce((a, e) => {
  a[e.id] = ++a[e.id] || 0;
  return a;
}, {});

console.log(array.filter(e => duplicates[e.id]));


Using Taylor series with remainder

Question: Arfken and Weber expand $(1+n^{-2})^{-1}$ as
$$(1+n^{-2})^{-1}=1-n^{-2}+n^{-4}-\frac{n^{-6}}{1+n^{-2}}$$
However, if I use Taylor/Maclaurin expansion
$$(1+x)^m=1+mx+ \frac{m(m-1)}{2!} x^2 + \cdots + R_k$$
with $m=-1$, $x=n^{-2}$ and remainder,
$$R_k=\frac {x^k}{k!}(1+x)^{m-k} m(m-1) \cdots (m-k+1)$$ I get
$$(1+n^{-2})^{-1}=1-n^{-2}+n^{-4}-\frac{n^{-6}}{(1+n^{-2})^{4}}$$
Note that the only difference is in the denominator of last term (remainder). So where did I go wrong?
Comment: Just use the division of $1$ by $(1+x)$ and stop whenever you want with the reminder of the division. Don't consider Taylor. Reminder of the division
Comment: You should have power 4 not $-4$ in the denominator.
Comment: @MhenniBenghorbal that was a typo. Corrected it now.
Comment: Thanks @ClaudeLeibovici. Got the answer with long division. Because of the form I thought it was Taylor expansion. Anyways got it now.
Comment: You are very welcome. I am glad you made it ! Cheers
Answer: What they did is this
$$ (1+x)^{-1} = 1-x+x^2-x^3( 1 - x + x^2 -\dots ) $$
$$ = 1-x+x^2 -\frac{x^3}{1+x}. $$
Now subs $x=1/n^2$.

Using Taylor series with remainder


Formatação de moeda

Question: Tenho o seguinte script no meu HTML, o que ele faz é simplesmente checar uma checkbox se ela está ou não selecionada e no caso de estar adicionar um valor, a minha dúvida é, como fazer para esse valor ser formatado em moeda? Por exemplo ao em vez de aparecer 400,00 ou 1.455,80 ele aparece tudo junto como um número inteiro no caso 400 e 145580, como fazer para mostrar os valores em reais?
Script:

function check() {
  var basic = 0;
  var add = 0;

  if(document.getElementById("cl45").checked) {
    add += 145580;
  }
  if(document.getElementById("trigger").checked) {
    add += 40000;
  }
  var p = basic + add;

  var price ="R$ " + p;
  document.getElementById('total2').innerHTML = price;
 }

check();
Comment: `price.toFixed(2)` Isso que você queria?
Comment: Qual a razão desse valor com virgula no script add += 400,00; Porque não entra com valor que o javascript requer para calculos, ou seja 400.00 com ponto decimal?
Comment: dá para postar o html? esse script não está completo, fica dificil reproduzir um exemplo que possamos testar
Comment: não se deve alterar a pergunta porque dai a resposta fica meio sem sentido
Comment: Não sei, comecei a trabalhar com js agora, vou dar uma pesquisada sobre isso, valeu.
Comment: Esse valor será exibido para o usuário, a ideia é que quando ele marque uma checkbox adicione um valor a um campo visível, de forma que algumas checkboxs adicionam 400,00 e outras 1.455,80, gostaria que o usuário pode-se visualizar a formatação em real comum e não que aparecesse "1455.8" ou "400".
Comment: Não é necessário, estou dando uma olhada em outra pergunta semelhante acredito que as repostas de lá podem me ajudar, já que essa minha pergunta foi duplicada. Se eu não conseguir qualquer coisa abro outra pergunta especificando melhor o meu problema, mas obrigado pela ajuda.
Comment: veja se a minha resposta ajuda
Answer:

function check() {
      var basic = 0;
      var add = 0;

      add += 1455.80;

      var p = (basic + add).toFixed(2);

      var result = p.toString();

     //substitui separador decimal ponto por virgula
     result=result.replace(".", ",");
     //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
     result = result.replace(/\B(?=(\d{3})+(?!\d))/g, ".");

     var price ="R$ " + result;

     document.getElementById('total2').innerHTML = price;

}
<input type="checkbox" id="trigger" onclick="check()">

Todas as linguagens tem como padrão o americano para inteiros e decimais, ou seja, você não vai conseguir fazer o cálculo corretamente, se houver valores decimais, se não trocar a vírgula pelo ponto.
Comment: Funcionou para os 400,00 tem como fazer algo semelhante para 1.455,80? da forma que está agora o número  é expresso "145.580,00".
Comment: Funcionou, tudo certo muito obrigado.

Formatação de moeda


Taylor Series - approximation of $\sin(x)$

Question: What polynomial degree should be taken in the function $f(x) = \sin(x)$ so that the largest modulus of the difference between the value of the Taylor polynomial and the value of the $\sin(x)$ function on the $[0, \frac{\pi}{2}]$ interval is not greater than $10^{-17}$?
I'm not quite sure how to do this task. I started by finding the general form of the Taylor series for $\sin(x)$. Then I found the general form of the remainder of the Taylor series as: $R_n(x) = \frac{\sin(c + \frac{n\pi}{2}) \cdot x^{n+1}}{(n+1)!}$. Then I constrained this function by $\frac{x^{n+1}}{(n+1)!}$. I think I need to calculate this inequality $\left|\frac{x^{n+1}}{(n+1)!}\right| < 10^{-17}$, but I have no idea what to take for $x$? The extreme values of the interval?
Answer: For a given $n$, your expression attains its maximum value on the interval when $x$ is equal to $\pi/2$. So yes, this is the value you should take for $x$.
Comment: Thank you so much!
Answer: First of all
$$\sin(x)=\sum_{n=0}^\infty (-1)^n\,\frac{x^{2n+1}}{(2 n+1)!}$$ to write
$$\sin(x)=\sum_{n=0}^p (-1)^n\,\frac{x^{2n+1}}{(2 n+1)!}+\sum_{n=p+1}^\infty (-1)^n\,\frac{x^{2n+1}}{(2 n+1)!}$$
Making the problem more general , you then want to solve for $p$
$$\frac {\left(\frac{\pi}{2 }\right)^{2 p+3} }{(2p+3)!} \leq 10^{-k}$$ that is to say
$$(2p+3)! \geq \left(\frac{\pi}{2 }\right)^{2 p+3} \,10^k$$
If you look at this old question of mine, you will see an almost exact solution proposed by @robjohn (one of our beloved moderators).
Adapted to your case, it write  as a real
$$p=\frac{\pi }{4}\,  e^{1+W(t)}-\frac{7}{4} \qquad \text{where} \qquad t=\frac{2 (k \log (10)-\log (\pi ))}{e \pi }$$ $W(.)$ being Lambert function.
Trying for $k=35$, this gives $p=16.67879$ while the "exact" solution is $p=16.67897$.
So, we should use $$p=\lceil  16.67879\rceil=17$$
Checking
$$\frac {\left(\frac{\pi}{2 }\right)^{2 \times 16+3} }{(2\times 16+3)!}=7.0\times 10^{-34} >10^{-35}$$ which is not acceptable.
But
$$\frac {\left(\frac{\pi}{2 }\right)^{2 \times 17+3} }{(2\times 17+3)!}=1.3\times 10^{-36} <10^{-35} $$
Answer: For every $x\in[0,\pi/2]$
$$
\left|\frac{x^{n+1}}{(n+1)!}\right|
\le
\max_{x\in[0,\pi/2]}\left|\frac{x^{n+1}}{(n+1)!}\right|
=\frac{(\pi/2)^{n+1}}{(n+1)!}\;.
$$
So you just have to solve
$$
\frac{(\pi/2)^{n+1}}{(n+1)!}\le10^{-17}\;.
$$
Comment: Thank you so much!