Diferença entre object, dynamic e var

Question: Estou realizando alguns testes e pelo que me parece object e dynamic realizam a mesma tarefa ao contrário de var que depois de atribuído é impossível mudar seu tipo, qual a diferença entre eles?
var variavel = 15; // É preciso atribuir um valor, se não não compila, não aceita iniciar como NULL;
object objeto = 15;
dynamic dinamico = 15;

Console.WriteLine(variavel.GetType().ToString()); // Int
Console.WriteLine(objeto.GetType().ToString()); // Int
Console.WriteLine(dinamico.GetType().ToString()); // Int

variavel = "Teste"; // Não deixa atribuir
objeto = "Teste";
dinamico = "Teste";

Console.WriteLine(variavel.GetType().ToString()); // Int
Console.WriteLine(objeto.GetType().ToString()); // String
Console.WriteLine(dinamico.GetType().ToString()); // String
Console.ReadKey();

Comment: Fiz uma resposta bem detalhada e exaustiva... se tiver mais alguma dúvida, fique a vontade para perguntar. =D
Answer: object
Refere-se ao tipo System.Object que é a base para todos os outros tipos,
sejam eles tipos-referência ou tipo-valor.
Uma variável/parâmetro desse tipo permite que se associe qualquer tipo de dados,
sendo que se for uma classe,
ocorre uma atribuição simples, e se for um tipo-valor, ocorre primeiro o boxing desse valor,
e depois uma atribuição.
Além disso, há tratamento especial para tipos nullable
(Nullable<TStruct>, no C# podendo ser representados por TStruct?), em que,
se o nullable .HasValue for falso, o valor é considerado null, caso contrário,
o valor contido no nullable é boxed e então é feita a operação de atribuição.
object x = 1; // vai ocorrer boxing do valor 1, pois Int32 é um value-type
object y = "str"; // não vai haver boxing, pois String é uma reference-type
// nullable é value-type, mas nunca será boxed dentro de um object
int? i = null;
int? j = 10;
object z1 = i; // z1 será null
object z2 = j; // z2 terá um Int32 com o valor 10 boxed e atribuido à variável

var
Isso é o que se chama de açucar-sintático.
É só uma palavra chave que é usada para que o compilador adivinhe o tipo na hora de compilar.
Isso se chama inferência de tipo. Vou ser direto:
var x = 1;
var y = "str";
var z = x == 2 ? new MeuObjeto("xpto") : new MeuObject("abc");

será traduzido pelo compilador para:
Int32 x = 1;
String y = "str";
MeuObjeto z = x == 2 ? new MeuObjeto("xpto") : new MeuObject("abc");

Quando var é a única opção?
Existe um uso em que var não é apenas açucar-sintático.
A grande sacada nessa inferência de tipo, são os tipos anônimos, ou seja,
tipos que são criados inline, e que não possuem nome:
var a = new { Nome = "Miguel" };

Não existe tradução em C# para isso. Mas na hora de compilar,
o C# vai gerar um tipo instantaneamente, e usá-lo:
<Projection>f__0 a = new <Projection>f__0 { Nome = "Miguel" };

Sendo gerada uma classe <Projection>f__0, perfeitamente válida!
dynamic
Essa é uma palavra chave que permite chamar métodos e propriedades de um objeto qualquer,
sem conhecer o seu tipo. Isso é conhecido como late-binding, ou seja, é associar a
chamada ao método/propriedade de destino somente no momento em que a chamada for feita.
Note que, ao fazer o dispatch, será usado um dispatcher que age exatamente como o C#
(ou o Visual Basic, se estiver usando dynamic no VB). Esse dispatcher tenta localizar o
método/propriedade/operação da mesma forma que o C# faria... e se falhar será lançada uma
exceção indicando que a chamada não poderá ser feita.
Procure saber mais sobre duck-typing, pois o conceito é muito semelhante...
senão o mesmo.
Performance do dynamic
Mas não ache que você vai perder rios de performance fazendo isso,
pois a implementação de uma chamada sobre um dynamic é muito eficiente.
No ponto exato em que é feita a chamada,
é compilado uma chamada a um objeto estático que faz cache do método a ser chamado em
um dicionário de tipos. Isso quer dizer que a chamada só é lenta da primeira vez para cada tipo,
mas da segunda vez que for executado o mesmo código com o mesmo tipo, será muito mais rápido.
Refere-se a essa chamada como call-site.
Note que uma linha de código pode conter vários call-sites, um para cada operação sendo feita:
// existem 2 call-sites na linha abaixo:
// - uma para a propriedade Length,
// - e outro para o type-cast para int
int a = (int)dyn.Length;

dynamic não é um tipo
dynamic não é um tipo, mas sim, uma palavra chave que determina uma forma diferente de fazer
dispatch (escolha de que método/propriedade será chamada de fato)... para se ter um paralelo,
herança e polimorfismo são duas outras formas de fazer dispatch,
diferentes daquela feita quando dynamic é usado.
Apesar de não ser um tipo, existem tipos que são associados à palavra chave dynamic.
Esses tipos fazem parte da DLR (Dynamic Language Runtime)
Referência:

Understanding the Dynamic Keyword in C# 4: explica a diferença entre as palavras chaves, além de fazer introdução à DLR (Dynamic Language Runtime)
Dynamic Dispatch – How dynamic work in C#: explica como é feita a chamada a métodos/propriedades e operadores quando usando dynamic, e porque é quase tão rápido quando usar o próprio método compilado
C# Dynamic - dotnetperls.com - artigo do dotnetperls, mostrando mais detalhes sobre dynamic. Achei interessante a análise da forma que o C# gera os call-sites.
Visão geral do Dynamic Language Runtime
Conversões boxing e unboxing (Guia de Programação em C#): sobre boxing e unboxing
var (C# Reference)
How Duck Typing Benefits C# Developers - Phill Haack - sobre duck typing (esse cara é f0d@)
Tipos anônimos (Guia de Programação em C#)
Can't return anonymous type from method? Really? - como são implementados tipos anônimos pelo C#
Comment: Duck-typing não necessáriamente involve tipagem ou dispatch dinámico. Em C++, nos templates, a conferência é feita em tempo de compilação e usando tipagem estática.
Comment: No C# só há a opção de duck-typing com dispatch dinâmico, sendo que o destino da chamada fica em um mapa, dentro de um campo estático que representa cada uma das chamadas feitas sobre `dynamic` no código. A isso se deu o nome de *Call-Site*.
Comment: Estava me referindo a duck-typing em templates: http://en.wikipedia.org/wiki/Duck_typing#Templates_or_generic_types
Answer: O tipo object é o tipo pai de todos os demais tipos em .NET. É por esse motivo que você pode usar uma variável do tipo object para apontar ou guardar todo tipo de informação em .NET. A quem tiver dúvidas sobre o porquê disso, sugiro estudar dois tópicos de orientação a objetos: herança e polimorfismo.
Se você utiliza a palavra reservada var para criar uma variável, ela será tipada estaticamente. O tipo que a variável terá será decidido pelo restante do código - o compilador se responsabiliza por determinar o tipo mais apropriado.
Se você utiliza a palavra reservada dynamic o comportamento é similar ao de object, mas nenhuma verificação de tipo é feita em tempo de compilação. (fonte: MSDN). Isso significa que quaisquer erros por chamadas ou atribuições inválidas não serão detectados antes do programa ser construído. Se tais erros passarem batidos pelo compilador, poderão se manifestar em tempo de execução.
A palavra reservada dynamic realmente parece não ter sentido em um mundo puramente .NET, no qual você poderia talvez desligar avisos e erros do compilador em certos casos. Porém pode ser útil quando você vai integrar .NET com alguma outra plataforma, ou quando utilizamos C# em conjunto com linguagens de tipagem dinâmica como Iron Python (isso é citado na fonte que usei acima).
Comment: @Mephy,o C# não seria fortemente tipado ao invés de fracamente tipada ?
Comment: `var` não é fortemente tipado, como qualquer outro tipo em C# (uma linguagem fracamente tipada), graças a polimorfismo e casting. O correto é dizer que `var` cria uma variável estaticamente tipada, ou tipada em tempo de compilação.
Comment: @Mephy tem razão. Vou editar, valeu pela dica.
Answer: Vou ser bem coloquial:

dynamic é uma aberração que a Microsoft criou para atender ao mundo web e as REST API's, é como se fosse um tipo variante no C# que pode receber um objeto de qualquer tipo. Por que aberração? Pois é um tipo não seguro (type-unsafe) dentro de uma liguagem que se diz type-safe.
var é uma facilidade para escrever e determina que o compilador no momento de compilação vai determinar qual será o tipo com base no primeiro valor que o objeto recebeu.
object é o nada e tudo ao mesmo tempo. Basicamente tudo deriva de object, mas na programação se vc quiser usá-lo será necessário testar e converter no tipo de objeto que se deseja...

Recomendo que leia os livros de programação básica em C#, gostei muito dos da Wrox (C# for Begginers)
Comment: "mas na programação se vc quiser usá-lo será necessário testar e converter no tipo de objeto que se deseja..." Se tudo que você quer é ler o hash ou o tipo de um objeto, `object` é bem conveniente e dispensa `cast`s ou outras manipulações de tipo.
Comment: Sim, concordo e acho que foram raros os casos em que eu testei o tipo de um objeto para não usá-lo. O uso de `object` é muito comum quando vamos usar apenas as funções padrões `.ToString()`, `.GetHashCode()`, `.GetType()`
Answer: public sealed class Exemplo()
{
     private String _nome;

     public Exemplo(String nome)
     {
          _nome = nome
     }

     public String Nome
     {
          get { return (String)_nome; }
          internal set { _nome = (Object)value; }
     }

     public String NomeInvertido
     {
          get
          {
             var ex = new Exemplo(_nome); //Boa hora para você usar var, você sabe que new Exemplo(String) gera um objeto do tipo Exemplo. Você está dentro da própria classe.
             ex.Inverte();
             return ex.Nome;
          }
     }

     private void Inverte()
     {
          Char[] letras = _nome.ToCharArray();
          String inverso = String.Empty;
          for (Int32 i = letras.Length - 1; i > -1; i--)
               inverso += letras[i];
          _nome = inverso;
     }
}

Exemplo explicito = new Exemplo("Guilherme");
//Object exemplo = new Exemplo("Guilherme");
var implicito = new Exemplo("Guilherme");
dynamic dinamico = new Exemplo("Guilherme");

//SUCESSO:
Console.WriteLine(explicito.Nome); //Guilherme
Console.WriteLine(implicito.Nome); //Guilherme
Console.WriteLine(dinamico.Nome); //Guilherme

//Acessando um método Private
explicito.Inverte(); //Método não é público. Não pode ser acessado daqui.
implicito.Inverte(); //Método não é público. Não pode ser acessado daqui.
dinamico.Inverte(); //Não vai dar problema na hora de compilar, porem no momento que você executar esse código vai gerar uma exceção.

dinamico.Sobrenome; //Não existe esta propriedade porem só vai descobrir isso depois de executar a aplicação. Digamos que você utilize uma DLL externa, e a classe Exemplo está nessa DLL, hoje você não tem essa propriedade, mas amanhã você atualiza essa DLL e essa propriedade irá existir sem problemas...

Diferença entre object, dynamic e var


Xcode 14 and missing sync with CFBundleVersion edit in Info.plist during Build/Archive

Question: In my iOS apps, i have a script (a build phase actually) that upgrades the target's Info.plist CFBundleVersion to a number related to the git commit count. I've been using for a while and it works for me, never a problem.
On Xcode 14, something has changed and the script keeps working (i mean the .plist file is correctly updated) but applications no longer shows the correct build number and it's missing on Archive too.
I'll add some screenshot (of a blank new project, so no settings have been altered in times).
This is Target's General Tab in Xcode 14
This is Target's Info Tab
This is Info.plist file correctly updated by Build Phase Script
In previous Xcode versions, on Target's General Tab i used to have the build number synced with the one in .plist file and it was also synced when Archiving builds.
Now, if i try to archive the build, it goes out as 1.0(1).
Am I missing something or am I doing something wrong?
Hope you can understand my English.
Thanks for your help.
Comment: Did you find a solution? I have the very same problem
Comment: Nope, sorry. Still changing "numbers" by hand.
Comment: I met the same issue.
Answer: I use xcconfig for set version and build in Xcode.
In Base.xcconfig set
MARKETING_VERSION = 22.47.0
CURRENT_PROJECT_VERSION = 221125.1437

Pay attention if you using CocoaPods you should create Release and Debug xcconfig with content
Debug.xcconfig
#include "../Pods/Target Support Files/Pods-{SET_PROJECT_HERE}/Pods-{SET_PROJECT_HERE}.debug.xcconfig"
#include "Base.xcconfig"

Release.xcconfig
#include "../Pods/Target Support Files/Pods-{SET_PROJECT_HERE}/Pods-{SET_PROJECT_HERE}.release.xcconfig"
#include "Base.xcconfig"

Set values in info.plist
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>

Hope its help
Answer: Feb 20th, 2023, my temporary solution:
step 0: delete the system generated info.plist
step 1: move all settings to your plist file as you did years ago and rename it to any+info.plist
step 2: after adding your any+info.plist file to project, delete it from 'Build phase copy bundle'
step 3: search build setting and make ALL "Generate info.plist" to NO
step 4: search 'Infor.plist File' and give the correct file path of you file
step 5: use this run script
#!/bin/bash

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
step 6: leave a real number in your plist as the bundle version e.g.100
step 7: clean build folder, restart Xcode 14, and build the project
Good Luck!
Comment: I am using similar versioning script, but recently the Build (number) in the Xcode targets - General tab is not showing the correct CFBundleVersion variable. The script is still working and the info.plist file is changing as before, but the Build in the General tab is not changing. It seems it is using the Build setting Current project version data now, but it is not reflected in the info.plist file.


Como evitar redundância de código nesses dois métodos sendo que um possui um parâmetro IEnumerable<> e outro não?

Question: Como eu posso simplificar esses dois métodos de forma a impedir repetição de código?
Método 1, com a primeira expressão tendo uma propriedade genérica do tipo IEnumerable<>:
public GenericDAO<TModel> LeftJoin<TProperty>(
    Expression<Func<TModel, IEnumerable<TProperty>>> joinMember,
    Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    var joinMemberMetadata = new Mapping.MapperClass<TProperty>().DoMapper();
    var joinMemberExpression = joinMember.Body as dynamic;
    var filterExpression = filter as dynamic;

    var paramThisModel = filterExpression.Parameters[0].ToString();
    var paramJoinMember = filterExpression.Parameters[1].ToString();

    _query = _query.Trim() + " left join " + joinMemberMetadata.TableName + " as " +
        joinMemberExpression.Member.Name + " on ";

    _query += filterExpression.Body.ToString()
        .Replace(paramThisModel, _metadataOfClass.TableName)
        .Replace(paramJoinMember, joinMemberExpression.Member.Name)
        .Replace("==", "=")
        .Replace("&&", "and");

    return this;
}

Com esse método eu posso utilizar expressão lambda em uma propriedade de tipo lista, assim:
libroDAO.Query().LeftJoin(livro => livro.Autores, ...)

Método 2, a primeira expressão desse método já não possui o IEnumerable<>:
public GenericDAO<TModel> LeftJoin<TProperty>(Expression<Func<TModel, TProperty>>
    joinMember, Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    var joinMemberMetadata = new Mapping.MapperClass<TProperty>().DoMapper();
    var joinMemberExpression = joinMember.Body as dynamic;
    var filterExpression = filter as dynamic;

    var paramThisModel = filterExpression.Parameters[0].ToString();
    var paramJoinMember = filterExpression.Parameters[1].ToString();

    _query = _query.Trim() + " left join " + joinMemberMetadata.TableName + " as " +
        joinMemberExpression.Member.Name + " on ";

    _query += filterExpression.Body.ToString()
        .Replace(paramThisModel, _metadataOfClass.TableName)
        .Replace(paramJoinMember, joinMemberExpression.Member.Name)
        .Replace("==", "=")
        .Replace("&&", "and");

    return this;
}

Com esse método eu posso fazer a mesma coisa para propriedades de classes simples:
livroDAO.Query().LeftJoin(livro => livro.Editora, ...)

Answer: O parâmetro joinMember e os parametro genérico TProperty só são usados nas primeiras duas linhas de ambos os métodos. Então podemos extrair todas as outras linhas para um método comum.
public GenericDAO<TModel> LeftJoin<TProperty>(
    Expression<Func<TModel, IEnumerable<TProperty>>> joinMember,
    Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    var joinMemberMetadata = new Mapping.MapperClass<TProperty>().DoMapper();
    var joinMemberExpression = joinMember.Body as dynamic;

    LeftJoin(joinMemberMetadata, joinMemberExpression, filter);
}

public GenericDAO<TModel> LeftJoin<TProperty>(Expression<Func<TModel, TProperty>>
    joinMember, Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    var joinMemberMetadata = new Mapping.MapperClass<TProperty>().DoMapper();
    var joinMemberExpression = joinMember.Body as dynamic;

    LeftJoin(joinMemberMetadata, joinMemberExpression, filter);
}

private GenericDAO<TModel> LeftJoin<TProperty>(
    Mapper<TProperty> joinMemberMetadata, //Nota: eu nao sei qual e' o tipo retornado por .DoMapper
    dynamic joinMemberExpression,
    Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    var filterExpression = filter as dynamic;

    var paramThisModel = filterExpression.Parameters[0].ToString();
    var paramJoinMember = filterExpression.Parameters[1].ToString();

    _query = _query.Trim() + " left join " + joinMemberMetadata.TableName + " as " +
        joinMemberExpression.Member.Name + " on ";

    _query += filterExpression.Body.ToString()
        .Replace(paramThisModel, _metadataOfClass.TableName)
        .Replace(paramJoinMember, joinMemberExpression.Member.Name)
        .Replace("==", "=")
        .Replace("&&", "and");

    return this;
}

Answer: public GenericDAO<TModel> LeftJoin<TProperty>(Expression<Func<TModel, TProperty>>
    joinMember, Expression<Func<TProperty, TModel, bool>> filter)
    where TProperty : class
{
    return LeftJoin(_ => new List<TProperty> { joinMember }, filter);
}

Isso não funciona:

Error 1   The best overloaded Add method 'System.Collections.Generic.List.Add(TProperty)' for the collection initializer has some invalid arguments    D:\Projects\GenericDAO\GenericDAO\GenericDAO.cs 125 56  GenericDAO
Error 2   Argument 1: cannot convert from 'System.Linq.Expressions.Expression>' to 'TProperty'  D:\Projects\GenericDAO\GenericDAO\GenericDAO.cs 125 56  GenericDAO

Já isso funciona:
return LeftJoin(x => new List<TProperty>(), filter);

Desculpem, não sou cadastrado e por isso não posso positivar respostas boas e nem negativar respostas ruins, muito menos aprovar uma resposta aceita.
Comment: E porque não se cadastrar? É tão fácil, nem precisa preencher nenhum cadastro.


Failing to obtain $\chi^2(1)$ asymptotic distribution under $H_0$ in a likelihood ratio test: example 1

Question: I have a large sample (a vector) $\mathbf{x}$ from a random variable $X\sim N(\mu,\sigma^2)$. The variance $\sigma^2$ is known, but the expectation $\mu$ is unknown. I would like to test the null hypothesis $H_0\colon \ \mu=0$ against the alternative $H_1\colon \ \mu>0$ using a likelihood ratio (LR) test. The test statistic is
$$
\text{LR}=-2\ln\frac{L(\mathbf{x}\mid 0,\sigma^2)}{L(\mathbf{x}\mid\hat\mu,\sigma^2)}.
$$
where $\hat\mu$ is the estimate of $\mu$ under $H_0 \cup H_1$ (thus $\hat\mu\geq0$).
I expected the asymptotic distribution of $\text{LR}$ under $H_0$ to be $\chi^2(1)$ but I am getting something else in a simulation below.
Questions: Why is that? Is my simulation wrong? Or is the test statistic not supposed to have the $\chi^2(1)$ asymptotic distribution under $H_0$, and if so, why?

(Related question: "Failing to obtain $\chi^2(1)$ asymptotic distribution under $H_0$ in a likelihood ratio test: example 2")

<code>n=3e3   # sample size
sigma=1 # standard deviation of X
m=3e3   # number of simulation runs

logL0s=logL1s=logLRs=rep(NA,m)
for(i in 1:m){
 set.seed(i); x=rnorm(n,mean=0,sd=sigma)
 logL0=sum(log( dnorm(x,mean=0,sd=sigma) ))
 logL1=sum(log( dnorm(x,mean=max(0,mean(x)),sd=sigma) ))
 logLR =-2*(logL0-max(logL0,logL1)) # the -2*ln(LR) statistic from this simulation run
 logL0s[i]=logL0; logL1s[i]=logL1; logLRs[i]=logLR
}

# Critical values: asymptotic nominal vs. empirical
crit.val=qchisq(p=0.95,df=1)
empirical.crit.val=quantile(x=logLRs,probs=0.95)
print(paste0("Asymptotic critical value = ",round(crit.val,2),", simulated critical value = ",round(empirical.crit.val,2)))

# Test size: asymptotic nominal vs. empirical
empirical.size=length(which( logLRs > crit.val ))/m # proportion of rejections at 0.05 level
print(paste0("Nominal test size = 0.050, simulated test size = ",round(empirical.size,3)))

# Plots illustrating the sampling distribution of -2*log(LR) statistic
par(mfrow=c(2,2),mar=c(2,2,2,1))
 plot(logLRs,main="Scatterplot of -2ln(LR) across simulation runs")
  abline(h=crit.val,col="red")
  abline(h=empirical.crit.val,col="blue")
 plot(NA)
 plot(density(logLRs),main="Density of -2ln(LR)")
  chisq.quantiles=qchisq(p=seq(from=0.001,to=0.999,by=0.001),df=1)
  chisq.density=dchisq(x=chisq.quantiles,df=1)
  lines(y=chisq.density,x=chisq.quantiles,col="blue",lty="dashed")      # Chi^2(1) overlay
  abline(v=crit.val,col="red")                                          # asympt. nominal crit. val. in red
  abline(v=empirical.crit.val,col="blue")                               # empirical crit. val. in blue
 br=24
 hist(logLRs,breaks=br,main="Histogram of -2ln(LR)")
  lines(y=chisq.density*m/br,x=chisq.quantiles,col="blue",lty="dashed") # Chi^2(1) overlay
  abline(v=crit.val,col="red")                                          # asympt. nominal crit. val. in red
  abline(v=empirical.crit.val,col="blue")                               # empirical crit. val. in blue
par(mfrow=c(1,1))
</code>
Comment: Related: ["Asymptotic null distribution of the LR statistic with point null and point alternative"](https://stats.stackexchange.com/questions/506750).
Comment: Related: ["What are the regularity conditions for Likelihood Ratio test"](https://stats.stackexchange.com/questions/101520).
Comment: You are on the boundary of the parameter space: the result you are relying on doesn't hold in such cases.  Typically the distribution of the LR is a mixture of chi-squared distributions.
Comment: @whuber, thank you so much! I was suspecting it, but I got confused about the definition of the parameter space. Is the parameter space defined by $H_0 \cup H_1$, so in my case, $\mu\in [0,\infty)$?
Comment: Yes: this became clear to me when I saw you force $\hat\mu$ to be non-negative in your code at `max(0,mean(x))`.
Comment: @whuber, well, I was just trying to follow the definition of the LR statistic. Should I have used unrestricted estimation instead? I think that would be at odds with the definition of the denominator in the LR formula.
Answer: Apparently the test statistic not supposed to have the $\chi^2(1)$ asymptotic distribution under $H_0$. Thanks to @whuber for pointing this out.
The example violates an assumption for the distribution to be $\chi^2(1)$. The assumption is that the parameter of interest in not on the boundary of the parameter space. I am not entirely sure how the parameter space is defined, but it seems it is defined by $H_0\cup H_1$. In my case this would mean $\mu\in [0,\infty)$. Now $\mu=0$ due to $H_0$ is on the boundary of $[0,\infty)$, so that constitutes a violation.


Does in this case exist necessarely an eigenvalue equal to $0$?

Question: I pasted more than I refer, hoping to be more clear.
Look at the claim of the theorem: it states we can change coordinates untill we reach a "good" form for the equation of $r$, which defines the hypersurface $M$.
So let's consider the equation
$$
r=y_1+\sum_{j=2}^{s^++1}|z_j|^2-\sum_{j=s^++2}^{s^++s^-+1}|z_j|^2 + o^2(x_1,z')
$$
if we take the Levi form of $r$ around $0$, looking at the previous equation, we MUST have an eigenvalue equal to $0$.
Do you agree? It seems a little bit strange: we are saying that the Levi form of every $r:\Bbb C^n\to\Bbb R$ twice differentiable has at least one eigenvalue equal to zero. Taking $r=|z_1|^2+\cdots+|z_n|^2$ we'd have all the eigenvalues equal to $1$. No eigenvalue vanishes.
Where is the problem?
Comment: The Levi form is defined as the complex Hessian of a defining function restricted to the complex tangent hyperplane, i.e. to a space of dim $n-1$. So, if you start with a (Levi)convex hypersurface and you write it locally as $y_1=Q+hot$ around the origin, the Levi form in the origin will be restricted to the hyperplane $z_1=0$ (the vanishing direction you were complaining about)
Comment: @wisefool: many thanks. Write your comment (just paste it) as an answer;  I'd be happy to put your answer as good.
Answer: The Levi form is defined as
$$L_M(z)=L_r(z)\vert_{T^{\mathbb{C}}_zM}$$
i.e. as the complex hessian of $r$ restricted to the maximal complex subspace of the tangent to $M$.
If you put $M$ in the form
$$y_1=Q(z_2,\ldots, z_n)+h.o.t.$$
locally around $0$, then the tangent hyperplane in $0$ is $y_1=0$, so the complex tangent is $z_1=0$, i.e.
$$T^{\mathbb{C}}_0M=\mathrm{Span}\{\partial_{z_2}, \ldots, \partial_{z_n}\}\;.$$
If you denote by $A$ the matrix associated with the quadratic form $Q$, then
$$L_r(0)=\begin{pmatrix}0&0&\cdots& 0\\0& &  &\\\vdots& &A& \\0& & & \end{pmatrix}$$
with respect to the basis $\{\partial_{z_1},\ldots, \partial_{z_n}\}$ of $T_0\mathbb{C}^n$. Now, if you restrict this to $T^{\mathbb{C}}_0M$, you obtain the $(n-1)\times(n-1)$ matrix $A$, which is $L_M(0)$.
If $Q$ was positive definite, then so it is $L_M(0)$. The direction of the $0$ eigenvector is precisely the one you get rid of when restricting to the maximal complex subspace of $T_0M$.


javax.servlet.ServletException: java.lang.ExceptionInInitializerErro

Question: Eu estou tentando criar meu primeiro projeto usando JPA, uso o Jboss 5, Oracle, Hibernate e primefaces. Depois de fazer o deploy do projeto eu tento criar e inseir um novo cliente no banco através da interface web, mas estou recebendo o seguinte erro:
   exception

javax.servlet.ServletException: java.lang.ExceptionInInitializerError
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

root cause

javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

root cause

java.lang.ExceptionInInitializerError
    Beans.ClienteBean.insertPedido(ClienteBean.java:27)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.el.parser.AstValue.invoke(AstValue.java:170)
    org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

root cause

javax.persistence.PersistenceException: [PersistenceUnit: MC] Unable to build EntityManagerFactory
    org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:677)
    org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
    com.bd.JpaUtil.<clinit>(JpaUtil.java:10)
    Beans.ClienteBean.insertPedido(ClienteBean.java:27)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.el.parser.AstValue.invoke(AstValue.java:170)
    org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

root cause

org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
    org.hibernate.cache.impl.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:79)
    org.hibernate.cache.UpdateTimestampsCache.<init>(UpdateTimestampsCache.java:58)
    org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:369)
    org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
    org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
    com.bd.JpaUtil.<clinit>(JpaUtil.java:10)
    Beans.ClienteBean.insertPedido(ClienteBean.java:27)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.el.parser.AstValue.invoke(AstValue.java:170)
    org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lif`enter code here`ecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96

Meu persistence.xml:
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="MC" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>jdbc/gt</jta-data-source>
    <non-jta-data-source>jdbc/gt</non-jta-data-source>
    <properties>
        <property name="hibernate.transaction.manager_lookup_class"
            value="org.hibernate.transaction.JBossTransactionManagerLookup" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle8iDialect" />
        <property name="hibernate.show_sql" value="false" />
        <property name="hibernate.cache.use_second_level_cache"
            value="true" />
        <property name="hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.format_sql" value="false" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>
</persistence-unit>

ClienteBean:
package Beans;

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

import javax.faces.bean.ManagedBean;
import javax.persistence.EntityManager;

import com.bd.Cliente;
import com.bd.JpaUtil;

import Repository.ClienteRepository;

@ManagedBean(name = "ClienteBean")
public class ClienteBean implements Serializable {

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

    private Cliente cliente = new Cliente();
    private static List<Cliente> listaClientes;

    public void insertPedido() {
        System.out.println(cliente);
        EntityManager manager = JpaUtil.getEntityManager();
        ClienteRepository.insertCliente(cliente, manager);
    }

    public void updatePedido() {
        ClienteRepository.updateCliente(cliente);
    }

    public void delete() {
        ClienteRepository.delete(cliente);
    }

    public void todosNomes() {
        listaClientes = ClienteRepository.todosNomes();
    }

    public void todosClientes() {
        listaClientes = ClienteRepository.todos();
    }

    public void consutaPorId(int id) {
        cliente = ClienteRepository.consultaCliente(id);
    }

    public static void consultaPorCpf(Cliente cliente) {
        listaClientes = ClienteRepository.consultaPorCpf(cliente);
    }

    public static void consultaPorNome(Cliente cliente) {
        listaClientes = ClienteRepository.consultaPorNome(cliente);
    }

public Cliente getCliente() {
        return cliente;
    }

    public List<Cliente> getListaClientes() {
        return listaClientes;
    }

}

ClienteRepository:
package Repository;

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

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.TransactionScoped;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import com.bd.Cliente;

public class ClienteRepository implements Serializable {

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

    private static EntityManager manager;
    static EntityTransaction trx;

    public static void setManager(EntityManager manager) {
        ClienteRepository.manager = manager;
        trx = manager.getTransaction();
    }

    public static void insertCliente(Cliente cliente) {

        trx.begin();

        manager.persist(cliente);

        trx.commit();
    }

    public static void updateCliente(Cliente cliente) {

        Cliente resultado = new Cliente();

        trx.begin();

        if (cliente == null)
            return;

        resultado = consultaCliente(cliente.getId());
        if (!cliente.getCpf().equals(""))
            resultado.setCpf(cliente.getCpf());
        if (!cliente.getNome().equals(""))
            resultado.setNome(cliente.getNome());
        if (!cliente.getRg().equals(""))
            resultado.setRg(cliente.getNome());

        manager.merge(resultado);

        trx.commit();

    }

    public static void delete(Cliente cliente) {

        cliente = consultaCliente(cliente.getId());

        trx.begin();

        manager.remove(cliente);

        trx.commit();
    }

    public static Cliente consultaCliente(int id) {
        Cliente resultado = manager.find(Cliente.class, id);
        return resultado;
    }

    public static List<Cliente> consultaPorCpf(Cliente cliente) {
        Query query = manager.createNamedQuery("Cliente.buscaPorCpf");
        query.setParameter("cpf", cliente.getCpf());
        return query.getResultList();
    }

    public static List<Cliente> todosNomes() {
        Query query = manager.createNamedQuery("Cliente.todosNomes");
        return query.getResultList();
    }

    public static List<Cliente> todos() {
        Query query = manager.createNamedQuery("Cliente.todos");
        return query.getResultList();
    }

    public static List<Cliente> consultaPorNome(Cliente cliente) {
        Query query = manager.createNamedQuery("Cliente.buscaPorNome");
        query.setParameter("nome", cliente.getNome());
        return query.getResultList();
    }

}

JpaUtil:
package com.bd;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JpaUtil {
    private static EntityManagerFactory factory;
    static {
        factory = Persistence.createEntityManagerFactory("MC");
    }

    public static EntityManager getEntityManager() {
        return factory.createEntityManager();
    }
}

Desde já agradeço qualquer ajuda!
Comment: Seu ManagedBean não tem `setCliente(Cliente cliente)`?
Answer: Adicione o seguinte parâmetro no seu persistence.xml
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>

Isso forçará o hibernate a usar o EhCache
Answer: Obrigado pela resposta!
Acrescentei o parâmetro no meu persistence e o erro mudou:
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.EhCacheProvider from BaseClassLoader@c3567a8{VFSClassLoaderPolicy@3b1f875f{name=vfsfile:/C:/jboss-5.1.0.GA/server/default/conf/jboss-service.xml domain=ClassLoaderDomain@2059d6e6{name=DefaultDomain parentPolicy=BEFORE parent=org.jboss.bootstrap.NoAnnotationURLClassLoader@3852865d} roots=[MemoryContextHandler@1054138533[path= context=vfsmemory://5c4o1k2u-5tiakz-j586yqxg-1-j586ysxn-7 real=vfsmemory://5c4o1k2u-5tiakz-j586yqxg-1-j586ysxn-7], DelegatingHandler@1593530820[path=ojdbc14.jar context=file:/C:/jboss-5.1.0.GA/server/default/lib/ real=file:/C:/jboss-5.1.0.GA/server/default/lib/ojdbc14.jar], DelegatingHandler@2035576212[path=antlr.jar context=file:/C:/jboss-5.1.0.GA/common/lib/ real=file:/C:/jboss-5.1.0.GA/common/lib/antlr.jar], **...**  org.jboss.wsf.common.concurrent, org.jboss.ejb.plugins.cmp.jdbc.bridge, javax.ejb] <IMPORT-ALL>NON_EMPTY}}
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:448)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:123)
at org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.<init>(RegionFactoryCacheProviderBridge.java:63)
... 64 more

DEPLOYMENTS IN ERROR:
  Deployment "persistence.unit:unitName=#MC" is in error due to the following reason(s): java.lang.ClassNotFoundException: org.hibernate.cache.EhCacheProvider from BaseClassLoader@c3567a8{VFSClassLoaderPolicy@3b1f875f{name=vfsfile:/C:/jboss-5.1.0.GA/server/default/conf/jboss-service.xml **...**
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:993)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:939)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:873)
    at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.checkComplete(MainDeployerAdapter.java:128)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:369)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Também coloquei o setCliente(Cliente cliente) no ManagedBean que havia esquecido.


Fundamental group of some spaces

Question: Which is the fundamental group of:
a) $X=\{(x,y,z) \in \mathbb{R}^3: \, x^2+y^2-z^2=0, z>0\}$;
b) A cylinder minus a point;
c) A triangle with the three vertices identified.
My answers are:
$a) \pi_1(X)=(0)$,
$b) \mathbb{Z}$,
$c) \mathbb{Z}*\mathbb{Z}*\mathbb{Z}$;
but I need a formal proof. Can you help me?
Answer: I am sorry that you are right, $X*I$ is a cylinder, it is $CX=X*I/X*{1}$, a quotient topology space. The top point is its retract, so the fundamental group is trivial (also its first homology group trivial).

