Após requisicao AJAX input não seta valor ao ManagedBean?

Question: Estou construindo um formulário de cadastro de endereço e implementei as combos referentes a Estado e Cidade respectivamente. Elas funcionam de forma habitual, com a combo da cidade sendo preenchida de acordo com o valor selecionado pela combo do estado.
Li um tutorial na internet a respeito de como implementar essa funcionalidade, entretanto estou tendo um problema bem chato no que se refere a campos obrigatórios e atribuição de valor dos inputs ao ManagedBean. Isto porque o evento ajax responsável por carregar a combo da cidade com base no valor do estado funciona, entretanto, após dar um submit no formulário de cadastro o valor da cidade não é setado no bean e o JSF cospe uma mensagem de "Campo obrigatório".
Estou a um tempo procurando a causa... mas ainda nao encontrei.
Minha implementação é a seguinte:
endereco.xhtml
<f:view>

        <h:panelGrid columns="2">
            <h:panelGrid columns="2">

            </h:panelGrid>

            <h:panelGrid columns="2">

            </h:panelGrid>

            <h:panelGrid columns="4">

            </h:panelGrid>

            <h:panelGrid columns="2">

            </h:panelGrid>

            <h:panelGrid columns="4">

                    <f:selectItem itemLabel="Selecione" />
                    <f:selectItems value="#{enderecoBean.listaEstados}" var="e"
                        itemValue="#{e}" itemLabel="#{e.sigla}" />
                    <f:ajax render="cidade" event="change"
                        listener="#{enderecoBean.alterarCidadesPorEstado}" />

                    <f:selectItem itemLabel="Selecione" />
                    <f:selectItems value="#{enderecoBean.listaCidades}" var="c"
                        itemValue="#{c}" itemLabel="#{c.nomeCidade}" />

            </h:panelGrid>
        </h:panelGrid>

</f:view>

EnderecoBean.java
package br.com.biblioteca.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import br.com.biblioteca.dao.CidadeDAO;
import br.com.biblioteca.dao.EstadoDAO;
import br.com.biblioteca.model.Cidade;
import br.com.biblioteca.model.Endereco;
import br.com.biblioteca.model.Estado;

@ManagedBean
@ViewScoped
public class EnderecoBean {

    private Endereco endereco;
    private Estado estadoEscolhido;
    private Cidade cidadeEscolhida;
    private List<Estado> listaEstados;
    private List<Cidade> listaCidades;
    private CidadeDAO cidadeDao;

    public EnderecoBean(){
        this.endereco = new Endereco();
        cidadeDao = new CidadeDAO();
        EstadoDAO dao = new EstadoDAO();
        listaEstados = dao.listar();
    }

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

    public Endereco getEndereco(){
        return this.endereco;
    }

    public Estado getEstadoEscolhido() {
        return estadoEscolhido;
    }

    public void setEstadoEscolhido(Estado estadoEscolhido) {
        this.estadoEscolhido = estadoEscolhido;
    }

    public Cidade getCidadeEscolhida() {
        return cidadeEscolhida;
    }

    public void setCidadeEscolhida(Cidade cidadeEscolhida) {
        this.cidadeEscolhida = cidadeEscolhida;
    }

    public List<Estado> getListaEstados() {
        return listaEstados;
    }

    public void setListaEstados(List<Estado> listaEstados) {
        this.listaEstados = listaEstados;
    }

    public List<Cidade> getListaCidades() {
        return listaCidades;
    }

    public void setListaCidades(List<Cidade> listaCidades) {
        this.listaCidades = listaCidades;
    }

    public void alterarCidadesPorEstado(final AjaxBehaviorEvent event){
        if(estadoEscolhido == null)
            return;

        try{
            this.listaCidades = cidadeDao.cidadeByEstado(estadoEscolhido);
        }catch(Exception e){
            e.printStackTrace();
            FacesMessage msgErro = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO","Falha ao buscar as cidades atreladas ao estado selecionado!");
            FacesContext.getCurrentInstance().addMessage(null, msgErro);
        }
    }
}

EstadoConverter.java
package br.com.biblioteca.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.biblioteca.dao.EstadoDAO;
import br.com.biblioteca.model.Estado;

@FacesConverter(value="estadoConverter")
public class EstadoConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if(value != null || !value.isEmpty()){
            EstadoDAO estadoDao = new EstadoDAO();
            Estado estado = estadoDao.buscar(Integer.valueOf(value));
            return estado;
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if(value instanceof Estado){
            Estado estado = (Estado)value;
            return String.valueOf(estado.getIdEstado());
        }
        return "";
    }

}

CidadeConverter.java
package br.com.biblioteca.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.biblioteca.dao.CidadeDAO;
import br.com.biblioteca.model.Cidade;

@FacesConverter(value = "cidadeConverter")
public class CidadeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value != null && !value.equals("")) {
            CidadeDAO dao = new CidadeDAO();
            return dao.buscar(Integer.valueOf(value));
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value instanceof Cidade) {
            Cidade municipio = (Cidade) value;
            return String.valueOf(municipio.getIdCidade());
        }
        return "";
    }

}

Alguma ideia?
Answer: Isso é um bug do Primefaces que pode ser corrigido facilmente colocando um elemento que envolve que o componente que será atualizado. Segue exemplo gernérico:

<h:panelGroup id="panel-pai">

</h:panelGroup>

Se estiver utilizando uma lista que depende de outra, não se esqueça de atualizar o próprio elemento:
<h:panelGroup id="panel-cidade">

</h:panelGroup>

<h:panelGroup id="panel-estado">

</h:panelGroup>

Ou então colocar ambos componentes dentro de apenas um elemento pai:
<h:panelGroup id="panel-endereco">

</h:panelGroup>

Para você fazer essa atualização você deverá:

Enviar ao seu managedBean a seleção do Estado
Através do Estado selecionado atualizar a lista das Cidades
Atualizará os elementos que envolvem os selectOneMenus correspondentes

Aplicado ao seu código:

        <f:selectItem itemLabel="Selecione" />
        <f:selectItems value="#{enderecoBean.listaEstados}" var="e"
                       itemValue="#{e}" itemLabel="#{e.sigla}" />

        <f:selectItem itemLabel="Selecione" />
        <f:selectItems value="#{enderecoBean.listaCidades}" var="c"
           itemValue="#{c}" itemLabel="#{c.nomeCidade}" />

Foi colocada um id para o panelGrid que envolve seus selectOneMenus
Seu update deverá ser em cima desse id que engloba os selectOneMenus sempre
Recomendo mudar  <f:ajax render="panelX"/> para

Seu h:panelGrid pode mudar p:panelGrid nativo do Primefaces se preferir

Recomendo utilizar o máximo de tags nativas do Primefaces do que misturar com as tags JSTL.

Mais uma observação, seu managedBean deverá estar serializado. Exemplo:
public class EnderecoBean implements Serializable {
    private static final long serialVersionUID = 1L;
}


some confusion about open set?

Question:
Is  $[0, \frac{1}{2})$  is open  in $[0,1]$ ?

My attempt  :  For  open    it complement must be  closed  . Now $ [0,1] - [0, \frac{1}{2})= [\frac{1}{2} , 1)$  which is not closed in  $[0,1]$
similarly we can  said that  $[0, \frac{1}{2})$ is also not open in $\mathbb{R}$
Is its  true ?
Comment: Note that $[0,1]\setminus \left[0,\frac12\right) = \left[\frac12,1\right]$, which *is* closed in $[0,1]$. You made an error.
Comment: you could say $[0,\frac12)$ is the intersection of $(-\infty,\frac12)$, which is open in the usual topology on $\mathbb R$, and $[0,1]$, so it is open in the subspace topology on $[0,1]\subset\mathbb R$
Comment: When we use the metric restricted to $[0,1]$, $[0,\frac12) = B(0, \frac12)$ a metric ball and hence open.
Answer: Since $[0,1]\setminus\left[0,\frac12\right)=\left[\frac12,1\right]$, which is closed in $[0,1]$ (since it is a subset of $[0,1]$ and a closed subset of $\mathbb R$), $\left[0,\frac12\right)$ is open in $[0,1]$.
Answer: Easier to simply note $(-\frac 12,\frac 12)$ is open in $\mathbb R$ so $(-\frac 12,\frac 12)\cap [1,1] = [0,\frac 12)$ is open in $[0,1]$.
But the complement of $[0,\frac 12) = [\frac 12, 1]$.  I do not see why you forgot to include the $1$. and that is closed in $[\frac 12, 1]$ (it is closed in $\mathbb R$) so $[0,\frac 12)$ is open in $[0,1]$
It is worth noting that had your space been $[0,1)$ then the complement of $[0,\frac 12)$ is equal to $[\frac 12,1)$.  And $[\frac 12,1) = [\frac 12, \infty) \cap [0,1)$ is closed in $[0,1)$ and $[0,\frac 12)$ is open in $[0,1)$.
Answer: Observe that the open sets of $[0,1]$ are precisely of the form $U \cap [0,1]$ for some open set $U$ of $\Bbb R.$ Now take any $a \in (-\infty,0)$ and consider the open interval $I=\left ( a,\frac 1 2 \right)$ in $\Bbb R.$ Since any open interval in $\Bbb R$ is an open set in $\Bbb R$ so $I$ is an open set in $\Bbb R.$ Now only observe that $\left [0, \frac 1 2 \right ) = I \cap [0, 1]$ and then you are through.

some confusion about open set?


Generating matlab array from union and replacement of two arrays

Question: I have two large arrays which I will illustrate using the following examples.
The first array A is:
[ 1 21;
  3 4;
  4 12;
  5 65 ];

The second array B is:
[ 3 56;
  5 121];

I want to obtain the final array C as following:
[ 1 21;
  3 56;
  4 12;
  5 121 ];

i.e. replace second column of A with elements of B when available.
I am using Matlab 2007.
Answer: MATLAB Solution
With ismember -
C = A;
[is_present,pos] = ismember(A(:,1),B(:,1))
C(is_present,2) = B(pos(is_present),2)

