How to test $ H_0: \mu=0 \quad \text{vs.} \quad H_a: \mu=1$?

Question: The Statement of the Problem:

Let $X_1,..., X_n$ be a random sample from $N(\mu, 1)$. Consider testing
  $$ H_0: \mu=0 \quad \text{vs.} \quad H_a: \mu=1. $$
Let the rejection region be $C = \{ \overline X > c\}$
  (a) Find $c$ so that the test has size $\alpha = 0.01$.
  (b) Find the power under $H_a$, i.e. find $\gamma_C(1).$
  (c) Show that $\gamma_c(1) \to  1$ as $n \to \infty$. How do you interpret this?

Where I Am:
I apologize if this is really basic, but I can't figure out how to do this. I know how to test for alternative hypotheses that are state that the mean is not a value, or larger than or smaller than some value; and I know how to test for the difference between means of different samples, but this doesn't really make sense to me. If someone could shed a little light on this, I'd appreciate it.
Comment: Testing an alternative of this form is essentially the same as a composite alternative.  The question is already specifying the form of the rejection region, so you want to consider the distribution of $\bar{X}$ when $\mu = 0$ and when $\mu = 1$, and how often you will be rejecting $H_0$ for different values of $c$ in either situation.
Comment: @Simone, it is best to ask the OP to add the SS tag & read it's wiki, rather than add the tag for them. That way, there is a better chance they will be familiar w/ our policy. If they don't add the tag, you can vote to close.
Comment: @gung Will do! Sorry. First-time poster.
Comment: is it a homework?
Comment: Yes, it is. (Here's some more characters).
Comment: @DeepNorth. I'm not sure what you mean; I wasn't given any data.
Comment: @dsaxton. I see, yes. I've only been exposed to simple hypothesis testing (as opposed to composite). Let me think about this. Thanks.
Comment: A pretty big hint is that if $X_1, \ldots, X_n$ are normal$(\mu, 1)$, then $\bar{X}$ is distributed normal$(\mu, 1 / n)$ (that is, with *variance* $1/n$).  How big then should $c$ be for $P(\bar{X} > c) = \alpha$ when $\mu = 0$?  What is $P(\bar{X} > c)$ when $\mu = 1$?
Comment: @dsaxton. Ah, right. So, $\overline X \sim N(\mu, 1/n)$ and so I just need to find $c$ such that $1 - P(\overline X \le c) = 0.01$, i.e. use the cdf of a normally distributed r.v. with parameters $\mu$ and $1/n$?
Comment: Actually, did they give you a value for $n$ in the problem?
Comment: @dsaxton. No. Hmm...
Comment: I think your c will be $qnorm(0.99,0,\sqrt{1/n})$ c  will vary according to your n.
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck.
Answer: $\bar{X}$, the sample mean, is distributed as $N(0,n^{-1})$ when $H_0$ is
true and as $N(1,n^{-1})$ when $H_1$ is true. (Here, the parameters
are $\mu$ and $\sigma^2$
Thus, we want $c$ to be that number for which $P\{\bar{X} > c \mid H_0\}$
equals $0.01$. But,
$$P\{\bar{X} > c \mid H_0\} =Q\left(c\sqrt{n}\right)$$
where $Q(\cdot)$ is the complementary standard normal distribution function, and a quick look at tables (or resort to an R-gument)
shows that $Q(2.33) \approx 0.01$. Hence,

$$c \approx \frac{2.33}{\sqrt{n}}\tag{1}$$

It follows that

$$P\{\bar{X} > c \mid H_1\} = Q\left((c-1)\sqrt{n}\right)
\approx Q\left(2.33 - \sqrt{n}\right)\tag{2}$$

Since the argument of $Q$ in $(2)$ diverges to $-\infty$ as
$n \to \infty$
(and so the value of $Q(\cdot)$ approaches $1$), we have part (c)
as well. The interpretation is that while the threshold $c$
converges to $0$ as $n\to\infty$ (cf. $(1)$), the variance
of $\bar{X}$
is converging to $0$, and thus, when $H_1$ is true,
the probability that $\bar{X} \sim N(1,\sqrt{n^{-1}})$ exceeds
the threshold $c$ is close to $1$. Even though that threshold
is quite close to the mean $1$ in absolute terms, it is zillions
of standard deviations away from the mean $1$.
Answer: Hints:
(a) Under $H_0$ we have $\bar{X} \sim$ normal$(0, 1 / n)$ and so $\bar{X} \sqrt{n} \sim$ normal$(0, 1)$, and so we want to find a $c$ such that $P(\bar{X} \sqrt{n} > c \sqrt{n}) = \alpha$.  It's perhaps a bit confusing that the author framed the question in this way since here $c$ will depend on $n$ in order to get proper size.
(b) You actually can't answer this without knowing $n$, because the power depends on $n$.  I'm beginning to wonder if the author made a mistake.
(c) Suppose we've chosen some $z$ to use as the lower bound of a rejection region of the form $\{ \bar{X} \sqrt{n} > z \}$ (i.e., $z = c \sqrt{n}$).  When $H_1$ is true we can look at the event of rejection in this way $\{ \bar{X} \sqrt{n} > z \} = \{ (\bar{X} - 1)\sqrt{n} + \sqrt{n} > z \} = \{ (\bar{X} - 1)\sqrt{n} > z - \sqrt{n} \}$.  What happens to the probability of this event as $n \to \infty$?
Answer: For (b), you will  reject $H_0$ if $\frac{\bar{X}-0}{\sigma/\sqrt{n}}\geq Z_{\alpha}$ (where $\sigma=\sqrt{1/n}$ in fact, it should be sample variance)
The power is the probability to reject $H_0$ if the $H_1$ is true
$\gamma_{(c)}(1)=P_{\mu}( \bar{X} \geq Z_{\alpha}\sigma/\sqrt{n} )=P_{\mu}(\frac{\bar{X}-1}{\sigma/ \sqrt{n}} \geq \frac{Z_{\alpha}\sigma/\sqrt{n}-1}{\sigma/\sqrt{n}})=P_{\mu}(\frac{\bar{X}-1}{\sigma/ \sqrt{n}}\geq Z_{\alpha}-\frac{1}{\sigma/\sqrt{n}})=1-\Phi(Z_{\alpha}-n)$
($\sigma=\sqrt{1/n},  \Phi $ is CDF of standard normal distribution)
So your power function is $1-\Phi(Z_{\alpha}-n)$. It depends on both $\alpha $ and $n$.
When $\alpha=0.01$
The power is $1-\Phi(1.64485-n)$
You also can see when $n\rightarrow\infty,  \Phi(1.64485-n)\rightarrow0$ so the power will be 1


Mapeamento com InheritanceType.JOINED Não funciona

Question: Estou tentando resolver uma atividade da faculdade onde foi passado especificações para mapearmos as classes com JPA. Tenho a seguinte herança para mapear: Funcionario (classe pai), Vendedor (filha) e Admistrativo (filha). Logo de primeira fiz o mapeamento utilizando a InheritanceType.TABLE_PER_CLASS, funcionou e criou as tabelas no banco. Porém o professor quer que utilizemos o InheritanceType.JOINED, e é ai que está o meu problema, fiz o mapeamento seguindo o exemplo dele e não funcionou, tentei vários exemplos na internet e tmbém não funcionou. Abaixo colocarei o mapeamento que fiz até agora e o erro do Hibernate.
OBS.: Para os InheritanceType.TABLE_PER_CLASS e o InheritanceType.SINGLE_TABLE funcioana perfeitamente, o problema é mapear com o InheritanceType.JOINED;
Classe Pai
@Entity(name = "tab_funcionario")
 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
 @Table(uniqueConstraints = {
    @UniqueConstraint(name = "un_funcionario_rg", columnNames = { "rg",  "rg_orgao_expedidor", "rg_uf" }) }

public abstract class Funcionario {

@Id
@Column(name = "cpf", length = 11, nullable = false, columnDefinition = "CHAR(11)")
private String cpf;

@Column(name = "nome", length = 40, nullable = false, columnDefinition = "VARCHAR(40)")
private String nome;

@Column(name = "rg", length = 12, nullable = true, columnDefinition = "CHAR(12)")
private String rg;

@Column(name = "rg_orgao_expedidor", length = 20, nullable = true, columnDefinition = "VARCHAR(20)")
private String rgOrgaoExpedidor;

@Column(name = "rg_uf", length = 2, nullable = true, columnDefinition = "CHAR(2)")
private String rgUf;

@ElementCollection()
@CollectionTable(name = "tab_funcionario_telefones", joinColumns = @JoinColumn(name = "cpf"))
@Column(name = "telefone", length = 12, nullable = false, columnDefinition = "VARCHAR(12)")
private List<String> telefone = new ArrayList<>();

@Temporal(TemporalType.DATE)
@Column(name = "data_nascimento", nullable = false, columnDefinition = "DATE")
private Date dataNascimento;

@Embedded()
@Column(name = "endereco", nullable = false)
private Endereco endereco;

Classes Filhas
@Entity(name = "tab_vendedor")
public class Vendedor extends Funcionario {

@Column(name = "percentual_comissao", nullable = false, precision = 10, scale = 2)
private BigDecimal percentualComissao;

@Convert(converter = SituacaoVendedorConverter.class)
@Column(columnDefinition = "char(3)", nullable = false)
private SituacaoVendedorEnum situacao;

@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "tab_vendedor_pessoa_juridica", joinColumns = {
        @JoinColumn(name = "cpf") }, inverseJoinColumns = { @JoinColumn(name = "cnpj") })
private List<PessoaJuridica> clientes = new ArrayList<>();

@Entity(name = "tab_administrativo")
public class Administrativo extends Funcionario {

@Column(name = "turno", nullable = false)
private Integer turno;

Erro do Hibernate
1    [main] ERROR org.hibernate.AssertionFailure  - HHH000099: an assertion failure occurred
(this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session):
org.hibernate.AssertionFailure: Table public.tab_funcionario not found

3    [main] ERROR br.ucsal.bes20191.bd2.mapeamentojpa.atividade.Teste  - Erro:
javax.persistence.PersistenceException: [PersistenceUnit: mapeamento-jpa] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:967)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at br.ucsal.bes20191.bd2.mapeamentojpa.atividade.Teste.main(Teste.java:14)

Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
... 4 more

Caused by: org.hibernate.AssertionFailure: Table public.tab_funcionario not found
at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5241)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 9 more

Persistence.xml
<persistence 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"
    version="2.0">

    <persistence-unit name="mapeamento-jpa">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <properties>

            <property name="javax.persistence.jdbc.driver"
                value="org.postgresql.Driver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:postgresql://localhost:5432/mapeamento-jpa" />
            <property name="javax.persistence.jdbc.user"
                value="postgres" />
            <property name="javax.persistence.jdbc.password"
                value="postgresql" />

            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.dialect"
                value="org.hibernate.dialect.PostgreSQL94Dialect" />
            <property name="hibernate.default_schema" value="public" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
    </persistence-unit>
</persistence>

Comment: Poderia por gentileza postar sua configuração do Hibernate?
Comment: Adicionei o conteúdo do persistence.xml
Answer: Acredito que você tenha encontrado a issue HHH-10490
A recomendação seria alterar a configuração do Hibernate para utilizar catalog ao invés de schema, você poderia trocar então de:
<property name="hibernate.default_schema" value="public" />

Para:
<property name="hibernate.default_catalog" value="public" />

Caso houver mapeamentos utilizando @Table, os mesmos devem ser alterados para utilizar catalog também, alterando de:
@Table(name="FOO", schema="BASE")

Para:
@Table(name="FOO", catalog="BASE")

Este mesmo bug foi reportado aqui, aqui e aqui
Comment: Fiz a alteração e continua aparecendo o mesmo erro.


Projeto no Android studio não roda por falta de libs

Question: Estou com esse erro ao tentar rodar um projeto Android que fiz a um tempo atrás, clonei o repositório do git e tentei rodar, atualizei o Android Studio a pouco tempo não sei o que fazer.
Erro:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
   java.io.FileNotFoundException: /home/geovanni/Documentos/UnB/2016.2/TecProg/TrabalhoTecProg/EuVou/app/libs/*.jar
  (Arquivo ou diretório não encontrado)
Answer: Os projetos do Android Studio usam o Gradle para fazer o build. Veja se no arquivo build.gradle existe a declaração para ele utilizar os jars da pasta libs como dependência. Geralmente como abaixo:
dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')

}


How can I access and adjust provider inside main() or runApp() to apply the value from firebase auth?

Question:   FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

I have this function inside the main() {}. I want to change riverpod state when it detects changes to Firebase Auth. But, right now I am stuck because I can't access my riverpod state without using WidgetRef ref that uses widget.
If I put that into my main widget, then there is a bit of a delay. Or, is this not recommended to do - putting firebase.auth function inside the main()?
Answer: This function shouldn't be in your main func, what you can do is to modify your main.dart to look like this:
void updateState(WidgetRef ref) {
FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
      ///update state with ref....

    } else {
      print('User is signed in!');

      ///update state with ref....

    }
  });
}
    void main() {
      runApp(const ProviderScope(child: MyApp()));
    }

    class MyApp extends ConsumerWidget {
      const MyApp({super.key});

      // This widget is the root of your application.
      @override
      Widget build(BuildContext context, WidgetRef ref) {

        WidgetsBinding.instance.addPostFrameCallback((_) {
         updateState(ref);
        });
        return MaterialApp(
          title: 'Flutter Demo',
          theme: MyTheme.appTheme,
          debugShowCheckedModeBanner: false,
          home: const HomeScreen(),
        );
      }
    }

Another approach could be to use an initstate in a ConsumerStatefulWidget, would look like:
  void updateState(WidgetRef ref) {
FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
      ///update state with ref....

    } else {
      print('User is signed in!');

      ///update state with ref....

    }
  });
}
    void main() {
      runApp(const ProviderScope(child: MyApp()));
    }

    class MyApp extends ConsumerStatefulWidget {
      const MyApp({super.key});

      @override
      ConsumerState<MyApp> createState() => _MyAppState();
    }

    class _MyAppState extends ConsumerState<MyApp> {
      // This widget is the root of your application.

      @override
      void initState() {
        // TODO: implement initState
        updateState(ref);
        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: MyTheme.appTheme,
          debugShowCheckedModeBanner: false,
          home: const HomeScreen(),
        );

  }
}

Comment: Thank you for the answer. Can I ask why they can't be inside the `main()`?
Comment: yes, your main.dart, contains your main function and you need to keep it as clean as possible.


passing this as parameter in static method

Question: I'm having some trouble with some code in Visual C# for Windows Phone
The trouble is not that it does not work, because it does, but I don't understand how =P
Within a static class, a static method is created, which gives itself as a parameter:
public static void MethodONe( this Timeline animation )
{
    //this class does not extend the TimeLine class, and is not connected to it in any
    //such way.
    animation.MethodTwo( );
}

public static void MethodTwo( this Timeline animation )
{
    someCode( );
}

How is this parameterpassing called, and what does it do, exactly?
Comment: possible duplicate of [What are Extension Methods?](http://stackoverflow.com/questions/403539/what-are-extension-methods), [Extension Methods](http://stackoverflow.com/questions/5730013/extension-methods), [Why we use "this" in Extension Methods?](http://stackoverflow.com/questions/2574311/why-we-use-this-in-extension-methods)
Answer: This is a so called extention method to the Timeline object. It adds functionallity without modifying the class itself.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
And in your case the animation parameter is the Timeline object (which is calling the function):
var timeLine = new Timeline();
timeLine.MethodTwo();

So the timeLine object will be passed as the animation parameter into the function.
There's a nice article on wikipedia which explains it futher in detail:
http://en.wikipedia.org/wiki/Extension_method
Comment: "...the parameter this is the Timeline object..." - that's not really correct. `this` is a _modifier_ in that case, not a _parameter_. The parameter is `animation` :-)


Would this predicate work ? this came on my quiz to find the position of element X in a data structure called list

Question: example:
        position(1,list(1,list(2,nil)),Z).
        Z = 1.
        position(3,list(1,list(2,list(3,nil)),Z).
        Z = 3.
      where Z is the position of element X in a data structure of a list in the above     format
Here was my solution:
      position(X,list(nil),0).                %empty list
      position(X,list(X,T),1).                %list with X as head or first element
      position(X,list(H,T),Z):-
                             position(X,list(T,nil),Z1), %X is in tail of list (H,T)
                             Z is Z1 + 1.

Answer: No, it won't work.
The correct predicate is:
position(X,list(nil),0).                %empty list
position(X,list(X,T),1).                %list with X as head or first element
position(X,list(H,T),Z):-
                position(X, T, Z1), %X is in tail of list (H,T)
                Z is Z1 + 1.

Writing position(X,list(T,nil),Z1), %X is in tail of list (H,T) will result in a loop, and it is a logic error as there is no reason to call position with a list(T, nil). T is already either a list or the nil atom.
Comment: yes ofCourse makes sense error in logic but isn't this equivalent to position(X,[],0).
position(X,[X|T],1).
position(X,[H,T],Z):- position(X,T,Z1), Z is Z1 + 1. for the predefined list structure in prolog. @andreapier


php.ini is not read after upgrading to PHP 5.6.25 from RHSC on RHEL7 with SELinux. How to debug?

Question: Configuration: I run a web server with RHEL7 with the SELinux kernel module and php-fpm.  By default, RHEL7 ships with PHP 5.4. This version of PHP is too old for my software, so I've upgraded to PHP 5.6.25 from RHSC.
Before upgrading, everything was working as expected.
When I run the upgraded php from the CLI, everything works fine.  For instance, I've changed the value for upload_max_filesize (on line 810) from 2M (the default) to 8M, and this change appears as expected when I query the PHP settings from the CLI:
php -v
php 5.6.25 (cli) ...
php -i | fgrep upload_max_filesize
upload_max_filesize => 8M => 8M

However, after the upgrade, it looks like php.ini is no longer read by read by Apache when Apache is restarted.  I.e.: the changes to php.ini have no effect (all values, including the value for upload_max_filesize stay at their defaults).
I've created a web-page to debug this, it contains the following snippet of PHP code:
$inipath = php_ini_loaded_file();
echo '
Loaded php.ini: ' . $inipath . '.
';
$contents = file($inipath);
if ($contents) {
  echo '
Line 810: ' . $contents[810] . '.
';
} else {
  echo '
Unable to read php.ini file.
';
}
echo '
ini_get(): upload_max_filesize = ' . ini_get('upload_max_filesize') . '.
';

It outputs:
Loaded php.ini: /etc/opt/rh/rh-php56/php.ini.
Line 810:  upload_max_filesize = 8M.
ini_get(): upload_max_filesize = 2M.

I.e. the path to the php.ini used by the webserver is /etc/opt/rh/rh-php56/php.ini, and it sets upload_max_filesize to 8M on line 810.  Still, the value returned when I call ini_get('upload_max_filesize') is the default.  (Yes, I have restarted Apache).
There are nothing that  sets upload_max_filesize in other .ini files or in .htaccess (I've searched extensively).
I have now exhausted my options for debugging, and hope for answers that will suggest how I can crack this.
Answer: Figured it out at last!
It turns out that restarting Apache (httpd) is not enough to make changes to php.ini take effect with this particular configuration. You also need to restart the FastCGI Process Manager.  The following command resolved it:
sudo systemctl restart rh-php56-php-fpm.service

Comment: To change the PHP configuration when using php-fpm, you don't need to restart Apache at all, only PHP.


Como faco para cadastrar varios registros

Question: Quero fazer vários registros de contatos, queria que fosse mais dinâmico, por exemplo, a pessoa tem uma quantidade de telefones ou celulares ou email's e enquanto esta no site, ela pode clicar em um sinal de soma e a página apresenta novas caixas de texto pra inserir esses dados e depois, precisaria cadastrar no banco de dados todas essas informações. Como eu posso fazer?
inserir.html

      <legend>Outros Contatos</legend>

            Telefone
            Celular
            E-mail

            {{ formCont.tel }}
            {{ formCont.cel }}
            {{ formCont.email }}
             +

models.py:
class RegisterContact(models.Model):
tel = models.CharField('Telefone', max_length = 15, blank=True, null=True)
cel = models.CharField('Celular', max_length = 20, blank=True, null=True)
email = models.EmailField('Email', blank=True, null=True)
ref_pes = models.OneToOneField(Pessoa)

def __str__(self):
    return self.tel

class Meta:
    verbose_name = 'Contato'
    verbose_name_plural = 'Contatos'

views.py:
def insert(request):
form = PessoaForm(request.POST or None)
formCont = RegisterContactForm(request.POST or None)

if form.is_valid():
    resp = form.save()
    formCont.save(resp.id)
    return redirect('accounts:home')

template_name = 'accounts/insert.html'
context = {
    'form': form,
    'formCont': formCont,
}
return render(request, template_name, context)

Comment: Por favor, Arrume a identação do seu código Python. Cole o código aqui e use o botão `{}` para formatar - você está apenas identando a primeira linha, e fazendo com que suas linguagens sejam código inválido no processo.
Comment: Pesquise Por FormsetFactory. Isso vai lhe atender, se ja não resolveu o problema após tanto tempo.
Answer: O que você quer pode ser facilmente resolvido com AJAX.
Crie um script e coloque uma funcção assim assim:
function delete_comment(comment_id) {
    //coloque sua url que leva a view de inserir contactos
    var insert_contact_url = "/url/insert_contact/";
    var contact_data = new FormData();

    var phone = $('#phone_input').val();
    var cellphone = $('#cellphone_input').val();
    var email = $('#email_input').val();
    var person = $('#person').val()

    //cheque a documentação de como passar o CSRF Token no ajax
    contact_data.append('csrfmiddlewaretoken', csrftoken);
    //Aqui será adcionado os dados que será eviado no POST
    contact_data.append('phone', phone);
    contact_data.append('cellphone', cellphone);
    contact_data.append('email', email);
    contact_data.append('person', person);
    $.ajax({
      url: insert_contact_url,
      type: 'POST',
      data: contact_data,
      processData: false,
      contentType: false,
      success: function(data){
          alert('Contato adicionado com sucesso');
      }
    });
}

Você está usando o django forms no caso pode passar as informaçoes assim:
var contact_data = new FormData($('#form_id'));

Isto irá gravar os dados com os respectivos nomes no objeto.
Você pode adptar o codigo da forma que quiser, o que importa e passar um FormData para o AJAX.
Lembrando que utilizei o Jquery nessa função.


Como reproduzir efeito fade in da modal bootstrap para dialog jquery ui?

Question: Estou padronizando os efeitos de visualização da modal, neste projeto possuo tanto modal do bootstrap quanto dialog, acontece que ambos possuem efeitos distintos. queria  deixa-los apenas com fade in, padrão do bootstrap.
Exemplo:

$(function() {
  $("#dialog").dialog({
    autoOpen: false,
    modal: true,
    show: "fade"
  });

  $("#btnDialog").on("click", function() {
    $("#dialog").dialog("open");
  });

  $("#btnModal").on("click", function() {
    $("#modal").modal("show");
  });
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

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

This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×
        </button>

Modal title

One fine body…

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

<button id="btnDialog">Open Dialog</button>
<button id="btnModal">Open Modal</button>

Tentei pegar o css do fade do bootstrap e adicionar no dialog ui, mas não adiantou.
Exemplo no jsfiddle
Comment: E criar um dialog com o modal? retirar o footer e manter o header. Não serve?
Comment: A questão não é a aparência, pois isto eu resolvi no css, as duas estão iguais, o problema é o efeito de transição na modal do bootstrap ela desce, na do dialog ela só aparece aumentando a visibilidade
Comment: Sim, mas a ideia que eu dei resolvia esse problema, se fossem os dois modal.
Comment: Você está falando para remover os dialog tudo e deixar só modal?
Comment: Sim, e usar o modal como dialog. Não pode ser?
Comment: Isto é uma solução definitiva que pretendo adotar, porém o sistema é bem grande e usa muito dialog, não seria algo rápido de se fazer, todas novas implementações já é solicitado que criem no modelo modal do bootstrap...
Comment: Eu acho que era a melhor forma, enquanto isso deixa ficar assim mesmo, não há grande stress, ou há?
Comment: acho q o problema esta na css
Answer: Eu encontrei essa resposta no https://stackoverflow.com/, acho que é isso o que você esta procurando: http://jsfiddle.net/945Tt/4/
Referência: https://stackoverflow.com/questions/17100651/how-can-i-make-jquery-modal-dialog-and-bootstrap-same
Não são exatamente iguais mas as vezes é uma boa solução temporária ate você conseguiu mudar tudo para Modal :)
Vou colocar o código aqui caso a referência fique indisponível.

$(function() {

$("#btnModal").on("click", function() {
    $("#modal").modal("show");
});

$( "#dialog" ).dialog({
autoOpen: false,
    position: { my: "center top", at: "center top+50", of: window },
show: {
effect: "drop",
duration: 1000,
    easing:"easeOutExpo",
    direction:"up",
    distance:300,
},
hide: {
effect: "drop",
duration: 800,
    easing:"easeInExpo",
    direction:"up",
    distance:300,
},
    beforeClose: function( event, ui ) {
        $( ".overlay" ).hide();
    }
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
    $( ".overlay" ).show();
});
});
body {
    font-family: "Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";
    font-size: 62.5%;
}

.overlay { background-color:rgba(0,0,0,0.5); position:fixed; width:100%; height:100%; top:0; left:0; }
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

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

This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×
        </button>

Modal title

One fine body…

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

<button id="opener">Open Dialog</button>
<button id="btnModal">Open Modal</button>


How to Scale and Center UIBezierPath?

Question: I am working with BezierPath and could make a basic star shape within a view successfully, it works great. However, the view's size can be changeable. And I cannot center this bezier path when the view size is changed, I managed to scale it but getting center was hard to me.

private func pointFrom(_ angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint {
    return CGPoint(x: radius * cos(angle) + offset.x, y: radius * sin(angle) + offset.y)//CGPointMake(radius * cos(angle) + offset.x, radius * sin(angle) + offset.y)
}

private func generateStar(width:CGFloat, height:CGFloat, radius:CGFloat) -> CAShapeLayer{
    let path = UIBezierPath()
    var scale = width / height
    if width > height{
        scale = height / width
    }

    let starExtrusion:CGFloat = 60.0

    let center = CGPoint(x: width / 2.0, y: height / 2.0)

    let pointsOnStar = 5

    var angle:CGFloat = -CGFloat(.pi / 2.0)
    let angleIncrement = CGFloat(.pi * 2.0 / Double(pointsOnStar))
    let radius = width / 2.0

    var firstPoint = true

    for _ in 1...pointsOnStar {

        let point = pointFrom(angle, radius: radius, offset: center)
        let nextPoint = pointFrom(angle + angleIncrement, radius: radius, offset: center)
        let midPoint = pointFrom(angle + angleIncrement / 2.0, radius: starExtrusion, offset: center)

        if firstPoint {
            firstPoint = false
            path.move(to: point)
        }

        path.addLine(to: midPoint)//addLineToPoint(midPoint)
        path.addLine(to: nextPoint)//addLineToPoint(nextPoint)

        angle += angleIncrement
    }
    path.apply(CGAffineTransform(scaleX: scale, y: scale))
    path.close()

    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath

    return maskLayer
}

How can I manage to make that? Thanks!
Answer: The center of your path moves with this command:
path.apply(CGAffineTransform(scaleX: scale, y: scale))

To keep your center in the center, scale it by 1 / scale so that when it is scaled by scale, it will end up in the center of the view (since (1 / scale) * scale == 1):
Change:
let center = CGPoint(x: width / 2.0, y: height / 2.0)

to:
let center = CGPoint(x: width / 2.0 / scale, y: height / 2.0 / scale)

The two scalings cancel each other and the center of the path then ends up where it was originally calculated to be.

That said, you are shrinking your star when height != width.  You might get a better result if you forget about the scaling and just choose the minimum of width and height for your radius calculation:
Get rid of scale, or set it to 1.0, then
Change:
let radius = width / 2.0

to:
let radius = min(width, height) / 2.0

That will let the star be as large as possible while still fitting fully within the view.

As you noticed, the star gets "fat" (more circular) as it gets smaller.  This is because you have a hard-coded constant of 60.0 for starExtrusion.  That value should be based upon the radius.
Set starExtrusion after calculating radius:
let radius = min(width, height) / 2.0
let starExtrusion = radius * 0.4

You can vary the 0.4 multiplier to alter the shape of the star.
Comment: Yes, you are definitely right, the problem is all about the extrusion. Since I calculated the starExtrusion dynamically, now it has been working. Thanks for the latest update.
Comment: I tried but it did not work, can you share fully code, maybe I did smth wrong.
Comment: I suggested two different things. Did you try each one  and did neither work?
Comment: Can you share your full code? For instance, what is `pointFrom()`?
Comment: I updated the answer to be clearer about what I changed.  Both of my suggestions worked with your code.
Comment: Sorry for the latency, I've just updated the full code. I tried the second solution, it worked about scaling and centering. But, for example, when the ratio of the view is 2:1, the star's shape is not a star anymore. It changed to like a circle.
Comment: Your star is misshapen because you have a constant value of `60.0` for `starExtrusion`.  It should be calculated based upon the value of `radius`.  You can set the multiplier to get the star shape you want; `0.4` works well.  Set `starExtrusion` after calculating the `radius` with: `let starExtrusion = radius * 0.4`
Comment: I rolled back your question to the original version but with the `pointFrom()` function added.  It fouls up the Q&A when the code in the question is changed to include suggestions from an answer.  Someone reading this later would be confused why my answer is talking about `scaling` when your code doesn't include it and suggesting making `radius = min(width, height) / 2.0` when your code already does that.
Answer: UIView's layoutSubviews got called when resized, you can reset the mask by overriding that method.
Comment: I already call layoutSubviews, but the problem is how to reset the mask? Because the mask is only working if the width and the height are equal.

How to Scale and Center UIBezierPath?


LRT of normal distribution - explanation of numerator

Question:
Let $X_1,...,X_n$ be random sample of $X$~$N(\mu,\sigma^2)$ with known
  $\sigma^2$. I am trying to derive test statistic for that distribution

I know that $\hat{\mu}=\overline{X}$
$$\lambda(x)=\frac{\sup_{\Theta_0}L(\theta|x)}{\sup_{\Theta}L(\theta|x)}=\frac{(2\pi)^\frac{-n}{2}(\sigma^2)^{\frac{-n}{2}}e^{-\frac{1}{2\sigma^2}\sum (x_i-\mu_0)^2}}{(2\pi)^\frac{-n}{2}(\sigma^2)^{\frac{-n}{2}}e^{-\frac{1}{2\sigma^2}\sum (x_i-\overline{x})^2}}$$
Which results in
$$\lambda(x)=e^{-\frac{n}{2\sigma^2}(\overline{x}-\mu_0)^2}$$
So my question now is. How to transform numerators exponent from $$\sum(x_i-\mu_0)^2$$ to $$\sum(x_i-\overline{x})^2+n(\overline{x}-\mu_0)^2$$
Whith results in:
$$\sum(x_i-\mu_0)^2 = \sum(x_i-\overline{x})^2+n(\overline{x}-\mu_0)^2$$
It is clearly some product of two exponential functions, but I don't understand it.
Answer: It's surprisingly simple, and a good trick to remember as it comes in handy in different applications as well:
$$\begin{eqnarray}
\sum(x_i-\mu)^2 &=& \sum(x_i-\bar{x}+\bar{x}-\mu)^2 \\
&=&\sum(x_i-\bar{x})^2 + \sum(\bar{x}-\mu)^2+2\sum(x_i-\bar{x})(\bar{x}-\mu) \\
&=& \sum(x_i-\bar{x})^2 + \sum(\bar{x}-\mu)^2 + 2(\bar{x}-\mu)\sum(x_i-\bar{x})\\
&=& \sum(x_i-\bar{x})^2 + \sum(\bar{x}-\mu)^2 \\
&=& \sum(x_i-\bar{x})^2 + n(\bar{x}-\mu)^2
\end{eqnarray}$$
as $\sum(x_i-\bar{x}) = \sum x_i - \sum\bar{x} = \sum x_i - n\bar{x} = \sum x_i - \sum x_i = 0$.


$f:[a,b]\to \mathbb R$ is continuous , has a finite number of local maxima and minima ; then how to prove that $f$ is bounded variation on $[a,b]$ ?

Question: If $f:[a,b]\to \mathbb R$ is a continuous function having  finite number of local maxima and minima ; then how to prove that $f$ is bounded variation on $[a,b]$ ?
Answer: Hint: Every monotonic function on a closed interval is of bounded variation.  Split your function into finitely many monotonic segments.
Comment: Please give some more details ; how to get those monotone functions ?
Comment: In between a min and a max, the function must be increasing.  In between a max and a min, the function must be decreasing.
Comment: How to show that in between a local max and min , the function must be decreasing ? And is it certain that min's and max's occur alternatively ?


get cookies set by javascript using curl

Question: I'm writing a script that uses curl to fetch the contents of a webpage. I search the headers for Set-Cookie to collect the names of all cookies set by the page. The problem is that some cookies are set from within a javascript file loaded into the page and of course these cookies aren't included in the response headers.
So, is there a way to get all cookies from a webpage using curl, including the ones that is generated through javascript?
Currently I'm doing something like this:
$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, <www.example.com>);
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_code == 200) {
  $headers = substr($response, 0, curl_getinfo($curl, CURLINFO_HEADER_SIZE));
  // check headers for all cookies sent in response
}
curl_close($curl);

Comment: no. it's not. not unless you want to parse/execute the JS code once you've spidered/slurped down the page.
Answer: cURL isn't going to run javascript, so no, there won't be a way to get those cookies. You'll have to emulate or automate a browser in order to achieve that. Fortunately there are tools to help you. Maybe take a look at PHP-webdriver
Comment: @KristerAndersson take a look at http://stackoverflow.com/questions/4331938/interpreting-javascript-in-php


MySQL - "SHOW VARIABLES LIKE '%version%'" not working in my Java application

Question: When I run SHOW VARIABLES LIKE '%version%' in MySQL command line console it runs very fine, but when I run the same code in the Java application I'm working on it produces the following error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'VARIABLES' in 'field list'

Here is my Java code:
ConnectionHelper.setDatabaseName('information_schema');

Statement statement = ConnectionHelper.getStatement();
ResultSet = statement.executeQuery ("SHOW VARIABLES LIKE '%version%'");

String serverVersion = null;
while (resultSet.next()) {
    serverVersion = resultSet.getString(3);
}

The ConnectionHelper is just a class that creates and sets up a connection to any database passed as parameter to the setDatabaseName() method.
I've even tried not to set any database since the query runs in MySQL command line console even without selecting any database, but still produces the same error.
Please I really need help.
Answer: You may use the INFORMATION_SCHEMA GLOBAL_VARIABLES and SESSION_VARIABLES tables like this:
SELECT *
FROM information_schema.global_variables
WHERE variable_name LIKE '%version%';

Sample output:

|           VARIABLE_NAME |                       VARIABLE_VALUE |
|-------------------------|--------------------------------------|
|          INNODB_VERSION |                               5.5.32 |
|        PROTOCOL_VERSION |                                   10 |
|         VERSION_COMMENT | MySQL Community Server (GPL) by Remi |
|                 VERSION |                               5.5.32 |
| VERSION_COMPILE_MACHINE |                               x86_64 |
|      VERSION_COMPILE_OS |                                Linux |
|  SLAVE_TYPE_CONVERSIONS |                                      |

Here is SQL Fiddle demo.

UPDATE (based on your comments)
You can specify all variable names that you need with IN clause
SELECT *
FROM information_schema.global_variables
WHERE variable_name IN ('version', 'hostname', 'port');

Sample output:

| VARIABLE_NAME | VARIABLE_VALUE |
|---------------|----------------|
|       VERSION |         5.5.32 |
|      HOSTNAME |            db2 |
|          PORT |           3306 |

Here is SQL Fiddle demo.
Comment: @Harmony Did it help? Do you need more help with your question?
Comment: Sorry for not responding as soon as I supposed to, I was sick.
Comment: I like your idea, but is there a way I can also get the server type?, like: localhost via TCP/IP  ?
Comment: See updated answer. You can specify all variable names you're interested in using `IN` clause.
Answer: You can try running this if you just want the DB version:
SELECT VERSION();

I tested this locally
sql = "SELECT VERSION() AS version";
rs = stmt.executeQuery(sql);
while (rs.next()) {
     System.out.println(rs.getString("version"));
}

Result: 5.6.13

You could also select any MYSQL variable like this:
SELECT @@version AS version;

The results of your original query on my machine is:

'innodb_version','5.6.13'
'protocol_version','10'
'slave_type_conversions',''
'version','5.6.13'
'version_comment','Source distribution'
'version_compile_machine','x86_64'
'version_compile_os','osx10.8'

So you could select each global variable one by one like this:
SELECT @@version as version,
       @@innodb_version as innodb_version,
       @@verision_compile_os as version_compile_os
       @@protocol_version as protocol_version
       @@version_compile_machine as version_compile_machine
.....

Comment: Sorry for not responding as soon as I supposed to, I was sick.
Comment: I really appreciate all your contributions, but which of these do you think would be the best, because apart from the mysql version I also intended to get the protocol version and server type
Comment: Both my answer and peterm's answer are more or less the same. He's directly accessing the table where the variables are stored `information_schema.global_variables` and I am using the shorthand notation for accessing global variables `@@`
Comment: Alright thanks so much, I have used the answer by MagicMan coz it seems shorter to me. Thankyou MagicMan.


Smooth function not analytic at any $ x$

Question: Does there exist function $ f $ that is smooth but not analytic for all $x\in \Bbb{R}$?
($f $ is a Real-valued function)
Comment: See also [A smooth function which is nowhere real analytic](https://en.wikipedia.org/wiki/Non-analytic_smooth_function#A_smooth_function_which_is_nowhere_real_analytic) on Wikipedia.
Comment: i want to find not analytic for all $x \in R$
Comment: not one point, i find not analytic for all $ x \in Z$
Answer: $$\phi(x) =  e^{-1/(1-x^2)} 1_{|x|< 1}\in C^\infty_c(\Bbb{R}), \qquad \Phi(x) =  \sum_{k=0}^\infty e^{-e^{e^k}}\sum_{n=-\infty}^\infty \phi(2^k x+n) \in  C^\infty(\Bbb{R})$$


About the function $x^2\sin{\frac 1 x}$ .

Question: My problem is to disprove, using the function $g(x):=x^2\sin{\frac 1 x}$ for $x\ne 0$ and $g(0):=0$, the following statement:
Let $f:(a,b)\to\mathbb R$ be differentiable. Let $(t_n)$ be a sequence converging to some $c\in(a,b)$. Then $\lim_n f'(x_n)=f'(c)$.
By looking into the graph of $y=g'(x)$, I see that there exist a sequence $(s_n)$ converging to $0$, such that $\lim_n f'(s_n)=1\ne0=f'(0)$. But I don't know how to proof the existence of such sequence.
Comment: $\frac{1}{n\pi}$?
Comment: How is this function possibly differentiable at $x=0$? If you look at the [graph of the derivative](http://www.wolframalpha.com/input/?i=derivative+of+x%5E2*sin%281%2Fx%29), the graph is going all over the place near $x=0$.
Comment: @ Noble, differrentiability does not imply continuous derivative.
Comment: @ᴊᴀsᴏɴ Then how is $\lim_{h \to 0} \frac{g(h)-g(0)}{h}$ defined? Isn't this $\lim_{h \to 0} h\cdot sin(1/x)$? -- Oh, wait, [the limit of this is defined](https://math.stackexchange.com/questions/1832068/about-the-function-x2-sin-frac-1-x#1832068). Sorry about that!
Comment: @NobleMushtak $\lim_{h\to 0} \frac{g(h)-g(0)}{h}=\lim_{h\to 0} \frac{ h^2\sin \frac{1}{h}}{h}=\lim_{h\to 0} h\sin \frac{1}{h} =0$
Answer: We see $$f'(x) = \left\{\begin{matrix} 2x \sin\left( \tfrac 1 x \right) - \cos\left( \tfrac 1 x \right), & x \neq 0, \\ 0, & x = 0. \end{matrix} \right.$$ If we put $x_n = \frac{1}{(2n+1)\pi}$ then $$f(x_n) = \tfrac{2}{(2n+1)\pi} \sin((2n+1)\pi) - \cos((2n+1)\pi).$$ But $\sin((2n+1)\pi) = 0$ and $\cos((2n+1)\pi) = -1$ so $$f(x_n) = 1$$ for each $n \in \mathbb N$. However, it is clear that $x_n \to 0$.
Comment: Here $f$ is continuous and differentiable on all of $\mathbb R$. So you could take the interval to be $\mathbb R$ or if you really wanted a finite interval just take it to be $(-a,a)$ for any $a > 0$ (then of course we will need to restrict to large enough $n$ so that $x_n \in (-a,a)$). EDIT: This comment was in response to other comments which have since been deleted.
Comment: My bad understanding!!! You are right! I did not notice to the function very well. Thanks.


Mac-friendly hotkeys?

Question: We get more and more customers that install our Windows application on Macs (via Bootcamp, WMWare, Parallels or Wine). We use TAB, Insert and Home as hotkeys for quick toggling of features.
Are there good alternatives to Home and Insert that would be easier to access on a Mac keyboard?
Comment: Doesn't macs have a home key???
Comment: Not to be too much of a smart-ass, but if they're going to jump through the hoops of Bootcamp, et.al., shouldn't they be astute enough to ascertain the equivalent keys on their Mac?  (BTW, I own a Mac and sure don't expect that anybody who sells Windows software is going to support emulator users with questions like this)
Comment: @KevinDTimm: I agree, but schools in Sweden have started to provide each student with a laptop. Some of them are handing out MacBooks. It is great marketing if the students can use our software in school. If we can make that easier it is a good investment.
Answer: You might be interested in: http://support.apple.com/kb/ht1343
Comment: These to articles are more relevant to keyboard mapping:
http://support.apple.com/kb/ht1167 and http://support.apple.com/kb/HT1220

Mac-friendly hotkeys?


why redux-offline with react-native not send the POST request?

Question: I have delete_task action that POST the task id to PHP file to delete the task , although the action I fired correctly and i see the effect in the console but the task not deleted, i tried many many times using GET OR POST OR JUST put the id statically in the URL but nothing changing,can anyone help me to solve the problem
tasksAction.js
export  const delete_task = id => ({
    type: DELETE_TASK,
    payload: {id},
    meta: {
        offline: {
            // the network action to execute:
            effect: { url: 'http://localhost/todos/remove.php', method: 'POST',body: {id} },
            // action to dispatch when effect succeeds:
            commit: { type: DELETE_SUCCESS, meta: { id } },
            // action to dispatch if network action fails permanently:
            rollback: { type: DELETE_FAILED, meta: { id } }
        }
    }
});

store.js
import React, { Component } from 'react';
import { applyMiddleware, createStore, compose } from 'redux';
import { offline } from '@redux-offline/redux-offline';
import offlineConfig from '@redux-offline/redux-offline/lib/defaults';
import {Provider} from 'react-redux';
import logger from 'redux-logger';

import RootNavigator from "./config/routes";
import reducers from './reducers'

// store
const middleware = [];
if(process.env.NODE_ENV === 'development'){
    middleware.push(logger);
}
const store = createStore(
    reducers,
    undefined,
    compose(
        applyMiddleware(...middleware),
        offline(offlineConfig)
    )
);

export default class App extends Component {

    render() {
        return (
            <Provider store={store}>
            <RootNavigator />
            </Provider>

        )
    }
}

Answer: In the offline object inside prev state, does it say online: false?
If it does, and you're developing in an Android emulator, Wifi is not available on the emulator if you are using below API level 25, so redux-offline thinks you have no connection and will not make the initial network request.
This occurred to me after testing redux-offline in an iOS simulator and everything worked.
Hope this helps.


Display and navigate inside a website in fullscreen

Question: I would like to display my website in a "full screen" mode. To do it, I add to my website this script: https://github.com/sindresorhus/screenfull.js. It allows me to display the page in a "full screen" mode.
I upload my footer in order to display a button that activate the full screen mode.
It's working great.
here is my footer:

Full screen

here is my Js:
if (screenfull.enabled) {
            // Display the button if the browser is compatible
    $('.fullscreen').show();
}

$('.fullscreen').toggle(function() {
    screenfull.request();
}, function() {
    screenfull.exit();
});

Otherwise, when I'm clicking on a link (redirect the user to another page), the "full screen" mode is cancelled. Does any one know how to fix it?
Is it possible to develop a website in a "full screen" mode and allow the user to navigate without quitting this mode? I'm taking any ressources.
Thanks
Answer: From what I see of this library, you need to put the page you are directing the user to in an iframe and then display that iframe. The library you point to has a sample page that includes a sample of how to load an external page in full screen. The code is as follows:
var iframe = document.createElement('iframe')
iframe.setAttribute('id', 'external-iframe');
iframe.setAttribute('src', 'http://bbc.com');
iframe.setAttribute('frameborder', 'no');
iframe.style.position = 'absolute';
iframe.style.top = '0';
iframe.style.right = '0';
iframe.style.bottom = '0';
iframe.style.left = '0';
iframe.style.width = '100%';
iframe.style.height = '100%';
$('#container').prepend(iframe);
document.body.style.overflow = 'hidden';

I pulled this code right out of the example at http://sindresorhus.com/screenfull.js/.


JavaScript function not called for all events

Question: I am new to Javascript and HTML programming and I couldn't fix this error.
There's a function Getvalues() in Javascript code that runs fine for the first
text box with ID = sq1, whenever onchange event is called. More precisely, its only working for the textbox with id=sq1, e.g if I swap the ids, it works for that box. So basically I want it to work with all onchange events. As I am learning the basics, I would appreciate any help.

 <TITLE>TEST Program</TITLE>

TEST Program

  <FORM>

     <input type="text" id="sq1" style= "font-size:50pt; text-align:center; width:100%; height:100%" onchange = "GetValues()" >

     <input type="text" id="sq2" style= "font-size:50pt; text-align:center; width:100%; height:100%" onchange = "Getvalues()" >

     <input type="text" id="sq3" style= "font-size:50pt; text-align:center; width:100%; height:100%"onchange = "Getvalues()" >

  </FORM>

Comment: Since you say you're just learning the basics, I'd suggest switching your reading material - whatever book or blog you're using appears to be outdated, just based on the capitalized elements and the deprecated table attributes. Also, you've got some invalid items, like your `title` being outside the `head`, and your `h3` being inside the `head` instead of the `body`.
Comment: I like to use books as my reference material than blogs or online content.
It would be very disappointing for you to know that I am learning using my notes made in my web engineering class. Guess my teacher is a orthodox.
What book do you suggest for HTML and JavaScript.  I am not willing to use CSS or php atm.
Answer: Don Bottstein appears to be right, your GetValues() function is misspelled in some tags in your HTML.
An easier way to do this than attaching a function to each tag in the HTML would be event propagation.  That is, attach an event to the parent, then use an if statement to figure out if the thing being changed is an input, and call the GetValues() function on it then.
Something like;

 //  Add an ID to the TR tag in the HTML

document.getElementById("values").addEventListener("change", function(e) {
    //  e is the object that's triggering the event
    if (e.target.type === "text") {
            GetValues();
        }
    })

Answer: Your onchange event is calling GetValues() for sq1, but Getvalues() for sq2 and sq3.


How can I use ajaxSuccess() outside of .ajax()

Question: Im using Woocommece in a WordPress website and some of the plugins installed make requests to an API to check and validate a vat field.
Id like to use .ajaxSuccess() to tap into the ajax response thats returned so I can check to see if part of it contains some data and do something on screen.
So far Ive got this.
jQuery(document).ready(function(){

   var event = 'updated_checkout'

   jQuery(document).ajaxSuccess(function(event){

       console.log('success');

   })

})

So the console spits out success. Great. But Im stuck as how I would move forward with this. I dont know how to get the XHR option or get he response in a variable.
Any help would be appreciated.
Answer: To get the response from the request in the $.ajaxSuccess() handler, retrieve the responseText property from the jqXHR object passed to the handler function in the second argument:
jQuery(document).ready(function($) {
  var event = 'updated_checkout'

  $(document).ajaxSuccess(function(e, xhr) {
    console.log(xhr.responseText);
  });
});

Comment: Ah, I thought I had to define them in some way before hand. Thanks


Analytic expression for $\mathbb E_X[(X^\top u)^p (X^\top v)^p]$, where $u$ and $v$ are fixed vectors in $\mathbb R^d$ and $X$ is uniform on sphere

Question: Let $u$ and $v$ be fixed vectors in $\mathbb R^d$. Let $X$ be a random vector uniformly distributed on the unit-sphere in $\mathbb R^d$, and let $f_p$ be a real polynomial of degree $p \ge 1$ (for simplicity, we might simply consider $f_p(t) \equiv t^p$).

Question. What is an analytic expression for the correlatetion $c(u,v) := \mathbb E_X[f(X^\top u)f(X^\top v)]$ ?

Special case $p=1$
In this case, a simple computation gives
$$
c(u,v) = \mathbb E[X^\top uv^\top X] = \mbox{trace}(\mbox{cov}(X)uv^\top) = \mbox{trace}((1/d) I_d uv^\top) = \frac{u^\top v}{d}
$$

Is it too crazy to conjecture that in general, $c(u,v) = K_{d,p} \cdot (u^\top v)^p$, for some constant $K_{d,p}$ which only depends on $d$ and $p$ ?
Answer: Here's a strategy for computing $c_{p,q}(u,v)=\mathbb{E}[(X^T u)^p(X^T v)^q]$. First compute the generating function $G(\lambda)=\mathbb{E}(e^{i\lambda^TX})$, then set $\lambda=au+bv$. The result is that we can express the quantities above as derivatives of the generating function:
$$c_{p,q}(u,v)=(-i)^{p+q}\frac{\partial^{p+q}}{\partial a^p \partial b^q}G(au+bv)\Bigg|_{a=b=0}$$
Calculating the generating function is fairly simple for $X$ uniformly distributed on the sphere by performing a rotation so that the vector $\lambda$ is in the $x_1$ direction:
$$G(\lambda)=\int e^{i\lambda\cdot x}\frac{d\Omega_{d-1}}{\mu(S_{d-1})}=\frac{1}{\mu(S_{d-1})}\int_{R^{d}}d^dx \delta(|x|-1)e^{i\lambda\cdot x}=\frac{1}{\mu(S_{d-1})}\int_{R^{d}}d^dx \delta(|x|-1)e^{i|\lambda| x_1}$$
Reverting back to spherical coordinates
$$G(\lambda)=\int e^{i|\lambda|\cos\theta}\frac{d\Omega_{d-1}}{\mu(S_{d-1})}=\frac{\mu(S_{d-2})}{\mu(S_{d-1})}\int_{0}^{\pi}\sin^{d-2}\theta~ e^{i|\lambda|\cos\theta}d\theta$$
We recognize the last integral as the Poisson integral for Bessel functions, and hence $G(\lambda)$ can be succinctly written in closed form
$$G(\lambda)=2^{d-2/2}\Gamma\left(\frac{d}{2}\right)\frac{J_{\frac{d-2}{2}}(|\lambda|)}{|\lambda|^{\frac{d-2}{2}}}$$
Using the series representation of the Bessel function one can show that
$$G(au+bv)=\sum_{n=0}^{\infty}\frac{(-1)^n \Gamma(d/2)}{n!\Gamma(n+d/2)2^{2n}}(a^2|u|^2+b^2|v|^2+2ab (u\cdot v))^n$$
We see immediately that the result is non-zero only when $p+q$ is even. It is also obvious that the conjecture cannot hold since
$$c_{2,2}(u,v)\propto 4(u\cdot v)^2+2 |u|^2 |v|^2$$
I have not found a satisfactory algebraic formula for arbitrary $p,q$, to be continued!
EDIT: I came up with a good way to expand this sum.
Obviously when one choose particular values $p+q=2m$, only the term with $n=m$ in the sum will contribute. All we need to do is expand the multivariable polynomial in parentheses above for any value of $n$. The trinomial theorem is not very illuminating so we pick a different route. First rewrite with $z=b/a$
$$(a^2u^2+b^2v^2+2ab(u\cdot v))^m=a^{2m}|v|^{2m}(z+\lambda e^{i\theta})^m(z+\lambda e^{-i\theta})^m$$
where $\lambda=|u|/|v|$, and, $|u||v|\cos\theta=u\cdot v$, $|u||v|\sin\theta=\sqrt{u^2 v^2-(u\cdot v)^2}$
Now we can use the binomial expansion on each of the individual terms
$$(a^2u^2+b^2v^2+2ab(u\cdot v))^m=a^{2m}|u|^{2m}\sum_{kl}{m\choose k}{m\choose l}\left(\frac{z}{\lambda}\right)^{k+l}(e^{i\theta})^{l-k}$$
All we need to do now is reindex the sum so that everything is written as a coefficient of $z^s$:
$$(a^2u^2+b^2v^2+2ab(u\cdot v))^m=a^{2m}|u|^{2m}\sum_{s=0}^{2m}z^s(\lambda e^{i\theta})^{-s}\sum_{l=\max(s-m,0)}^{\min(s,m)}{m\choose s-l}{m\choose l}e^{i2l\theta}$$
One can explicitly show that this expression is real. We take the real part of the right hand side and since $\cos(n\theta)=T_n(\cos\theta)$ are the Chebyshev polynomials
$$(a^2u^2+b^2v^2+2ab(u\cdot v))^m=a^{2m}|u|^{2m}\sum_{s=0}^{2m}z^s\lambda^{-s}\sum_{l=\max(s-m,0)}^{\min(s,m)}{m\choose s-l}{m\choose l}T_{2l-s}\left(\frac{u\cdot v }{|u||v|}\right)$$
with the understanding that $T_{-n}(x)=T_n(x), n>0$. Finally, we conclude that
$$c_{2m-p,p}(u,v)=\frac{\Gamma(d/2)\Gamma(p+1)\Gamma(2m-p+1)}{2^{2m}\Gamma(m+d/2)\Gamma(m+1)}|u|^{2m-p}|v|^p\sum_{l=\max(p-m,0)}^{\min(p,m)}{m\choose p-l}{m\choose l}T_{2l-p}\left(\frac{u\cdot v }{|u||v|}\right)$$
I haven't attempted to try and simplify the Chebyshev polynomials much further. Further simplification occurs when $m=p$ but not to the point of a compact expression better than
$$c_{p,p}=\frac{\Gamma(d/2)\Gamma(p+1)}{2^{2p}\Gamma(p+d/2)}|u|^p |v|^p\sum_{l=0}^{p}{p \choose l}^2T_{2l-p}\left(\frac{u\cdot v }{|u||v|}\right)$$
Comment: Great. Thanks. Upvoted. Leaving this open for a while more, then will come back an accept your answer.
Answer: Let $Y=(Y_1,\ldots,Y_d)$ be a collection of iid $N(0,1)$'s. Then by using (hyper)spherical coordinates
$$
E[(Y\cdot u)^p(Y\cdot v)^q]=(2\pi)^{-\frac{d}{2}}\int_{0}^{\infty}dr\ {\rm vol}(S^{d-1}) \ r^{d-1+p+q}\ e^{-\frac{r^2}{2}}
\ E[(X\cdot u)^p(X\cdot v)^q]
$$
$$
=\frac{2^{\frac{p+q}{2}}\Gamma\left(\frac{p+q+d}{2}\right)}{\Gamma\left(
\frac{d}{2}\right)}\times
\ E[(X\cdot u)^p(X\cdot v)^q]
$$
We need $p+q$ even for a nonzero result, so we assume that. The Gaussian expectation
$E[(Y\cdot u)^p(Y\cdot v)^q]$ can be computed with the Isserlis-Wick Theorem. It amounts to a sum over complete matchings of a set with $p+q$ elements subdivided into two compartments, one of size $p$ and one of size $q$. Let me organize the count according to $k$, the number of matched pairs joining the two compartments. We then get
$$
E[(Y\cdot u)^p(Y\cdot v)^q]=
$$
$$
\sum_{k}\binom{p}{k}\binom{q}{k}
\times k!\times\frac{(p-k)!}{2^{\frac{p-k}{2}}\left(\frac{p-k}{2}\right)!}
\times\frac{(q-k)!}{2^{\frac{q-k}{2}}\left(\frac{q-k}{2}\right)!}
\times (u\cdot v)^{k}(u\cdot u)^{p-k}(v\cdot v)^{q-k}
$$
where the sum is over $0\le k\le\min(p,q)$ of same parity as $p$ and $q$.
Finally, after some cleanup,
$$
E[(X\cdot u)^p(X\cdot v)^q]=
$$
$$
\frac{p!q!\ \Gamma\left(
\frac{d}{2}\right)}{2^{p+q}\ \Gamma\left(
\frac{p+q+d}{2}\right)}\times \sum_k
\frac{2^k}{k!\left(\frac{p-k}{2}\right)!\left(\frac{q-k}{2}\right)!}\times
(u\cdot v)^{k}(u\cdot u)^{p-k}(v\cdot v)^{q-k}
$$
with the same range of summation for $k$.
(this is a quick computation, didn't yet check for errors typos etc.)
Comment: Great (upvoted). This is in the same spirit as the alternative answer I posted above. The interesting thing in your answer is that you've explicitly developed it as a $(p+q)$-degree polynomial in $u^\top v$, $\|u\|^2$, and $\|v\|^2$ (which was to be expected, since these are traces of powers of the psd matrix $(uv^\top + vu^\top)/2$).
Answer: Here's an alternate solution I came up with. So, let $Z$ be a random vector in $\mathbb R^d$ with iid components distributed according to $N(0,1)$. Set $R := \|X\|$ and note that

$X$ and $Z/R$ have the same distribution.
$R$ and $Z$ are independent.

Let $A := (uv^\top + vu^\top)/2$, a psd matrix, and note that $E[(X^\top u)^p(X^\top v)^p] = E[(X^\top A X)^p]$. One computes
$$
E[(Z^\top A Z)^p] = E[R^{2p}]\cdot E[(X^\top AX)] = E[R^{2p}]\cdot E[(X^\top u)^p(X^\top v)^p]. \tag{1}
$$
Now, $E[R^{2p}] = E[(\|Z\|^2)^p] = 2^p \cdot \dfrac{\Gamma(p + d/2)}{\Gamma(d/2)}$, the $p$th moment of a chi-squared random variable with $d$ degrees of freedom It remains to compute. Combining with (1) then gives
$$
E((X^\top u)^p(X^\top v)^p] = \frac{\Gamma(d/2)}{2^p\Gamma(p+d/2)}\cdot\sigma_p(A).\tag{2}
$$
It remains to compute $\alpha_p(A) := E[(Z^\top A Z)^p]$.
Now, since as early as this paper https://www.janmagnus.nl/papers/JRM003.pdf, it is known that the $\sigma_p(A)$ is a polynomial in the first $p$ cumulants $\kappa_1,\ldots,\kappa_p$ of $N(0,1)$, and in fact for the first $2$ values of $p$, evaluates to
$$
\begin{split}
\sigma_1(A) &= \mbox{tr} A = u^\top v\\
\sigma_2(A) &= (\mbox{tr} A)^2 + 2\mbox{tr} A^2 = 2(u^\top v)^2 + \|u\|^2 \|v\|^2\\
&\;\;\vdots
\end{split}
$$
In particular, using (2) gives $E[(X^\top u)(X^\top v)] = \dfrac{u^\top v}{d}$ (which was already computed directly) and
$$
E[(X^\top u)^2(X^\top v)^2] = \dfrac{2(u^\top v)^2 + \|u\|^2 \|v\|^2}{4(d/2 + 1)(d/2)} = \dfrac{2(u^\top v)^2 + \|u\|^2\|v\|^2}{d(d+2)}.
$$


Como restringir acesso por usuário no Codeigniter

Question: Tenho um sistema que eu preciso restringir acesso em algumas áreas como a Administração do Usuário, por exemplo.
Eu não estou sabendo como pegar o usuário que está logado.
Sei que eu preciso restringir acesso ao arquivo e ocultar o menu.
<?php
        $this->load->model('Usuarios_model');
            if($usuario) { ?>

            Usuários

<a href="<?php echo base_url('usuario/visualizar_todos'); ?>">Visualizar

<a href="<?php echo base_url('usuario/cadastrar'); ?>">Cadastrar

        <?php  }; ?>

Comment: Você pode usar sessão para fazer isso. Se o usuário tentar acessar alguma página num controller admin, no __contruct desse controle vai ter a verificação de sessão admin, se a sessão não for válida, redireciona ele para login.
Comment: Você teria como me explicar com mais detalhes?
O meu está assim:

public function __construct()
    {
        parent::__construct();

        if(!$this->session->userdata('logado'))
        {
            redirect('conta/entrar');
        }
    }

Eu não tenho muita experiência. Estou começando a aprender.
Comment: É exatamente isso, só que essa sessão pertence ao usuário. É só você criar uma igual para o admin, mas lembre-se de mudar o nome da sessão de admin, exemplo: admin_logado, isso vai de seu gosto.
Comment: Seria algo como:
$this->session->userdata('adm_logado');
Eu quero ocultar o menu e bloquear o acesso de quem não é adm.
Não estou compreendendo.
Comment: Como está organizado a questão de login admin e usuário na pagina web ? Ambos usam a mesma página de login  ?
Comment: Cuidado ao bloquear páginas admin somnte usando ifs no menu, se eu tiver conhecimento da URL e digitar ela no browser, certamente eu vou conseguir acessar o recurso. Para evitar isso, você precisa criar um sessão admin e verificar se a sessão está ativa no __construct() do controller que está sendo acessado.
Answer: Fabrício, você precisará configurar as variáveis de sessão, tente assim, crie um controlador de LOGIN.
public function entrar(){
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        $this->form_validation->set_rules('senha', 'Senha', 'required|trim');
            if ($this->form_validation->run() == TRUE){

                $formData = $this->input->post();

                $this->load->library('usuario');
                $user = new Usuario;

                if( $user->_check($formData['email'], $formData['senha']) == FALSE ) {
                    $this->session->set_flashdata("msg",'
Usuário / Senha não conferem
');
                } else {
                    $this->session->set_userdata("logado", TRUE);
                    $this->session->set_userdata("userID", $user->getId());
                    redirect("dashboard");
                }
            }

        $this->load->view("login/v_header", array('pageTitle'=>'Entrar no Sistema | miPague', 'title'=>'Entrar no sistema'));
        $this->load->view("login/v_loginForm");
        $this->load->view("login/v_footer");
    }

No meu caso eu criei uma library para cuidar do usuário, mas pode ser um model também, fica por sua escolha. Minha library tem a função _check que tem a seguinte estrutura:
 public function _check($email, $senha){
        $CI =& get_instance();
        $CI->load->model(array('m_login','m_clientes'));
        $CI->load->library(array('safe'));
        $user_mail = $CI->m_clientes->buscar_email($email);
        if($user_mail){
            $user_pass = $CI->m_login->check_user($user_mail->id);
            if($user_pass){
                $q = $CI->safe->valid_crypt($senha, $user_pass->senha);

                if($q == FALSE){
                    return FALSE;
                } else {
                    $this->setId($user_mail->id);
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

Perceba que esta função carrega um comando chamado $CI =& get_instance();  isso me permite carregar outra library/model dentro dele diretamente usando apenas o comando $CI->load->model('nome_model');
A biblioteca safe, se encarrega de criptografar a senha do usuário e validar se a senha enviada pelo usuário confere com a cryptografada. Não postarei a minha rotina de criptografia pois ela tem particularidades que não desejo expor.
De qualquer modo, voltando ao Controlador de Login, há um if logo após o comando: $user = new Usuário; Este if faz o seguinte, SE a senha e o usuário não existirem, gera um erro na sessão usando o $this->session->set_flashdata("var","mensagem aqui dentro")
Caso exista o usuario e a senha for válida, seta a variável "logado" como TRUE e o id do usuário na variável de sessão "userID"
Depois para checar se existe na sessão um usuário ( userID ) basta usar o um dos seguintes comandos:
$this->session->userdata("userID");
// Ou usar
$_SESSION['userID'];

Agora basta usar comandos básicos do PHP como empty ou exists para mostrar/ocultar o que quiser no sistema, ou mesmo redirecionar.
Deixarei um link para um tutorial bem legal e completo de onde eu aprendi a fazer o sistema:
Dicas Codeigniter - Tela de Login com Bootstrap e CI
Abraço...


How many singular values of a positive stochastic matrix (Google matrix) are greater than $1$?

Question: By chance I've decided to calculate the following svd composition, which is the example shown here in figure 3. I've typed in MATLAB's command window:
$S=\begin{pmatrix}
0 & 1/2 & 1/3& 0 &1/5\\
     1& 0& 1/3& 1/3& 1/5\\
     0& 1/2& 0& 1/3& 1/5\\
     0&  0 &1/3& 0& 1/5\\
     0& 0& 0& 1/3& 1/5\\
\end{pmatrix}$
$G = 0.85*S + 0.15*(1/5)*ones(5,1)*ones(1,5)$;
If you type the command:
$[U,S,V,flag]=svds(G)$
MATLAB will return the singular values: $1.1159, 0.7068, 0.4007, 0.2864, 0.0000 $ and $flag 0$ (converged).
I've done the same for other small Google matrices and they returned JUST ONE singular value greater than one.
MY QUESTION IS:
How many singular values are greater than $1$ in a Google matrix?
Comment: Please define a google matrix. You mean each column sums to 1?
Comment: @J.M.isnotamathematician Hmm, no. The "Google matrix" in the OP is not $S$, but $G$, which is a convex combination of $S$ and the all-one matrix. In the original PageRank paper, the weight for the all-one matrix (called a "damping factor") is a strictly positive number. The convex combination is also entrywise positive. There isn't any zero entries.
Comment: It looks like what you call a "Google matrix" is more conventionally called a "left stochastic" or "column stochastic" matrix.
Comment: @J.M.isnotamathematician Not exactly. A so-called Google matrix is an *entrywise positive* stochastic matrix.
Comment: @user, I see, so that terminology assumes $0$ is positive... ;)
Answer: Here's a partial answer: if the matrix is $n\times n$, it can have as many as $\lfloor\frac n2\rfloor$ singular values greater than $1$. I don't know whether there can be more (although I guess not), but $\lfloor\frac n2\rfloor$ is always achievable if you don't impose a positive lower bound to the entries of $G$.
By a continuity argument, it doesn't matter whether the matrix is entrywise positive or merely nonnegative. So, it's OK to allow zero entries. Let $M= \lceil\frac n2\rceil $ and $m=\lfloor\frac n2\rfloor$ (so that $M\ge m$ and $n=M+m$). Note that when $G$ is a generic stochastic matrix in the form of
$$
G=\pmatrix{I_M&0\\ X&Y},
$$
the leading principal $M\times M$ submatrix of $G^TG$ is given by $I_M+X^TX$. Since $X$ is $m\times M$, we can always find $G$ such that $X$ has full row rank. Therefore $I_{\lceil n/2\rceil}+X^TX$ has $m$ eigenvalues greater than $1$ (and $M-m$ eigenvalues exactly equal to $1$, but that is irrelevant here). Consequently, by Cauchy's interlacing inequality, $G^TG$ must have at least $m$ eigenvalues greater than $1$, i.e. $G$ has $m$ singular values greater than $1$.
So, to generate an entrywise positive stochastic matrix with $m$ singular values greater than $1$, you may consider some $G$ of the form $\pmatrix{A&B\\ X&Y}$ where $A$ is close to $I_M$.
Comment: @ user1551 where have you got the idea of using a BLOCK TRIANGULAR MATRIX? (I think you have studied the concept of INVARIANT SUBSPACES described in [Universal Emergence of PageRank](https://arxiv.org/pdf/1105.1062.pdf))
Comment: @RicardoS. It was just an attempt to boost up the eigenvalues of $G^TG$.


Inserting more than 1000 rows using the table value constructor as a derived table

Question: I have the following T-SQL query which inserts a list of values into a temporary table. My issue is that the INSERT function is limited to 1,000 rows and I have a list of 4,000 rows.
Here is an extract of the query:
USE MyDatabase

create table #t1
(

ResaID numeric (20) NOT NULL,
CtyRes varchar (20) NOT NULL

);

INSERT INTO #t1 VALUES

('304475','GB'),
('304482','GB'),
('304857','GB'),
('314643','GB'),
('321711','GB'),
('321714','GB'),
...

...and the list goes on till Row 4,000
As per Microsoft documentation, this limitation can be bypassed using a table value constructor as a derived table.
Example from Microsoft: Inserting more than 1,000 rows
CREATE TABLE dbo.Test ([Value] int);

INSERT INTO dbo.Test ([Value])
  SELECT drvd.[NewVal]
  FROM   (VALUES (0), (1), (2), (3), ..., (5000)) drvd([NewVal]);

How do I modify my existing SQL query to adapt it to this example?
Comment: What about the documentation don't you understand; it shows you how to change the logic. What's wrong with the example displayed there?
Comment: @Larnu OP wants to extend this logic for multiple columns. MS example shows how to do it for single one
Comment: @LukaszSzozda Thanks for the link. exactly what I needed. If you post as an answer, I will vote accordingly.
Comment: [How do I insert multiple rows WITHOUT repeating the "INSERT INTO dbo.Blah" part of the statement?](https://stackoverflow.com/a/42703601/5070879) - example with 2 columns
Comment: @Larnu I am not saying it's wrong. I am just having some difficulties given in my case, I have 2 values for each row.
Comment: @user3115933 Please check the link I provided
Comment: Yes, but a `SELECT` can return multiple columns `SELECT Col1, Col2 FROM (VALUES('a','b')) V(Col1,Col2);`
Comment: You should mark this as a dup, @LukaszSzozda, as that gives exactly what the OP needs.
Answer: You could extend MS example to handle multiple columns by using:
INSERT INTO #t1(ResaID, CtyRes)
SELECT ResaId, CtyRes
FROM (VALUES
('304475','GB'),
('304482','GB'),
('304857','GB'),
('314643','GB')) AS sub( ResaId, CtyRes);

db<>fiddle demo


webSql select query error

Question: In developing in PhoneGap for Android, I'm trying to store data in database and want to retrieve it, and during the select query I am getting errors: the .code will be zero and the .message will be "the statement callback raised an exception or statement error callback did not return false". Sometimes both message and code are undefined.
In my code below I am mentioning where I am getting error. Otherwise all is working fine. I think my usy call back function I solved the synchronous problem so please I think some syntax error. Sometimes it calls my success method and there it shows length is not undefined.
$scope.data_for_net=function(check){
//var db = window.openDatabase("JiyoNatural", "1.0", "JiyoNatural", 200000);
    var today=new Date();

     var dd=today.getDate();

     var mm=today.getMonth()+1;

     var yyyy=today.getFullYear();

     if(dd<10) {

         dd='0'+dd;

     }

    if(mm<10) {

        mm='0'+mm;

        }

     today = yyyy+'-'+mm+'-'+dd;

      todayDate=today.toString();

    db.transaction(function(tx){

            var query='SELECT * FROM Recipe WHERE Recipe_Date=?,Recipe_meal_Type=?';

            //var sql_query='select * from Recipe where Recipe_Date="'+todayDate+'" and Recipe_meal_Type="+Lunch"'

            // tx.executeSql('select * from Recipe where Recipe_Date=?,Recipe_meal_Type=?;', [todayDate]["Lunch"], $scope.query_data_fatch_for_lunch, $scope.transaction_error);//here i am getting error

             tx.executeSql(query, [todayDate],['Lunch'], $scope.query_data_fatch_for_lunch, $scope.transaction_error);

         });
   }

    }

//this is my method

$scope.query_data_fatch_for_lunch=function(tx,result){

console.log("data_fatch_for_lunch is calling");

var RecipeInfo=[];

var recipe={};

var rowData=[];

for(var i=0;i<result.rows.length;i++){

    var meal_type=result.rows.item(i).Recipe_meal_Type;

    var recipe_item=result.rows.item(i).Recipe_Name;

    console.log(recipe_item);

    var energy=result.rows.item(i).Recipe_energy;

    var carbohydrate=result.rows.item(i).Recipe_corbohydrates;

    var protein=result.rows.item(i).Recipe_protein;

    var fat=result.rows.item(i).Recipe_fat;

    rowdata.push(recipe_item);

    rowdata.push(energy);

    rowdata.push(carbohydrate);

    rowdata.push(protein);

    rowdata.push(fat);

    console.log("data is successfull add");

}

recipe.itemInfo=rowdata;

recipe.itemType=meal_type;

RecipeInfo.push(recipe);

}

Answer: I think you are pretty close although I haven't tested the above code very thoroughly...
But tx.executeSql(query, [todayDate],['Lunch'], $scope.query_data_fatch_for_lunch, $scope.transaction_error); line seems a bit weird.
Can you replace [todayDate],['Lunch'] with [todayDate, 'Lunch']?
Because that is the way the parameters work.
Comment: Also the where clause is not logically correct `WHERE Recipe_Date=?,Recipe_meal_Type=?';`. There should be an OR or AND operator like  `WHERE Recipe_Date=? AND/OR Recipe_meal_Type=?';` depending upon his requirement.
Comment: how to tell thank you i don`t know...it`s from my heart thank you so much for help.

webSql select query error


Deploying Postfix, how to setup DNS to point to server?

Question: I've set up a postfix server, listening on port 25 on an Azure VM (Ubuntu). I've just used the default configuration but set the domain to my domain

example.com

In the DNS management, what does the MX record need to look like? is it simply just the IP of the server?
# example.com

mail         aaa.bbb.ccc.ddd

I've followed a few tutorials, but none seem to cover all aspects of deployment, like when some cloud providers block port 25, how do I set up a relay?
Is there a good tutorial of setting up a mail server with a domain from start to finish?
Answer: Here is how MX record in DNS should look like:
Domain          TTL   Class    Type  Priority      Host
example.com.        1936    IN  MX  10         onemail.example.com
example.com.        1936    IN  MX  10         twomail.example.com

(source here)
You can check also this article for explanations
<name>: The first field contains the domain name.
<ttl>: Time to live specifies how long the information is guaranteed to be valid.
<class>: The class field specifies the type of network.
<type>: The DNS record type in this case is MX.
<priority>: The smaller the value, the higher the mail server's priority.
<rdata>: Resource data defines the mail server name.


nginx logrotate config

Question: Whats the best way to rotate nginx logfiles? In my opinion, I should create a file "nginx" in /etc/logrotate.d/ and fill it with the following code and do a /etc/init.d/syslog restart after that.
This would be my config (I havn't tested it yet):
 /usr/local/nginx/logs/*.log {
    #rotate the logfile(s) daily
    daily
    # adds extension like YYYYMMDD instead of simply adding a number
    dateext
    # If log file is missing, go on to next one without issuing an error msg
    missingok
    # Save logfiles for the last 49 days
    rotate 49
    # Old versions of log files are compressed with gzip
    compress
    # Postpone compression of the previous log file to the next rotation cycle
    delaycompress
    # Do not rotate the log if it is empty
    notifempty
    # create mode owner group
    create 644 nginx nginx
    #after logfile is rotated and nginx.pid exists, send the USR1 signal
    postrotate
       [ ! -f /usr/local/nginx/logs/nginx.pid ] || kill -USR1 `cat
       /usr/local/nginx/logs/nginx.pid`
    endscript
 }

I have both the access.log and error.log files in /usr/local/nginx/logs/ and want to rotate both daily. Can anyone please tell me if "dateext" is correct? I want the log filename to be something like "access.log-2010-12-04".
One more thing: Can I do the log rotation every day on a specific time (e.g. 11 pm)? If so, how? Thanks.
Comment: FYI - No restart of syslog is necessary.  Logrotate varies a bit from one distribution to the next, but generally runs from /etc/cron.daily rather than as a service.
Answer: man logrotate
   dateformat format_string
          Specify  the  extension for dateext using the notation similar to strftime(3) function. Only %Y %m
          %d and %s specifiers are allowed.  The default value is -%Y%m%d. Note that also the character sep‐
          arating log name from the extension is part of the dateformat string. The system clock must be set
          past Sep 9th 2001 for %s to work correctly.  Note that the datestamps  generated  by  this  format
          must be lexically sortable (i.e., first the year, then the month then the day. e.g., 2001/12/01 is
          ok, but 01/12/2001 is not, since 01/11/2002 would sort lower while it is later).  This is  because
          when using the rotate option, logrotate sorts all rotated filenames to find out which logfiles are
          older and should be removed.

Can anyone please tell me if "dateext" is correct? I want the log
  filename to be something like "access.log-2010-12-04".

Insert a dateformat directive to your configuration file, something like this:
 /usr/local/nginx/logs/*.log {
    daily
    dateext
    dateformat -%Y-%m-%d
    ...

One more thing: Can I do the log rotation every day on a specific time
  (e.g. 11 pm)?

By default, logrotate is running via cron at 4 A.M:
/etc/cron.daily/logrotate
#!/bin/sh

/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

You can move this file to somewhere and rename to logrotate.sh, then create a new file in /etc/cron.d/ as belows:
0 23 * * * root /path/to/logrotate.sh

Answer: You can rotate all vhosts at once:
/var/www/vhosts/*/logs/*.log { ... }

Answer: The value for dateext is given by the dateformat directive and defaults to %Y%m%d (year, month and day of month). You can customize it like %Y-%m-%d.
If you already have logrotate installed and working, it's probable that it runs everyday as a cron job, you just have to find it to change the time (remember that other stuff influence that, like the usage or not of anacron, but it varies to each system).

nginx logrotate config


Carregar combobox com dados de $.getJSON

Question: Estou fazendo um método que vai no BD faz uma query e retorna os códigos.
Com esses códigos eu carrego a Combobox com os respectivos itens.
Tem vezes que preenche certinho, tem vezes que não preenche... Alguma ideia?
$.getJSON("carrega.php?id_usuario=" + id_usuario + "&id_cord=" + id_cordao,function(data){
    $.each(data.cord, function(i,user){
        //Carrega o Combo com o Valor do BD
        $('#cbo1').val(user.cord1);
        $('#cbo2').val(user.cord2);
        $('#cbo3').val(user.cord3);
        $('#cbo4').val(user.cord4);
    });
});

Engraçado é que quando eu coloco um alert antes de preencher o Combo, ele funciona :)
Comment: Coloca o teu HTML e o que vem nesse JSON senão fica dificil de ajudar. Tentando adivinhar, talvez isto te ajude? http://jsfiddle.net/0pdxwhx0/
Comment: Ao invés de colocar um alert, use o `console.log(...)`. Dessa maneira fica mais fácil entender o que houve pois o problema de sincronismo continuará ocorrendo. Além disso, você poderia usar promisses e imprimir os resultados nos eventos de `done`, `fail` e `always`.
Comment: Ola Eduardo! A funcao toda eh isso ai...ele retorna 5 campos do php...O que eu percebo eh que ele traz certinho os dados, mas da esses bugs na hora de preencher o .val
Comment: e cara, nao entendi muito bem o q vc respondeu...mas vc falou certo..eh algum problema de sincronismo...
Comment: @RafaelSpessotto o que dá `console.log(JSON.stringify(data));` se colocares antes do `$.each`?
Comment: Sergio ele retorna normal os dados do BD...mas nao preenche o combo com essas informacoes... :(
Comment: @RafaelSpessotto podes mostrar aqui o que dá o `console.log(JSON.stringify(data));`? não faço ideia de como o teu JSON é, e vendo-o a coisa fica mais fácil.
Answer: Fala Rafael,
Quando você utiliza .val(valor) em um combo box, você na realidade está selecionando um item existente no box.
Para popular um combo box através de resultados do banco de dados, você pode fazer isso:

var frutas = ['maca','pera','uva'];

var _htmlOptions = "";
$.each(frutas,function(i,fruta){
   _htmlOptions += "<option val='"+fruta+"'>"+fruta+"</option>";
});

$("#comboFrutas").append(_htmlOptions);

<select id="comboFrutas"></select>
Comment: Fala Gustavo! Obrigado pela resposta....Mas o combo esta preenchido anteriormente sim..eu tneho uma rotina que preenche ele...O Problema esta em justamente eu conseguir preencher o combo, com o ID do item que veio do BD.. Exemplo: ID 2 ITEM: RAFAEL... Eu vou no BD, pego o valor 2, e quero que o combo fique com o valor "RAFAEL", entao eu uso o .val...so que quando eu executo no browser, ele da algum problema, pois tem horas que ele muda o valor para "RAFAEL" e horas que ele nao faz nada e fica no primeiro item adicionado..
Comment: Entendi, para conseguirmos te ajudar, precisamos saber o que está retornando na variável data;

Pelo que eu vi, para cada usuário dentro de data.cord, você está modificando o valor do combo, é isso mesmo?
Comment: {"cord":[{"ID":"8","ID_USUARIO":"2","ID_CORD":"1","ESP1":"63","ESP2":"104","ESP3":"105","ESP4":"106","ESP5":"0","ESP6":"0"}]}
Comment: Esse é o retorno Gustavo... Obrigado pela ajuda!


Doubt about sheafification

Question: There is a requirement in the definition of sheafification that looks superfluous to me and I'd like to know what I'm missing. Let $\mathscr{P}$ be a presheaf on the space $X$. We define its sheafification $\mathsf{sh}(\mathscr{P})$ as:
$$\mathsf{sh}(\mathscr{P})(U):=\left\{\varphi:U\to \bigsqcup_{x\in U} \mathscr{P}_x:\forall x\in U\ \ \varphi(x)\in \mathscr{P}_x \text{  and }  (\star)\right\}$$
where $(\star)$ is the following condition: for  every $x\in U$ there is an open neighbourhood of $x\in V\subseteq U\subseteq X$ such that $\varphi(x)=[(V,s)]$ for some section $s\in \mathscr{P}(V)$.
The condition $(\star)$ looks useless to me, because we are already imposing that $\varphi(x)=[(W,t)]$ for some neighbourhood $x\in W$ and for some section $t \in \mathscr{P}(W)$. But by definition of stalk at $x$, we have that:
$$\varphi(x)=[(W,t)]=[(U\cap W, t|_{U\cap W})].$$
And this means that condition $(\star)$ is automatically satisfied. What am I missing?
Answer: You should double-check the definition in the source you're using, since ($\star$) is not the condition involved in sheafification.  Sheafification instead involves the condition ($\star\star$): for every $x \in U$ there is an open neighborhood $x \in V \subseteq U \subseteq X$ and section $s \in \mathscr{P}(V)$ such that $\phi(y) = s_{y}$ for all $y$ in $V$.  We don't just require that $\phi$ agree with $s$ at $x$ (as you say, this is covered by $\phi(x) \in \mathscr{P}_{x}$); rather we require that $\phi$ agree with $s$ everywhere on some open neighborhood $V$ of $x$.
Comment: Thank you very much!

Doubt about sheafification


Munin vs Nagios

Question: We're currently using Nagios to monitor about 20 Linux machines (services and functional links). I just find out about Munin and I wonder if this is a Nagios replacement, or it can be used together with Nagios? I don't want to spend hours setting it up, just to discover that I already have all that functionality with Nagios.
I'd especially appreciate if someone who used both programs can give some insight about your experience. Which is better for which task and what do you recommend to use?
Note: we also used Cacti for some time. The main problem we have with Nagios is that setup takes too long and isn't very straightforward.
Answer: Munin and Nagios are really different tools.
From the official Munin website:

Munin is a networked resource monitoring tool that can help analyze
  resource trends and "what just happened to kill our performance?"
  problems. It is designed to be very plug and play. A default
  installation provides a lot of graphs with almost no work.

Nagios is a monitoring (alerting) tool. Munin could be considered a replacement for Cacti.
We use both of them: Nagios and Munin.

Nagios tell us in real time if something is wrong: like web server down, database load average, etc.
Using Munin you can see the trends and the history about why that happenend.
Comment: This is a great description +1.

I have something to add: with munin you can not only see the trends, but you can set thresholds. It one of these thresholds are exceeded munin will (can) notify nagios (with passive check).

Then you can use nagios' sophisticated notification framework.
Comment: .. it's worth mentioning that munin can alert - if you put the work in setting thresholds & contacts for things you care about nagios gets a bit redundant... In a recent infrastructure refresh I did ust that; nagios wasn't worth the complication for the very little extra it was offering us.  Munin alerts us (through a scheduled alerting sms gateway we have) when something goes offline.
Answer: Munin definitely works best in parallel with Nagios. It can also tie into it, sending notifications of thresholds being exceeding into the Nagios notification system. The reason we use it is because it is virtually trivial to set up new monitors. Nagios requires a little bit more effort.
Note also though that PNP4Nagios gives graphing capabilities to Nagios - most plugins will report performance data, and then PNP4Nagios will store that info in RRD databases and display it as graphs in the Nagios interface. We use it in addition to Munin, as it gives graphs of network services (munin's main strength is monitoring the local box).
One final note - we also use Cacti, as it is the most useful tool for graphing switch and router ports via SNMP. We have <10 devices monitored by it. It's too much of a pain to set it up to manage actual servers - munin and Nagios/NRPE are much easier to manage than SNMP agents.
Comment: I used to use Nagios. And this is the reason that I left it. It's a terrific tool, but you need lots of hours and "satellite" tools in order to have something usefull. This is way I switched to ZABBIX. It's everything integrated in just one tool.
Answer: Any time I search for anything to do with monitoring Nagios is prominent in the answers, yet I'd never heard of Munin till I saw your question. That's a bit of a clue to me. A qquick look at the web site you linked to doesn't really make things clear.
Why not set up Munin in parallel with Nagios and see what it will do for you? That's what I intend to do. Who knows, in the future it might be THE monitoring tool to use.
Answer: There's a number of related reasons why you want these monitoring tools.  It's worth keeping these in mind as separate needs that likely require separate tools, though there's certainly overlap in what the tools can provide.

Focus attention on problems as they occur.
Provide information for analyzing what's going wrong and when.
Automate responses.

Eg these are the primary focusses of:

Nagios
Munin or Cacti
Monit

You certainly can have monit send alerts, but it's a clumsy tool for situational awareness.
You can also integrate performance graphing into Nagios, but I'm not sure there's a convincing case for doing so.  Munin is so much easier to configure.
Comment: We just bought mmonit, with is monit centralized server. amazing piece of software. i'm in love with this thing. it's like working 24 hours from the bar. still I have to do some config files it's nice and sweet.

Munin vs Nagios


JRadioButton setMnemonic broken Java 1.5

Question: I am attempting to convert a short JComboBox to a JRadioButton group. When defining the radio buttons, it is telling me it doesn't like my setMnemonic syntax.
My code:
public JRadioButton mailRadio = new JRadioButton("Mail");
mailRadio.setMnemonic(KeyEvent.VK_M);

It will show setMnemonic(int) in intellisense (or whatever the java version is called), but as soon as I accept that, mailRadio.setMnemonic is underlined for a syntax error. Hovering over it gives the error "Type mailRadio.setMnemonic not found." Compiling gives the error "Invalid method declaration; return type required."
As far as I know, I am attempting to do neither of these things. I haven't used Java in a long time, and I'm very rusty. I don't know what I'm doing wrong.
I have three JRadioButtons like this, and it will only show the error on the first one, until I comment it or remove then, then the error moves down to the next.
I am using JDeveloper 10.1.3.5, Java 1.5.0_06. Upgrading either is not an option at the moment, unfortunately.
Comment: You will probably find that going through the basic Java tutorials will help immensely with your Swing coding as without a basic understanding, Swing coding can be very frustrating indeed.
Answer: Seeing that you used public to declare the variable, I'm assuming the code snippet is inside a class declaration.
You can't use statements (and a method call such as setMnemonic is a statement) in a class declaration. You should call this method inside a constructor :
public class XXX {
    public JRadioButton mailRadio = new JRadioButton("Mail");

    public XXX() {
        mailRadio.setMnemonic(KeyEvent.VK_M);
    }
}

An alternative that looks more like what you initially tried to do is an initializer block:
public class XXX {
    public JRadioButton mailRadio = new JRadioButton("Mail");

    {
        mailRadio.setMnemonic(KeyEvent.VK_M);
    }
}

But this is bad practice, I'm only mentioning it for completeness' sake.
More details in the doc.
Comment: Thank you. This was my problem, and thanks for the link to the doc. I'll this as the answer as soon as it lets me.


Launching new instance in CC2 instance

Question: Anyone used CC2 machine?
What is the cost of the small instance for an hour?
If anyone used, can you share the environmental experience, so that I can start launching the new instance for testing?
Also, is there any micro instance available for testing purpose?
Answer: You can get answers to the cost (for a small isntance) and testing (free tier) questions on the AWS site: http://aws.amazon.com/ - it depends on the region and OS.
Everyone can have a single micro instance available for free to try (the 'free tier') and everything else is fairly cheap for short period to try; you'll only get charged for each hour your instance is running.
Unless you have very specific, very demanding processing needs, and a decent budget, the CC2 instance type is overkill.
The general environment for EC2 is fairly easy-to-use, you should just give it a go, or do some research with Google.

Launching new instance in CC2 instance


prove that Petersen graph has no cycles less than or equal to 4

Question: I studying the proof that the Petersen graph is not Hamiltonian, and in the proof, they used an observation that seems intuitively correct but I want to provide rigorous proof for it, given that I'm taking an introductory course to discrete mathematics.

Claim: Petersen graph has no cycles less than or equal to 4

I want to prove it by contradiction using the basics ideas, can you help me with that?
Comment: How you prove it will depend on how you defined the Petersen graph. Did you define it as the complement of the line graph of $K_5$?
Comment: Does this answer your question? [Why girth of Petersen Graph is five? (Proof)](https://math.stackexchange.com/questions/1462092/why-girth-of-petersen-graph-is-five-proof). The first answer provides a proof by contradiction for your question.
Answer: We can use a simple argument by coloring the edges of the Petersen's graph as shown below:

First note that there are 3 types of edges:

5 blue edges forming outer cycle of length 5
5 pink edges forming inner cycle of length 5
5 green edges connecting outer nodes with inner nodes

Now, since there is a blue cycle of length 5 with 5 outer blue nodes, it makes it impossible to have a blue monochrome cycle of length $\leq 4$, because

for creating a length-4 or length-3 cycle we must connect two non-adjacent blue nodes by an additional blue edge.
in order to accommodate that additional blue edge, we must remove an exisiting blue edge from the blue cycle.
but, minimum number of blue edges needed to construct a length-5 blue cycle with 5 blue nodes is 5, with each node having one incoming and one outgoing blue edge.
hence, we can't remove an edge from the existing length-5 blue cycle, which contains 5 blue edges only.

Using same argument we can show that we can't have an inner monochrome pink cycle of length $\leq 4$.
Also, a cycle which is not monochromatic must have a green edge (connecting an inner and an outer node). Now, in order to have a non-monochrome cycle of length $\leq 4$, we must have

either a couple of green edges from a pink node, which is impossible (since there is exactly one green edge incident on each pink node),
or a couple of green edges incident on a blue node (again impossible),
or it would need at least one additional blue edge (connecting two non-adjacent blue nodes) or one additional pink edge (connecting two non-adjacent pink nodes), making it impossible to have blue or pink cycles of length 5.
Comment: In summary, the above firstly proves cycles of length $\le 4$ are impossible for only blue or pink nodes because cycle-5 can't have one smaller cycle inside it. Then we must have one green edge which already has nodes, then for the cycle-3 either one pink edge or one blue is added but then we can't proceed to form one cycle. For cycle-4, similarly 2 blue edges, 1 blue 1 green, 1 pink 1 green or 2 pink. But all of them can't form one cycle.


Entropy Equation (Information Theory)

Question: I am studying basic language models before than CRF from http://www.eng.utah.edu/~cs6961/papers/klinger-crf-intro.pdf.
But I am stuck at the page 6.
It says the conditional entropy as
$H(y|x)=-\sum_{(x,y) \in Z} p(y,x) \log p(y|x)$
Should not it be
$H(y|x)=-\sum_{(x,y) \in Z} p(y|x) \log p(y|x)$
Why is it $p(y,x)$ instead of $p(y|x)$?
(https://en.wikipedia.org/wiki/Entropy_(information_theory))
Can we use the both interchangeably?
Thank you.
Answer: The correct definition is the one appearing in the text. You may understand the conditional entropy as follows. Let $Y$ and $X$ be random variables, with a joint distribution $p_{X,Y}(x,y)$. Now, given $X=x_0$, $Y$ is described by the conditional distribution $p_{Y|X}(y|x_0)$, and has an entropy equal to
$$
H(Y|X=x_0) = -\sum_y p_{Y|X}(y|x_0) \log p_{Y|X}(y|x_0)
$$
Note that the notation $H(Y|X=x_0)$ is unconventional (although appearing every now and then). Here, it only serves to remind that we are actually computing the entropy of $Y$ using the standard definition, however, since we know that $X=x_0$, we use the conditional distribution of $Y$ given $X=x_0$ (instead of the marginal distribution $p_Y(y)$).
Now the conditional entropy of $Y$ given $X$ (not $Y$ given $X=x_0$; note the difference) is the average of $H(Y|X=x_0)$ over all possible $x_0$, that is
$$
\begin{align}
H(Y|X) &= \sum_{x_0}p_X(x_0) H(Y|X=x_0) \\
&=-\sum_{x_0} \sum_y p_X(x_0)p_{Y|X}(y|x_0) \log p_{Y|X}(y|x_0) \\
&=-\sum_{x_0} \sum_y p_{Y,X}(y,x_0) \log p_{Y|X}(y|x_0),
\end{align}
$$
which is the same formula as the one in your text.
Answer: In practice, it is often assumed, that all input variables xi are conditionally independent
of each other. That Probabilistic Models
means that p(xi|y, xj ) = p(xi|y)

Entropy Equation (Information Theory)