Fundamental group of some spaces


Bit String evaltuation?

Question: Im trying to figure out what this question is trying to find?
Evaluate:
(01011^11001)v 01110 =?
(11011 v 01010) ^ (10001 v 11011) = ?
Initially i said the first one was False, and the second was true, but that was incorrect
Answer: It looks like what you're supposed to do here is bit string flicking; you should perform bitwise operations on each pair of strings, and your result should be a string of the same length as one of your input. I'll do the first for you, and hopefully you'll be able to get the second by yourself.
I am a little confused by your notation here; in C++, the caret means "exclusive or", but judging by the context, I'll assume that ^ is and and v is or, though the standard notations for each are & and | respectively.
01011 ^ 11001 means you look at both strings at each index and perform the logical operator on the two values. Here, we have "and", which gives true, or 1, if both values are true, and 0 otherwise. In the first place, we have 0 & 1 = 0. Next, we have 1 & 1 = 1, and then 0 & 0 = 0. Continuing in this fashion, we get 01001. This can be seen as showing where they both have 1, and 0 everywhere else.
Next, we have 01001 v 01110. Here, the operation is "or", which gives false, or 0, if both values are false, and 1 otherwise. In the first place, we have 0 & 0 =0. Next, we have 1 & 1 = 1, and then 0 & 1 = 1. Continuing in this fashion, we get 01111. This can be seen as showing where they both have 0, and 1 everywhere else.
Thus, the answer to the first should be 01111.
Answer: It usually means bitwise operation in the context of computer programming, for example $(01001\wedge11001)\vee01110=01001\vee01110=01111$.