Or use bsxfun to replace ismember -
[is_present,pos] = max(bsxfun(@eq,A(:,1),B(:,1).'),[],2);

Sample run -
>> A,B
A =
     1    21
     3     4
     4    12
     5    65
B =
     3    56
     5   121
     4    66
>> C = A;
[is_present,pos] = ismember(A(:,1),B(:,1));
C(is_present,2) = B(pos(is_present),2);
>> C
C =
     1    21
     3    56
     4    66
     5   121

Bonus: NUMPY/PYTHON Solution
You can use boolean indexing with np.in1d -
import numpy as np

mask = np.in1d(A[:,0],B[:,0])
C = A.copy()
C[mask] = B

Sample run -
In [34]: A
Out[34]:
array([[ 1, 21],
       [ 3,  4],
       [ 4, 12],
       [ 5, 65]])

In [35]: B
Out[35]:
array([[  3,  56],
       [  5, 121]])

In [36]: mask = np.in1d(A[:,0],B[:,0])
    ...: C = A.copy()
    ...: C[mask] = B
    ...:

In [37]: C
Out[37]:
array([[  1,  21],
       [  3,  56],
       [  4,  12],
       [  5, 121]])

Comment: @SanthanSalai Well numpy is interesting thing to try out, and people there care a lot about performance which makes sense to me :)
Comment: Sorry I don't have this functionality. Can you please provide a code for a Matlab 2007.
Comment: @user1243255 Sorry, didn't read the tags properly, edited with MATLAB code.
Comment: About to request you,, just don't dump Matlab for Numpy  :P


Samba Domain Controller - is DNS required?

Question: I am looking into setting up a Samba domain controller using Ubuntu Server, for some Windows XP/7 clients, and I have one important question: Given the importance of DNS in a Microsoft Active Directory infrastructure, why do none of the setup guides mention configuring DNS to support a Samba domain?
I have installed an LDAP/Samba server in a test network that I will be attempting to join using an XP client very soon, but I'm just confused as to how the client will actually "discover" the domain - as I know this is how AD domains work.
I hope someone can shed some light on this!
Answer: Samba 3, the current version, does not use the active directory protocols. Instead it uses the older NT4 domain protocols. As Jasper mentioned, this uses NetBIOS for lookups which uses broadcasts. You might want to consider setting up Samba as a WINS server, if you have more than one subnet its a requirement.
If you are using a Samba4 alpha which does use the AD protocols then you will need a DNS server. There are some brave souls that are using Samba4 in production without major issue, it is actually quite stable.
Comment: I had suspected as much. Thanks for the clear answer.
Answer: NetBIOS uses its own lookup mechanism, that's what the nmbd daemon is busy with.
I don't know about AD domains, but samba domains only use DNS for dynamically mapping windows workstation hostnames from NetBIOS lookups to DNS, so non-windows workstations can reach them by name. This is by no means compulsory, though.
Answer: Netbios or WINS resolution is far more commonly used with Samba and DNS is optional resolution method depending on how you have configured your clients.
Netbios or WINS is not required to use Samba. If you disable netbios almost all SMB clients will attempt to use DNS resolution.
From the the howto

When NetBIOS over TCP/IP is disabled,
  the use of DNS is essential.

There are some ancient clients that don't support using DNS.  But most SMB clients that do not support DNS also do not support TCP/IP.
This article includes ways you can configure your windows clients to use wins,
Answer: Have you checked out SAMBA AD Ubuntu
for CentOS
Answer: When setting up samba 3 as a domain controller a WINS server is required if you do not currently have one on the network. Otherwise your windows clients will have no way to locate the domain controller.
This is simple and can be enabled by setting wins support = yes in the smb.conf.
After enabling this option, restart samba and wait 10 minutes. Then on your linux box locate the wins.dat entry and you should see a list of your windows clients on the network.

Testlabs Team.
www.testlabs.com.au


Add comboBox in a JTable for a DB foreign keys

Question: I am doing a DatabaseManager Proyect where I display all the data of a db table in a JTable. Now I want to insert a feature so that the foreign keys of a table are displayed as a ComboBox with the values of the foreign table. So I was wondering which is the most optimal way to do it, I know that the Column which represent the foreing key is going to be filled with comboBoxes with the exact same values, but every each of them will have a specific default starting value. Here is the code that I have right now to just fill the data without comboBoxes:
<code>private Collection<Map<String, String>> allData;
Object[] rowToAdd = new Object[manager.get((String) DatabaseJList.getInstance().getSelectedObject()).getDataManager().getColumnNumber()];
for (Map<String, String> rowz: allData)
            {

                rowx = rowz.values();

                int i = 0;
                for (String str : rowx)
                {
                    rowToAdd[i] = str;
                    i++;
                }
                tableModel.addRow(rowToAdd);
            }
</code>
So since rowToAdd is an array of Objects, can I just create a comboBox and put it inside?Any suggestions how to do this?
Thanks a lot everyone.
Answer: You don't add the data to the model. You just specify that a combo box is to be used as the editor for the specific. See the section from the Swing tutorial on Using a Combo Box as an Editor for a working example.


Proof of the derivative of sine

Question: When proving the statement, $\dfrac{dy}{dx}=\cos(x)$, when $y(x)=\sin x$ there is a step that I do not fully understand.  I understand the beginning steps of $$\dfrac{dy}{dx}=\lim_{h\to0}\frac{\sin(x+h)-\sin(x)}{h}
=\dfrac{\sin(x)\cos(h)+\cos(x)\sin(h)-\sin(x)}{h}$$ but do not understand how this leads to the expression $$\sin(x)\left(\dfrac{\cos(h)-1}{h}\right)+\cos(x)\left(\dfrac{\sin(h)}{h}\right)$$
Any explanation for this would be greatly appreciated.
Comment: $$\sin(x)\cos(h)-\sin(x)=\sin(x)(\cos(h)-1)$$
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/).
Answer: For $h\neq 0$,
$$\begin{align}
\frac{\sin(x)\cos(h)+\cos(x)\sin(h)-\sin(x)}{h}
&= \frac{\sin(x)\cos(h)-\sin(x)+\cos(x)\sin(h)}{h}\\
&= \frac{\sin(x)(\cos(h)-1)+\cos(x)\sin(h)}{h}\\
&= \frac{\sin(x)(\cos(h)-1)}{h}+\frac{\cos(x)\sin(h)}{h}\\
&= \sin(x)\frac{\cos(h)-1}{h}+\cos(x)\frac{\sin(h)}{h}\\
\end{align}$$
Answer: hint
factor
$$\frac {ab-b+d}{c}=\frac{b (a-1)+d}{c} $$
and isolate
$$\frac{A+B}{C}=\frac {A}{C}+\frac {B}{C} $$

Proof of the derivative of sine


$t$ - th graded piece of the coordinate ring of $Y \times Z$

