Erro de java.lang.IllegalArgumentException no Hibernate ao trabalhar com enum

Question: Dá uma olhada na mensagem de erro:
jun 02, 2015 5:23:57 PM com.sun.faces.lifecycle.ApplyRequestValuesPhase execute
ADVERTÊNCIA: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
javax.el.ELException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:359)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    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:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    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: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:461)
    at org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:449)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1605)
    at org.hibernate.loader.Loader.getRow(Loader.java:1505)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:713)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:943)
    at org.hibernate.loader.Loader.doQuery(Loader.java:911)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2526)
    at org.hibernate.loader.Loader.doList(Loader.java:2512)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
    at org.hibernate.loader.Loader.list(Loader.java:2337)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:266)
    at com.algaworks.pedidovenda.repository.Clientes.porNome(Clientes.java:38)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean.completarCliente(CadastroPedidoBean.java:60)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean$Proxy$_$$_WeldClientProxy.completarCliente(CadastroPedidoBean$Proxy$_$$_WeldClientProxy.java)
    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:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 29 more

2015-06-02 17:23:57,353 ERROR [com.algaworks.pedidovenda.util.jsf.JsfExceptionHandler] Erro do sistema/WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
javax.faces.FacesException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:86)
    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:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    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.el.ELException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:359)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    ... 25 more
Caused by: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:461)
    at org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:449)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1605)
    at org.hibernate.loader.Loader.getRow(Loader.java:1505)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:713)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:943)
    at org.hibernate.loader.Loader.doQuery(Loader.java:911)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2526)
    at org.hibernate.loader.Loader.doList(Loader.java:2512)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
    at org.hibernate.loader.Loader.list(Loader.java:2337)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:266)
    at com.algaworks.pedidovenda.repository.Clientes.porNome(Clientes.java:38)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean.completarCliente(CadastroPedidoBean.java:60)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean$Proxy$_$$_WeldClientProxy.completarCliente(CadastroPedidoBean$Proxy$_$$_WeldClientProxy.java)
    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:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 29 more

Pelo que entendi o erro está no método completarCliente.
Classe CadastroPedidoBean:
package com.algaworks.pedidovenda.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.algaworks.pedidovenda.model.Cliente;
import com.algaworks.pedidovenda.model.EnderecoEntrega;
import com.algaworks.pedidovenda.model.FormaPagamento;
import com.algaworks.pedidovenda.model.Pedido;
import com.algaworks.pedidovenda.model.Usuario;
import com.algaworks.pedidovenda.repository.Clientes;
import com.algaworks.pedidovenda.repository.Usuarios;
import com.algaworks.pedidovenda.service.NegocioException;
import com.algaworks.pedidovenda.util.jsf.FacesUtil;

@Named
@ViewScoped
public class CadastroPedidoBean implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Inject
    private Usuarios usuarios;

    @Inject
    private Clientes clientes;

    private Pedido pedido;

    private List<Usuario> vendedores;

    public CadastroPedidoBean() {
        limpar();
    }

    public void inicializar(){
        if(FacesUtil.isNotPosBack()){
            this.vendedores = usuarios.vendedores();
        }
    }

    public void limpar() {
        pedido = new Pedido();
        pedido.setEnderecoEntrega(new EnderecoEntrega());
    }
//
//  public FormaPagamento[] getFormasPagamento() {
//      return FormaPagamento.values();
//  }

    public List<Cliente> completarCliente(String nome){
        return this.clientes.porNome(nome);
    }

    public void salvar() {
        throw new NegocioException(
                "Pedido não foi salvo, pois ainda não foi implementado");
    }

    public Pedido getPedido() {
        return pedido;
    }

    public void setPedido(Pedido pedido) {
        this.pedido = pedido;
    }

    public List<Usuario> getVendedores() {
        return vendedores;
    }

    public void setVendedores(List<Usuario> vendedores) {
        this.vendedores = vendedores;
    }

}

Classe cliente que está no repositório:
package com.algaworks.pedidovenda.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import com.algaworks.pedidovenda.model.Cliente;

public class Clientes implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Cliente porId(Long id) {
        return this.manager.find(Cliente.class, id);
    }

    public List<Cliente> porNome(String nome) {
        return this.manager.createQuery("from Cliente " +
                "where upper(nome) like :nome", Cliente.class)
                .setParameter("nome", nome.toUpperCase() + "%")
                .getResultList();
    }

}

Essa é minha entidade Cliente;
package com.algaworks.pedidovenda.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

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

    private static final long serialVersionUID = 1L;

    private Long id;
    private String nome;
    private String email;
    private String documentoReceitaFederal;
    private TipoPessoa tipo;
    private List<Endereco> enderecos = new ArrayList<>();

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

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

    @Column(nullable = false, length = 100)
    public String getNome() {
        return nome;
    }

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

    @Column(nullable = false, length = 255)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "doc_receita_federal", nullable = false, length = 14)
    public String getDocumentoReceitaFederal() {
        return documentoReceitaFederal;
    }

    public void setDocumentoReceitaFederal(String documentoReceitaFederal) {
        this.documentoReceitaFederal = documentoReceitaFederal;
    }

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 10)
    public TipoPessoa getTipo() {
        return tipo;
    }

    public void setTipo(TipoPessoa tipo) {
        this.tipo = tipo;
    }

    @OneToMany(mappedBy = "cliente", cascade = CascadeType.ALL)
    public List<Endereco> getEnderecos() {
        return enderecos;
    }

    public void setEnderecos(List<Endereco> enderecos) {
        this.enderecos = enderecos;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.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 (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

E essa é minha classe enum TipoPessoa
package com.algaworks.pedidovenda.model;

public enum TipoPessoa {

    FISICA, JURIDICA

}

Comment: `Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]`. Como é este seu enumerado? Como é o mapeamento para ele na entidade `Cliente`? O problema é na camada de persistência, aparentemente.
Comment: acabei de colocar as classe, poderia verificar minha postagem de novo
Comment: Você inseriu enums no banco manualmente com letras minusculas no banco de dados. Possivelmente seja isso a causa de Unknown name value """[fisica]""".
Answer: Esta é a sua mensagem de erro:
Caused by: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]

Este é o seu enum:
package com.algaworks.pedidovenda.model;

public enum TipoPessoa {

    FISICA, JURIDICA

}

Observe a diferença entre maiúsculas e minúsculas. fisica e FISICA são diferentes!
De onde veio o fisica? Aparentemente é o que está salvo no banco de dados:
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)

Então, tenho três sugestões. Escolha uma:

Rodar um UPDATE cliente SET tipo = 'FISICA' WHERE tipo = 'fisica' no seu banco de dados.
Trocar o enum para fisica ao invés de FISICA.
Mudar o mapeamento para String, mas expor apenas os métodos que trabalham com TipoPessoa:

    private String tipo;

    @Transient
    public TipoPessoa getTipo() {
        return tipo == null ? null : TipoPessoa.valueOf(tipo.toUpperCase(Locale.ROOT));
    }

    public void setTipo(TipoPessoa tipo) {
        this.tipo = tipo == null ? null : tipo.name();
    }

    @Column(nullable = false, length = 10, name = "tipo")
    protected String getTipoString() {
        return tipo;
    }

    protected void setTipoString(String tipo) {
        this.tipo = tipo;
    }

Comment: muito bom, excelente solução, meus parabéns. :)
Comment: @wladyband Se a resposta lhe resolveu o problema marque-a como correta por favor. Se tiver duvidas de como funciona o StackOverflow veja o tour http://pt.stackoverflow.com/tour


Why is this limit $0$?