Bit String evaltuation?


Array[] em banco de dados, como criar e manipular?

Question: Eu possuo um array de inteiros, um int[].
É possível salvá-lo diretamente no banco de dados sem precisar Serializar? Como por exemplo:
CREATE TABLE teste(
    numeros integer[]
);

E depois usar SELECT numeros FROM teste? Pesquisei e não achei muita informação sobre isso principalmente em Java, a maioria é tudo em PHP.
É recomendado fazer isso? Ou é melhor serializar?
Comment: Você pode usar o tipo JSON e salvar nesse formato, salvar como string no formato que quiser, por exemplo, CSV, ou criar uma tabela números e adicionar uma linha pra cada número referenciado a tabela original
Comment: Acho que salvar me JSON seria valido também, embora eu não estivesse afim de usar JSON eu acho que isso também é valido, acho que vou seguir a dica do Maniero e vou serializar mesmo.
Comment: QUe caminho você foi?
Comment: Eu optei por salvar em `Text` no banco de dados, usei `StringJoiner` pra formatar no java e depois transformei em `String` pra salvar no banco de dados. Na hora de obter os dados de volta do banco eu uso a função `split`, funciona tudo perfeitamente sem erros e esta bem otimizado.
Answer: Só no PostgreSQL (entre os mais conhecidos) pode fazer isso e mesmo assim passará por alguma adaptação antes de gravar ou recuperar informação. Em qualquer outro banco de dados terá que criar um mecanismo próprio de manipulação de gravação e recuperação de dados no banco de dados.
O mais comum é fazer isso via VARCHAR onde você definirá um formato onde terá os dados (JSON é só um exemplo), podendo usar um separador, um tamanho padrão ou outra forma, que no fundo é uma forma de serializar, seja por texto ou binário. Se for fazer binário é melhor usar um BLOB.
Coloquei no GitHub para referência futura.
Comment: então o objeto to tipo `Array` do `java.sql` serve apenas para o PostgreSQL? Tava dando uma olhada na documentação do Java e encontrei isso, porém ao olhar na documentação do MySQL não achei nada falando sobre. (por isso resolvi criar o tópico)
Comment: Para criar o Array `connection.createArrayOf(typeName, elements)` e para resgatar o Array `resultSet.getArray(columnLabel)`
Comment: Não sei o que é `java.sql` e sua pergunta não o cita.
Comment: `java.sql` é a package da classe `Array`