Question: Let $Y \subseteq \Bbb{P}^n$ and $Z \subseteq \Bbb{P}^m$ be two projective varieties. By $Y \times Z$, we really mean the image of $Y \times Z$ via the Segre embedding $\psi$ in $\Bbb{P}^N$ with $N = (n+1)(m+1) - 1$. We want to determine the $t$ -th graded piece of the coordinate ring of a product of two projective varieties $Y$ and $Z$. Now I have looked in many texts (Hartshorne, Liu, Shafarevich, Fulton, Gortz - Wedhorn, Milne's notes, etc) but no one seems to say what it is!

My guess is: $$S(Y\times Z)_t \cong S(Y)_t \otimes_k S(Z)_t$$

Now I have tried to prove this as follows. First let $x_{00},\ldots,x_{nm}$ be coordinates on $\Bbb{P}^N$, $y_0,\ldots,y_n$ coordinates on $\Bbb{P}^n$ and $z_0,\ldots,z_n$ coordinates on $\Bbb{P}^m$. Then the induced map $\psi^\ast$ that sends $x_{ij} \mapsto y_i \otimes z_j$ is actually a surjection when we restrict to graded pieces
$$\psi^\ast : k[x_{ij}]_t \to k[y_0,\ldots,y_n]_t \otimes_k k[z_0,\ldots,z_m]_t.$$
Thus we get a surjection $\psi^\ast : k[x_{ij}]_t \to S(X)_t \otimes_k S(Y)_t $.

My question is: Why is the kernel of this map $I(\psi(X \times Y))$? It seems almost impossible to prove this because in general to say what elements are actually zero in a tensor product, difficult it is to tell. How can I prove my claim above via an alternative method?
Answer: First assume that $Y = \Bbb{P}^n$ and $Z = \Bbb{P}^m$
The map $\psi^\ast : k[X_{ij}] \to k[Y_0,\ldots,Y_n] \otimes_k k[Z_0,\ldots,Z_m]$ defined by $X_{ij} \rightarrow Y_i \otimes Z_j$ will induce a well defined map $\overline{\psi^\ast} : k[x_{ij}] \to k[Y_0,\ldots,Y_n] \otimes_k k[Z_0,\ldots,Z_m]$. where
 $k[x_{ij}] \equiv \frac{k[X_{ij}]}{(X_{ij}X_{pq} - X_{iq}X_{pj})}$. Clearly as you have observed the map $\overline{\psi^\ast}_t : k[x_{ij}]_t \to k[Y_0,\ldots,Y_n]_t \otimes_k k[Z_0,\ldots,Z_m]_t$ is onto for all $t$. Now we shall claim that it is also one one.
From the  relations we can prove that $x_{i_1j_1}x_{i_2j_2} \ldots x_{i_tj_t} = x_{i_1 \sigma(j_1)}x_{i_2 \sigma(j_2)} \ldots x_{i_t \sigma(j_t)}$ and  $x_{i_1j_1}x_{i_2j_2} \ldots x_{i_tj_t} = x_{\sigma(i_1)j_1}x_{\sigma(i_2)j_2} \ldots x_{\sigma(i_t)j_t}$ in $k[x_{ij}]$ for any permutation $\sigma$ of $t$ symbols.
This will give $x_{i_1j_1}x_{i_2j_2} \ldots x_{i_tj_t} = x_{p_1q_1}x_{p_2q_2} \ldots x_{p_tq_t}$ in $k[x_{ij}]_t$ if $\{i_1, i_2, \ldots, i_t\} = \{p_1, p_2, \ldots, p_t\}$ and $\{j_1, j_2, \ldots, j_t\} = \{q_1, q_2, \ldots, q_t\}$.
So from these conclude that $k[x_{ij}]_t$ can be generated by elements as many as in the basis of $k[y_0, y_1, \ldots y_n]_t \otimes k[z_0, z_1, \ldots z_m]_t$. So the map $\overline{\psi^\ast}_t : k[x_{ij}]_t \to k[Y_0,\ldots,Y_n]_t \otimes_k k[Z_0,\ldots,Z_m]_t $ is injective for all $t$. Therefore $\overline{\psi^\ast}$ is injective.
For two positively graded rings $R = \oplus_{i =0}^\infty  R_i$ and $S = \oplus_{j =0}^\infty  S_j$ define $V(R, S) = \oplus _{t =0}^\infty R_t \otimes S_t$.
The map $\psi^\ast: k[X_{ij}] \to k[Y_0,\ldots,Y_n] \otimes_k k[Z_0,\ldots,Z_m]$ has image $V(k[Y_0,\ldots,Y_n], k[Z_0,\ldots,Z_m])$.
Let $Y$ and $Z$ be arbitrary projective variety with  $I(Y) = (f_1, f_2, \ldots, f_u)$ and $I(Z) = (g_1, g_2, \ldots, g_v)$. Then $I(Y \times Z) = {\psi^\ast}^{-1}(f_1 \otimes 1, f_2 \otimes 1, \ldots, f_u \otimes 1, 1 \otimes g_1, 1 \otimes g_2, \ldots, 1 \otimes g_v)$. So $\psi^\ast$ will induce a one one map $\overline{\psi^\ast} : \frac{k[X_{ij}]}{I(Y \times Z)} \rightarrow \frac{[Y_0,\ldots,Y_n]}{I(Y)} \otimes_k \frac{k[Z_0,\ldots,Z_m]}{I(Z)} = S(Y) \otimes_k S(Z)$ with image $V(S(Y), S(Z))$
Comment: Dear @A.G. thanks for your answer. I am now trying to prove this for arbitrary $Y$ and $Z$ but how do I know what is in $I(Y \times Z)$?
Comment: I have edited my answer.


How to edit CCK form?

Question: How I change node edit form, which created by CCK module?
Now if the form is submitted, CCK update some field in mysql database. I need to change this, because in one form input contains three values, and this values need to be recorded in three fields in databse. How can I do this?
Jimmy Ko said, that I can retrieve the submitted value in $form_state['#values'], but I don't know in what .php file I can do this?
Comment: You should keep in mind that Drupal 6 is no longer supported by the community, and all Drupal 6 sites should plan to upgrade to Drupal 7 or 8 soon.
Comment: I know it, but site does not have the ability to update to Drupal 7 or newest version
Answer: For achieving this goal you have to implement hook_nodeapi
In presave operation you can get desired value.
Example code you can get from the D6 release of the Examples for Developers module.
Comment: Thanks. Can you give exaple of this hook?
Comment: And at that php file i need implement this hook?

How to edit CCK form?


How to make all items in a section of a UICollectionView float over the scroll view?

Question: I want the items of one section in a UICollectionView to remain stationary while the rest of the items inside the UICollectionView are being scrolled.
I tried to achieve this by setting Autolayout constraint that pin the items to the superview of the UICollectionView. However, this does not seem to work because the constraints complain about UICollectionViewCell and the UICollectionView's superview not having a common ancestor.
Is there any other way to achieve it?
Comment: Use another view.. Don't add it in collection view.
Comment: The problem is the user needs to be able to drag and drop items from one section to another. Introducing another view makes it much harder to do so
Comment: Did you try using header for collection view? A floating header can be implemented as mentioned [here](http://stackoverflow.com/questions/13511733/how-to-make-supplementary-view-float-in-uicollectionview-as-section-headers-do-i)
Comment: This approach seems to only work for supplementary views (headers and footers) but I need the actual UICollectionView items to remain stationary
Answer: Thanks to Ad-J's comment I was able to implement the solution.
I needed to override UICollectionViewFlowLayout and implement the following methods:
override func prepareLayout() {
    super.prepareLayout()

    //fill layoutInfo of type [NSIndexPath:UICollectionViewLayoutAttributes]
    //with layoutAttributes you need in your layout

    if let cv = self.collectionView {
        for (indexPath, tileToFloat) in layoutInfo {
            if indexPath.section == 0 {
                var origin = tileToFloat.frame.origin
                origin.y += cv.contentOffset.y + cv.contentInset.top
                tileToFloat.frame = CGRect(origin: origin, size: tileToFloat.size)
            }
            tileToFloat.zIndex = 1
        }
    }
}

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
    return true
}

This will make all items in the first section stationary.


Convert date format to 'Month-Day-Year'

Question: I have a column full of dates of 2 million rows. The data format is 'Year-Month-Day', ex: '2019-11-28'. Each time I load the document I have to change the format of the column (which takes a long time) doing:
pd.to_datetime(df['old_date'])

I would like to rearrange the order to 'Month-Day-Year' so that I wouldn't have to change the format of the column each time I load it.
I tried doing:
df_1['new_date'] = df_1['old_date'].dt.month+'-'+df_1['old_date'].dt.day+'-'+df_1['old_date'].dt.year

But I received the following error: 'unknown type str32'
Could anyone help me?
Thanks!
Comment: Does this answer your question? [Change date format of pandas column (month-day-year to day-month-year)](https://stackoverflow.com/questions/58327249/change-date-format-of-pandas-column-month-day-year-to-day-month-year)
Answer: You could use pandas.Series.dt.strftime (documentation) to change the format of your dates. In the code below I have a column with your old format dates, I create a new columns with this method:
import pandas as pd

df = pd.DataFrame({'old format': pd.date_range(start = '2020-01-01', end = '2020-06-30', freq = 'd')})
df['new format'] = df['old format'].dt.strftime('%m-%d-%Y')

Output:
  old format  new format
0 2020-01-01  01-01-2020
1 2020-01-02  01-02-2020
2 2020-01-03  01-03-2020
3 2020-01-04  01-04-2020
4 2020-01-05  01-05-2020
5 2020-01-06  01-06-2020
6 2020-01-07  01-07-2020
7 2020-01-08  01-08-2020
8 2020-01-09  01-09-2020
9 2020-01-10  01-10-2020

Convert date format to 'Month-Day-Year'


Hypothesis testing equality of parameters in MORE than 2 Bernoulli populations

Question: I am giving the number of trials and number of successes for 4 Bernoulli samples.
I want to test the null hypothesis that p1 = p2 = p3 = p4 versus the alternative hypothesis that pi != pj for any i and j between 1 and 4. (px is the probability of success for population x)
How do I go about this?
I only understand how to do this with two populations.
Answer: You can use Pearson's chi-squared test to do this. See

A test of homogeneity compares the distribution of counts for two or more groups using the same categorical variable (e.g. choice of activity—college, military, employment, travel—of graduates of a high school reported a year after graduation, sorted by graduation year, to see if number of graduates choosing a given activity has changed from class to class, or from decade to decade).[3]

Code example:
<code> #fake data

 nl <- c(20,25,30,20) # sample size
 pl1 <- c(0.2,0.3,0.4,0.5) # diffrent p
 pl2 <- c(0.3,0.3,0.3,0.3) # same p

 tab1 <- sapply(1:4,function(i){
   s <- sum(rbinom(nl[i],1,pl1[i]))
   return(c(nl[i]-s,s))
 })
 tab2 <- sapply(1:4,function(i){
   s <- sum(rbinom(nl[i],1,pl2[i]))
   return(c(nl[i]-s,s))
 })

 tab1
 #     [,1] [,2] [,3] [,4]
 #[1,]   19   19   24    8
 #[2,]    1    6    6   12

 # testing
 chisq.test(tab1) # p-value = 0.0006819
 chisq.test(tab2) # p-value = 0.8818
</code>


how to extract text in between every two regex words in a large chunk of text in python?

Question: I have a df with just one column 'text' that contains a large chunk of text structured like:
text
"dd ee Apple A1 a b c d Apple A2 e f g Apple B1 hi g Apple C1 r 5 6 Apple D1..."

How to I get below output:
text_new
Apple A1 a b c d
Apple A2 e f g
Apple B1 hi g
Apple C1 r 5 6
Apple D1 ...
...

in the sense that every row include all texts between every occurance of the regex "Apple[space][letter][number]"?
Answer: With Series.str.findall and specific regex pattern:
pd.DataFrame({'text_col': df['text'].str.findall(r'(Apple .+?)(?=Apple|$)')[0]})

            text_col
0  Apple A1 a b c d
1    Apple A2 e f g
2     Apple B1 hi g
3    Apple C1 r 5 6
4       Apple D1...

Or with Series.str.extractall:
df['text'].str.extractall(r'(Apple .+?)(?=Apple|$)').reset_index(drop=True)

                   0
0  Apple A1 a b c d
1    Apple A2 e f g
2     Apple B1 hi g
3    Apple C1 r 5 6
4       Apple D1...

Answer: Try this:
s = "Apple A1 a b c d Apple A2 e f g Apple B1 hi g Apple C1 r 5 6 Apple D1..."

result = ["Apple " + p
          for p in s.split("Apple ") if p]

print('\n'.join(result))

One-liner approach:
print(*(f'Apple {p}' for p in "Apple A1 a b c d Apple A2 e f g Apple B1 hi g Apple C1 r 5 6 Apple D1...".split("Apple ") if p), sep='\n')

Prints:
Apple A1 a b c d
Apple A2 e f g
Apple B1 hi g
Apple C1 r 5 6
Apple D1...

Answer: Your example doesn't need a regular expression, but this should work if " Apple" might appear somewhere else and it has to be done on Apple[space][letter][digit].
import re

text = "Apple A1 a b c d Apple A2 e f g Apple B1 hi g Apple C1 r 5 6 Apple D1..."

re.sub(r' (Apple [A-Z]\d)', r'\n\1', text)

Answer: I do not like wrecking my head with complicated regex. So let me offer an alternative.
Split the string before 'Apple' and remove white spaces with .strip(). The result will have one empty element from the start of the my_strwhich can be removed by selecting elements if its not empty. if substr at the end of the list comprehension performs this task.
my_str = "Apple A1 a b c d Apple A2 e f g Apple B1 hi g Apple C1 r 5 6 Apple D1"

# Split the input at 'Apple'
substrings = [substr.strip() for substr in my_str.split('Apple') if substr]

# add 'Apple' to the beginning of each substring
result = ['Apple ' + substr for substr in substrings]

df = pd.DataFrame({'text_new': result})

Output:
    text_new
0   Apple A1 a b c d
1   Apple A2 e f g
2   Apple B1 hi g
3   Apple C1 r 5 6
4   Apple D1


Abstract algebra homomorphism question

Question: This was a question on my abstract algebra test. I didn't know what to do with it.
Let $\phi:\mathbb{Z}\rightarrow \mathbb{Z}_8$, such that $\phi(1) = 6$. For what values of $n$ does $\phi(n) = 0$?
This is a homomorphism.
I listed the multiples of $8$, since they are all equal to $0\bmod 8$. That's obviously wrong, though, and I should be ashamed.
Comment: All of the multiples of 8 are acceptable values of $n$; it's just that there are also other values of $n$. However, it's a good guess, so I do not think you should be ashamed.
Comment: No, the $\phi(1)=6$ is important, too, as shown by the below answers. Also, abstract algebra is hard to get used to, but I'm sure that you'll get better over time! Just don't lose hope!
Comment: There is no person on the planet (including babies) who is worse at abstract than me. Thanks for the encouragement. I really hope that I remembered the question correctly. I somehow doubt it.
Comment: So the phi(1) = 6 is just to throw people off? I should've listed the relatively prime values. I'm not sure why I didn't.
Comment: Too late. Abstract is for the smart people.
Answer: We have $\phi(n)=\phi(1+1+\cdots+1)=n\phi(1)=6n$.
To find $\ker \phi$, we must solve $6n \equiv 0 \bmod 8$.
This equation reduces to $3n \equiv 0 \bmod 4$, or $n \equiv 0 \bmod 4$.
Therefore, $\ker \phi = 4\mathbb Z$.
Answer: Start by applying the homomorphism axioms:
We have $\phi(1) = 6$, so $\phi(1+1) = \phi(1) + \phi(1) = 6 + 6$, and $\phi(1+1+1) = \phi(1) + \phi(1) + \phi(1) = 6+6+6$, and so forth (all reduced mod $8$ of course).  When do we hit $0 \pmod{8}$?  When $\phi(n) = n \times 6$ is a multiple of $8$ when unreduced.
Notice that the first $n$ for which this happens will satisfy $n \times 6 = \displaystyle \operatorname{lcm}(6, 8) = \frac{6 \times 8}{\gcd(6, 8)}$.
Once we've wrapped around to zero, the cycle repeats itself.
Using this logic, you should convince yourself that, in general, if we have a homomorphism $\phi:\mathbb{Z} \rightarrow \mathbb{Z}_m$ defined where $\phi(1) = k$, then the integers $n$ such that $\phi(n) = 0$ are precisely the multiples of $\operatorname{lcm}(k, m)$.
Answer: The trick here is the following:
$$\phi(n) = \phi(1+1+1+1+...+1) = \phi(1)+\phi(1)+\phi(1)+...\phi(1) = n\cdot\phi(1)$$
Regardless of what the homomorphism is, if the domain is the additive group of $\Bbb{Z}$, then we have $\phi(n)=n\cdot \phi(1)$. This is a really important hint in a lot of abstract algebra problems. In this problem, it gives us the following:
$$\phi(n) \equiv n\cdot \phi(1) \equiv 6n \pmod 8$$
Thus, we need to solve $6n \equiv 0 \pmod 8$, which is the same as:
$$6n=8k \text{ (for some} k \in \Bbb{Z} \text{)}$$
Divide both sides by $2$:
$$3n=4k \text{ (for some} k \in \Bbb{Z} \text{)}$$
Turn back into a modulo equation:
$$3n \equiv 0 \pmod 4$$
Multiply both sides by $3$ since $3 \cdot 3 \equiv 1 \pmod 4$:
$$n \equiv 0 \pmod 4$$
Thus, the answer is all multiples of 4, not just the multiples of 8.
Comment: I'm still confused. 44 is a multiple of 4 but is equal to 4, not 0, in mod 8.
Comment: The question asks if $\phi(n) \equiv 0 \pmod 8$. If you look at the top of your answer, we have: $$\phi(n) \equiv 6n \pmod 8$$ Therefore: $$\phi(44) \equiv 6\cdot 44 \equiv 264 \equiv 0 \pmod 8$$ Thus, $\phi(44) \equiv 0 \pmod 8$, which is why $n=44$ is a solution.
Comment: I still say this is a little too challenging for 55 minutes (with 2 other proofs/hard questions, plus other questions). Yeah, I get it, it's college, but come on.
Comment: @T-1000'sSon It is definitely challenging if the teacher has not taught $\phi(n)=n\cdot \phi(1)$, but other than that, if you understand the concept of homomorphisms and how to manipulate modulo equations, I think this is a reasonable question. Of course, if there are other hard questions worth more points and you only have 55 minutes, then this question might be the one to skip.
Comment: It was worth 12 points. She taught us about homomorphisms, but nothing really like this. I think she has to give me some credit. I did get part of the answer correct.
Comment: @T-1000 In most cases the credit she gives is totally up to her, so you have to play her game, she doesn't have to play yours. That's another feature of college.
Comment: @MattSamuel Yeah but most people have morals about this. A good proof is usually a good proof regardless. Also there are deans and department heads and ratemyprofessors.com
Comment: @Alephnull That's why I said in most cases. A Dean or a department head will do nothing unless it is extremely, outstandingly obvious that the grading was egregiously wrong, and I can't imagine how that could ever happen, at least at my school.
Comment: @MattSamuel Yeah I think you're right. Its just a slightly lighter "have to" makes many actually do their job. Also you can always go to office hours or disrupt class to get your way.
Comment: You don't have to be patronizing, Matt. I'm aware of how college works.
Answer: Since $\phi(1)=6$ and $\phi$ is a homomorphism under additive notation, $\phi(4)=\phi(1+1+1+1)=\phi(1)+\phi(1)+\phi(1)+\phi(1)=[6]+[6]+[6]+[6]=[24]=[0]$.
This is effectively saying that $ker(\phi)={4n:n\in\mathbb{Z}}$. So all multiples of 4 in $\mathbb{Z}$ will be mapped to $[0]$ in $\mathbb{Z}_{8}$
Comment: Won't all multiples of 2 also map to 0?
Comment: $\phi(2)=\phi(1)+\phi(1)=[6]+[6]=[12]=[4]\neq[0]$
Comment: So not all multiples of 2 gets mapped to [0]
Answer: f(1)=6. f(4)=24=0 . 4 is the least in absolute value that maps to 0. 4Z maps to 0.

Abstract algebra homomorphism question


How to Django ORM update() multiple values nested inside a JSONField?

Question: I have a Django JSONField on PostgreSQL which contains a dictionary, and I would like to use the queryset.update() to bulk update several keys with values. I know how to do it for one value in a JSONField (and for multiple fields in general):
from django.db.models import Func, Value, CharField, FloatField, F, IntegerField

class JSONBSet(Func):
    """
    Update the value of a JSONField for a specific key.
    """
    function = 'JSONB_SET'
    arity = 4
    output_field = CharField()

    def __init__(self, field, path, value, create: bool = True):
        path = Value('{{{0}}}'.format(','.join(path)))
        create = Value(create)
        super().__init__(field, path, value, create)

This seems to work - with some gaps as per my other question - like this:
# This example sets the 'nestedkey' to numeric 199.
queryset.update(inputs=JSONBSet('inputs', ['nestedkey_1'], Value("199"), False))

But if I now wanted to update a second nestedkey_2 inside the same inputs, I obviously cannot use the inputs argument twice like this:
queryset.update(inputs=JSONBSet(...'nestedkey_1'...), inputs=JSONBSet(...'nestedkey_2'...)

Is there a way to do this?
Comment: Does this answer your question? [How to 'bulk update' with Django?](https://stackoverflow.com/questions/12661253/how-to-bulk-update-with-django)
Comment: @AnkitTiwari No. Normally, update() is called with keyword arguments where each keyword names a separate field to be updated. Here, the problem here is that the same argument name must be used.
Answer: I finally figured it out. Postgres has the jsonb operator "||" which can be used with Django like this:
from django.db.models import Func
from django.db.models.functions import JSONObject

class JSONBUpdate(Func):
    def __init__(self, field, update):
        super().__init__(update)
        self.template = "{} || %(expressions)s".format(field)
#
# Form a dict with the key-value pair we want to overwrite.
#
tmp = JSONObject(**{'inputs-0-value': Value("199999"), 'inputs-1-value': Value("123456")})
#
# Overwrite 'inputs-0-value' and 'inputs-1-value' using the dict.
#
queryset.update(inputs=JSONBUpdate('inputs', tmp))

Simples!
FWIW, it seems that other databases have a more-or-less standardised function with a name like jsonb_update which I suspect does something similar to the "||".
Comment: @jmunsch Indeed, I referenced https://code.djangoproject.com/ticket/32519 when I was researching the problem.
Comment: I added a rough draft a bit ago, it may support multiple database backends, i only tested sqlite, and postgres, it can be found here : https://github.com/django/django/pull/15422 just adding that here in case anyone else might find it useful


redirect traffic to www.example.com through DNS from example.com

Question: I have a bit of a unique problem.
for the domain (example.com) I want people to go to www.example.com
however I'm also throwing GSLB into the mix.  for GSLB the devices(one in each datacenter) need to be the nameserver for portion of the domain that they are going to answer for(www.example.com)
so I know I can make the NS record of www.example.com just fine and have it point to each GSLB device.  However that only helps for www.example.com NOT example.com.
I don't want to make my root NS of example.com my GSLB as my enterprise managed DNS provider does an excellent job of all DNS stuff.
any ideas?
Answer: You'll need to set up a web server at example.com and do redirects. I would suggest that the redirects are 301 (permanent) and not 302 (temporary) as you want any links to example.com to count as links to www.example.com from an SEO point of view. There are services out there that can handle the redirects for you, or you can roll your own.
A CNAME-based solution is suboptimal because 1) technically you can't have CNAMEs when you have other records, and 2) you'd be surfacing identical content at two different addresses and search engines don't like that.
Answer: A common approach to overcome this limitation in DNS is to provide a HTTP 302 redirect from example.com to www.example.com.
Here are the restrictions based on the RFCs:

CNAMEs must have no other resource records of other types (MX, A etc) as specified by RFC 1034 section 3.6.2 and RFC 1912 section 2.4. The exception is when DNSSEC is being used, in which case there can be a DNSSEC related recrd such as RRSIG, NSEC, etc. (RFC 2181 section 10.1)
CNAME records that point to other CNAME records should be avoided. In particular, it is possible to create infinite loops with CNAME records, and other error conditions. RFC 1034 section 5.2.2.
Other DNS record types, such as NS, MX, PTR, SRV, etc that point to other names should never point to a CNAME. RFC 1034 section 3.6.2, RFC 1912a, section 2.1.
Answer: Use redirection of a web server and in dns define CNAME www to example.com.
Answer: A CNAME record should be able to redirect requests for example.com to www.example.com.
Comment: DNS cannot do re-directs
Comment: My DNS provider won't let me create an empty CNAME.


Recursive regular expression

Question: If there is a text like ${placeholder1.${placeholder2}}, is it possible to have a regular expression to match the text recursively like ${placeholder1.${placeholder2}} ${placeholder2}
Comment: Yes, it is possible with Python PyPi regex module, .NET regex, PCRE, PCRE2, Onigmo (Ruby), Boost. Even Lua patterns have recursion support. What is your regex flavor?
Comment: No, that is not possible in Golang. Unless you use a PCRE library port.
Comment: @WiktorStribiżew I'm trying in golang.
Answer: No, not using a standard regular expression. This is why it is strongly advised not to use a regex to parse HTML. Perl, PCRE and Ruby support an extended form that will instruct the regex to return to the beginning of the pattern and reevaluate the match. See Regular Expression Recursion for more.
In the general case, I'd write a quick parser to handle this use case using a library like PegJS.
Comment: See [.NET regex](http://regexstorm.net/tester?p=%28%3f%3d%28%5c%24%7b%28%3f%3e%5b%5e%7b%7d%5d%2b%7c%28%3f%3co%3e%7b%29%7c%28%3f%3c-o%3e%7d%29%29*%28%3f%28o%29%28%3f!%29%29%7d%29%29&i=%24%7bplaceholder1.%24%7bplaceholder2%7d%7d) demo and [this PCRE regex demo](https://regex101.com/r/0b8VGf/2/). Your answer is wrong if you say it is not possible as it is possible with regex.
Comment: There is no standard regular expression. Each regex flavor is different, and some support recursion, some support balanced groups, some do not support these things.
Comment: Hm, I think IEEE POSIX would disagree with you. ;) See https://www.regular-expressions.info/posix.html
Comment: @RobRaisch I'm trying in golang.

Recursive regular expression


Parameters vs latent variables

Question: I have asked about this before and have really been struggling with identifying what makes a model parameter and what makes it a latent variable. So looking at various threads on this topic on this site, the main distinction seems to be:
Latent variables are not observed but have an associated probability distribution with them as they are variables and parameters are also not observed and have no distribution associated with them which I understand as that these are constants and have a fixed but unknown value that we are trying to find. Also, we can put priors on the parameters to represent our uncertainty about these parameters even though there is only one true value associated with them or at least that is what we assume. I hope I am correct so far?
Now, I have been looking at this example for Bayesian weighted linear regression from a journal paper and been really struggling to understand what is a parameter and what is a variable:
$$
y_i = \beta^T x_i + \epsilon_{y_i}
$$
Here $x$ and $y$ are observed but only $y$ is treated as a variable i.e. has a distribution associated with it.
Now, the modelling assumptions are:
$$
y \sim N(\beta^Tx_i, \sigma^2/w_i)
$$
So, the variance of $y$ is weighted.
There is also a prior distribution on $\beta$ and $w$, which are normal and gamma distributions respectively.
So, the full log likelihood is given by:
$$
\log p(y, w, \beta |x) = \Sigma \log P(y_i|w, \beta, x_i) + \log P(\beta) + \Sigma \log P(w_i)
$$
Now, as I understand it both $\beta$ and $w$ are model parameters. However, in the paper they keep referring to them as latent variables. My reasoning is $\beta$ and $w$ are both part of the probability distribution for the variable $y$ and they are model parameters. However, the authors treat them as latent random variables. Is that correct? If so, what would be the model parameters?
The paper can be found here (http://www.jting.net/pubs/2007/ting-ICRA2007.pdf).
The paper is Automatic Outlier Detection: A Bayesian Approach by Ting et al.
Comment: It might help to list a cite to the paper (& maybe a link). Part of the problem is that what these are exactly differs b/t the Frequentist & Bayesian perspectives. From the Bayesian perspective, a parameter *does* have a distribution--it isn't just something added on to represent uncertainty.
Comment: Thanks, @Luca. It wouldn't be good if you were *requiring* people to read the paper, but having it there for context is nice. I think you've done this right.
Comment: I thought it would be unfair as people would think that I expect them to read the paper without explaining things but I have put it now.
Comment: Why can't you put a prior on a latent variable? I'm a Bayesian novice, but it seems like you should be able to do that.
Comment: I think one certainly can, of course and have to in the Bayesian setup. However, I am not sure why $w$ or $\beta$ are variables in this setting. To me they looks like parameters of the model. I am having trouble telling what is it that makes say $w$ a variable rather than a parameter in this setup. I am a novice as well, as you can clearly see...
Answer: In the paper, and in general, (random) variables are everything which is drawn from a probability distribution. Latent (random) variables are the ones you don't directly observe ($y$ is observed, $\beta$ is not, but both are r.v). From a latent random variable you can get a posterior distribution, which is its probability distribution conditioned to the observed data.
On the other hand, a parameter is fixed, even if you don't know its value. Maximum Likelihood Estimation, for instance, gives you the most likely value of your parameter. But it gives you a point, not a full distribution, because fixed things do not have distributions! (You can put a distribution on how sure you are about this value, or in what range you thing this value is, but this is is not the same as the distribution of the value itself, which only exists if the value is actually a random variable)
In a Bayesian setting, you can have all of them. Here, parameters are things like the number of clusters; you give this value to the model, and the model considers it a fixed number. $y$ is a random variable because it is drawn from a distribution, and $\beta$ and $w$ are latent random variables because they are drawn from probability distributions as well. The fact that $y$ depends on $\beta$ and $w$ doesn't make them "parameters", it just makes $y$ dependent on two random variables.
In the paper they consider that $\beta$ and $w$ are random variables.
In this sentence:

These update equations need to be run iteratively until all parameters
  and the complete log likelihood converge to steady values

in theory they talk about the two parameters, not the ones that are random variables, since in EM this is what you do, optimizing over parameters.
Comment: The question was about **latent** variables.
Comment: fixed, I hope it is clearer now.
Comment: In Bayesian inference, parameters are also random variables.
Comment: follow up Q: difference between hyperparam and latent varibales? if mixture component in GMM are latent variables then what are hyperparam in GMM?
Comment: Hyperparameters are also parameters. They might be the parameters of an hyper-prior, for instance. In a GMM, you might represent the means of the $K$ components as $K$ latent variables drawn from a Gaussian distribution with (hyper-)parameters $\mu_0, \Sigma_0$.

Parameters vs latent variables


WPF and ObservableCollection

Question: I have an ObservableCollection<IRuleCondition> that I want to display - the IRuleCondition interface is used by 2 different classes I want to display, a RuleCondition that simply displays one rule condition (info such as priority, property to check and so on), and a RuleConditionGroup, that can contain 2 or more RuleConditions, grouped in such a way that any of the conditions could match, or all etc.
In the XAML I was wondering is there a way to display a different ListView.ItemTemplate depending on what the type is that it encounters in the ObservableCollection<IRuleCondition>? Or would I need to implement two different ObservableCollections?
Comment: DataTemplate might solve your problem
Answer: Here is a simple example of how this works
This is how the objects are defined
public interface Person
{
    string Name { get; set; }
}

public class Manager : Person
{
    public string Name { get; set; }
}

public class Employee : Person
{
    public string Name { get; set; }
    public string ManagerName { get;set;}
}

This is the MainWindow code behind
public partial class MainWindow : Window
    {
        ObservableCollection<Person> mPeople = new ObservableCollection<Person>();

        public ObservableCollection<Person> People
        {
            get
            {
                return mPeople;
            }
        }

        public MainWindow()
        {
            DataContext = this;
            mPeople.Add( new Employee{ Name = "x" , ManagerName = "foo"});
            mPeople.Add( new Manager { Name = "y"});

            InitializeComponent();
        }
    }

This is the MainWindow XAML
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication1"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Window.Resources>
        <DataTemplate  DataType="{x:Type my:Employee}">
            <StackPanel Background="Green" Width="300">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding ManagerName}" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate  DataType="{x:Type my:Manager}">
            <StackPanel Background="Red"
                        Width="300">
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding People}"></ListBox>
    </Grid>
</Window>

As you can see there are two datatemplates one for Manager and one for Employee

And this is how the crappy output looks like. Notice the green and red background and extra field displayed for the Employee compared to the manager
Comment: Tried to do it this way, yet everytime I try and start it it says

'Failed to create a 'Type' from the text 'local:EditableRuleConditionModel'.' Line number '13' and line position '53'.

Yet the intellisense is picking up my class names etc fine :S
Comment: Try turning all exceptions on and watch the output window for binding failures
Comment: Trying that now - for some reason when I coped all the DataTemplate stuff from the resource file and into the main .xaml file it worked no problem!
Comment: Finally got it... turns out the ResourceDictionary file needs to be set as a "Page" rather than "Resource" and suddenly it all works now, thanks! :)
Answer: Just define two different DataTemplates in the Resources section, one for each RuleCondition type.
Comment: I have something like that already in a Resources file, but I'm not sure how to go about switching them - I've been using this example, but for some reason I keep getting a "Cannot create unknown type" from my DataTemplateSelector class
Comment: http://msdn.microsoft.com/en-us/library/ms742521.aspx

Sorry, forgot the link to the sample I've been using!
Answer: 1) Create your two different data templates, just as you say you've already done.
2) Create a custom DataTemplateSelector to choose the appropriate template.
One of your comments states that you're getting an error from your DataTemplateSelector. Verify that you're implementing the class correctly, perhaps paste your implementation. It should be fairly small and straightforward.
Comment: Yeah figured out what was wrong, ResourceFile needed to be set as a "Page" for it to work, thanks for the help :)