Question: If we have $g'(f(c)) = \lim_{y \to f(c)} \frac{g(y)-g(f(c))}{y-f(c)}$
and let $d(y)$ be the difference:
$d(y) = \frac{g(y)-g(f(c))}{y-f(c)} - g'(f(c))$
Where $g \circ f$ is differentiable at $c$ and $f$ is also differentiable at $c$.
Then why does
$\lim_{y \to f(c)} d(y) =0$ ?
Answer: It's by the difference rule for limits. Since $g'(f(c))$ is constant, $\lim_{y\to f(c)} g'(f(c)) = g'(f(c))$. So
$$\lim_{y\to f(c)} d(y) = \lim_{y\to f(c)} \frac{g(y) - g(f(c))}{y - f(c)} - \lim_{y\to f(c)} g'(f(c)) = g'(f(c)) - g'(f(c)) = 0.$$
Comment: Thank you for this response, it makes sense to me now.
Answer: $f(c)$ is just a fixed number in your limit; it does not depend on $y$. So just call it $z$ instead. Now you're really just calculating that
$$\lim_{y \to z} \left ( \frac{g(y) - g(z)}{y-z} - g'(z) \right ) = 0$$
which is just a restatement of the definition of the derivative.
Comment: Thank-you for this response, that clears things up!

Why is this limit $0$?


Using SQL to perform a match and index function

Question: I am trying to create a new table (Table B), where i will input the value for column "S/N" and by default it will return the corresponding value from Table A when it matches with the value in S/N.
Table A
S/N  Content
1      A
2      B
3   C
4   D
Table B
S/N Content
2
1
3
I am new to SQL, appreciate if you can show the code on how to create table B please.
Comment: What do you mean `default it will match against Table A `, I am not sure what's your insert logic
Comment: I have amended my question, this should be clearer now.
Comment: read up on foreign keys and joins in SQL
Answer: IF OBJECT_ID ('dbo.TableA')IS NOT NULL
DROP TABLE TableA
IF OBJECT_ID ('dbo.TableB')IS NOT NULL
DROP TABLE TableB

CREATE Table TableA ([S/NContent] VARCHAR(20))
INSERT INTO  TableA
SELECT '1 A' UNION ALL
SELECT '2 B' UNION ALL
SELECT '3 C' UNION ALL
SELECT '4 D'

SELECT SUBSTRING([S/NContent],1,PATINDEX('%[0-9]%',[S/NContent])) AS [S/NContent] INTO TableB
FROM TableA

SELECT * FROM TableA
SELECT * FROM TableB

Comment: I think u are mistaken, Table A contains two column (S/N and Content). I am trying to create Table B. For example when I input 3 in table B, it will return C for column Content for Table B.
Answer: As far as I understand the question
Are you asking about relations in SQL? If SN is primary key in A, reference SN column in B as primary key.
create table A (
    SN int primary key,
    Content varchar(10)
)

create table B (
    --dunno what the primary key will be
    SN int foreign key references A(SN),
    Content varchar(10)
)

Here's how to use it. You join two tables on foreign key
select *
from B
join A on A.SN = B.SN


Twitter Bootstrap 3: How to center a block

Question: It seems to me that the class center-block is missing from the bootstrap 3 style sheets.  Am I missing something?
Its usage is described here, http://getbootstrap.com/css/#helper-classes-center
Comment: can we see your work?
Answer: It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...
Demo: http://bootply.com/91632

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

...

Answer: It works far better this way (preserving responsiveness):

      Hi there!

http://www.bootply.com/0L5rBI2taZ
Comment: works but give a horizontal scrollbar because of the row class. more info there https://www.dvdheiden.nl/2013/12/04/bootstrap-3-row-class-causes-horizontal-scrollbar/
Comment: You can use class `.center-block` in combination with `style="width:400px;max-width:100%;"` to preserve responsiveness.
Answer: You have to use style="width:value" with center block class
Answer: center-block can be found in bootstrap 3.0 in utilities.less on line 12
and mixins.less on line 39
Answer: You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.
Using .col-md-* class with .center-block will not work because of the float on .col-md-*.
Answer: center-block is bad idea as it covers a portion on your screen and you cannot click on your fields or buttons.
col-md-offset-? is better option.
Use col-md-offset-3  is better option if class is col-sm-6. Just change the number to center your block.
Answer: A few answers here seem incomplete. Here are several variations:

This div is centered with .center-block

This div is centered with .center-block

This div is centered with .center-block

To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.
Check it out on bootply.


How useful are linear hypotheses?

Question: In a linear model $Y=X\beta + \varepsilon$, one can easily test linear hypotheses of the form $H_0: C\beta = \gamma, $ where $C$ is a matrix and $\gamma$ is a vector with dimension equal to the number of rows in $C$. Namely, one can derive a test statistic which has an F distribution under the null and go from there.
Theoretically, these tests are very interesting to me and seem quite flexible, as $C$ and $\gamma$ can be anything.
However, I'm interested to know how useful these hypotheses are in practical applications  and what are some interesting examples of these applications? (besides testing if a single coefficient is 0 or all coefficients of the model being zero, which is included in every lm call in R for example)
Comment: $\gamma$ is the vector with dimension equal to the number of rows in matrix C. (not size of $\beta$)
Comment: @a_statistician Yes, sorry, I'll edit that.
Answer: These linear hypotheses on the coefficient vector have three main uses:

Testing the existence of relationships: We can test the existence of relationships between some subset of the explanatory variables and the response variable.  To do this, let $\mathbf{e}_\mathcal{S}$ denote the indicator vector for the subset $\mathcal{S}$ and test the linear hypotheses:

$$H_0: \mathbf{e}_\mathcal{S} \boldsymbol{\beta} = 0 \quad \quad \quad H_A: \mathbf{e}_\mathcal{S} \boldsymbol{\beta} \neq 0.$$

Testing a specified magnitude for the relationship: We can test the magnitude of a relationship between an explanatory variables and the response variable using some specified value of interest.  This is often useful when a particular specified magnitude has some practical significance (e.g., it is often useful to test if the true coefficient is equal to one).  To test $\beta_k = b$ we use the linear hypotheses:

$$H_0: \mathbf{e}_k \boldsymbol{\beta} = b \quad \quad \quad H_A: \mathbf{e}_k \boldsymbol{\beta} \neq b.$$

Testing the expected responses of new explanatory variables: We can test the values expected values of responses corresponding to a new set of explanatory variables.  Taking new explanatory data $\boldsymbol{X}_\text{new}$ we get corresponding expected values $\mathbb{E}(\boldsymbol{Y}_\text{new}) = \boldsymbol{X}_\text{new} \boldsymbol{\beta}$.  This means that we can test the hypothesis $\mathbb{E}(\boldsymbol{Y}_\text{new}) = \boldsymbol{y} $ via the hypotheses:

$$H_0: \boldsymbol{X}_\text{new} \boldsymbol{\beta} = \boldsymbol{y} \quad \quad \quad H_A: \boldsymbol{X}_\text{new} \boldsymbol{\beta} \neq \boldsymbol{y}.$$
As you can see, the first use is to test for whether some of the coefficients are zero, which is a test of whether those explanatory variables are related to the response in the model.  However, you can also undertake more general tests of a specific magnitude for the relationship.  You can also use the linear test to test the expected response for new data.
Answer: When you fit a linear model, the statistical softwares give you the point estimate, confidence interval, test statistics, and p-values of the $\beta$_s. If you are just interesting in these $\beta$s, you can stop here (for example, the simple linear regression just have on intercept and one slope, so $\beta$s themselves are enough). But for little complicated model, you will not satisfied by $\beta$s, and you want to estimate, test the linear combinations of $\beta$s. At this time The importance of C matrix is obvious. For complicated model, such as model with interactions, C matrix must needs be constructed.
Example 1: For ANOVA, one categorical covariate has 3 level. Suppose level 1 is reference. Two $\beta$ will give you the difference between level 2 vs 1 and level 3 vs 1. If you want the difference between level 2 and 3, you need C matrix (0 1 -1). (the first 0 is for intercept). If you want to estimate the means for level 3, C=(1 0 1) is needed.
Example 2: If you want to the multiple hypothesis simultaneously, see Testing the general linear hypothesis: $H_0: \beta_1 = \beta_2 = \beta_3 = \beta_4 = \beta$. Here T=C.
Example 3: If the interactions exist, we need to have the linear relation for each combination (cell) of interaction. Here is 16x16 C matrix to get 8 intercepts and slopes. How to understand the coefficients of a three-way interaction in a regression?
You can find more example on the internet, textbooks.
In summary, for linear model, constructing C matrix is equal to half of theory of linear model.

How useful are linear hypotheses?


Auto layout iOS não funciona corretamente Xcode 8.2

Question: Estou desenvolvendo um App em Xcode 8.x.
Estou com um problema em redimensionar 4 botões na primeira tela.
Trabalho no design do iPhone 5 ou 6 e configuro todo o auto layout, quando rodo em todos os devices está legal menos no Iphone 4 onde posso abrir no Ipad, mas os botoes no redimensionam apenas sobe, queria uma sugestão no onde eu estaria errando, estou usando o auto layout da seguinte forma, clico com o direito e arrasto para o lado e uso o horizontal space etc. e sucessivamente.
veja as imagens:
Comment: Alguma chance de você estar usando altura fixa para os botões e a tela não ter altura suficiente para exibir todos eles um acima do outro na altura definida?
Comment: Se o problema for esse, voce pode colocar os botões em uma stackview. Aí ela se encarrega de fazer a distribuição dos botões de forma que eles caibam na tela
Comment: Então eu fiz sempre da mesma maneira para UIView, estou achando q seja isso mesmo, vou rever esse conceito.
Comment: a melhor forma que achei foi, verificar o device, e posicionei e redimensionei eles em seus lugar, foi o mais rapido deu certinho.
Answer: Bom, uma alternativa para você poder apresentar o último botão no iPhone 4 é usar uma TableView com células estáticas :)
E caso sua lista de itens aumente, você não vai mais ter este problema este modelo de iPhone.
Comment: Obrigado pela sugestão, acho que será uma alternativa.vou ver se consigo fazer dessa forma. valeu.
Comment: Se não me engano pra usar células estáticas, você obrigatoriamente precisa ter um TableViewController (não pode ser um ViewController com uma TableView dentro). Não sei se é viável no seu projeto
Answer: Amigo,
fica difícil dar qualquer sugestão a partir de Autolayout... onde há diversas formas de você chegar em um resultado.
Uma alternativa seria você tentar configurar o layout a partir do iPhone 4s, e deixar o iOS e as constraints adaptarem para os demais devices.
Da seguinte forma:

uma vez o seu layout "encaixado" no tamanho do iphone 4s, o restante irá funcionar.
Quanto ao tamanho dos botões, tente utilizar altura baseado no tamanho da tela... é um trabalho meio "chato" mas é uma solução bem boa. Já usei diversas vezes. Basta fazer para um botão, e dar um "equal height" para os demais.
Tipo isso:
1 - Iguala altura da view em questão igual a altura da superview

2 - Vai na constraint que voce acabou de criar, e clica em editar:

3 - No atributo multiplier, você seleciona o multiplicador dessa constraint. O valor funciona como porcentagem. Sendo 0: zero porcento; e 1: 100%. No meu exemplo coloquei 12% do tamanho da tela, ou seja 0.12.

Após isso, você poderia deixar os demais botão com a altura igual ao do botão que você acabou de alterar.
Enfim... é isso. Espero que ajude.
JLU.


Encrypt password (RSA) with public key


How can I find an $f'(x)$ such that $f'(x) = f(x)(1 - f(x))$?

Question: One function I use often is the logistic sigmoid function:
$$f(x) = \frac{1}{1+e^{-x}}$$
Its derivative has the property such that:
$$\begin{align}
f'(x) &= \frac{d}{dx} \frac{1}{1+e^{-x}} \\
&= \frac{e^{-x}}{(1+e^{-x})^2} \\
&= \left(\frac{1}{1+e^{-x}}\right)\left(1 - \frac{1}{1+e^{-x}}\right) \\
&= f(x)(1 - f(x))
\end{align}$$
But this is a function and derivative that I know by heart. How could I find an $f'(x)$ that satisfies the condition $f'(x) = f(x)(1 - f(x))$ without using an existing example? Do other functions exist?
This appears as a question on a unit in integration, so I've tagged it as such. I know one such example but not how to algebraically come to it.
Answer: $$\frac{df(x)}{dx}=f(x)(1 - f(x))$$
$$\implies \frac{df(x)}{f(x)-f^2(x)}=dx$$
$$\implies \ln\left|f(x)\right|-\ln\left|1-f(x)\right|=x+C$$
$$\implies \ln\left|\frac{f(x)}{1-f(x)}\right|=x+C$$
$$\implies \frac{f(x)}{1-f(x)}=Ce^x$$
$$\implies f(x)=Ce^x-Ce^xf(x)$$
$$\implies f(x)=\frac{Ce^x}{1+Ce^x}$$
Answer: Separation of variables. $f' = df/dx=f(1-f)$, so $ dx = 1/(f(1-f)df$. Now integrate both sides of the equality (do not forget an additive constant).
Answer: Suppose $f$ is never $0$ or $1$. Then by dividing the LHS by $f(x)(1-f(x))$, we get
$$\frac{f'(x)}{f(x)} + \frac{f'(x)}{1 - f(x)} = 1$$ Integrating from $0$ to $t$ (and then replacing t by x), we get the general form $\frac{f(x)}{1 - f(x)} = e^x/c$, which gets us $f(x) = \frac{1}{1 + ce^{-x}}$.
If $f$ is $0$ or $1$ you can prove that it is a constant function.


Avoid adding zsh command to history

Question: I use the following binding to allow me to press Control-Z to resume a program I previously backgrounded. I set histoptignorespace and put a space in front of fg so the command doesn't persist in my history.
However, it still appears when I press the up arrow. Any way to remove this as well? I would like pressing the up arrow to ignore the fact that fg was ever entered.
# Allow Ctrl-z to toggle between suspend and resume
function Resume {
  zle push-input
  BUFFER=" fg"
  zle accept-line
}
zle -N Resume
bindkey "^Z" Resume

Comment: I don't think this is possible, alas. The "up history" is really just replaying what you typed.
Comment: @ChrisKitching I think you're basically right although it turns out that running `fg` directly followed by accepting an empty line solves my problem :)
Answer: The following worked for me. It really just runs fg directly. The rest is necessary to get back to the prompt.
# Allow Ctrl-z to toggle between suspend and resume
function Resume {
  fg
  zle push-input
  BUFFER=""
  zle accept-line
}
zle -N Resume
bindkey "^Z" Resume

Avoid adding zsh command to history


Como esperar uma requisição HTTP acabar no Angular 5

Question: estou criando um método que faz uma requisição HTTPSERVICE na minha API mas necessito que termine essa requisição antes de continuar o restante do meu Método, como eu poderia forçar o Angular aguardar o fim da minha requisição
Aqui esta a requisição
<code>this.httpService.wait();
this.httpService
  .post('/custom/pedido/gerar-financeiro-pedido', listasEnviar)
  .subscribe(result => {
    if (result.error || result.nfeIds.length == 0) {
      this.exibirMensagem(result);
      this.httpService.done();
      return;
    }

    const listasEnviar = {
      pedidos: result.nfeIds,
      empresa_id: this.dblinkedSessionService.empresa.id,
      usuario: this.sessionService.loggedUser.id
    };

    this.httpService.wait();
    this.httpService
      .post(`${this.configService.flaskFinUrl}/flaskfin/boleto/post-boleto`, listasEnviar)
      .subscribe(result => {
        if (result.error) {
          this.exibirMensagem(result);
          this.httpService.done();
          return;
        }

        const httpOptions2 = {
          headers: new HttpHeaders({
            'Authorization': this.configService.bearerApi,
            'Cache-Control': 'no-store, max-age=0'
          }),

          responseType: 'blob' as 'json'
        };
        this.httpService.wait();
        this.httpClient
          .get(`${this.configService.flaskFinUrl}/flaskfin/boleto/get-boleto-zip(${result.id})`, httpOptions2)
          .subscribe(res => {
            let link = document.createElement('a');
            let url = window.URL.createObjectURL(res);
            link.href = url;

            let fileName = result.id
            link.download = fileName;
            link.click();

            window.URL.revokeObjectURL(url);
            this.httpService.done();
          },
            error => this.httpService.handleError(error, () => this.inicializar()),
            () => this.httpService.done()
          );
      },
        error => this.httpService.handleError(error, () => this.inicializar()),
        () => this.httpService.done()
      );
  },
    error => this.httpService.handleError(error, () => this.inicializar()),
    () => this.httpService.done()
  );
});
</code>
Answer: voce pode fazer uma função assíncrona que retorna uma promisse
private async ngOnInit(){
await this.getPermission();
}
private getPermission(){
return new Promise(async (resolve, reject) => {
// LOGICA
resolve(true); // QUANDO CAI AQUI RETORNA
})
}


Erro de analisador na minha aplicação

Question: Boa noite pessoal, estou tentando rodar minha aplicação mas aparece este Erro do Analisador. Já entrei na webforms de Fornecedor para ver se encontro algum erro no código mas nada, compilo o projeto e da nada de erro.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fornecedor.aspx.cs" Inherits="SoftwareSalgado.Paginas.Fornecedor" %>