How to make Auto Layout for Universal App

Question: I'm now doing an universal app; I faced a problems on auto layout; I need to make two views with same size on all devices; I worked on storyboard with view wAny hAny; and here the images I reach
The problem on iPad the bottom view it's very big and I need these two vies almost same height like on the attached photo for iPhone-4inch
The following photos shown my constrains
The following for top view

and the following for bottom view

if i do equal height there's the photo

and herewith the constrains

and here the output

here the modification as you see iPad is problem
bottom view
Answer: On the upper view set left right and top constraint, on the lower view set bottom, equal width, align leading and equal Heights. Set vertial spacing between both views.
Comment: the problem on iPad; coz big view; not matching with these constrains; if i can do anything special for iPad ; advice
Answer: If you want the two views to be the same height, give them an equal height constraint, and eliminate the constraint between the bottom view and the top of the superview. You make an equal height constraint by selecting both views and choosing "Equal Heights" from the pin menu. If you want them to not be exactly equal, you can edit that constraint to change the multiplier value to whatever you want.
Comment: i do this but it's not success; if you know special constrain to give for iPad only; coz the main problem on iPad; moreover if i do equal height for both views the bottom view on iPad the height will be more than the upper view
Comment: @user3143330, If you give them equal heights, they will be equal -- if you're not seeing that, then you're doing something wrong. I can't tell what without seeing what you did.
Comment: i make edit for my question; please check and tell me
Comment: The top view should not have a constraint to the bottom of the super view. The top view should have a constraint to the top of the superview, the bottom view should have one to the bottom of the superview, and there should be a space constraint between the two views. Other than the equal height constraint, there should not be any other vertical constraints. You also need to edit the equal height constraint so the multiplier is 1.
Comment: the problem on iPad coz iPad have a big screen; these constrain not matching with iPad; if you know a good tutorial for auto layout for universal app; please advice
Comment: @user3143330 The problem has nothing to to with the iPad. If you add the correct constraints, as I outlined, your views will be equal heights. You should edit your question again to show your latest attempt. There are 3 videos from the WWDC 2012 on auto layout. you should watch those.
Comment: ok; i'll edit my question with the result; can you wait a moment
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79589/discussion-between-user3143330-and-rdelmar).


Continuity for a nonlinear functional

Question: I'd like to check the continuity for the nonlinear  functional $T: (C^{0}([0,1],\Vert \cdot \Vert_{\infty}) \rightarrow  (C^{0}([0,1],\Vert \cdot \Vert_{\infty}) $ , with $T(f)(x)=\arctan(f(x))$.
I need to show that for $f_n \rightarrow f$ in infinity norm, then $T(f_n) \rightarrow T(f)$, also in infinity norm.
So, I need to compute $\sup_{x \in [0,1]} | \arctan(f(x))- \arctan(f_k(x))|$, and I want to show it goes to zero, but how can I compute it formally?
Answer: $|arctan (a) -arctan (b)| \leq |a-b|$ by MVT so $Tf_n \to Tf$ uniformly.
Comment: The conclusion is clear, but I don't understand why that inequality comes from the mean value theorem !
Comment: @VoB $arctan (a)-arctan (b)=(a-b) \frac 1 {1+x^{2}}$ for some $x$ between $a$ and $b$. Note that $\frac 1 {1+x^{2}} \leq 1$.
Comment: Perfect, it's clear ! One last question: how am I using continuity in $[0,1]$ here?
In order to apply MVT I see that $x \mapsto \arctan(x)$ satisfies the hypothesis of MVT. But where can I use the continuity of $f$?
Comment: MVT is applied for arctan on the real line. It has nothing to do with $f$. After you get the inequality you just replace $a$ by $f(x)$ and $b$ by $f(y)$