WPF and ObservableCollection


Where do I place custom PHP code (functions, classes) when creating a theme?

Question: WordPress has a place for it - functions.php, which is included automatically. Is there one for Drupal?
Answer: The theme's template.php is used for logic and data processing. See the Drupal theming guide.
From the guide:

For all the conditional logic and data
  processing of the output, there is the
  template.php file. It is not required,
  but to keep the .tpl.php files tidy it
  can be used to hold preprocessors for
  generating variables before they are
  merged with the markup inside .tpl.php
  files. Custom functions, overriding
  theme functions or any other
  customization of the raw output should
  also be done here. This file must
  start with a PHP opening tag "<?php",
  but the close tag is not needed and it
  is recommended that you omit it.


Difference between Fantasia and Rhapsody?

Question: This question is pretty straight forward. From my knowledge, both forms are written freely without much restriction.
How can I tell the two apart and what are some of the things that make them different?
Answer: I assume you seek an empirical answer, but here is a philosophical one. I am giving such an answer because I deem giving the kind of answer which I assume you seek as impossible. Below is my argument for why it is impossible.

How can I tell an SUV apart from a van?
What are some of the things that make a truck different from a
lorry?

Before you evaluate the rest of my argument, please actually looking at what these things look like by following the above links.
To come up with an empirical answer to 'what are some of the things that make a fantasia different from a rhapsody', one can reason by induction: gather exemplars of each concept, and look for commonalities among each set of exemplars, and look for differences between the two sets. One can reason by deduction: formulate a theory of what each concept is by describing a prototype or archetype corresponding to each concept, perhaps using empirical observations from induction, then compare the two theories formulated for differences.
I deny such theory to be useful because composers can always invent new pieces that defy such theory (or 'definition'). For example, imagine historians adjusting their definitions of what a symphony is after Webern composed his Opus 21. Why do theorists define concepts like fantasia or rhapsody (by formulating theories ABOUT actual pieces, using concepts that REFER to empirical observations) even though they know new empirical data (which are man-made instead of occurring naturally) can make such theory obsolete? They do so not necessarily to build theories that are true, but ones that are USEFUL. I now pass a value judgment on your question by saying that the answers to your questions cannot be useful because of my observation of the lack of inducible conceptual differences between actual pieces named as rhapsody and those named as fantasia.
My line of reasoning in the above paragraph may not be so convincing to you because you may not agree with my judgments. I therefore started this answer with a completely different approach: instead of reasoning with you with induction and deduction, I reason with you by analogy, in my questions above as answers. My reference to Webern's Symphony was also meant to be analogous to pieces that have the word rhapsody or the word fantasia in their titles.