Alguém pode me ajudar?
Comment: conseguiu resolver?
Answer: Primeiro você deve confirmar se o namespace está correto SoftwareSalgado.Paginas.  Depois, você precisa verificar se a classe Fornecedor é uma partial e está herdando System.Web.UI.Page.
Por último, mas não obrigatório, é interessante você implementar o o método Page_Load para inicializá-la e controlar o PostBack.
namespace SoftwareSalgado.Paginas
{
    public partial class Fornecedor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

Comment: Obrigado Leandro, deu certinho.
Comment: @MarcoRibeiro Era esse mesmo o problema? Se a proposta é a resposta para a sua pergunta, é importante votar como útil e aceitar como resposta, assim a sua pergunta e a solução podem ser úteis para outros usuários que venham a enfrentar o mesmo problema

Erro de analisador na minha aplicação


Apache - php executing on http is ok, but with https is not

Question: i have new dedicated linux web server.
my hosting provider give me a setup of apache server with php on it.
when i open url in browser called with ip, ie: http://xxx.yyy.zzz.vvv/test.php, i get executed php script, and it works fine. so, everything works fine in that case.
problem occur if i call https in a browser, like https://xxx.yyy.zzz.vvv/test.php
in that case, i get browsers option Save as, and all i can do is save php file on my pc.
so, it looks to me that there is some misconfiguration with apache.
providers support told me that this will work ok when i build certificate in apache server. but, i'm not sure in that.
can you tell me if providers support is right.
also, on server is installed plesk. plesk made a lots of problems in the past. could it be that plesk made that problem?
if you can help me to solve this. thank you in advance!
Comment: That is wrong, the server has misconfiguration on apache, even if you do not have a valid certificate aslong as the apache configuration is done right the php should work. Having a valid SSL only issues that your https connections will be safe etc.
Comment: Unless they've made modifications to the default Apache configuration, Plesk shouldn't case this problem - it typically houses SSL and HTTP under the same location and they share configuration, so if it works with the https it should work with it. Are both of the site configurations visible inside Plesk?
Answer: your host lies, if there's no certificate you will get a bad certificate message not a source code download. My guess is that your https settings are too way strict avoiding script from being executed. I'm sending a copy of a proper configurated https .conf file:
NameVirtualHost domain.tld:80
<VirtualHost your_server_ip:80>
ServerAdmin firstname.lastname@example.com
DocumentRoot /path/to/site/root/
ServerName domain.tld
ScriptAlias /cgi-bin/ "/path/to/site/root/"
</VirtualHost>

NameVirtualHost domain.tld:443
<VirtualHost your_server_ip:443>
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "/path/to/your/file.crt"
SSLCertificateKeyFile "/path/to/your/file.key"

<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

CustomLog "logs/domain.tld-ssl-request_log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

DocumentRoot /path/to/domain/root
ServerName domain.tld
ServerAdmin email@example.com
ScriptAlias /cgi-bin/ "/path/to/domain/cgi-bin/"
</VirtualHost>

At your's httpd.conf you might want to include/check for this:
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
Include /etc/httpd/conf/ssl/*.conf
</IfModule>

In my case i have separated files for domains with ssl certificates, so i include them on the statement above.
And finally make sure you have the OpenSSL pack installed on your server.
That's it, you can generate self signed certificates to test it out.


PHP e MySqli. Problema na ligação à tabela

Question: Estou a seguir um toturial, está tudo igualzinho. O meu problema é que não consigo ligar-me à tabela.
connect.php:
<?php

    $db = new mysqli('127.0.0.1', 'user', 'pass', 'app');

    if ($db -> connect_errno) {
        die ('Sorry, we are having some problems.');
    }

?>

Este funciona corretamente, a ligação à DB é feita sem probs.
O problema está aqui:
index.php
<?php
    require_once('db/connect.php');

    $result = $db->query("SELECT * FROM people") or die ($db->error);

    if ($result->num_rows) {
        echo 'yay';
    }
?>

O query dá esta mensagem de erro sendo esta:

Table 'app.people' doesn't exist

Sendo que, só people é o nome da tabela
Comment: No seu php no lugar de `select ... people` mude para `show tables` e veja se vai aparecer a tabela `people`. Na dúvida tente recriar ela.
Comment: "yay", creio que seja bom sinal.... Apesar de não perceber o que se passa neste caso
Comment: vc precisa  de um forech em `$result` ou um `print_r()` para ver o resultado da consulta.
Comment: Miguel, mas afinal chega no "yay" ou não?
Comment: Sim, com 'show tables' chegou.
Comment: 'print_r($result)' = "mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 1 [type] => 0 ) ".... está errado
Comment: Pode ser problema de permissão, tentou acessar com o usuário root do seu mysql?
Comment: Também já tinha pensado nisso, mas creio que não... A permissão está do lado www-data (linux)
Answer: A sintaxe de conexão é:
$mysqli = new mysqli("meu_host", "meu_usuário", "minha_senha", "meu_banco");

Portanto no seu caso, o erro está informando que não existe a tabela people no banco de dados app, certifique-se que exista em seu banco app esta tabela. Veja mais...
Comment: Muito obrigado, mas a tabela existe sim
Answer: Desse jeito funcionou para mim:
connect.php
<?php
// Mantenha o @, ele esconde o echo automatico do erro
$mysqli = @new mysqli("127.0.0.1", "user", "pass", "app");

/* checar conexão */
if (mysqli_connect_errno()) {
    printf("Erro ao contectar:: %s\n", mysqli_connect_error());
    exit();
}

index.php
<?php
require_once('db/connect.php');

/* Executar query */
$result = $db->query("SELECT * FROM people");

/* Checar se a query teve sucesso */
if (!$result) {
    printf("Erro ao executar query: %s\n", $db->error);
}

/* Pegar o numero de linhas */
$rows=mysqli_num_rows($result);

/* Checar se o numero de linhas selecionadas é maior que 0 */
if ($rows>0) {
    echo 'Yay';
}

Se ainda não funcionar cheque as permissões da db ou tente num server online...


Opening I frame in react-native

Question: I'm  integrating stripe payment in react-native and wants to open an iframe with specific url from after buttton click.
Scenario : user will enter the card details, details will be given to api end point and it will return an url that will contain the authentication part like OTP. So I want that url to be opened how to do so ? Let me if is there any better way to open that authentication middleware.
Adding code below
Payment.js

import React, { Component } from 'react';
import { View, Button } from 'react-native';
import stripe from 'tipsi-stripe';
import { doPayment } from '../api/api';
import { Auth } from './Auth';

stripe.setOptions({
  publishableKey: 'pk_test_********',
});

export default class Payment extends Component {
  state = {
    isPaymentPending: false
  }
  requestPayment = () => {
    this.setState({ isPaymentPending: true });
    return stripe
      .paymentRequestWithCardForm()
      .then(stripeTokenInfo => {
        return doPayment(10330, stripeTokenInfo.tokenId);
      })
      .then((res) => {
        let url = ""
        console.log(res, url);
        openAuthentication(url);  --->>>> here i'm calling a function with url
      })
      .catch(error => {
        console.warn('Payment failed', { error });
      })
      .finally(() => {
        this.setState({ isPaymentPending: false });
      });
  };

  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Make a payment"
          onPress={this.requestPayment}
          disabled={this.state.isPaymentPending}
        />
      </View>
    );
  }
}

openAuthentication = (url) => {
  console.log("Here with props :::::::", url);
 // here I want to open an iframe, i'm getting correct url, I've checked it in a static html page and it is working
  <Auth url={url} />
}

const styles = {
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
};

Auth.js

import React, { Component } from 'react'
import {
  View, StyleSheet
} from 'react-native'
import { WebView } from 'react-native-webview'

export default class Auth extends Component {
  constructor(props) {
    super(props)
    console.log(props, ">>>>>>>>>>>")
  }
  render() {
    console.log("In Auth -----------");
    return (
      <View style={styles.container}>
        <WebView
          source={{ uri: 'myUrl' }}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  }
})

Error:

React.createElement type is invalid, expected a string or a class/function.
Comment: Have you tried displaying the iFrame inside a WebView?
Comment: I'm not able to open up my Auth page.
I've added code for the same. I've logged some print statements but it's not working. I've added error in the question
Answer: Auth needs to be returned by a render function, otherwise nothing will show up.
So, you'll want something similar to this:
render() {
    return (
        <View style={styles.container}>
            <Button
                title="Make a payment"
                onPress={this.requestPayment}
                disabled={this.state.isPaymentPending}
            />

            {this.state.url && (
                <Auth url={this.state.url} />
            )}
        </View>
    );
}

You only want to render auth when you have the url.
For this, you want to update your state to look something like this:
state = {
    isPaymentPending: false,
    url: undefined
}

And
.then((res) => {
    let url = "";
    this.setState({ url });
})