Continuity for a nonlinear functional


Criar RadioGroup baseado em seleção de ComboBox utilizando INI, dinamicamente em Delphi

Question: Contexto:
Com a utilização de uma aplicativo pessoal feito em delphi-7, fui adicionando novas ações conforme necessidade em um TRadioGroup, porém agora contém muitos itens (16), prejudicando a usabilidade da aplicação.
O que eu queria fazer seria categorizar esse itens do TRadioGroup em um TComboBox, assim teria algumas categorias e o TRadioGroup ficaria com
menos opções, assim melhorando a disposição visual e facilitando a escolha.
Necessidade:
Criar um TComboBox dinamicamente baseado em um arquivo .ini, como se
fosse uma configuração para carregamento do `TComboBox, seria mais ou menos assim:
[CATEGORIA]
0=CATEGORIA1
1=CATEGORIA2
2=CATEGORIA3

Com a categoria definida e carregando no TComboBox então carregar os itens do TRadioGroup com base no grupo, um .ini, mais ou menos assim, pensei:
[CATEGORIA_1]
0=ITEM1
1=ITEM2

[CATEGORIA_2]
0=ITEM1
1=ITEM2
2=ITEM3
3=ITEM4
4=ITEM5

[CATEGORIA_3]
0=ITEM1
1=ITEM2
2=ITEM3

Atualmente meu código utilizando o INI é somente para salvar a ultima opção selecionada, e ao reabrir o programa já trazer:
.INI
[CONFIG]
INDEXGROUP=1

Procedure SalvarINI:
procedure SalvarINI;
var
   vlIni: TIniFile;
begin
  try
    vlIni := TIniFile.Create(ExtractFileDir(Application.ExeName) +'\'+ ExtractFileName(Application.ExeName)+'.ini');
    try
      vlIni.WriteInteger('CONFIG', 'INDEXGROUP',rgItens.ItemIndex);

      vlIni.UpdateFile;
    finally
      vlIni.Free;
    end;
  except
    on e: exception do
    begin
      ShowMessage('Ops..não conseguimos Salvar as configurações: '+ e.Message);
    end;
  end;
end;

carregarINI
procedure carregarIni;
var
  vlIni: TIniFile;
begin
  vlIni := TIniFile.Create(ExtractFileDir(Application.ExeName) +'\'+ ExtractFileName(Application.ExeName)+'.ini');

  try
    RGProduto.ItemIndex := vlIni.ReadInteger('CONFIG' ,'INDEXGROUP',1);
  finally
    FreeAndNil(vlIni);
  end;
end;

Obrigado
Answer: Para resolver o problema, deveria ter uma forma de carregar os TComboBox assim com base no .ini já criado:
[CATEGORIA]
0=CATEGORIA1
1=CATEGORIA2
2=CATEGORIA3

Um for resolveria, mas para cada categoria deveria carregar o seu itens, então sendo necessário mais um for. Mudei um pouco o .ini dos itens para ficar mais fácil o algoritmo:
[CATEGORIA_1]
0ITEM=DESCRICAOITEM0CAT1
1ITEM=DESCRICAOITEM1CAT1

[CATEGORIA_2]
0ITEM=DESCRICAOITEM0CAT2
1ITEM=DESCRICAOITEM1CAT2
2ITEM=DESCRICAOITEM1CAT2

[CATEGORIA_3]
0ITEM=DESCRICAOITEM0CAT3
1ITEM=DESCRICAOITEM1CAT3
2ITEM=DESCRICAOITEM2CAT3

Então criei um procedimento para resolver isso dinamicamente:
procedure TFormF.carregaRadioGroup;
var
  i,j : Integer;
  strValGrupo,
  strProdutos : TStringList;
  vlCopy : String;
  vlGrupoProduto : String;
  count : integer;
  LIni: TIniFile;
begin

  strValGrupo := TStringList.Create;
  strProdutos := TStringList.Create;

  try
    rgDinamicoProduto.Items.Clear;
    LIni := TIniFile.Create(ExtractFileDir(Application.ExeName) +'\'+ ExtractFileName(Application.ExeName)+'.ini');

    if LIni.SectionExists('CATEGORIA') then
    begin
      LIni.ReadSection('CATEGORIA',strValGrupo);

      for i:=1 to strValGrupo.Count do
      begin
        vlGrupoProduto := 'CATEGORIA_'+IntToStr(i-1);

        if LIni.SectionExists(vlGrupoProduto) then
        begin
          LIni.ReadSection(vlGrupoProduto, strProdutos);

          if (cbGrupo.ItemIndex = i-1) then
          begin
            count := trunc(strProdutos.Count/3);
            for j:=1 to (count) do
            begin
              rgDinamicoProduto.Items.Add(LIni.Readstring(vlGrupoProduto, IntToStr(J-1)+'ITEM',''));
            end;
          end;
        end;
      end;
    end;
  finally
    FreeAndNil(LIni);
  end;
end;

O problema foi resolvido, mas o que vocês acham da solução?


How do I populate form fields on a page from a database based on the page url?

Question: Hello first I'd like to say, please excuse my ignorance to this all, as I'm very new to this all.  I just started and still trying to understand this.
So far I have a database set up and I'm trying to retrieve values from a database to fill in a form on a page when it loads.  The record or row/values that need to be retrieved from a database depend on the page's URL.
I'm ok with html and css but still trying to learn more about jquery, JavaScript, sql, php and so on and so forth.  I realize I have a ways to go and honestly some of the guides and tutorials online are kind of confusing because everyone has a different way of coding.  So I'm a bit confused.
I've included a simple chart to breakdown what I'm trying to do.

If someone could point me in the right direction I'd be really grateful! Thanks.
Comment: Do you have some way to tell witch keys need to be associated with witch page?
Comment: A similar one,http://stackoverflow.com/questions/15733454/populating-select-field-from-database
Comment: I dont thats why im trying to go by the page url if thats even possible
Comment: Well, how do **you** know, what data should be put there?
Comment: i guess thats what I'm trying to really figure out
Comment: When you find out, what data should go to what page, then add an extra id field in your database ( like page ID or something ) and after that you can fetch the fields by the received id.
Answer: If I understand you well, you want to setup a form and populate some fields of this form with a query forms a database, the primary key of the record being relative to the url.
The first step is to build the url, you can pass some parameters to an url by adding a ? at the end of the url followed by the parameter name, the = sign and the parameter value. If you have more than one parameter, you should separate each parameter with the sign &.
So your url could be something like this :
www.examplesite.com/page&.html?key=key_A1
Then, you'll have to choose if you want to build the page on the server side with a language like php, in which case you retrieve the parameter, query the database, build the html form and send it to the client.
You can also go client side with plain javascript or jquery, in which case you will still have to do some server side programming to query the database but will use an ajax call to get the data and will populate the fields in Javascript or JQuery.
Answer: You can do this using Javscript(using Ajax)

U need the key to search for get the results from database
Using ajax call get the data, You might have to write code to get the details from database  using any server side prog language
Using javascript to fill the form input with the received data.

Google for jquery ajax examples, and how to populate input using javascript.
There are many frameworks out there that have DataBinding built-in that do the same job a lot easier.  My favourite would be Angular Js, you can try Ember and lot more out there, choose the one you feel comfortable with.


validate correctness of prediction

Question: I have two datasets. 1st contains original data. 2nd contains predicted data. I want to count how well the prediction was. I was assuming following algorithm:

Calculate absolute difference between original and prediction
Divide this absolute difference by largest number found in original dataset
The result should be numbers from 0 to 1 where 1 represents worst prediction and 0 best

e.g:
<code>O;P;ERR
10;0;1
10;5;0.5
3;7;0.4
9;1;0.8
</code>
Is this correct approach or is there any better methods? Thank you very much.
Comment: I've mostly seen mean squared error or mean absolute deviation as the main accuracy metrics.
Answer: Without knowing anything else about your data (like the scale of the variables), I think that's a perfectly fine way to do it. It constitutes a simple rescaling of absolute error, which is a common error metric. Another common choice is squared error, which differs from absolute error in that it penalizes larger differences more harshly.

validate correctness of prediction


Can anyone specify what kind of function can be used in this case?

Question: I have some data as shown in the figure, and I just want to collapse all the 4 curves into a single curve.
The 4 curves correspond to 4 different values $a$ mentioned in the legend.
I think the best way may be is to multiply the $y$ values with an expression which is a function of both $a$ and $x$ to get $y = 1$ in all the 4 curves.
For this, I can multiply the purple and green curves with something like $(1/a)^{f(x)}$. But this function is proving good for the purple curve and not the green one.
Moreover, when I use this for the blue and red curves too, their values shoot up a lot.
So I am thinking how best to collapse the curves using a single function, $f(a,x)$ which on multiplying with the purple and green curves give 1, and on multiplying with the red and blue curves do not change its value.
I tried some exponential functions, but I am not quite getting any success.
Any solution to this or advice?
Answer: Except for a=0.25,
all the curves
look pretty linear.
You might try
a standard linear least squares fit
of each data set
to get
y = mx+b
and see what
m and b look like
as functions of a.
Do you have a model
of what the curves should look like?
If you do,
I think you should
try to fit that type of curve
to each data set.


Python django, is possible to present the output of a view directly in a html template?

Question: Let's suppose you have a django project, the response of one of its views is an image, if you want to insert that image inside an HTML document you do:

Then, when the user open the Webpage that return that HTML document he will see the image. Nothing new at this point.
Now, what happens if the response of that "view" is not an image but a simple text, there is no HTML tag to embed a simple text, so, how would you do it?
The view code that return a simple text is:
from django.http import HttpResponse

def view(request):
    return HttpResponse('Simple line of text returned by my view')

So, what I would like to do in my html is something like this:

The exit of the view was: <?HTML_TAG? src="/path_to_my_view/">

Or something like this (using Django template language):

The exit of the view was: {{ MyProjectApp.view }}

But I have not found any one of those alternatives yet.
The current solution to the problem is by using the object HTML tag:
<object width="400" height="400" data="/path_to_my_view/"></object>

However I'm not happy with this solution, it seems like using a cannon to kill a bug, I think that I'm missing something.
Thank you for your support!
Answer: I think you are looking for an , which is the way of embedding one HTML document inside the other:

However since these are both views on the same server, I don't know why you want to embed it via HTML. Why not simply call the view from your other view and pass the result as a context variable? Or, even better, factor out the code whose result you want into a common method, called by both views.
Answer: You have 2 choices here: either you use a TemplateView that you map directly to your url and in that template you add your html code.
The other solution is to interpret a string as a template and render it.
Answer: I found a solution to my question:
View.py
def myview(request):
    content ='Hello I am an innocent string'
    response = HttpResponse(content, content_type='text/plain')
    return response

template.html
<object type="text/plain" data="/myapp/"></object>

Hope it helps someone else!
Bye!


Rocktuner CT2 problem

Question: I have a problem with a piece of equipment I have. I've found in the old locker this tuner, and wanted to tune my guitar with it. But after I do that, I find that my guitar is 2-3 pitches higher than it should be (I used standard EADGBE).
This tuner has three modes: bass, guitar and wind instruments, and I assume that my problem is because the different mode is turned on. Maybe if anybody used or use this tuner, he could give a tip, how should I use it. I tried all buttons, but the mode is unchanged.
I also cannot get, how clefs (keys) are working and why they are needed, and should I set my pitch to 440?
My default screen looks exactly like on the screenshot under the link, with a letter C in the lower right.
Answer: Remove the battery.
I think it is set to some other base pitch for a transposing instrument, like an E-flat clarinet, so while it is probably calibrated correctly, it is not displaying the same note names as on the piano. I don't think A=440 or A=450 or some other tuning is the issue. You want to get it back into "guitar" mode.
Usually the easiest way to re-initialize this kind of electronic device to its default mode is to remove the battery, wait a few minutes, and put the battery back in. Try this and see if it solves the problem.
Update:
I found a list of the features of this particular model of tuner. To wit:
http://www.amazon.com/Rocktuner-Auto-Chromatic-Clip-On-Guitar-instr/dp/B003VKB74E

3 Modes: Guitar, Bass, Wind instruments
4 selectable keys: C, F, Bb, Eb
A4 calibration: from 430 to 450 Hz

The person asking the question said that the tuner is displaying 3 half-steps away from where it should be.

But A=415 is one half-step lower than A=440, and A=466 is one half-step higher than A=440. Note that this tuner can only accommodate from A=430 to A=450, which is less than a half-step in either direction. So this is clearly not what the person asking the question is experiencing.
Therefore, the problem is that the tuner is set to accommodate a transposing instrument in F, B-flat, or E-flat, like the list of features says. E-flat tuning is three half-steps transposed from C tuning.
The person asking the question needs to get his unit back to C and out of the Eb key transposition mode.
Here is how to do this:

Hold down the button labeled "Key".
Use the up and down arrow keys until the "Key" transposition indicator on the unit's display, in the lower-right corner, says "C" and not "Eb" or something else.
Comment: @Wheat-an Eb clarinet ? a rare beast indeed ! However, I think you're probably in the right direction, as this tuner can be set in different 'keys'(clefs), so maybe an Eb on an alto would show as a C on the tuner.
Comment: @Tim - you are right, Wheat has it backwards. Electronic tuners always show concert pitch; they *never* transpose. The OP did not say *how* he was using the tuner. If he's not tuning DI with a jack, he can't really count on an accurate reading from the tuner's small microphone. If using the microphone, readings will be inconsistent. That said, removing the battery definitely can't hurt.  While you're at it, I would take it a step further and put in a fresh one as well.
Comment: @jjmusicnotes - I certainly wouldn't advocate using the mic., but the DI or the vibration sensor should do the job well. OP stated acoustic gtr. so maybe no DI.
Comment: @Tim - the mic is ok for wind instruments. Contact mics can be problematic as well - you have to place them on the correct part of the instrument otherwise your readings will also be funky.
Comment: @jjmusicnotes - I was referring to using the mic for the OP's acoustic guitar - it often picks up other sounds as well, confusing it.
Comment: @WheatWilliams - I stand corrected, this is the first electric tuner I have seen that apparently transposes. That said, I **do not** appreciate being patronized - as a composer and professor, I *certainly* know my instruments and their transpositions, among other things.
Comment: Sorry, @jjmusicnotes, I was not intending to be patronizing. I was just as surprised as you to find out that this tuner, while sold by the Warwick bass guitar company and labeled "Rocktuner" actually seems to be designed for transposing orchestral instruments. And I am neither a composer nor a professor; I'm just an avid amateur musician, so I defer to your superior knowledge.
Comment: @Wheat - thanks for the extra homework, my suggestion was only a wild guess.Interesting stuff. Well done ! Can't help asking - what patronising ?
Comment: I made a couple of comments that jjmusicnotes thought were patronizing to him, and I apologised and deleted them. All this happened during StackExchange being taken down by a DDoS attack yesterday, so even getting to the site and adding comments was difficult.
Comment: I had to look up some info on transposing instruments to write my answer here. I have only ever been a singer who plays a bit of guitar and even less piano, and I have never worked with a transposing innstrument myself, although I have done some copyist work on orchestral scores that require taking this into account.
Comment: @WheatWilliams Sorry, I forgot to answer. It appeared that the battery was near dead. When I changed the battery, it become functioning properly. But your answer was extremely helpful to figure out how to use the tuner, so I'm marking it. Thanks!

Rocktuner CT2 problem


Is there a replacement for this double math

Question: Is there a Java operator that would create a value equal to count but in fewer lines?
    double theta = //Some value;
    int count = 0;
    while (theta > 0) {
        theta -= pi * (1.0 / 8.0);
        count += 1;
    }

Answer: You've just implemented division by repeated subtraction.
So, if you had actual real numbers in Java, you could do ...
int result = (int) (theta / (Math.PI / 8)) + 1;

... to get the same result. However due to repeated rounding errors in your code, that has many more steps than a simple division, the answers will diverge a bit. The results will be the same for thetas up to around 55 million.
The rounding errors are there because float and double are not accurate representations of real numbers.
See also: Is floating point math broken?
Comment: This would give a different output if `theta = Math.PI / 8`
Comment: @Eran Yours gives a different output if `theta == Math.PI * 8` :-)
Answer: Assuming theta > 0, something like this should work:
int count = (int)Math.ceil (theta/(Math.PI * (1.0 / 8.0)));

or
int count = (int)Math.ceil (theta*8/Math.PI);

Comment: The code posted by the OP does neither exactly `Math.ceil` nor `+ 1`, there are edge cases for both (take theta is `Math.PI / 8` or `Math.PI * 8`)
Answer: How about this: Math.ceil( theta/(pi * (1.0 / 8.0)))?


Discrete distribution model

Question: I am wondering if its possible to model or fit a discrete distribution where there are only three possible outcomes: 0, 1, and 3. These outcomes are numbers which result from a game. I get hung up on the fact that 2 is not an allowed outcome and don't really see how to do it. A sample table is below.
I will also mention that the intention is to determine the average and error on that average, so if there is an alternate method I am oblivious to, please let me know.
<code> Obs | Counts
--------------
 0   |  35
 1   |  22
 3   |  25
</code>
Any help is appreciated.
Comment: what are 0, 1, 3, lables or numbers? In other word where do they come from?
Comment: They are numbers which result from a game. I edited my question to add this info.
Comment: I still don't get it. What kind of number are they? Counts or what? If they are labels then Glen_b's answer should be satisfying. And, is 2 an impossible event or just it never appears by chance?
Answer: Wouldn't you just specify a multinomial distribution?
That is, you can just have a $p_0$, $p_1$ and $p_3$ such that $p_0+p_1+p_3=1$ and $p_i>0,i=0,1,3$, and a number of observations $n$, so that you can accommodate any set of probabilities to the three outcomes.
Let the counts for each category be $\mathbf{X} = (X_0,X_1,X_3)^\prime\,,$ where (where $X_0+X_1+X_3=n$)
You observe
$(X_0,X_1,X_3)^\prime = (x_0,x_1,x_3)^\prime$
with probability
$\qquad\frac{n!}{x_0! x_1! x_3!} p_0^{x_0} p_1^{x_1}  p_3^{x_3} \:$ (with $x_0+x_1+x_3=n$).
The MLEs of the $p$ parameters are just the sample proportions.
You can compute an average just fine, since the category labels are integers (0,1,3), so the expectation is just $n(p_1+3p_3)$. The estimate of the mean is the sample mean $\bar{x}=(x_1+3x_3)/n$ and the variance of the sample mean is $\frac{1}{n^2}[\text{Var}(X_1)+9\text{Var}(X_3)+6\text{Cov}(X_1,X_3)]$.
Note that $\text{Var}(X_i) = np_i(1-p_i)$ and $\text{Cov}(X_i,X_j)=-np_ip_j$ for $i\neq j$.
So we can obtain the standard error of the mean fairly directly.
Or did you want something less general?

Discrete distribution model


Yii CGridView add class or style for header cell

Question: I want to set some style or css class for header cell in specific column.
This changes css only for data cells in a column.
        'columns'=>array(
            array(
                'name'=>'id',
                'header'=>'#',
                'htmlOptions'=>array('style'=>'width: 50px; text-align: center;', 'class'=>'zzz'),
            ),

How to set css or style in header cell of this column?
Answer: Use headerHtmlOptions.
'columns'=>array(
        array(
            'name'=>'id',
            'header'=>'#',
            'htmlOptions'=>array('style'=>'width: 50px; text-align: center;', 'class'=>'zzz'),
            'headerHtmlOptions'=>array(...),
        ),

Comment: Thanks!!! I can't understand why Google didn't help me with my 'yii cgridview header htmloptions' like queries
Comment: You can access http://www.yiiframework.com/doc/api/ then find class you want and all public properties... you can see it... :D
Comment: And one more thing, if you need to set the class/style for filter ( for me it was for responsive features ) use `filterHtmlOption` the exact same way.
Answer: filterHtmlOptions
If you want to style the content that the user enters in the filterbox - for
example "text-align : right" - then
'filterHtmlOptions'=>array('style'=>'text-align: right'),

is not going to work, because it will only style the outer table cell (td), and not the inner filter-container (div) or input element:

        <input>

What you can do is add a class to the outer table cell:
'filterHtmlOptions'=>array('class'=>'filterBoxRight'),

which will result in this:

        <input>

Then run the following code:
$(document).on('ready', function(){
    $('.filterBoxRight').find('.filter-container').find(':input').css({
        'text-align': 'right',
    });
});


Stepwise regression based on F-statistic in R

Question: I know that the stepAIC function in R allows us to perform stepwise regression but I was wondering if there's any option (or other function) to perform a F-statistic based stepwise regression ?
I've looked in the help of the stepAIC function but didn't find any answer.
Thanks a lot
Comment: Stepwise selection based on F-tests isn't going to be any better than stepwise selection based on the AIC or any other metric.  To a first approximation, all stepwise selection is bad (cf, [Algorithms for automatic model selection](https://stats.stackexchange.com/a/20856/7290)).
Comment: Questions that are only about software (e.g. error messages, code or packages, etc.)
are generally off topic here. If you have a substantive machine learning or
statistical question, please edit to clarify.
Comment: Ok thanks I'll keep that in mind for my next questions.
Answer: So I've found the answer I was looking for.
The dropterm function for the MASS package allows us to perform backwards variable selection using any statistic we want. The equivalent function addterm allows to do the same with forward regression.
To do so, you simply need to add the argument test=c("none","Chisq","F") for the statistic you want. Keep in mind that the F-statistic selection only works for model of the class lm and aov.


Would the function pthread_cleanup_push() work with threads created with _beginthreadex()?

Question: In my project I use a third-party DLL, that creates some threads, which in turn call my function. The threads in the third-party DLL are created with _beginthreadex(), the DLL is compiled with MSVC.
My project is compiled with MINGW.
In my function I use the thread-local variable, using the __thread keyword, like the following:
__thread Env* env;

Env* getEnv() {
   if(env) return env;
   return env = createNewEnv();
}

// called by the 3rd-party thread
void myFunction() {
   Env* env = getEnv();
   // do work
}

From time to time the third-party library kills all threads and later spawn new ones, for which I receive a notification. In order to prevent memory leak I need to delete the Env instances created by the now-dead threads. The problem is that I don't know how to access these instances, because the pointers are thread-local.
I've google up an idea to use the pthread_cleanup_push() function, which is present in the MINGW runtime. That would ideally solve my issue, but I'm not sure if it would work with threads created with _beginthreadex().
Any ideas? May be another workaround exists?
Comment: I'm guessing that the `pthread_cleanup_push()` technique only works with threads the pthreads library knows about, but you can always test that hypothesis by putting a `printf()` (or whatever) in the callback-function and seeing if it gets printed.
Comment: You are right. Moreover, it turned out that I misunderstood the usage of this function, it's not applicable in my case. Now considering the pthread_key_create() with destructor.
Answer: Finally, the idea of using pthread_cleanup_push() turned out completely wrong, because it can be used only within a thread main function, which I don't have access to. It is not even a  real function. Actually it's a #defined chunk of code, which should be used together with pthread_cleanup_pop().
I solved the problem of cleaning thread-local variables by implementing a dllmain() in which I process the DLL_THREAD_DETACH event.
Very useful discussion on this topic is here:
How to release the object in a TLS-slot at thread exit on Windows?


Is it possible a method with the name of a number in ruby?

Question: This works:
if 1
    if 1
    elsif 2
    elsif 3
    end
end

But this produces a syntax error: unexpected '(', expecting keyword_then or ';' or '\n'. I'm trying to execute the method 1.
if 1
    if 1()
    elsif 2
    elsif 3
    end
end

I don't know what I should assume based on the error. That something earlier in the code is causing a problem? Or something later in the code is causing a problem?
Comment: Why do you add parentheses after `1`? They have no functionality.
Comment: But `1` is _not_ a function, nor can it ever be a function.
Comment: let's say it's a function
Answer: When you write
1()

it is the syntax for calling a method named 1.
But 1 is not a legal method name in Ruby, method names cannot start with a number.
If you had a method foo in scope, then you could write foo() in the place where you wrote 1(), but it's superfluous to include the parens, as they are the wrappers for the method's arguments, and you are not passing any arguments.
1 is interpreted by ruby as an integer, if you open an irb session and type 1() you'll see the same error message that you saw "syntax error, unexpected '('", it has nothing to do with the fact that it's the condition on an if statement. This works fine:
def foo
  true
end

if foo()
  puts "hooray"
else
  puts "boo"
end

Comment: See the [Ruby Method Names](https://ruby-doc.org/core-2.7.1/doc/syntax/methods_rdoc.html#label-Method+Names) documentation.
Comment: I should not have called it 1. I was trying to make the minimal code. Actually it is a function, and If I pass an argument, I get the same result. Should I edit the question to reflect this?
Comment: @stephen definitely.
Answer:
Methods starting with numbers in ruby are not allowed.

You should not define a method with the name of a number.

It is not necessary to use parentheses in ruby to execute methods.
If you don't pass arguments:
some_method

If you pass some arguments:
some_method 'white'


Function to determine whether my Cart is empty?

Question: I want to set an access callback on a menu item (primary links) for the shopping cart so that it only displays when there is something in the cart.  However, I can't find an obvious function to to this, and I don't know where to start with my own code.
Any suggestion is appreciated.
Answer: Using the same technique as commerce_cart_block_view (thanks to Ryan Szrama for the assist!), you'll need to:

Get the order using commerce_cart_order_load, then check to see if there are no line items.
Apply the entity metadata wrapper to retrieve further wrappers for the entity properties
Count line items in the cart, filtering for products only

For the access callback itself, take a look at Do you have an example of hook_menu() access callback? for several examples and links to documentation.
Therefore, the callback should be something like:
function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    return commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()) > 0;
  }
  return FALSE;
}

Comment: Note that you can't do a simple count on the commerce_line_items field, because it may still contain a reference to a non-product line item. Check out commerce_cart_block_view() in commerce_cart.module to see how I determine if the cart is empty for the purposes of showing the empty cart block vs. the cart block view.
Comment: Excellent point, much appreciated! I've updated my answer accordingly. Thanks for all your work on DC!
Comment: Thanks guys.  I'm working on my first Commerce site and am super impressed at how it leverages all the goodness of Drupal that I (nearly) understand.
Answer: Apply this patch here then you can call commerce_cart_is_cart_empty() from your code:
if (!commerce_cart_is_cart_empty()) {
  // your code
}

Answer: Actually you might want to check the args, to avoid presenting the user with an access denied page when they remove the last item from their cart:
function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $items = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
    return $items > 0 || arg(0) == 'cart';
  }
  return FALSE;
}


Characteristic of an integral domain: doubt in the proof

Question: Suppose by absurd that the characteristic of an integral domain is an integer $n$ not prime, say $n=n_1 \cdot n_2$.
Now we have $$na=(n_1 \cdot n_2)a=0 \implies (n_1 \cdot a) \cdot (n_2 \cdot a)=0 \implies n_1 \cdot a=0 \space \lor n_2 \cdot a=0$$
In my book it is considered a contradiction (for the minimality of $n$) but a priori it could be possible that $n_1$ and $n_2$ don't satisfy characteristic property.

Adopted definition of characteristic of an integral domain (with $charD \neq 0$):
$$charD := min \{n \in \mathbb{N}| \space n \cdot a=0 \space \forall a \in D\}$$
In my book an integral domain is a commutative ring without non-zero zero divisors. I do not assume identity.
Comment: @RGS In the definition you have "for all a".
Comment: I don't really get what is your question, sorry. Could you enlighten me?
Comment: Sure: I don't see the contradiction... neither $n_1$ nor $n_2$ have the characteristic property (if $m$ is the characteristic then $m \cdot a=0$ $\forall$ a in D)
Comment: @LeonardoVannini Are you saying your definition of integral domain does not include multiplicative identity? Because that is a rare assumption for integral domains.
Comment: @rschwieb Yes, for my book an integral domain is a commutative ring without non-zero zero divisors
Comment: @LeonardoVannini What you wrote does no answer my question clearly. Do you mean *yes, I do not assume identity*?
Comment: Sorry, I do not assume identity
Comment: @LeonardoVannini Next time, directly edit in your assumptions into the question from the start. Putting them in the comments later is helpful... but you really ought to refine the question with them too.
Answer: You still have proved that any vector will be killed by either one of $n_1$ and $n_2$. What you want is to be able to take the same $n_i$ for all vectors.
So assume that there is a vector $a_1$ annihilated only by $n_1$ and a vector $a_2$ annihilated only by $n_2$.
Who kills $a_1+a_2$ then? If it is $n_1$ then $n_1(a_1+a_2)=0$ together with $n_1a_1=0$ proves that $n_1a_2=0$, which is a contradiction.
Comment: $n_1 n_2=n$, which I have assumed to be the characteristic of D...
Comment: @LeonardoVannini I have edited to make it clearer.
Comment: @rschwieb Yes it does, because in that case there is nothing to prove since the OP has already proved that for any vector $a$, either $n_1a=0$ or $n_2a=0$.
Comment: @ArnaudMortier Or rather that case falls out before your argument is necessary, I see. Yes, it works, with a little grease :)
Comment: Yes. In fact this is how you prove the property that you have mentioned.
Comment: @ArnaudMortier Yes, behind the disguise of annihilators is the same group-theoretic argument.
Answer: You've shown that for every element $r\in R$, $n_1r=0$ or $n_2r=0$.
You can check that $I_1=\{x\mid n_1x=0\}$ and  $I_2=\{x\mid n_2x=0\}$ are additive subgroups of $R$, and moreover by your discovery above, $R=I_1\cup I_2$.
But a group is never a union of two proper subgroups, so one of them is in fact all of $R$. That contradicts the minimality of $n$.

In my book it is considered a contradiction (for the minimality of $n$) but a priori it could be possible that $n_1$ and $n_2$ don't satisfy characteristic property.

If your book considers it a contradiction without resolving this detail, then I think it is highly likely your book assumes an integral domain has an identity. In that case, you can conclude the proof much more simply. Suppose $n$ is the additive order of $1$. Then obviously $n\cdot x=(n\cdot 1)\cdot x=0$ for every $x\in R$. If $n$ is were composite, $n_1n_2\cdot 1=(n_1\cdot 1)(n_2\cdot 1)=0$, at which point we would have to conclude one of the factors is zero... but that would contradict the minimality of $n$ as the additive order of $1$.


Drupal Commerce Caching Modules

Question: I've been trying to improve the speed of my Commerce site with various caching and performance modules. But the general ones recommended don't work or break my site. I can't see anything else out there that answers my question!
Boost - I thought this would work on static pages such as About or Contact, but the module doesn't cache anything at all.
Agrcache - breaks the JavaScript slideshow on the front page.
Core Library - breaks the login page (which is odd!)
I have views cache installed and that's the only one I've got working so far...
Comment: Have u tried entity cache?
Comment: I haven't heard of that one. It looks good - and I discovered there's an entity cache specifically for drupal commerce too, that caches orders, line items, and products. Thanks for the tip!
Comment: You are requesting caching recommendations, but you haven't told us what your bottlenecks are, and what the exact numbers are. If you yourself don't know them, then you won't get far with optimizing.
Comment: I'm just looking into this myself and curious as to why Boost was of no use?
Answer: You can use

https://drupal.org/project/commerce_entitycache

It will cache the commerce entities, rather than build them on each request.
While it works ok as is, after the two "Needs review" patches I added to the issue queue:

https://drupal.org/project/issues/commerce_entitycache?categories=All

I'm using it myself without any problems.
As mentioned previously:

https://drupal.org/project/authcache
https://drupal.org/project/commerce_authcache

Also work well with Commerce
Answer: I've look at entity_cache, then wrote bridge hooks to register the different commerce entities.
http://drupal.org/project/entitycache
I'll need to also write some business logic to expire the cache. I create both a "timed" expire of about 24 hours and a cache on create/update events.
Answer: Hi If you need to cache users on Drupal commerce I recommend using
Commerce Auth Cache

Authcache provides a way to cache pages for authenticated users, updating parts of the page via AJAX requests for dynamic content. In case of Drupal Commerce, many parts of some pages are unique to the current user. For example, the cart block is unique per user, and thus cannot be cached with the page it's displayed on. With Commerce Authcache, the cart block gets loaded via an AJAX request after the page is first loaded. This means the page loads very fast, and the cart is still relevant to the current user.

And of course
Auth Cache

The Authcache module offers page caching for both anonymous users and logged-in authenticated users. This allows Drupal/PHP to only spend 1-2 milliseconds serving pages, greatly reducing server resources.

Please note that enabling authenticated user caching will require modifying how your user-customized content displays on your pages. You should be an experienced Drupal developer if you choose to implement the full functionality of this module.
But if you need to more :
then I suggest Varnish + Memcached

Drupal Commerce Caching Modules


IP ending in all zeros: valid (for /128) or possibly confusable with anycast?

Question: Host Europe assigned a VM I just rented from them an IP address ending in all zeros (2xxx:xxxx:xxxx:xxxx::/128).
I claimed this as possible interop problems as addresses with the last 64 bits all zeros are normally anycast addresses for the subnet router, and I fear other nodes may treat it specially.
Their support says: "It's only syntactically a subnet anycast address, but you can use it no problems because we use a /128 subnet size." (translation mine)
I'm only semi-convinced. Is there anything that allows a node to handle addresses of that kind specially, or can I really just use this like a regular address?
Answer:
I claimed this as possible interop problems as addresses with the last 64 bits all zeros are normally anycast addresses for the subnet router,

For a subnet, an interface ID of all-zeros would be the subnet anycast. Although in theory it was defined as 64 bits for IPv6 global unicast, in practice the subnet prefix length is what defines the length of the interface ID – it is usually 64 bits because that's what you have left minus the /64 prefix, but an /128 address has no subnet, nor an interface ID for that matter (it would be a 0-bit IID).

and I fear other nodes may treat it specially.

Similar to the case with IPv4 all-ones "subnet broadcast" addresses, the subnet-router anycast (or any other kind of local-subnet anycast that's defined in IPv6) is only meaningful once it actually reaches a router of said subnet. Only the subnet routers are able to give it any kind of useful treatment to begin with; hosts or routers that are not in that subnet can't do anything else but route it onward as a regular unicast address. So if the address is statically routed 'via' your host, then only your own machine is the "subnet router" for it and the other nodes don't really have a say.
(This seems to mirror IPv4 classful addressing, where passing nodes might have "known" that 192.168.4.255 is special based on it being Class C address... but despite that knowledge, they still weren't going to be able to do anything else but route it anyway like a normal address. And now that classful addressing is long gone, nodes can't even know whether it is special anymore because they don't know what prefix length the final subnet is using.)
Answer: A one host net can be set on an IPv6 host and be routed. Even though a subnet-router address is meaningless here and should be disabled, there still are questions about if you can get a proper /64, and if their address planning is ready for that.
IPv6 on link determination is a protocol thing, so there does not need to be router IP addresses in the same subnet, like v4 has. Traffic via some other on-link net works fine, almost certainly the default gateway's link local address.
A similar long prefix thing whose debates are recorded in RFCs is the practice of /127s on point-to-points in RFC 6164. People thought that would break things, but it can work. Those recommendations include if multiple prefixes are to be assigned out of one /64, the all zeros interface ID should not be used.  "Otherwise, nodes may receive packets that they are not intended to receive." This is less important if you are the only customer in the /64, but I don't interpret their response to guarantee that.
One address per rented VM is not very generous to say the least. There are use cases to IP your own containers, or IP based virtual hosts. However, this would require routing an entire prefix to your host, which most providers are not doing. If they are not already doing so, could be a good idea for address planning reasons for them to reserve an entire /64, even if only one IP is attached to your guest. There is more than enough address space to support this.
Its nice having the shortest vanity address possible, but that's not really necessary. 2001:db8:c6ad:a661::1 is only slightly longer in text form than 2001:db8:c6ad:a661::. And the name in DNS is the same length either way.


Combine Observables with latest of any one and previous value of the other observables

Question: Let say I have observables A, B, C. I have to listen to change of these three and alter a caculation.
i.e., On value change on any one of the obseravable, I need to recalculate with the new value from the present and the old value for the rest of the observables.
I tried to use combineLatest, which was perfect except the first behavior that all the observables should have a latest/change in the value.
Comment: That's what `combineLatest` does already. But first, all source Observables have to to emit at least one value.
Comment: I am looking for an option that can handle without all the observables emit the first time.
Answer: You can just prefix each source Observable with startWith operator before passing them into combineLatest:
combineLatest(
  obsA$.pipe(startWith(null)),
  obsB$.pipe(startWith(null)),
  obsC$.pipe(startWith(null)),
)

Then you'll have to check manually what values are null.
Comment: Thanks! This was the solution I was looking for, In my situation, Instead of null I passed in the existing/default value that I could use and it works like a charm!


Replace MDL icon font hamburgeur icon with svg

Question: Partly so I don't have to wait for the entire font file to load before icon displays, and because I've been reading a bit of discussion (pro and con) about using svg's instead of icon-fonts I am experimenting with using an svg instead of MDLs native icon font for the Material Design Lite mdl-navigation drawer.
On compatible browsers, they add the icon using the following script, which I don't want to modify, in case of upgrades.
if (this.drawer_) {
    var drawerButton = this.element_.querySelector('.' + this.CssClasses_.DRAWER_BTN);
    if (!drawerButton) {
        drawerButton = document.createElement('div');
        drawerButton.setAttribute('aria-expanded', 'false');
        drawerButton.setAttribute('role', 'button');
        drawerButton.setAttribute('tabindex', '0');
        drawerButton.classList.add(this.CssClasses_.DRAWER_BTN);
        var drawerButtonIcon = document.createElement('i');
        drawerButtonIcon.classList.add(this.CssClasses_.ICON);
        drawerButtonIcon.innerHTML = this.Constant_.MENU_ICON;
        drawerButton.appendChild(drawerButtonIcon);
    } # etc...
}

I came up with this:
var mdl_drawer_button = document.querySelector('.mdl-layout__drawer-button');
mdl_drawer_button.innerHTML = '<svg viewBox="0 0 100 100" class="icon nav-icon"><use xlink:href="#nav-icon"></use></svg>';

However, '.mdl-layout__drawer-button' doesn't exist until the MDL script has run, so am adding a 500ms timeout as seen in this fiddle.
Does my approach make sense? It there a more dependable way to run my function once the MDL code has run?
UPDATE:
Trying a slightly different method now using a recursive function with a test for .mdl-layout__drawer-button not being null:
//Replace MDL icon with our sprite
function mdl_drawer_btn() {
    var mdl_drawer_button = document.querySelector('.mdl-layout__drawer-button');
    if (mdl_drawer_button != null) {
        mdl_drawer_button.innerHTML = '<svg viewBox="0 0 100 100" class="icon nav-icon"><use xlink:href="#nav-icon"></use></svg>';
      } else {
        setTimeout(mdl_drawer_btn, 100);
      }
  }

setTimeout(mdl_drawer_btn, 100);

Comment: Further discussion: https://github.com/google/material-design-lite/issues/1014
Answer: It's hard to advise without knowing how your whole site is implemented, but I would have thought it should be enough to put your script as the last script on the page.  Then to make sure all DOM changes, that previous scripts have made, are complete, wrap it in a 0ms timeout.
setTimeout(mdl_drawer_btn, 0);

Comment: Even with this code as the last line before the `` tag, `document.querySelector('.mdl-layout__drawer-button')` is `null`.


Component is missing template or render function after publishing vue3+vite package

Question: I want to publish a vue3+vite package to npm, but after publishing, I encountered "Component is missing template or render function" console warning when used in a test project and my component isn't working, and I can't access its methods. any suggestions?
entrypoint(install.ts):
import Print from '~/components/Print.vue'

export default {
  install: (app: any, options: any): void => {
    app.component('Print', Print)
  }
}

vite.configs.js:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
const path = require("path")
export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/install.ts'),
      name: 'vcp',
      fileName: (format) => `vcp.${format}.ts`,
      rollupOptions: {
        external: ['vue'],
        output: {
          globals: {
            vue: 'Vue'
          }
        }
      },
    }
  },
  plugins: [vue()],
  server: {
    port: 8080
  },
  resolve: {
    dedupe: [
      'vue'
    ],
    alias: {
      "~": path.resolve(__dirname, "./src"),
      "@": path.resolve(__dirname, "./src"),
    },
  },
})

package.json:
{
  "name": "vcp",
  "version": "0.9.926",
  "private": false,
  "author": "Alireza Safari <email@example.com> (http://alireza-safari.ir)",
  "license": "MIT",
  "main": "./dist/vcp.umd.ts",
  "module": "./dist/vcp.es.ts",
  "description": "Vue Client Print with Template Builder",
  "exports": {
    ".": {
      "import": "./dist/vcp.es.ts",
      "require": "./dist/vcp.umd.ts"
    },
    "./dist/style.css" : "./dist/style.css"
  },
  "keywords": [
    "vcp",
    "vue print",
    "vue client print",
    "template builder",
    "vue report",
    "vue report generator"
  ],
  "files": [
    "dist/*"
  ],
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "test:ui": "vitest --ui",
    "test:run": "vitest run",
    "test": "vitest",
    "coverage": "vitest run --coverage"
  },
  "dependencies": {
    "dom-to-image": "^2.6.0",
    "file-saver": "^2.0.5",
    "print-js": "^1.6.0",
    "register-service-worker": "^1.7.2",
    "typescript": "^4.6.2",
    "vitest": "^0.6.1",
    "vue": "^3.2.31",
    "vue-i18n": "^9.1.9"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.2.4",
    "@vitest/ui": "^0.6.1",
    "@vue/compiler-sfc": "^3.2.31",
    "cz-conventional-changelog": "^3.3.0",
    "vite": "^2.8.6"
  }
}

Comment: Can you add your component syntax too?
Comment: Its options api
Answer: I got my answer from here, I had to export my component individually as well.
install method to be able to use it with app.use() method (or vue.use() - vue2)
to add component globally (install method register component by itself)
and individual export for app.component() method or (vue.component() - vue2) to import component in single file.
my new install.ts:
import Print from '~/components/Print.vue'

export default {
  install: (app: any, options: any): void => {
    app.component('Print', Print)
  }
}

export { Print }