Google OAUTH2 - how to detect user is already logged in

Question: I'm using Google OAUTH2 for my website. I can successfully login using the google authentication.
Here is what I want to do is:
1) user goes to website homepage and user signs in by clicking "sign in with google" and login is successful and user is taken to logged user dashboard page.
2) user comes back after half hour, user goes to home page and they should get automatically redirected to logged in user dashboard instead of homepage since they already have a valid session.
question - how can you detect if the user is already logged in? Should I be storing the access_token in the session to detect this? what's the recommended way to acheive this with Google OAUTH2?
Answer: Yes, you can store the access token in the session, but keep in mind that it could be expired. You should be able to get a new one with an immediate request.
You could also try and do session synchronization from JavaScript, if your site does not have its own session management:
https://developers.google.com/+/web/api/javascript#gapiauthchecksessionstatesessionparams_callback


$\int_R xy^2ds$ where $R$ is the upper half of the circle $x^2+y^2=25$.

Question: Is my procedure correct for the following problem?
Calculate
$$\int_R xy^2ds$$
where $R$ is the upper half of the circle $x^2+y^2=25$.
What I did was parametrize the circle which gives $g(t) = (5\cos(t), 5\sin(t))$ and $0 \leq t \leq \pi $. This ends in the integral
$$\int_0^{\pi} (125 \sin^2(t)\cos(t))(5)dt=0$$
Is it correct that it's $0$ or did I make an incorrect parametrization? Thanks.
Comment: How did you change a 2 dimensional integration into a 1 dimensional one? Your id suggests extra powers, but you have access to some axioms not usually included in a standard curriculum.
Comment: Already answered, but I just wanted to add that you can verify it is $0$ intuitively by symmetry. Every point $(x,y)$ is "balanced out" by $(-x,y)$, because $-(xy^{2})=(-x)y^{2}$
Comment: This looks to be the line integral of  $f(x,y) = xy^2$ over the upper semicircle of radius $R,$ not a double integral over the half disk.
Comment: This is a line integral with respect to the arclength so you are doing it right
Answer: I am going to assume that you are interested in the integral of $f(x,y) = xy^{2}$ over the region $R$:
\begin{align*}
I = \int_{R}xy^{2}\mathrm{d}y\mathrm{d}x = \int_{-5}^{5}\int_{0}^{\sqrt{25-x^{2}}}xy^{2}\mathrm{d}y\mathrm{d}x
\end{align*}
If we make the change of variables $x = r\cos(\theta)$ and $y = r\sin(\theta)$, one  gets that
\begin{align*}
I = \int_{0}^{5}\int_{0}^{\pi}r^{4}\cos(\theta)\sin^{2}(\theta)\mathrm{d}\theta\mathrm{d}r & = \int_{0}^{5}r^{4}\mathrm{d}r\int_{0}^{\pi}\cos(\theta)\sin^{2}(\theta)\mathrm{d}\theta = 625\times 0 = 0
\end{align*}
EDIT
If you are interested in the line integral, here it is:
\begin{align*}
\int_{\gamma}f(x,y)\mathrm{d}s & = \int_{0}^{\pi}f(\gamma(t))\|\gamma'(t)\|\mathrm{d}t\\\\
& = \int_{0}^{\pi}5\cos(t)\times25\sin^{2}(t)\times\sqrt{25(-\sin(t))^{2}+25\cos^{2}(t)}\mathrm{d}t\\\\
& = 625\times\int_{0}^{\pi}\cos(t)\sin^{2}(t)\mathrm{d}t = 0
\end{align*}
Comment: To be fair, ending with zero does not mean that the antecedents are correct. Your steps are good, but the OPS are missing an entire dimension.
Answer: It's unclear whether you want the surface integral over the region enclosed or the line integral over the boundary of the semicircle, but you can use a symmetry argument in any case.
Here is how you would do it for the surface integral. Let us split your region into two disjoint parts $A$ and $B$, where $A = \{(x, y) ~|~ x = 0\}$ and $B = \{(x, y) ~|~ x \neq 0\}$. Note that for every point $(x, y)$ with $x \neq 0$ in region $B$, the point $(-x, y)$ also lies in the region. Since the integrand is odd in $x$ (i.e. $xy^2 = -((-x)y^2$), and hence $\int_B xy^2 ds = 0$. In addition, the integrand is zero on every point in $A$, so it follows that $\int_A xy^2 ds = 0$. Hence,
$$\int_R xy^2 ds = \int_A xy^2 ds + \int_B xy^2 ds = 0$$
The symmetry argument for the line integral is similar.


4 member committees with more women than men

Question:
From a group of 10 men and 5 women, 4 member committees are to be formed each of which must contain at least one woman. Then the probability for these committees to have more women than men is:

$\frac{2}{23}$
$\frac{1}{11}$
$\frac{21}{220}$
$\frac{3}{11}$

Since each committee must have at least one woman, 4 women have already been placed into separate committees. There is one woman yet to be placed. For a committee to have more women than men, there can be 2 women and 0 men or 1 man. For a committee having only one woman, there must not be any more men in the committee.
This is what I could reason so far. But I don't know how to proceed.

Edit:
I might have misinterpreted four-member committees (having 4 members) as 4 committees.
Comment: "the probability for these committees to have more women than men" - That's awfully vague. For at least one of these committees to contain more women than men? For all of them to contain more women than men? For one chosen at random to have this property? All these interpretations would give different results.
Comment: @TMM That's exactly my point. I was totally confused during the exam. Hence I did not attempt it ultimately. (There is negative marking.)
Comment: Are you quoting the exact question then? If so, that's pretty bad on the examiners side.
Comment: Yes. It is the exact question. The exam took place on Sunday 9th April (and 8th as well): The online version of JEE Mains 2017.
Answer: The probability that there is at least one woman in the committee is 1 minus the probability that no woman is in the committee
$$P(W\geq 1)=1- \frac{{10 \choose 4}\cdot {5 \choose 0}}{15 \choose 4}$$
Then it is asked for $$P(W\geq 3|W\geq 1)=\frac{P(W\geq 3\cap W\geq 1)}{P(W \geq 1)}=\frac{P(W\geq 3)}{P(W\geq 1)}$$
And $$P(W \geq 3)=\sum_{x=3}^4 \frac{{10 \choose 4-x}\cdot {5 \choose x}}{{15 \choose 4}}$$
Comment: In the last line... shouldn't it be $\sum_{x=3}^{4}$ instead of $\sum_{x=3}^{5}$?
Comment: Yes you´re right.
Answer: each group should have at least one women  so total no of ways $=\binom{15}{4}-\binom{10}{4}$
$$P(W \ge 3) =\frac{\binom{5}4 \binom{10}0+\binom{5}3\binom{10}1}{\binom{15}4-\binom{10}4}$$
Answer: If you consider each committee to contain 4 members and assume that there are 4 committees,
P(4 member committees which contain at least 1 woman) = P(3M,1W)+P(2M,2W)+P(1M,2W)+P(0M,4W) =
{10C3.5C1 + 10C2.5C2 + 10C1.5C3 + 10C0.5C4}/ 15C4 = 1155/1365
P(committees to have more women than men) =
{ P(1M,3W) + P(0M,4W) }/ {P(3M,1W)+P(2M,2W)+P(1M,2W)+P(0M,4W)}
=(105/1365)/(1155/1365) = 1/11, which is the required probability.


Testar valor de saída para conferir se é INTEIRO

Question: Montei a função abaixo, para verificar se o valor de saida é integer ou real.
 funcao menu_8():inteiro
    var
    logaritmo :real
    inicio
    para contador de 0 ate 12 faca
          logaritmo <- ((log(i[contador])) / (log(2)))
          se ((logaritmo % 2 = 0) OU (logaritmo % 2 = 1)) entao
             escreva(" é Potencia de 2: ", i[contador])
          fimse
    fimpara
    escreval(" ")
    fimfuncao

Caso ela seja real, não deve exibir nada na tela.
Caso seja integer, deve exibir uma mensagem "é potencia de 2"
Como testar se LOGARITMO é INTEIRO?
Comment: seria que se for inteiro entao ele exibe na tela a mensagem caso contrario nao exibe pois o numero nao é potencia de dois.
Comment: por isso o topico esta com o nome Testar valor de saída para conferir se é INTEIRO se o teste = int entao imprime mensagem caso contrario nao faz nada!
Comment: Até onde eu sei, não é possível fazer MOD(%) em números reais, caso isso seja possível seu algoritmo já faz isso, pois caso ele seja real ele retornaria um valor real como resultado do MOD  e não passaria na condição do SE.
Answer: Use a função int para truncar o valor. Se o valor original for igual ao truncado, é inteiro.
SE logaritmo = int(logatimo) ENTAO


How can I theme "Error generating image." error 500's in Drupal 7?

Question: I wish to theme the error pages generated by the image module in drupal 7, I'm not sure it can be done as this is the code that runs when imagecache fails to generate a style:
<code>else {
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
    drupal_add_http_header('Status', '500 Internal Server Error');
    print t('Error generating image.');
    drupal_exit();
}
</code>
I'm not intending on having a whole themed page, but something that isn't quite as ghastly as white screen with just "Error generating image." on it. Rather at least some way for a visiting to navigate away from it and remain on the site if they wish. It would be even better if I could return a 404 instead.
This is of course, without hacking core. So anyone have any ideas or have I missed something?
Comment: Have you tried to fix the error first ? Do you know what is causing this in the first place ?
Comment: The error is beyond my control. It happens when someone comes to the site from google image search, the image is still indexed by google, but has been removed from the site. So clicking "Full-size image" from the right sidebar in the overlay results in "Error generating image" and what should appear as the image in the image overlay when you arrive at the site from image search is also sometimes "Error generating image" though it is unpredictable. It also bothers me that google is being fed error 500's when the image no longer exists so it should be a 404.
Answer: You can't.
This is hardcoded in http://api.drupal.org/api/drupal/modules--image--image.module/function/image_style_deliver/7.
You would need to completely override this page callback to change what it does. You could do this with hook_menu_alter() but that means that you would need to make sure that you also apply any upstream changes to that function to your own copy.
Can't you just leave the images there instead of deleting them? And if they are just a temporary resource, maybe exclude them from search with robots.txt?
Comment: I had realised it was hardcoded but I thought I had missed something as this is one limitation I have run into with Drupal. I think I will go with hook_menu_alter() then.
Comment: Missed the 5 minute comment edit mark, robots.txt is out as the images should be indexed and blocking 3 styles per 4 - 8 images on a daily basis would be a huge robots.txt, the particular site is a proving ground for methods I am interested in using but which lack personal production environment experience, so it already consumes more than it's "fair" share of time. Not removing them is also out as the site owner uses it as a catalogue of the best images they wish to keep organised.


Boat Word Problem

Question:
A crew can row a certain course upstream in 84 minutes;
  they can row the same course down stream in 9 minutes less than
  they can row it in still water: how long would they take to row
  down with the stream.

The equations I came up with are:
$$\frac{d}{x - y} = 84$$
$$\frac{d}{x + y} = \frac{d}{x} - 9$$
Where $d$ is the distance covered in their course, $x$ is the rate of the people rowing the boat, and $y$ is the rate of the stream.
I tried substituting $d$ with $84(x -y)$, and that rendered the equation $3x^2 - 25xy + 28y^2 = 0$. As far as I know, this equation isn't solvable. Any attempts I make to obtain other equations or results leads to this same equation.
If there's any alternate method to solving this, I would love to know.
Thanks.
Answer: That equation is perfectly solvable. You're implicitly assuming $x$ and $y$ are non-negative from the way you've structured your equations, so you can fix a non-negative $y$ and try and figure out if there exists a positive solution $x$. That is, if we fix $y$, then
$$3x^2-75yx+28y^2=0$$
is a regular old quadratic equation in $x$. The solution will be some formula involving $y$, and you can check for which $y$ that formula gives a positive real number.
Comment: Can't believe I didn't realize that...Thanks.
Answer: HINT
Your task is not to figure out $d,x,$ or $y$, your task is to figure out how long it takes the crew to go down with the stream.

Boat Word Problem


Using perlbrew to build a perl with debugging symbols

Question: I'm trying to track down a segmentation fault that I've been able to isolate to just a few lines of code on different versions of Perl. I use perlbrew to manage my various versions for development and testing, but it doesn't build perl with debugging symbols, so using gdb to analyse the core dump file is pretty useless.
So what's the best way to have perlbrew build with debugging symbols enabled. And if possible I'd like to be able to have it be a separate perl that I could switch to instead of overriding the standard one for the same version.
Answer: perlbrew install -v 5.14.2 --as=5.14.2d -DEBUGGING=-g

(--as puts it under a different name, so you can keep your existing builds.)
There's also the following which includes the above and stuff you surely don't need:
perlbrew install -v 5.14.2 --as=5.14.2d -DEBUGGING=both

See INSTALL in the root dir of the Perl distro.
Comment: This seems like just what I was looking for, however it doesn't seem to work. I ran this command `perlbrew install perl-5.8.8 --as='perl-5.8.8-debug' -DEBUGGING=both`. Then to inspect it with gdb I ran `gdb /home/mpeters/perl5/perlbrew/perls/perl-5.8.8-debug/bin/perl` and gdb still says "Reading symbols from /home/mpeters/perl5/perlbrew/perls/perl-5.8.8-debug/bin/perl...(no debugging symbols found)", so obviously I'm still missing something.
Comment: `-DEBUGGING=both` might not have existed back then? Check the `INSTALL` file for the right version distro. (`-Doptimise=-g` should work even back then.) You really should mention it when you're using ancient software. (5.8 was first released 10 years ago. 5.8 and 5.10 are no longer supported, and 5.12 is about to be EOLed too.)
Comment: Thanks for the hint about the options being version specific. I went with `perlbrew install perl-5.8.8 --as='perl-5.8.8-debug' -Doptimize='-g'` and it worked like a charm. Thanks.


Can I play pipe organ as a pianist?

Question: I've never played pipe organ. I'm a pianist and a friend of mine ask me to play on the church on his wedding on a pipe organ.
Are there enough difficulties playing a piano song on the pipe organ to make any problem? What considerations do I have to take on the performance?
I've been asked to play the Wedding March only.
Comment: Keep attention, if the instrument is an ancient one: if the lowest octave is only partially present, it may have compressed layout, so (semi-)tones are missing and the remaining are crammed to the existing keys - good luck.
Comment: Others have given great descriptions of the differences between the instruments, so I just want to tack on this half-answer: Since the biggest adjustments are getting used to not having a sustain pedal and the volume not being touch sensitive, you can practice fairly effectively by using a keyboard set to a non touch sensitive sound and ignoring the pedal.  It might also help to use an unweighted keyboard if you have one handy.
Comment: Do you have easy access to a synthesizer? If so, you can set it to play like an organ, with the constant loudness in place of the piano's percussive attack and sustain. It's even better if the synthesizer includes a swell pedal. If you ask nicely at a time when business is slow, and explain your situation, they might let you practice on their keyboard.
Comment: I know this is a very old thread, but I'm curious about how it worked out with the wedding music. Were you able to successfully make the transition to playing the organ?
Comment: I've loved playing on both the piano and pipe organ since I was in my early teens, and I've researched them extensively! I learnt how to utilise the bass pedals and finger substitution, and I now have a pump organ from the late 1800's!
Answer: The black and white bits are the same, except you will probably only get 49/61 of them instead of the 88 you're probably used to. The action will be rather different, too. No matter how loudly or quietly you try to play, the volume will remain the same.
There is no sustain pedal, so that will be different, too. You'll have to acclimatise yourself to playing with your two hands on separate boards. Instead of the sustain pedal, you'll use your right foot on a swell pedal, but once set, it can be left alone - till you accidentally knock it!! Don't bother with the pedals, that's a skill for another day.
A basic knowledge of what the stops do will make what is played more listenable - using the same sound for everything gets quite boring. Certainly get some practice in before the big day. Good luck!
Comment: You wouldn't necessarily play on two manuals for something like the Mendelssohn or Wagner wedding marches: they're homophonic pieces, and the sound should be more or less consistent through the whole texture. You'd only use separate manuals if there was a second voice in the texture for which you wanted different registration in order to give a tonal contrast.
Answer: It's obvious when you think about it, but the biggest difference between an organ and a piano is the way their sounds decay.
A piano is a hammer hitting a string. The loudest sound is right at the beginning, and from there on the sound decays organically as the string returns to rest. If you let the dampers do their thing, the decay is shortened, but it's still there. The shape of the volume envelope of a piano is a sharp peak, followed by a progressively more gentle slope eventually settling back to zero.
An organ is the opening and then closing of a valve that pumps air into a pipe. There is no decay at all until you release the key, then the air and sound shut off virtually immediately. The shape of the volume envelope is like a table: straight up, then flat across the highest level, then straight back down to zero. If you use the swell pedal to open or close the enclosure around the pipes, you are affecting volume (that is, making the table top uneven), but you are not changing the fact that there is no gradually flattening decay. Of course, the reverberation of the room/church does it's thing after you release the note, but this is not at all similar to the way a piano string decays, and in any case you can't control it by, say, hitting the key harder.
This all means that you have to be very precise about something when you play an organ that you do not have to nearly as precise about when playing a piano: the moment you release the key.
On an organ: Release is an important as attack. Release is as much a rhythmical event as attack. And release changes the harmonic content suddenly.
Don't be worried about this. See it as a very cool additional feature of the instrument. You get two rhythmical elements for the price of one. It's really interesting to focus on the end of the sound as much as the beginning. It will also improve your technique and musicality on the piano.
Comment: This.  A consistent leggiero is so much harder to achieve than on a piano that it is not funny.  Those differences distinguishing "a child plays the instrument" and "a musician interprets music" are totally different between piano and organ.  Perhaps try the instrument out with a reasonably large safety margin, and if you can't feel satisfied with your play in a reasonable amount of time, pull the plug in time for a replacement.
Answer: It sounds like you're probably going to play the Mendelssohn Wedding March. If so, this should be okay for you to play on the organ. Just looking on Google, there are loads of arrangements of this piece, both for piano and organ. Of course, a piano version will suit you much better, as you won't need to play the third stave, which is the pedal part played with the feet, and you'll be able to practise it on piano.
I think the most important thing to do, is make sure you have practised the piece plenty, and are confident playing it on the piano before the day; then, you should be able to play it on the organ more easily.
If the range of the music is too large to play on one manual (keyboard), you can play with different hands on different manuals. This will sound more interesting too, as you can set different sounds for different manuals using the stops.
If you are able to, it might be worth trying to get in touch with the church; they'll know if the organ has any peculiarities - organs do tend to differ quite a lot. It would be even better if you had a chat with their organist...
Have fun!
Comment: Aha! I'll completely rewrite my answer then!
Comment: I have to play the wedding march only (I don't know yet which one). And I will have only time to practice the organ on the wedding day
Answer: Organ playing requires more legato, learn to slide around the keyboard. Sometimes it helps to change fingers while the note is still held down so that you can move more smoothly to the next note. It's a good exercise for a pianist wanting to get a cleaner legato line.
Comment: Organists who are learning to play the piano tend to make a heck of a lot more finger substitutions than pianists do.  They are easier on the organ because you don't have to strike the key with as much force, and more necessary because you can't connect notes with the sustain pedal.
Answer: In a situation like this, the present church organist/pianist should be contacted regarding the organ for any helpful pointers, etc.  This is  an especially respectful approach to take.  It's best to meet with this individual before the wedding day so that there aren't any surprises.
If the organ is locked, someone needs to be there that has a key or knows where the key is kept so that you have access.
Once organ is unlocked, you need to know where the power switch is.  It's not always obvious.
When an organist approaches the organ bench, we slide onto the bench, we DON'T stand on the pedals.
Like a piano bench, you can adjust an organ bench to your comfort level by dismounting the bench and moving it to your comfort zone.
If you do play pedals, you play them with FLAT shoes.  When you're not playing the pedals, you can rest your feet comfortably on the back of the bench rail.
You can place your music on the rack just like you would at the piano.
Before the week or day of the wedding, it's best to make arrangements with church personnel sir you to show up to practice on organ so that you can get the organ sound you're needing, prior to day and of wedding.
FYI:  There are preset buttons under each manual.  Choose one of the manuals and try each preset button under that manual.  Play a couple of measures from your music.  You will be hearing soft and louder to much louder as you go from one preset button to the next.
I would do this with each manual and presets.  These have been set by an experienced organist, so I know that you'll find something you like.
If you don't hear one on that manual, go to the next manual and try each preset button.
Continue to do this, until you hear what you like..
The day of the wedding:
The pastor will take his place which is the que for the groom, best man and other groomsmen to take their place by the pastor.
I always got a signal from the wedding coordinator that all was well and ready.
I played the "Trumpet Voluntary" for the bridesmaids processionsal down the aiisle and get into place.
I started the Wedding Processional only after the bridesmaids were in place up front and bride and Dad were standing in place at back of sanctuary.
When you play that octave F intro on the organ of the Wedding March, that's the signal for the congregation to stand up and turn toward the back of the church to watch the bride and her Dad start processing down the aisle to the front of the church.  I rarely ever had to go to the second page of the Wedding March.  The organ sets the tempo for them to walk down the aisle.
Once they are standing in front of pastor, you can delicately end the Traditional Wedding Processional.
If you are responsible for playing the traditional Wedding Recessional.  After the pastor says
"I now pronounce you husband and wife. You you may kiss your bride" the congregation rises and applades and then the traditional Wedding  Recessional is played.
Best of everything and most of all, have fun!
Comment: This seems less like an answer to the posted question of differences between piano playing and organ playing and more like an answer to a question of what to possibly expect as an organist playing his or her first wedding.
Comment: "There are preset buttons under each manual." This only applies to certain organs, definitely not all. Dealing with stops without presets would be something to discuss with someone who knows that instrument, or at least who knows organs in general.
Answer: There are slight differences between keyboard technique on organ and piano, but if you're a good pianist and have a decent ear, you'll probably make a lot of the adjustments automatically. As an experienced pianist, I did not find it difficult to learn to play organ manuals. Note that organ notes sustain as long as you hold the key, but there's no sustain pedal as on the piano.
However, you should get familiar with how the stops work (if you're not already), and also develop some basic pedal technique if possible.
Answer: You'll manage!  Don't try to be clever.  Set up a loud sound on one manual of the organ, a softer one on another.  Play with both hands on the same manual, but move to the other one as appropriate.
Make sure you can play the pieces on piano with no pedal and no pianistic tricks.  You have to plonk ALL the notes down NOW.  Don't worry about legato, the acoustics of the church will take care of that.
If it all shows signs of turning pear-shaped, rather than playing handfuls of wrong notes, just play the top and bottom notes of the music.  It will sound fine.
If possible, get help.  Ask if the church organist will give you a little time on the morning of the wedding.  Church people SHOULD be kindly and charitable (funny how that doesn't always happen, isn't it?).    Set up suitable sounds.  Show you how to turn the thing on!   He will appreciate your desire to contribute to your friend's wedding.  If absoultely necessary he will probably be prepared to rescue you.
Alternative - most churches have a piano.  Or a digital one can be brought in.  Tell your friend you'd love to take part, but would be much happier playing a familiar instrument.  Maybe you could also play something during the registry signing?
Answer: One large aspect in organ-playing not present in piano-playing is the decision of which stops to pull for certain parts of the piece. This decision will vary from organ to organ as each will have its own set of stops (sounds). Sometimes, the editor of the piece will give suggestions at the top of the first page, and will sometimes tell you to pull (activate/turn on) or push (deactivate/turn off) certain stops throughout the score. Most of the time, it will be up to you to decide to see which combination sounds appropriate.
If you haven't had the opportunity to tinker around with a pipe organ, I'll give you a few quick and dirty pointers:

The number on the stops, if divisible by 2, signifies which octave will sound when you press a key. 8' is the same pitch as the piano. 4' means an octave higher than the key pressed, 2' means two octaves higher. 16' means one octave lower than the key pressed. Adding higher octaves produces a brighter sound. The 16' gives more volume, but be careful that it can cause a passage to sound muddled.
You will notice that there may be more than 1 stop marked 8'. Each of these 8' stops have a different timbre or sound. Typically, there is the diapason, which is supposedly the signature organ sound, the flute, and some string imitations like gamba or viola. Each of these different sounds may also have their 4' and 2' stops. The choice of which "sound" depends on the piece and you as the organist.
Some organs will have reed pipes, whose sound resemble reed or brass instruments. They are also marked with a number that is a power of 2 as with the other pipes. Newer organs will print the pitch and name in red to indicate that it's a reed stop. Typically, you will want to use a reed stop if your piece has a solo and accompany setup like Trumpet Voluntaries. You will typically play the melody an upper keyboard using that reed stop, while your left hand plays the great (lower or lowest) keyboard using diapasons and/or flute stops.
Some stops are marked with a Roman numeral starting with II and up. These are the mixture stops. These are a series of really high-pitched pipes, several of them sounding when you press a single key. These add brilliance to the overall sound. You will want to pull these for loud/grand passages. You will want to use these mixture stops for that Wedding March at the end, but maybe not the Bridal March (too loud/bright).
Some organs may have stops marked with 1 1/3' or other mixed number. These are high-pitched pipes that are not of the same octave as the note pressed. These tend to make the overall sound "nasal" like a clarinet or other soft single-reed instrument. They are not the "shrill-sounding" mixtures.
For prelude pieces, you will want softer sounds. You'll probably stick with 8' and 4' non-reed stops most of the time, no mixtures. You will also use similar soft settings if you would accompany a singer or solo instrument player.
For that Bridal March, you can add 2' stops, but maybe not mixtures. Experiment. That organ's mixture may be soft enough.
Go all out on the Wedding March, but I would still be cautious about 16' in the manuals. Add reeds and mixtures.

Another aspect is pedals. You don't just tap every single note with the toe of your left foot, as I've seen many first-time organ players do. If you tinkered with an organ's pedals, you'll discover that you will need to use your heel as well, and both feet to achieve the required legato. You may end using your right foot to the lower pedal notes and your left foot on the higher pedal notes, which may cause you to lose your balance and fall over. You will gain the balance over time, but I don't think there are very many technically demanding organ pieces and arrangements for weddings.
But as already mentioned, you will need to make arrangements with the church to allow you in during the week to practice. You will need to do this for every other church's organ you're playing for each wedding, since each has a vastly unique feel compared to the variation between 2 different pianos.
Answer: The pipe organ itself is not related to the piano in any way other than the scales of notes, and is about as similar to a piano as a xylophone is (actually it is more similar to a harpsichord). To be a good organist, you have to scrap much of what you have learned about piano technique, because very little of it will help you when you get onto the organ bench. You may be able to play it, but if you're playing the organ as if it were a piano, you might as well be playing the cello as if it were a violin.
There are vast differences between the two instruments. To play the organ well, you need to start from the beginning and learn the basics of registration, pedal technique, tracker and electropneumatic organ playing, and expression (that is, the use of the swell pedals.)
That said, it is possible to play tunes on the organ, such as arrangements of the Mendelssohn Wedding March, by playing the organ as if it were a piano. Some Allen organs have something called a "Great Bass Coupler" which makes it sound like a pedal part is being played when activated, which is frowned upon for permanent church musicianship but is occasionally necessary.
Comment: I'd downvote this if I had enough reputation. My piano technique helped my organ playing greatly—I didn't have to scrap it to get good on the organ. I also play harpsichord, and don't find the technique similar to organ at all.
Comment: I like your piano/xylophone and cello/violin analogies here! I often describe the differences between playing classical and electric guitar as being as different as playing saxophone and flute. Having said that, it seems as though quite a few answers on this page have been giving the questioner a pretty hard time; it sounds as though he wants to contribute something to his friend's wedding, rather than start a career as an organist!
Answer: It really depends on how much time you have to prepare. You can probably adjust to the organ well enough to play a simplified version of the march at the wedding in 6 months, assuming you find a qualified private teacher and diligently follow his instructions. It will require a lot practice for you but is doable if you have the time.
Comment: xD Wedding is in less than two weeks and I will have no teacher neither possibility to practice on a pipe organ
Comment: @SysDragon Well, you'll need to get some time to practice on the instrument before the wedding, even just for an hour or two, if you want to be sure you can play it.
Comment: @SysDragon I would suggest you turn this down. The organ is a very unique instrument, if you don't learn how to play it properly (and you'll certainly need more than 2 hours) it will sound very bad.
Answer: If you are sure you can press the right keys at right time, it will probably sound like a music for the most of the listeners (excluding serious organists, these will probably see many things done unprofessionally). I tried to switch my digital piano into "organ mode" - no touch sensitivity any longer but sounds interesting and nice, while I only play very simple pieces.
I would say go an try, will be a great day to remember anyway. Just be very careful not to break anything on the unknown instrument.
Answer: Forget it! If you are playing a large organ with 3 to 4 keyboards and upwards of 30 or 40 stops or more you may be eaten alive or worse - disappear for good. To play an organ well needs a lot of time and effort, without that you don't stand a chance against the beast.
It won't sound right without using the pedal board and a least 2 manuals for the wedding march. Saying a prayer isn't going to help you much either.

Can I play pipe organ as a pianist?


How Gower's dissimilarity handle missing values in numeric columns?

Question: I would like to ask a question about Gower dissimilarity, I was wondering how Gower measure handle missing values in numeric columns, especially that Gower  standardized each column based on the range of the same attribute ?
I have read both details of functions daisy and gower.dist in R and their original source (chapter 1 of Kaufman and Rousseeuw (1990)) but I got confuse.
http://www.inside-r.org/packages/cran/StatMatch/docs/gower.dist
https://stat.ethz.ch/R-manual/R-devel/library/cluster/html/daisy.html
I tried also to look at similar discussions in this website
Gower distance and MDS: How to determine which variables count?
but I did not find an answer.
also imputing the data with a dummy/mean values are not an option for me, I need my data as it is. my data is students' exams marks.
Comment: The ideas behind [Gower similarity](http://stats.stackexchange.com/a/15313/3277) are themselves unrelated to the question of missing values. It is left on function and it options. Normally, _pairwise_ treatment of missings should be allowed. In this regime, all cases are taken and two cases are compared (produce the similarity) if there is at least one variable where both are valid values. Additionally, for binary variables, the two cases are compared only if at least one of the two has "1" value in the binary variables.
Comment: (cont.) In _listwise_ regime, cases are excluded whenever they have at least one missing datum. You should consult with the documentation of your function to know how it is there.
Answer: It's your choice. There is no "correct" way.
The most "correct" way would be the work with two similarities. An upper bound and a lower bound.
Consider this toy example:
<code>dist(  [A, B],  [C,?] )
</code>
if the missing value is D then you get a similarity of 0, that is your worst case. But if the missing value is B, and say you don't have any other records with a B and no A either, then it even could be the most similar object.
But then you would need algorithms that can handle this well, and I don't know of any.
A popular approach is missing value imputation. By replacing missing values (at least temporarily) with your best estimate, you are often closest to the real result.
Another popular approach is to ignore records with missing data.


Disk encryption without cooperation from system

Question: I have a small embedded system that supports fat32. It does not have any encryption options for the files that it saves to a external usb connected disk. Modifying the source to support encryption is not an option. Are there any external drives, or somethings that can be used to encrypted the files once the land on the disk? Something that does not require the cooperation of the embedded system?
I realize that this is a bit far fetched, but you never know!
Comment: What's the use scenario? Do you have to read from the device on the embedded system as well as write to it? I'm thinking you have a key management problem here.
Answer: The IronKey USB devices have on-device encryption.  A Google search for encrypted hard drive yields some useful looking results.
Comment: It looks like this one requires a software install on the system.
Comment: Hmm, I missed that.  Some of the other devices looked completely self-contained.
Answer: There a few options which allow you to disarm the encryption until the next power cycle.
https://superuser.com/questions/296750/independent-hardware-based-encryption-tool-used-with-non-cooperative-system-and


How to manage reservations with Drupal for something that is not something like a room?

Question: I am looking for a reservation module for either Drupal 6 or 7. I know there is a really good looking module for room reservations for Drupal 7 but my use case is different. I am looking for a reservation/booking module that could be used for booking photographers or DJs. I have searched around but haven't really found anything suitable yet.
The Room Reservations module that is being created for Drupal 7 looks great, but it needs to be generalized so that the administrator could define what it is that needs to be booked. Right now it is hard coded for rooms only.
Does anyone know of such a module and more importantly worked with it?
Answer: For Drupal 6 there is a stable release of Simple Reservation module.

This module provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

For Drupal 7 you can try Reservations API.

The core focus in on the Reservations API that enables any Content Type to be reservable based on a variety of default settings. A Reservation -> Confirmation -> Checkout -> Checkin workflows is included, but it is created entirely using Views. Additional modules can enforce custom validation, add pricing, or add additional availability to the basic hours of operation.
Comment: I will look into both suggestions. I take it that both can be integrated with Ubercart?
Answer: Check the following module: Booking Time Slots.
This module works as extension to Calendar and provides nice UI (customisable) for slot booking (reservation).
This is the screenshot of the UI exposed from the module.
Drupal 6.x

You can customize how many slots are period (hour, half-hour or custom). You can easily override template files based on your needs. Once the user make the reservation of specified slot, it's booked.
Drupal 7.x

For other modules, check: Comparison of Booking System modules
Comment: This looks interesting for my use case. Thanks for posting about this particular module.
Answer: Below is a summmary of the modules and/or distributions you may want to look at for managing reservations, for something that is not a room (or a variation of that). These modules have a stable release, and can be used  for either D6 or D7 (quotes are from their project pages):

Availability Calendars (D6 or D7).

... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation (D6 or D7).

... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI (D6 or D7).

... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (D6 or D7).

... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Booking Systems Comparison
Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.
This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).
How to pick the module that fits best
I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.
So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards.
Here is the intro about it (from that page):

... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.
Also note that I've ordered my shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.
Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph),
I hope this does not violate the site's policy on self-promotion.