In order to update you state with the received url when the promise resolves. This will update your state, set the url, and re-render. Because you have an url, Auth should be rendered as well.
LE:
Your Auth.js should look something like this in order to be able to display static HTML. this.props.url should be valid HTML.
render() {
    console.log("In Auth -----------");
    return (
        <View style={styles.container}>
            <WebView
                source={{ html: this.props.url }}
                originWhitelist={['*']}
            />
        </View>
    );
}

Comment: Your answer works, i'm getting url in my Auth screen but unable to open iframe in webview? can you please help me with this
Comment: Updated the answer. You can first try to display some dummy html string instead of the iFrame to make sure it works, and replace it with your iFrame afterwards.
Comment: I followed this question and it works. thanks btw. https://stackoverflow.com/questions/54025762/react-native-style-iframe-to-fit-webview

Opening I frame in react-native


+ is supposed to be greedy, so why am I getting a lazy result?

Question: Why does the following regex return 101 instead of 1001?

console.log(new RegExp(/1(0+)1/).exec('101001')[0]);

I thought that + was greedy, so the longer of the two matches should be returned.
IMO this is different from Using javascript regexp to find the first AND longest match because I don't care about the first, just the longest.  Can someone correct my definition of greedy?  For example, what is the difference between the above snippet and the classic "oops, too greedy" example of new RegExp(/<(.+)>/).exec('a')[0] giving b>a</b?
(Note: This seems to be language-agnostic (it also happens in Perl), but just for ease of running it in-browser I've used JavaScript here.)
Comment: @Kev:  And it is correct output because `exec` only returns 1 match. To get multiple matches, you need to use `exec` inside a loop checking if there is a match.
Comment: `+` is greedy, but it will take the first match, and the middle  `1` is included in the first match, so it wouldn't be included in future matches and the `1001`  won't ever be matched.
Comment: Greedy means *up to the rightmost occurrence*, it never means the *longest in the input string*. If you see such an explanation, know it is wrong. Still, since the string is parsed from left to right, `101` will get matched in `101001` and the rest (`001`) just does not match (the matches are overlapping). You might use `(?=(10+1)).` and then check the length of each Group 1 value to get the longest one.
Comment: Indeed, this is not a duplicate. This question asks to get the longest match. The question it's closed as a duplicate of asks to get the first match, and in case of a tie, the longest match. They're not the same thing, and the question should not have been closed.
Comment: @Kev with `1011001`, `1001` will be second match, since `101` was matched first going left to right.
Comment: Regex is not the correct tool to extract the longest match. You might get all the substrings, test with `^10+1$` pattern and get the longest one using the language specific means.
Comment: use `/1(0+)1/` regex on match function and find the longest match by applying length function on the result.
Comment: @muru What's the difference between this and the classic HTML tag example `<.+>`?
Comment: The terminal characters are different. `` is a different case from, say `<foo<bar<blah<`
Comment: @muru `new RegExp(/<(.+)</,'g').exec('<b<a</b<')[0]` still gives `b<a</b`, though...is it the `.` that makes `+` extra greedy, or something?  Why doesn't that one stop at `b`?
Comment: @WiktorStribiżew, that doesn't seem to hold true though, e.g. `new RegExp(/1(0+)1/).exec('1011001')[0]` gives `101` still instead of `1001` even though there is no overlap because of the extra 1.
Comment: @Kev O.o for me, it gives the entire string. For a comparable regexp to `1(0+)1`, try `<[^<]+<`.
Comment: @muru sorry my bad, I had the wrong subscript in there.  You're right.  But still, it gives a longer result than `b`, that is what I meant.
Comment: @WiktorStribiżew Ah!  OK, this combined with the other suggestions helps it make sense for me.  Thank you.
Answer: Regex always reads from left to right!  It will not look for something longer.  In the case of multiple matches, you have to re-execute the regex to get them, and compare their lengths yourself.
Comment: And as @muru already said, regex does not go back: meaning when 101 is already match, it is "consumed" so only `001` is left.
Comment: Can you provide a better definition of 'greedy' then?  (Doesn't it mean, find the longest?)
Comment: greedy means that it matches as much as possible. For example: your string "101001". if you use this regex `1.+1` it would match all, because it is greedy. But if you use this regex `1.+?1` it is not greedy and would only match "101" (see https://regex101.com/r/GeDOZL/1). I hope my explanation is clear
Comment: Right, so isn't the string that matches `1(0+)1` as much as possible `1001`, not `101`?
Comment: no, because regex reads from left to right and it will take the FIRST match. `101` already matches see https://regex101.com/r/giYk8A/1
Answer: Greedy means up to the rightmost occurrence, it never means the longest in the input string.
Regex itself is not the correct tool to extract the longest match. You might get all the substrings that match your pattern, and get the longest one using the language specific means.
Since the string is parsed from left to right, 101 will get matched in 101001 first, and the rest (001) will not match (as the 101 and 1001 matches are overlapping). You might use /(?=(10+1))./g and then check the length of each Group 1 value to get the longest one.

var regex = /(?=(10+1))./g;
var str = "101001";
var m, res=[];

while ((m = regex.exec(str)) !== null) {
  res.push(m[1]);
}
console.log(res); // => ["101", "1001"]

if (res.length>0) {
  console.log("The longest match:", res.sort(function (a, b) { return b.length - a.length; })[0]);
} // => 1001


Drush doesn't download module version specified as dependency

Question: My module has a dependency to specific version of Media module (7.x-2.0-alpha4) and I have specified that in my info file as documented in Writing module .info files (Drupal 7.x) documentation, just like this:
name = mymodule
description = MyModule description.
package = Media

dependencies[] = file_entity
dependencies[] = media (7.x-2.0-alpha4)
dependencies[] = media_internet
dependencies[] = views

When I try to enable my module with it's dependencies drush en -y mymodule, Drush downloads current stable version of media module (7.x-1.5) instead of the specified one and then enabling my module fails because of unmet dependency. I'm doing this on plain Drupal installation v7.34, DevDesktop stack v 2 RC build Mar 18 2015, Drush v7.0.0-alpha9 (from DevDesktop).
I have also tried to specify the version as (2.0-alpha4) and (2.x) - without success.
What am I doing wrong? Thanks for any hints!
Answer: The Drush download code actually pre-dates this feature; as you have observed, it is not supported.
I have posted a feature request in the Drush issue queue, here:
https://github.com/drush-ops/drush/issues/1285
Comment: Thanks for the clarification Greg! I'll watch the issue on GitHub as well.
Answer: As @greg_1_anderson says, this feature is not supported yet, so such a dependency has to be downloaded and enabled in two steps
drush dl media-7.x-2.0-alpha4
....
drush en mymodule

Just running drush en -y mymodule will fail on unmet dependency.


Tensorflow Custom Cost Function

Question: I have 2 concrete classes, say A and C.  I want to use an NN to classify them into classes A, B, C, such that samples that are too close to confidently classify are just classed as B.  The cost function should be as follows:  A misclassification, (an A classified as C, or vice versa) will have a very large cost.  A correct classification will have zero cost.  Classifying an item as B will have very low cost.  The result is that we only distinguish samples that we are VERY SURE fit into their respective classes.
I have only worked through the simple tutorials in TensorFlow, but it didn't cover how to define more specific costs functions such as this.  Can anyone explain how this can be accomplished in TensorFlow
Here is my relevant code, where I currently classify using only 2 classes. It is straight from the TensorFlow tutorial:
<code>cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(y, y_))
train_step = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)
</code>
y is the output of the NN (will look like [[1,0,0],[0,1,0]] for a two sample set with 3 classes), and y_ is the correct classes for the sample which might be [[1,0,0],[0,0,1]].  In this example, we would have classified the second sample as B because we were uncertain, but the true class was C.
Comment: Where's your code?  Please see [Ask].  You also didn't even bother to take the 2-minute site [tour].
Answer: I think you have some fundamental misunderstanding of how NN classifiers work. You should probably read up on that a bit if you are going to go deeper into coding them. I highly recommend online book by Michael Nielsen Neural Networks and Deep Learning.
That said, the solution you are looking for is not in creating a special cost function, but in how you interpret the results you get from NN. You do not have 3 classes, you have 2. The "I have no idea what this is" is not a class by itself, but rather a measure of NN's confidence in its answer. So, your network should have 2 outputs, one for each class, just like in the TendorFlow guides. And you should train it just like in the guides. Once your network is trained, when you feed it a sample to classify, you get 2 numbers, lets call them A' and C'. These numbers indicate NN's confidence in what class the sample belongs to. For example, if you get A' == 0.999 and C' == 0.00001, the network is pretty damn sure that your sample is class A. If you get A' == 0.6 and C' == 0.59, your network has no idea if the sample is A or C, but slightly favors the theory that it is class A. It is now up to you to say what your confidence intervals are. To make this easier, you should probably use softmax for the output layer non-linearity (the way TensorFlow MNIST guides do). One of the useful features of softmax is that the sum of all your classes will always be 1 and you can easily make decisions based on the difference between A' and C'.
Comment: Thanks for your reply.  The specific problem I'm facing is one of optimizing the classifications such that specific types of mistakes have very specific costs.  I was hoping to be able to accomplish the optimization of the specific true/false positive/negative rates within the network.  Are you saying that there isn't a way to create a custom cost function that accomplishes this?  I understand that there are other ways to accomplish this.  I realize this isn't a traditional application, but the maths should work out anyway if the cost function to minimize is chosen correctly
Comment: No, you cannot solve this with just a different cost function. Think about it. When you start training your network, your weights are set to some random values taken from a standard or uniform distribution. Your network is not sure about anything and it is from comparing labels with predictions the weights are updated to make better and better predictions. So, by your own rules of "if you don't know if this is A or C, this is B" everything will be classified as B and the network will never actually train to recognize A and C. This is kind of a crude explanation.
Comment: Of course, if you are looking for some very specific mistakes and you can label those mistakes in your training data corpus as class B you can train the network to recognize these... probably... if the mistakes you are looking for are distinct enough from regular A and C. But your recognition accuracy of A and C will likely suffer.
Comment: The point though is that if the cost is higher for classifying something as B than it is for classifying it correctly, in minimizing the cost function the network will learn to classify as much as it can as A or C.  It's not going to just stay content classifying everything as B, as you are imagining. Moving the weights one direction might classify one "A" as an A and leave the rest as B.  That's lower cost than before. That's what I want.  Do you or do you not know how to create a custom, specific cost function in Tensor Flow? That's the question
Comment: This is not how loss function works. The value of the loss function is lower when your classification is more correct, not when a particular class is recognized.

Tensorflow Custom Cost Function


Using "IN" with db_query()

Question: First off, let me say that I've tried the Drupal 6 answer shown in Using IN clause in db_query and it doesn't work.
I have a query that previously only needed to include items from a single taxonomy id:
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid = %d AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, 134, $displays_count);

The requirement has changed and we now need to pull images from multiple taxonomy ids. Based on the linked post above, I tried this:
$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$images = db_query("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, $tax_ids, $displays_count);

I just get a blank screen there. When I turn on Devel and display the query log, what it shows as running is:
SELECT n.nid, n.title, f.filepath, cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = 1)
WHERE n.type = 'imagevault' AND tn.tid IN (1,5) AND n.status = 1
ORDER BY n.created DESC LIMIT 0

I have no idea where the 1,5 is coming from in the rendered query. What do I need to do to make this work? Does it only work for nid when selecting directly from a node? If so, how can I use an array in the query? Do I skip the placeholder for that param and just put it directly in the WHERE clause?
Updated info
So it appears that completely aside from the strange case of 134, 139 being translated to 1,5, I also have another issue. Although the variable $displays_count is set further up the page to 5, it's still translating in the query to 0. (I've echoed the value out right before the query, and it's still 5 there, so I don't know what's happening or why changing the tn.tid placeholder would have any effect on the limit placeholder.)
$tax_ids = array(134, 139);
$params = $user->uid;
$params[] = $tax_ids;
$params[] = $displays_count;

$images = db_query(db_rewrite_sql("SELECT n.nid, n.title, f.filepath,
cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND tn.tid IN (" . db_placeholders($tax_ids) .") AND n.status = 1
ORDER BY n.created DESC LIMIT %d"), $params);

Answer: The last three arguments you are passing to db_query() are wrong; you should merge them in an array, and pass that instead of them.
block_list() contains the following code:
$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

Similarly, blogapi_mt_validate_terms() contains the following code:
  $term_list = array_unique($node->taxonomy);
  $params = $term_list;
  $params[] = $node->type;
  $result = db_query(db_rewrite_sql("SELECT t.tid, t.vid FROM {term_data} t INNER JOIN {vocabulary_node_types} n ON t.vid = n.vid WHERE t.tid IN (" . db_placeholders($term_list) . ") AND n.type = '%s'", 't', 'tid'), $params);

In your specific case, your code should be similar to the following one:
$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$args = array_merge(array($user->uid), $tax_ids, array($displays_count));

/**
 * Alternatively the previous three lines could be replaced by the following ones:
 * $args = array(134, 139);
 * $placeholders = db_placeholders($args);
 * array_unshift($args, $user->uid);
 * $args[] = $displays_count;
 */

$images = db_query("SELECT n.nid, n.title, f.filepath,
  cti.field_iv_source_name_value AS source, bf.nid AS flagged
  FROM node n
  JOIN content_type_imagevault cti ON n.nid = cti.nid
  JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
  JOIN files f ON cfaf.field_att_file_fid = f.fid
  JOIN term_node tn ON tn.nid = n.nid
  LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
  WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
  ORDER BY n.created DESC LIMIT %d", $args);

Answer: For now, since we only have two options, I've decided to just go with an OR clause, instead of trying to deal with the IN.
$images = db_query("SELECT n.nid, n.title, f.filepath, cti.field_iv_source_name_value AS source, bf.nid AS flagged
FROM node n
JOIN content_type_imagevault cti ON n.nid = cti.nid
JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn ON tn.nid = n.nid
LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
WHERE n.type = 'imagevault' AND (tn.tid = %d OR tn.tid = %d) AND n.status = 1
ORDER BY n.created DESC LIMIT %d", $user->uid, 134, 139, $displays_count);

Using "IN" with db_query()


my thread loops exactly 43 times then throws an exception

Question: I cant figure it out. My code runs perfectly 43 times and then I get a LineUnsupportedException when the Clip object tries to reopen the line. Its a metronome so precise timing is important and I've got the code worked out to a mostly functional point. I create an Clip[] of Clip objects, there are as many as there are beats in a measure, I cycle through those in my while loop and each measure close and flush the clip and define a new Clip[] of Clip objects, if I don't close the line now and then and reset everything the audio will just stop playing, I'm not sure if the clips isActive() method returned false or what happened but that solution seemed to have fixed the problem until I started getting this exception, any thoughts on might be causing it?
Here is my output from the last working loop to the exception...
0
Tick...
COUNT:: 42
Loop completed in: 6
Beat Duration should be: 499
Time left to sleep: 493
1
Tick...
COUNT:: 43
unable to obtain a line
java: /build/buildd/openjdk-6-6b24-1.11.5/build/../pulseaudio/src/native/org_classpath_icedtea_pulseaudio_Stream.c:720: Java_org_classpath_icedtea_pulseaudio_Stream_native_1pa_1stream_1cork: Assertion `stream' failed.
and the two classes currently involved in this thread...
Ticker.java
package com.timer;

import java.io.IOException;

 import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Ticker extends Thread {

private App app;

private String[] soundFiles;

private Ticker() {
}

public Ticker(App app) {
    this.app = app;
    soundFiles = new String[app.getBeatsPerMeasure()];
}

private AudioInputStream stream;

private Clip[] ticks;
AudioFormat format;
DataLine.Info dataLineInfo;

public String setFileNames() {
    for (int i = 0; i < app.getBeatsPerMeasure(); i++) {
        soundFiles[i] = "firstBeatCut.au";
    }
    return "";
}

public String loadArray(int... iArray) {
    if (iArray.length != app.getBeatsPerMeasure()) {
        return "Sorry there was an error.";
    }
    for (int i = 0; i < iArray.length; i++) {
        iArray[i] = i;
        System.out.println(iArray[i]);
    }
    return "";
}

public void tick() {
    long difference, timeTaken, timeAllowedToSleep, before, after;
    long idealTime;

    int i = 0;
    int count = 0;

    ticks = new Clip[app.getBeatsPerMeasure()];

    while (app.isTicking()) {
        System.out.println("Tick...");

        before = System.nanoTime();

        try {

            stream = AudioSystem.getAudioInputStream(this.getClass()
                    .getResource("./firstBeatCut.au"));

        } catch (UnsupportedAudioFileException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (ticks[i] != null && ticks[i].isRunning()) {
            ticks[i].stop();
            if (ticks[i].isActive()) {
                ticks[i].close();
            }
        }

        count++;
        System.out.println("COUNT:: " + count);
        try {
            ticks[i] = (Clip) AudioSystem.getClip();
            if (!ticks[i].isOpen()) {
                ticks[i].open(stream);
            }
        } catch (LineUnavailableException e) {
            System.out.println(e.getMessage());

        } catch (IOException e) {
            e.printStackTrace();
        }
        ticks[i].setMicrosecondPosition(0);

        if (ticks[i].isOpen()) {
            ticks[i].setMicrosecondPosition(0L);
            ticks[i].start();
        } else {
            try {
                ticks[i].open(stream);
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            ticks[i].setMicrosecondPosition(0);
            ticks[i].start();
        }

        idealTime = app.calculateSleep(app.getBPM())
                - ticks[i].getMicrosecondLength();

        after = System.nanoTime();

        timeTaken = (after - before);
        difference = (idealTime - timeTaken);
        System.out.println("Loop completed in: " + (timeTaken / 1000000L)
                + "\nBeat Duration should be: " + (idealTime / 1000000L)
                + "\nTime left to sleep: " + (difference / 1000000L));

        timeAllowedToSleep = difference;

        if (timeAllowedToSleep > 0) {
            try {
                Thread.currentThread().sleep(timeAllowedToSleep / 1000000L);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(i);

        stopTick(ticks[i], ++i);
        if (i == app.getBeatsPerMeasure()) {
            i = 0;
        }
    }
}

public void closeTick(Clip tick) {
    tick.close();
}

public void stopTick(Clip tick, int index) {
    tick.stop();
    if (index == 4) {
        closeTick(tick);

        try {
            tick = AudioSystem.getClip();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }
}

public void play(Clip tick) {
    tick.setMicrosecondPosition(0L);
    tick.start();
}

public long calculateTimeAllowedToSleep(long sTime, long time) {
    long diff = time - sTime;
    long timeToSleep;
    long ssTime = 60000 / 120;
    timeToSleep = ssTime - diff;
    return timeToSleep;

}

}

ActionHandler.java
package com.timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ActionHandler implements ActionListener, ChangeListener {

private App app;
Ticker ticker;
Thread t1;
private int beatsInMeasure;
private boolean ticking;

public ActionHandler(final App app) {
    this.app = app;
    this.ticker = new Ticker(app);
    beatsInMeasure = app.getTimeSignature()[0];
    ticking = app.isTicking();
    ticker.loadArray(0,1,2,3);
}

private Runnable doTick = new Runnable() {
    public void run() {
        while (app.isTicking()) {

            ticker.tick();

        }
    }
};

public void actionPerformed(ActionEvent e) {
    JButton b = (JButton) e.getSource();
    if (b == app.getBtnStart()) {
        if (b.getText().equalsIgnoreCase("Start")) {
            app.setStartText("Stop");
            app.resetEnabled(false);
            ticker.setFileNames();
            app.setTicking(true);
            t1 = new Thread(doTick);
            t1.start();
        } else {
            app.setStartText("Start");
            app.resetEnabled(true);
            app.setTicking(false);
            app.setTicking(false);
            try {
                t1.join();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    } else if (b == app.getBtnReset()) {
        app.reset();
    }
}

@Override
public void stateChanged(ChangeEvent e) {
    JSpinner sp = (JSpinner) e.getSource();
    SpinnerNumberModel model = app.getModel();
    if (sp.getValue() != null) {
        app.calculateSleep(Integer.parseInt(String.valueOf(
                sp.getModel().getValue()).toString()));
    }
}
}

Comment: Show the code and the exception...
Comment: Sounds like `AnswerToUniverseOverflowException`. Please create as short as possible code to reproduce the problem.
Comment: That's kind of an "off by one"-error since you exceeded the answer to the Ultimate Question of Life, the Universe, and Everything by one when you reach 43.
Comment: Can you please provide your code?
Comment: I was afraid of that, okay I'm gonna have to clean it up a little first. I've been debugging it so there's all kinds of random stuff all over the place and I'm not going to make you sift through it so I'll post it in a few minutes.
Comment: in[] of clip object. This question is troll.
Comment: I don't see it, but I'll search for it in an editor. But doesn't that raise even more questions? Why does it even work in the first place if its the wrong data type? I better go find out where this is and see when its getting called.
Comment: The search in Eclipse and Geany both returned nothing, where do you see that?
Comment: @KevinBigler it is stated in your question `I create an int[] of Clip objects`.
Comment: Oh that makes more sense, okay then back to the initial question, I'll edit that.
Comment: I tried adding `count < app.getBeatsPerMeasure() * 4` to the while loop in the tick method so it would break out of it every 16 loops (with the current time signature) and then get called again from the original thread and sure enough on the 3rd time around it looped 11 times then I got the same exception. 16+16+11=43, I'm really stumped, could it be a data issue? Maybe I'm using up all my lines in the `AudioSystem`?
Answer: If you open a line close it as soon as you're done with it every time. i removed the if statement from the stop method in Ticker and it works perfectly. I'm going to sleep, thanks to everyone who commented.


What data type is "Date" in Postgres?

Question: I don't have access to a client database, but need to know how a "Date" CCK field stores its information.
I'm using MySQL, and this easily found in the structure of the table. Anyone use Postgres and can check?
Is it a timestamp or a date?
Answer: Why do you need access to the database for this information?
Have you looked here?
http://drupalcode.org/project/date.git/blob/b7502f3a86628e5c4995c01f20ac64d5cee5888b:/date.install
/**
 * @file
 * Install, update and uninstall functions for the Date module.
 */

/**
 * Implements hook_field_schema().
 */
function date_field_schema($field) {
  $db_columns = array();
  switch ($field['type']) {
    case 'datestamp':
      $db_columns['value'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    case 'datetime':
      $db_columns['value'] = array(
        'type' => 'datetime',
        'mysql_type' => 'datetime',
        'pgsql_type' => 'timestamp without time zone',
        'sqlite_type' => 'varchar',
        'sqlsrv_type' => 'smalldatetime',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    default:
      $db_columns['value'] = array(
        'type' => 'varchar',
        'length' => 20,
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
  }
  // ... more stuff

The answer to your question is that depending on the Drupal "Date" value you're storing it -- for Postgres it is 1 of the following values:

(drupal field of) datestamp = int DBMS field
(drupal field of)datetime = timestamp without time zone DBMS field
(other drupal field of) date = varchar DBMS field analyzed by Date module on save and usage

EDIT
My answer is for Drupal 7. The same module API can be referenced for Drupal version 6 if needed. You didnt specify what version of Drupal you are using and "CCK" can be apart of both.
Comment: The CCK field in question appears as "Date" on the content type page. (As opposed to "Date (ISO)" or other options)
In MySQL, it's stored as a datetime, so at looking this, it must indeed be the Postgres data type 'timestamp without time zone'

What data type is "Date" in Postgres?


Question on Detailed Balance and Bayes' Rule

Question: I think I am confused due to the lax notation typically used when dealing with probabilities and not having a formal probability background.
Bayes' Rule tells me that
$$Pr(X_t=a|X_{t+1}=b)Pr(X_{t+1}=b) = Pr(X_{t+1}=b|X_t=a)Pr(X_t=a)$$
Detailed balance is that for a transition matrix P there exists a stationary distribution such that:
$$Pr(X_t=a|X_{t+1}=b)Pr(X_{t+1}=b) = Pr(X_{t+1}=b|X_t=a)Pr(X_t=a)$$ where the marginals correspond to the stationary distribution.
I am getting confused by the similarities between both of these. Am I conflating two completely different issues?
Edit: I am basing the definition of detailed balance on the one given on the wikipedia page for detailed balance. It states that let $\pi(s)$ be a density and $P(s',s)$ be a transition density from state $s'$ to $s$, then detailed balance is given by
$$\pi(s')P(s',s) = \pi(s) P(s,s')$$
Bayes rule that I originally gave is based on probabilities but also holds for densities.
Comment: How did you get that equation for detailed balance?
Comment: Could you edit that information into the question? Something like "Wikipedia article states (equation),  because (explanation) I interpret this to mean (equation currently in question)".
Comment: It's not Bayes rule, it's [conditional probability](https://en.wikipedia.org/wiki/Conditional_probability) $P(A \cap B) = P(A|B)P(B)$.
Comment: @JuhoKokkala The wikipedia page on detailed balance states that define P(s',s) to be transition probability density from state s' to state s and $\pi(s)$ as a probability density then detailed balance is $\pi(s') P(s',s) = \pi(s) P(s,s')$. This is in densities but bayes theorem also holds for densities.
Comment: @JuhoKokkala done.
Comment: This is missing the "because" part - how does $\pi(s')\,P(s',s) = \pi(s)\,P(s,s')$ imply your equation?  Am I guessing correctly: you think that when $a=s, b=s'$, $P(s,s')=P(X_t = a \mid X_{t+1}=b)$?
Comment: @JuhoKokkala $a=s, b=s', P(s,s') = P(X_{t+1} = b | X_t = a)$. Note $P(s,s')$ is going from state $s$ to $s'$.
Comment: @Tim I am using the statement of Bayes' Theorem on wikipedia page and just taking the denominator to the other side. https://en.wikipedia.org/wiki/Bayes%27_theorem
Comment: @user52932 sorry I mixed up $s$ and $s'$,   I was after the $P(X_t = a \mid X_{t+1} = b)$ factor that appears on the left hand side of your previous eq, where do you get that? ($P(s', s)?$)?  (I think this is a good question if this part is clarified, and an interesting answer can be written.  I'll try to get back to this later if no-one else answers)
Comment: @JuhoKokkala I am assuming you are asking about the detailed balance equation. The LHS is $Pr(X_t = a | X_{t+1}=b) Pr(X_{t+1}=b)$. This corresponds to $P(s',s) \pi(s')$ from the wiki definition. And the right hand side is similarly defined.
Answer: It is indeed confusing when using confusing notations! As, e.g., in your question with $Pr(\cdot)$ for all probabilities.
Let us consider an MCMC algorithm where detailed balance holds. This means that, given the Markov transition kernel $K$ with density $k(x,x')$ [which is also the generator of the Markov chain in that $X_{t+1}|X_t=x\sim k(x,x')$], there exists a probability density $\pi$ such that$$\pi(x)k(x,x')=\pi(x')k(x',x)$$i.e., there is time reversibility in the Markov chain: if $X_t$ is distributed from $\pi$, $X_t\sim\pi$, then $X_{t+1}$ is distributed from $\pi$,and also $X_{t-1}$ is distributed from $\pi$.
Why is this different from Bayes' rule? It is true that Bayes' rule allows for the inversion of a joint distribution from marginal of $X$ times conditional of $Y$ to marginal of $X$ times conditional of $Y$. However, if one starts with a random variable $X_t$ with marginal distribution (density) $\pi_t$ and applies the Markov kernel $K$, then $X_{t+1}$ will be distributed from a marginal distribution (density) $\pi_{t+1}$, providing the general equality
$$\pi_t(x)k(x,x')=\pi_{t+1}(x')\tilde{k}(x',x)$$
where $\tilde{k}$ denotes the density of the time-reverse kernel [obtained as the distribution of $X_t$ given $X_{t+1}$]. Therefore the detail balance property is very specific wrt Bayes' inversion formula in that

$\pi_t(x)=\pi_{t+1}(x)$ [stationarity]
$k(x,x')=\tilde{k}(x,x $ [reversibility]

and it only holds for a subfamilly of MCMC algorithms like the Metropolis-Hastings algorithm.


How to get coordinates of Run or other WordProcessing element via OpenXML?

Question: I was wondering if it is possible to find the coordinates of a specific Run (text, no drawing or other elements that have offset parameter) on a page in a Word document using OpenXML SDK. I know that OpenXML is basically .. well XML, and simple runs have no relative, numerical position embedded in them.
I was reading through OpenXML SDK API and found no clues but maybe I have missed something. By coordinates I mean any tuple that can be mapped to pixels if I would generated an image out of the page (imagine you made a screenshot of page)
I suspect, if this is possible, it is not trivial.
Appreciate your help!
Answer: The Open XML SDK does not include this functionality. This would require a layout engine, which is not part of the SDK.
Comment: @Proko, thanks (and please also upvote if the answer is helpful). To add to that, the Open XML SDK is a very low-level library that just lets you process (create, change, delete) the Open XML parts and markup making up an Office document. There is no abstraction and there are no higher-level features.
Answer: Word is not a page layout program, it's a word processor. Therefore:
No, it's not possible because...
The Word application dynamically lays out a page when it's opened in the Word application. Exactly how it's layed out and where things appear on-screen (or on the printed page) depends on how Word calculates font size as well as line, character and paragraph spacing (in all directions) for the currently selected printer driver. So it can vary and thus cannot be saved in the Open XML file.


which monitoring system would you prefer: nagios, zabbix, cacti

Question: We have a web system like this:
10 servers with files and one front server which serves the web.
We need to see the whole picture of what's going on with them. What monitoring system would you recommend: Nagios, Zabbix, Cacti or maybe something else.
Comment: This should be moved to serverfault.com, the mentioned solutions are all NMS
Answer: Nagios is primarily a monitoring tool. That is, it monitors any number of conditions for the services and servers you define. Then if there is a problem (eg outage, slow load time or anything you define) then notifications are sent out.
Cacti is not so much a monitoring tool but a tool for gathering reports and drawing graphs from data such as SNMP.
Zabbix is a bit of a combination of the two.
We moved from Nagios to Zabbix about a year ago mainly for this hybrid approach. We liked the easy integration with JMX data, SNMP and more to draw graphs, as well as a pretty sophisticated monitoring and alerting tool (very similar to Nagios in that way).


In-center related. Prove that the indicated quadrilateral is also a rhombus.

Question: AE and BD are the angle bisectors of $\triangle ABC$ with in-center I. P is any point on DE produced. X, Y, and Z are the feet of the perpendiculars from P to CB, BA, and AC respectively.

(1) Through P, draw a line parallel to AB cutting BC at $B_1$, BD at B', AE at A', and AC at $A_2$.
(2) Through B', draw a line parallel to BC cutting AB at $B_2$, and AC at $C_1$. Let $PC_1$ cut BC at $C_2$.
CI, the third angle bisector of $\triangle ABC$, cuts $C_1C_2$ at F, cut $B_2C_1$ at C', and cut PX produced at G. Then, $\triangle A'B'C'$ is a miniature of $\triangle ABC$ and with its in-center also located at I. Let C'A' produced cut AB at $A_1$.
The question is:- "will $CC_1C'C_2$ be also a rhombus as the other two?"

A solution has been found through an alternate construction method. See question no. 2882211
Answer: Yes, since it is also a parallelogram in which one diagonal is also an angle bisector, it will be a rhombus.
Comment: I think we need to prove that $A'C'C_2$ is a straight line first before we can say it is a parallelogram.
Comment: Oh point! I didn't read the question properly


C++ implicitly calling class member's constructor when initializing the class instance

Question: I'm still learning the beauty of C++. I came across some code today and hopefully someone can give me some guidance.
I have 2 classes
class B
{
public:
    B( std::string s )
        : m_string( s )
    {
    }

private:
    std::string m_string;
};

class A
{
public:
    A( B b )
        : m_b( b )
    {
    }

private:
    B m_b;
};

Main.cpp
A a = A(std::string("hello"));

I'm a bit confused about how can such initialization work? How does the compiler know that the std::string("hello) is to be passed to B's constructor instead?
I was trying to find relevant documentation but no luck..
Answer: When a class has a constructor taking a single argument, that constructor can be used to implicitly convert that argument to an instance of that class.  This means that wherever a B is required, your B( std::string s ) constructor allows passing a string instead.
If you want to inhibit this implicit conversion, you write explicit B( std::string s ).  Some people consider this good practice for most single-argument constructors.


Limit user views to infopath files created within Share Point 2007

Question: I am a new admin for our SharePoint 2007 site. I've searched for and found many similar questions but none quite like what I'm trying to achieve.
So here's the rundown.
I've created an Infopath form that everyone has to fill out. IT's an emergency contact form. The tricky part is that I don't want anyone to see anyone elses form that is submitted. The managers are allowed to see them all. I've limited the view for users to view only what they create, but they can easily change the view to see them all.
We have too many people, and too many groups to limit everyone. I work for a large company.
Any ideas how to approach this? IS there a way to have the creation of the form on one page and the storing/submission of the form to save in another location(with limited access to that particular site)?
I'm open to all ideas here, as I said, I'm new to this and am trying to learn as fast as I can.
Thank you in advance for any help.
Answer: I figured it out. The fix was actually in the InfoPath form itself, not SharePoint. I just had to change the destination on the submit properties to a secured location.
Sort of embarrassed I didn't figure that one out a lot sooner. :/
Thanks