How to flash error text using WPF animation

Question: I have textbox displayed using the DataTemplate. In the below code TextBoxViewModel is derived from IDataErrorInfo.
protected String m_ValidationErrorMessage;
protected String ValidationErrorMessage
{
    get { return m_ValidationErrorMessage; }
}

private bool m_ShowErrorMessage = false;
public bool ShowErrorMessage
{
    get { return m_ShowErrorMessage; }
    set { this.m_ShowErrorMessage = value; }
}

private String m_DisplayValue;
public String DisplayValue
{
    get { return this.m_DisplayValue; }
    set
    {
        if (m_DisplayValue != value)
        {
            if (IsTextValid(value, out m_ValidationErrorMessage))
            {
                // Set data to model
                this.SendPropertyChangedEvent(nameof(this.DisplayValue));
            }
            else
            {
                ShowErrorMessage = true;
            }
        }
    }
}

public string this[string columnName]
{
    get
    {
        if (columnName == nameof(this.DisplayValue))
        {
            if (ShowErrorMessage)
            {
                return ValidationErrorMessage;
            }
        }
        return null;
    }
}

xaml for TextBoxViewModel
<DataTemplate DataType="{x:Type vms:TextBoxViewModel}">
    <DockPanel>

        <TextBox DockPanel.Dock="Left" Text="{Binding Path=DisplayValue,Mode=TwoWay, UpdateSourceTrigger=Default,ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource ErrorTemplate}"/>
    </DockPanel>
</DataTemplate

<ControlTemplate x:Key="ErrorTemplate">
    <StackPanel Orientation="Horizontal">
        <AdornedElementPlaceholder x:Name="textBox"/>
        <ItemsControl ItemsSource="{Binding}" VerticalAlignment="Center" HorizontalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</ControlTemplate>

I am trying to flash the error text for few seconds and hiding it after that. Is there any way to achieve this using the XAML (WPF animation)?
Answer: You could for example animate the Opacity property of the TextBlock using a DoubleAnimation. Something like this:
<ControlTemplate x:Key="ErrorTemplate">
    <StackPanel Orientation="Horizontal">
        <AdornedElementPlaceholder x:Name="textBox"/>
        <ItemsControl ItemsSource="{Binding}" VerticalAlignment="Center" HorizontalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ErrorContent}" Foreground="Red">
                        <TextBlock.Triggers>
                            <EventTrigger RoutedEvent="Loaded">
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                                         From="0" To="1"
                                                         AutoReverse="False"
                                                         Duration="0:0:0.5"
                                                         RepeatBehavior="3x" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger>
                        </TextBlock.Triggers>
                    </TextBlock>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</ControlTemplate>

Comment: @FaisalM: Set the `AutoReverse` property to `true`.
Comment: Thanks, it works. Is it possible to hide the `TextBlock` when the animation is finished?
Comment: In my application there are a number of tabs. The `TextBlock` is in one tab, the problem now I am facing is whenever I switch to this tab the ErrorText is flashing if it was previously shown. I think this is because we specify the `RoutedEvent="Loaded"`. I want the error to be shown only if it is explicitly set again.
Comment: @FaisalM: Please ask a new question if you have another issue.


Trigger inserir e alterar dados

Question: Boa tarde, estou tentando criar uma trigger que depois de inserir dados(after insert) na tabela prodvdmat, ela vai na tabela "entradarm" e verifica se existe o dado nela, se não existir cria um registro novo, se existir atualiza(quantidade e valor).
--

-- Acionadores `prodvdmat`

--

DROP TRIGGER IF EXISTS `trg_entradarm`;

DELIMITER //

CREATE DEFINER=`root`@`localhost` TRIGGER `bailledados`.`trg_entradarm` AFTER INSERT ON `prodvdmat` FOR EACH ROW
BEGIN
  declare codV int;
  declare codA int;
  select codVendedor, codArmar INTO codV, codA from prodvdmat;
  IF (codV <> new.codVendedor and codA <> new.codArmar) then
     insert into entradarm set codVendedor = new.codVendedor, codArmar = new.codArmar, quantidade = new.quantidade, valor = new.valor;
  else
    UPDATE entradarm SET quantidade = quantidade + new.Quantidade, valor = valor + new.valor WHERE codVendedor = new.codVendedor and codArmar = new.codArmar;
  end if;
END//

DELIMITER ;

Esta dando este erro:

Operation failed: There was an error while applying the SQL script to
  the database.
ERROR 1172: 1172: Result consisted of more than one row

SQL Statement:
INSERT INTO `bailledados`.`prodvdmat` (`codVendedor`, `codArmar`, `quantidade`, `valor`, `datacompra`) VALUES ('1', '1', '4', '25.00', '2019-01-14 00:00:00')

CREATE DATABASE IF NOT EXISTS `bailledados` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `bailledados`;

-- --------------------------------------------------------

--
-- Estrutura da tabela `entradarm`
--

CREATE TABLE IF NOT EXISTS `entradarm` (
  `codEntra` int(11) NOT NULL AUTO_INCREMENT,
  `codVendedor` int(11) NOT NULL DEFAULT '0',
  `codArmar` int(11) NOT NULL DEFAULT '0',
  `quantidade` int(11) NOT NULL DEFAULT '0',
  `valor` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`codEntra`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=5 ;

--
-- Extraindo dados da tabela `entradarm`
--

INSERT INTO `entradarm` (`codEntra`, `codVendedor`, `codArmar`, `quantidade`, `valor`) VALUES
(1, 1, 1, 6, '21.90'),
(2, 5, 3, 5, '10.00'),
(3, 1, 1, 2, '10.00'),
(4, 0, 0, 0, '0.00');

-- --------------------------------------------------------

--
-- Estrutura da tabela `prodvdmat`
--

CREATE TABLE IF NOT EXISTS `prodvdmat` (
  `codPrdvdmat` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT,
  `codVendedor` int(11) NOT NULL,
  `codArmar` int(11) NOT NULL,
  `quantidade` int(11) NOT NULL,
  `valor` decimal(10,2) NOT NULL,
  `datacompra` datetime NOT NULL,
  PRIMARY KEY (`codPrdvdmat`),
  KEY `FK_prodvdmat_codVendedor` (`codVendedor`),
  KEY `FK_prodvdmat_codArmar` (`codArmar`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;

--
-- Extraindo dados da tabela `prodvdmat`
--

INSERT INTO `prodvdmat` (`codPrdvdmat`, `codVendedor`, `codArmar`, `quantidade`, `valor`, `datacompra`) VALUES
(0000000004, 5, 5, 1, '10.80', '2018-11-25 00:00:00'),
(0000000005, 5, 6, 1, '19.80', '2018-11-25 00:00:00'),
(0000000006, 6, 7, 6, '89.40', '2018-11-25 00:00:00'),
(0000000007, 6, 8, 6, '6.00', '2018-11-25 00:00:00'),
(0000000008, 9, 9, 1, '24.90', '2018-10-21 00:00:00'),
(0000000012, 1, 1, 4, '11.90', '2018-11-09 00:00:00'),
(0000000013, 4, 4, 2, '5.20', '2018-11-25 00:00:00'),
(0000000014, 5, 3, 5, '10.00', '2018-12-15 00:00:00'),
(0000000015, 5, 3, 2, '10.00', '2019-01-09 00:00:00'),
(0000000017, 1, 1, 2, '5.00', '2019-01-09 00:00:00');

--
-- Limitadores para a tabela `prodvdmat`
--
ALTER TABLE `prodvdmat`
  ADD CONSTRAINT `FK_prodvdmat_codArmar` FOREIGN KEY (`codArmar`) REFERENCES `armarinhos` (`codArmar`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `FK_prodvdmat_codVendedor` FOREIGN KEY (`codVendedor`) REFERENCES `vendedores` (`codVendedor`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Executing:
INSERT INTO `bailledados`.`prodvdmat` (`codVendedor`, `codArmar`, `quantidade`, `valor`, `datacompra`) VALUES ('1', '1', '4', '25.00', '2019-01-14 00:00:00');

Answer: Experimente desta forma:
DROP TRIGGER IF EXISTS trg_entradarm;
DELIMITER //

CREATE DEFINER=root@localhost TRIGGER bailledados.trg_entradarm
AFTER INSERT ON prodvdmat
FOR EACH ROW
BEGIN
    SET @existe =   (
                        SELECT  1
                        FROM    entradarm
                        WHERE   codVendedor = new.codVendedor
                            AND codArmar    = new.codArmar
                    );

    IF IFNULL(@existe, 0) = 0 THEN
        INSERT  INTO entradarm(codVendedor, codArmar, quantidade, valor)
        VALUES  (new.codVendedor, new.codArmar, new.quantidade, new.valor)
    ELSE
        UPDATE  entradarm
        SET     quantidade  = quantidade + new.Quantidade
            ,   valor       = valor + new.valor
        WHERE   codVendedor = new.codVendedor
            AND codArmar    = new.codArmar;
    END IF;
END//

DELIMITER ;

Comment: Erro -> DECLARE @existe int; - sintax error: unexpected '@existe' at text sufix

se tirar @ da este erro  Operation failed: There was an error while applying the SQL script to the database.
Executing:

ERROR 1175: 1175: You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column
SQL Statement:
Comment: Resposta editada. Em MySql não é necessário declarar a variável.
Comment: Valeu funcionou - executou com sucesso
Comment: Perfeito! Dê um UP na resposta e marque-a como correta :)

Trigger inserir e alterar dados


How to prove that if $C_{S_n}(\sigma)\subset A_n$ then $cl_{S_n}(\sigma)=cl_{A_n}(\sigma)\coprod cl_{A_n}(\tilde{\sigma})$

Question: Let $n\ge 3$, $\sigma\in A_n$, $cl_{S_n}(\sigma)$ be the conjugacy class of $\sigma$ in $S_n$ and $cl_{A_n}(\sigma)$ be the conjugacy class of $\sigma$ in $A_n$.

Show that  if $C_{S_n}(\sigma)\subset A_n$ then $cl_{S_n}(\sigma)=cl_{A_n}(\sigma)\coprod cl_{A_n}(\tilde{\sigma})$ where $\tilde{\sigma}=\tau \sigma \tau^{-1}$ with $\tau\in S_n\backslash A_n$

Thanks for your help
Comment: I'm voting to close for merely being a problem statement (the same problem stated in [this already closed](https://math.stackexchange.com/questions/2625545/conjugacy-class-in-a-n) question).
Answer: First, note that $C_{A_n}(\sigma)=C_{S_n}(\sigma)\cap A_n$. In particular, if $C_{S_n}(\sigma)\subset A_n$, then $C_{S_n}(\sigma)=C_{A_n}(\sigma)$. Hence,
$$|cl_{S_n}(\sigma)|=[S_n:C_{S_n}(\sigma)]=[S_n:C_{A_n}(\sigma)]=[S_n:A_n][A_n:C_{A_n}(\sigma)]=2|cl_{A_n}(\sigma)|.$$
Continue to assume $C_{S_n}(\sigma)\subset A_n$, and let $\tau\in S_n$ be any odd permutation. Observe that $\tau\sigma\tau^{-1}\notin cl_{A_n}(\sigma)$. Indeed, if there exists $\rho\in A_n$ such that $\rho\sigma\rho^{-1}=\tau\sigma\tau^{-1}$, then $\tau^{-1}\rho\in C_{S_n}(\sigma)\leq A_n$, a contradiction.
As distinct conjugacy classes are disjoint, it follows that $cl_{A_n}(\sigma)\sqcup cl_{A_n}(\tau\sigma\tau^{-1})\subset cl_{S_n}(\sigma)$. To show equality, it is enough to show $|cl_{A_n}(\sigma)|=|cl_{A_n}(\tau\sigma\tau^{-1})|$, since $|cl_{A_n}(\sigma)|=\frac{1}{2}|cl_{S_n}(\sigma)|$ by the first paragraph. But, this follows from the equality $\tau C_{A_n}(\sigma)\tau^{-1}=C_{A_n}(\tau\sigma\tau^{-1})$.
Indeed, $\tau\rho\tau^{-1}\in C_{A_n}(\tau\sigma\tau^{-1})$ whenever $\rho\in C_{A_n}(\sigma)$. Hence, $C_{A_n}(\tau\sigma\tau^{-1})\subseteq \tau C_{A_n}(\sigma)\tau^{-1}$ Now, conjugation is order preserving, so equality holds. Hence,
$$
|cl_{A_n}(\sigma)|=[A_n:C_{A_n}(\sigma)]=[A_n:C_{A_n}(\tau\sigma\tau^{-1})]=|cl_{A_n}(\tau\sigma\tau^{-1})|
$$ which completes the proof.


How do I reference successive components (button1, button2, etc.)?

Question: I need to get the number after the button to increment in a for loop. For example, button1 becomes button2, etc. I have tried appending a variable which increments but C++ Builder gives an error saying "Button is not a member of TMain." Is there any way to achieve the end goal or get around this?
Comment: Specify what exactly do you need. Do you need to make buttons with texts like "button1" "button2", or do you need to _make_ the buttons with _names_ like this, or do you need to _search_ for existing buttons with names like this?
Comment: Sorry, I want the caption to be like that so that it will get a word from a table and I have it in a loop so that the table keeps going to the next record but only the first button ever has a word inside of it
Answer: You can't construct new identifiers from others at run time. The compiler is correct that Button really isn't a member of your TMain class.
Instead, build the string name of the component you want, and then call your form's FindComponent method to get the component with that name.
for (int i = 1; i <= 2; ++i) {
  std::string name = "Button" + IntToStr(i);
  TButton* button = dynamic_cast<TButton*>(this->FindComponent(name));
}

That requires that the buttons' Name properties be set accordingly.
Another solution is to forego the component names and put your objects in a proper container, like a vector. For example, you can override the Loaded method (which is where you can be sure all your form's components have been created) and fill a vector there:
void TMain::Loaded() {
  TForm::Loaded();
  this->m_buttons.push_back(Button1);
  this->m_buttons.push_back(Button2);
}

Now when you want to iterate over your buttons, you just iterate over the vector instead:
for (std::vector<TButton*>::const_iterator it = m_buttons.begin();
     it != m_buttons.end();
     ++it) {
  // ...
}

Comment: Ok, you first solution got rid of my original problem but how do I assign data from a table to the caption of the buttons? I did have this, "Main->Button->Caption=Table2->FieldByName ("ItemName")->AsString;" but that only works for the one button called button. Also with that solution it says that variable button is declared but never used.
Comment: That's easy. I showed you how to get a pointer to the button control named "Button1" or "Button2" and store it in a variable named `button`. So use that variable to assign the caption of each button: `button->Caption = Table2->FieldByName("ItemName")->AsString`. Using my second example: `(*it)->Caption = ...`. I'm not sure what you mean by the "original problem." The only problem described in your question is the one about `Button` not being a member. I showed you that it doesn't need to be because you can access the buttons through other means.
Comment: Ah thank you very much! It's sorted I'll make sure to remember this :)


$\int 5\sqrt{x^3+2x}\, \textrm{d}x$

Question: I can not find any method to solve this, why do the typical methods fail?
I have tried subtituion, parts, strange subitution, etc.
How does one solve this integral?
Comment: This is a very [ugly integral](http://www.wolframalpha.com/input/?i=integral%20of%205(x%5E3%20%2B%202x)%5E(1%2F2)%20dx&t=crmtb01) involving the inverse hyperbolic sine, and elliptic integrals of the first and second kind.
Comment: @Java, the ugliness is only because Wolfram is rather crappy with the business of evaluating elliptic integrals.
Comment: I think it may not have a closed form, which means it cannot be presented by elementary functions. I think it has something to do with elliptic integrals.
Comment: @Java, some of us consider elliptic integrals to be quite beautiful.
Comment: @Gerry: I do too, actually!  Ugly was a bad choice of words here.
Comment: @JavaMan So how does one solve ellipitic integrals?
Comment: @GerryMyerson Know of a reference text on Elliptic integrals?
Comment: @GerryMyerson which one do you suggest?
Comment: I'm sorry, I'm not familiar with the available texts on elliptic integrals. It might not be a bad idea to post a new question to this site, asking for recommendations for learning about elliptic integrals. Be sure to include some information about how far you have already gone in mathematics, so that people who are familiar with the sources can suggest something at the right level for you.
Answer: This is an elliptic integral. The elliptic integrals represent solutions for the arc length of an elliptic arc and they cannot be expressed in terms of elementary functions.
I do not know if the above statement is proved, or closed forms in terms of elementary functions exist but not yet discovered. Anyways, among the people who tried to find a solution was Euler and Legendre.
The elliptic integrals can be expressed (reduced) to Legendre canonical forms (there are three of them).
Comment: What are those 3 Legendre canonical forms?
Comment: @Mao, the canonical forms are listed [here](http://dlmf.nist.gov/19.2.ii).

$\int 5\sqrt{x^3+2x}\, \textrm{d}x$


php fills $_POST data instead of php://input


EM algorithm for normal mixtures with constraints

Question: I have $G$ groups, each with $N_g$ data points $y_{ig}$, $g=1,\dots,G$ and $i = 1, \dots, N_g$. The group for each data point in observable.
I want to estimate the normal mixtures model with $K$ unobservable types, assuming that the type proportions $q_{kg}, k = 1,\dots, K$ are common across groups; i.e. for each $k$ I assume $$q_{k1} = q_{k2} = \dots = q_{kG} = q_k, \quad \text{where} \quad \sum_k q_k = 1. \tag1$$
In other words, I assume a data point $y_{ig}$ is drawn from a normal distribution $\Phi(\cdot; \mu_{kg}, \sigma_{kg})$ with probability $q_{kg} = q_k$. The problem is, how to estimate the parameters $\mu_{kg}, \sigma_{kg}$ and $q_{k}$.
By using expectation-maximization algorithm, I could easily estimate the model separately for each group, but the type proportions $q_{kg}$ would then not agree across different groups. Thus, I need to implement the constraint (1) in the estimation procedure. The question is, how to do it in the context of the EM algorithm?
I use R for the numerics, although as a first step a mathematical explanation suffices.
Edit: an example
Here is an example I have tried to solve: First, I simulate the data, and then I try to estimate it by using the EM algorithm, but something goes wrong, and I am not able to reproduce all the parameters from the simulated data set.
I assume I observe each individual's group $g \in \{1,2\}$ together with three iid data points $y_{it} \sim \Phi(\cdot; \mu_{kg}, \sigma_{kg}), t \in \{1,2,3\},$ for each individual. Here $k \in \{1,2,3\}$ is the unobservable latent type of the individual.
<code>require(data.table)

lognormpdf <- function(Y,mu=0,sigma=1)  {
  -0.5 * (  (Y-mu) / sigma )^2   - 0.5 * log(2.0*pi) - log(sigma)
}

logsumexp <- function(v) {
  vm = max(v)
  log(sum(exp(v-vm))) + vm
}

logrowSumexp <- function(v) {
  vm = max(v)
  log(rowSums(exp(v-vm))) + vm
}

model.fun <-function(nk) {

  model = list()
  # model for Y1,Y2,Y3|k
  model$A     = array(3*(1 + 3*runif(3*nk)),c(nk))
  model$S     = array(1,c(nk))
  model$pk    = c(0.1,0.5,0.4) # rdirichlet(1,rep(1,nk))
  model$nk    = nk
  return(model)
}

model.simulate <-function(model,N,sd.scale=1) {

  Y = array(0,sum(N))
  K  = array(0,sum(N))

  A   = model$A
  S   = model$S
  pk  = model$pk
  nk  = model$nk

  K = sample.int(nk,N,TRUE,pk)

  Y1  = A[K] + S[K] * rnorm(N) *sd.scale
  Y2  = A[K] + S[K] * rnorm(N) *sd.scale
  Y3  = A[K] + S[K] * rnorm(N) *sd.scale

  data.sim = data.table(y1=Y1,y2=Y2,y3=Y3)

  return(data.sim)
}

N = 100000
nk = 3
ng = 2

set.seed(123432)

model = model.fun(nk)
model2 = model.fun(nk)
data = model.simulate(model, N/2)
data2 = model.simulate(model2, N/2)

data$g = 1
data2$g = 2

data = rbind(data, data2)

Y1 = data$y1
Y2 = data$y2
Y3 = data$y3
G = data$g

tau = array(0,c(N,nk))
lpm = array(0,c(N,nk))
lik0 = 1
lik = 0
pk = array(c(1/3,1/3,1/3),c(3,1))

A = array(rnorm(9, 5, 1), c(nk,ng))
S = array(abs(rnorm(9, 1, 10)), c(nk,ng))
tol = 1e-24
iter = 0
# tauold = 1

Xg = array(0, c(N, ng))
Xg[,1] = as.numeric(G ==1)
Xg[,2] = as.numeric(G ==2)

while (abs(lik-lik0)>tol) {
  lik0 = lik
  lik = 0

  ###### E-step #########

  ltau = array(1,N)%*%t(log(pk))
  lnorm1 = lognormpdf(Y1, t(A[,G]), t(S[,G]))
  lnorm2 = lognormpdf(Y2, t(A[,G]), t(S[,G]))
  lnorm3 = lognormpdf(Y3, t(A[,G]), t(S[,G]))
  lall = ltau +lnorm1 + lnorm2 +lnorm3
  lik = logsumexp(lall)

  # Q1 = sum(tau*lpm)
  # Q2 = sum(tau*lall)

  tau = exp(lall - logrowSumexp(lall))
  lpm = lall

  # H1 = -sum(tauold*log(tauold))
  # H2 = -sum(tauold*log(tau))
  # tauold = tau

  pk = colMeans(tau)

  ##### M-step ########

  # Solve for means by group

  A = t(tau* (Y1 %*% t(rep(1,nk))+Y2 %*% t(rep(1,nk))+Y3 %*% t(rep(1,nk)))) %*% Xg/(3*t(tau) %*% Xg)

  # Solve for standard deviations by group

  S = sqrt((t(tau* ((Y1 %*%t(rep(1,3))-t(A[,G]))^2+(Y2 %*%t(rep(1,3))-t(A[,G]))^2+(Y3 %*%t(rep(1,3))-t(A[,G]))^2)) %*% Xg)/(3*t(tau) %*% Xg))

  # print(c(iter, abs(lik-lik0), lik, Q2-Q1, H2-H1))
  print(c(iter, abs(lik-lik0), lik))
  iter = iter+1
}
</code>
Comment: $q_k = 1/k$ since you fix it before hand it it has to sum up to $1$. Then you take the Q function, compute partial derivatives, equal with 0, derive the equations for the two steps. This is what you ask?
Comment: It would be nice to see the complete model as an equation, since "groups" is not an usual term for mixtures. From reading the question, it seems the likelihood is a product of $G$ Normal mixture likelihoods, all sharing the same weights. If so, EM can be easily adapted to this setting.
Comment: @Xi'an: no, thanks for your responses! I think I tried to do the problem exactly as you mentioned before asking the question, but wasn't able to get the solution to converge. I now spent some time understanding the theory better. My true set-up is actually slightly more complicated, and I believe that's producing the problems, but I think I might now understand the problem. I will try to check, if I can fix it, and if everything works in the end.
Comment: I don't see why $q_k = 1/k$; the only constraints are that they need to sum up to 1 and $\{q_{kg}\}_g$ has to be independent of $g$.
Answer: If the observed log-likelihood reads
$$\sum_{g=1}^G \sum_{i=1}^{N_g} \log \sum_{k=1}^K q_k \varphi(y_{ig};\mu_{gk},\sigma_{gk})$$
the completed log-likelihood reads
$$\sum_{g=1}^G \sum_{i=1}^{N_g} \sum_{k=1}^K z_{kig}\log \{q_k \varphi(y_{ig};\mu_{gk},\sigma_{gk})\}$$
where the $z_{kig}$'s are the component indicator variables. The E-function can thus be written as
\begin{align}Q(\theta_0,\theta)&=\mathbb E_{\theta_0}\left[\sum_{g=1}^G \sum_{i=1}^{N_g} \sum_{k=1}^K Z_{kig}\log \{q_k \varphi(y_{ig};\mu_{gk},\sigma_{gk})\} \big| \mathbf y\right]\\
&=\sum_{g=1}^G \sum_{i=1}^{N_g} \sum_{k=1}^K \mathbb E_{\theta_0}\left[Z_{kig}\big| \mathbf y\right]\log \{q_k \varphi(y_{ig};\mu_{gk},\sigma_{gk})\}\\
&= \sum_{k=1}^K \log \{q_k\}\sum_{g=1}^G \sum_{i=1}^{N_g}\mathbb P_{\theta_0}\left[Z_{kig}=1\big| \mathbf y\right]\\
&\quad+\sum_{g=1}^G \sum_{i=1}^{N_g} \sum_{k=1}^K \mathbb P_{\theta_0}\left[Z_{kig}=1\big| \mathbf y\right]\log \{\varphi(y_{ig};\mu_{gk},\sigma_{gk})\}\\
\end{align}
which means that the update of the $q_k$'s in the EM algorithm is based on the expected allocations across groups. Nothing changes for the other group-specific parameters.
Comment: I tried to do this, but I probably misunderstood something, since I cannot seem to get it working. I edited my question with a reproducible code of my implementation. It first simulates a panel data of 3 observations for each individual along with an observable group (1 or 2). I then try to estimate the group specific parameters, but for some reason it doesn't seem to be working. It's possible I have a mistake somewhere in the code, but I wasn't able to spot it.
Comment: I ran the code and the only parameter that is poorly estimated is the mean vector.
Comment: But the performances vary with the `seed` value.
Comment: The mean vector is my main parameter of interest, so I would need to get it right. Is there any hope to fix it? Is there a reason, why EM doesn't work here (assuming I don't have a mistake in the code?

I also noticed that the seed value affects the performance a lot, and for illustrative purposes, for this example I chose a seed, which estimates the parameters relatively fast. I think the problem is that if the true parameters are close to each other, the convergence is very slow and the estimates might be off even more.
Comment: It seems that the estimated parameters actually give higher likelihood than the true parameters used for the simulation. Is it possible that this is all just the bias of MLE? Increasing the sample size to 1,000,000 slightly improves the fit, but it's still quite far for the mean vector.


Find the ordered pair $(a,b)$ of real numbers for which $x^2+ax+b$ has a non-real root whose cube is $343$.

Question: Because $x^2 + ax + b$ has all real coefficients, we know the roots must be complex conjugates. So let $\lambda e^{i \theta}$ be a root, so we know that $(x - \lambda e^{i \theta})(x - \lambda e^{-i \theta}) = x^2 - \lambda x (e^{i \theta} + e^{-i\theta}) + \lambda^2$ is our polynomial.
We also know that $(\lambda e^{i \theta})^3 = 7^3 \implies \lambda e^{i \theta} = 7$, and since $|\lambda e^{i \theta}| = |\lambda| = 7,$ we know that $\lambda = 7$.
This means that $e^{i\theta} = 1$ and so $\theta = 0$. But clearly this doesn't give the right answer, since our polynomial isn't supposed to have real roots. Where is the flaw in my reasoning?
Comment: Note:  $x^3-343=(x-7)(x^2+7x+49)$
Comment: What does this have to do with fake proofs?
Comment: Only that $\lambda=7$ and that $e^{i\theta}$ is the third root of $1$. You have three roots, one real and two complex. And they told you specifically not to use the real one.
Comment: $(\lambda e^{i\theta})^3=7^3$ does not imply $\lambda e^{i\theta}=7$, similar to $(-1)^2=1^2$ does not imply $-1=1$
Comment: @lulu I put it in fake proofs because I think my logic works out fine?
Comment: @Andrei So what does it imply?
Comment: Hello, isn't your question supposed to be $x^3+ax+b$ instead of $x^2+ax+b$? @politeproofs
Comment: @Letsintegreat I think so, but I want to make sure before I edit it, or let them edit it
Comment: @SomeGuy No it's not.
Comment: Oh wait I see thanks
Comment: @politeproofs gotcha, I made an answer that answers what you ment
Answer: $(\lambda e^{i \theta})^3 = 7^3 \implies e^{3i \theta} = (\frac{7}{\lambda})^3e^{0}$
Using De Moivre's theorem
$\implies e^{i \theta} = (\frac{7}{\lambda}) e^{\frac{2k\pi}{3}i}, \text{k = 0,1,2}$
$\implies \lambda=7$
But as given in the question, roots are not real, so $k$ can not be $0$, therefore,
Roots are $7e^{\frac{2\pi}{3}i}$ and $7e^{\frac{4\pi}{3}i}$
$\implies 7(-\frac{1}{2} + \frac{\sqrt3}{2}i) \text{ and } 7(-\frac{1}{2} - \frac{\sqrt3}{2}i)$
Answer: We have $x^3 = 343$ because we need to find an $x$ that when cubed is $343$. Now rearrange to form $x^3 - 343=0$. Use the difference of cubes factorization which is $a^3-b^3=(a-b)(a^2+ab+b^2)$ by letting $a=x$ and $b=7$. So, we get $(x-7)(x^2+7x+49) = 0$. This simplifies down to $(x^2+7x+49) = 0$, which is a quadratic with roots that fit our condition that $x^3$ = $343$, because we derived this equation from that fact. Use the quadratic formula on $x^2+7x+49$ to get $\frac{-7}2 \pm {7i\sqrt{3} \over 2}$ as our nonreal roots that when cubed make $343$.


Confidence interval and margin of error

Question: Lets say I have confidence interval at 85% with 4% margin of error, and I get a value from my analysis equal to $x$.
Does this mean that if I were to perform the test 100 times, then at least 85 times we would expect to see a value for $x$ ranging from $.96x$ to $1.04x$?
Answer: No.
It is possible that just by chance your value of X is very high or low compared to the population value. If so, you'd expect few (or at least fewer than 85%) repetitions to have values in your confidence interval.
The correct interpretation is that if you repeated the experiment and calculations many times, you'd expect 85% of those confidence intervals to include the true population value, and for the other 15% to exclude that true population value. Unless you are doing simulations, you won't know the true population value, so will never know if a particular experiment is part of the 85% or part of the 15%.  (This interpretation is based on a bunch of standard assumptions about sampling, and the population distribution.)
Comment: I guess I don't fully understand. Let's say I have 5000 population, and I sample 1176 of them (necessary size for 95% confidence interval and 2.5% margin of error if I am not mistaken). Then what are we technically saying if we get an average value of x for something among those 1176?
Comment: Now you switched from 85% confidence interval to 95%, which is more typical. You can be 95% confident that the range you computed includes the true population value. I say "value" which is vague, because your question is vague. Are you computing a confidence interval for a mean, a median, a proportion, a percent survival....?
Comment: I don't understand what any of this means, would you be able to express things more mathematically? What does it mean to be "95% confident that the range I computed includes the true value?" What is the range, and 95% of what technically? (and let's say x = a mean) I don't understand what a confidence interval / "true population mean" implies going forward after doing an analysis. Does that mean if we performed infinitely many samples, then 95% of the recorded values would be between .95x and 1.05x, and 5% would be outside that range?
Comment: The "range" is what you included in the question: .96x to 1.04x

if you repeated the experiment and calculations many times, you'd expect 95% of those confidence intervals to include the true population mean, and for the other 5% to exclude that true population mean. Unless you are doing simulations, you won't know the true population mean, so will never know if a particular experiment is part of the 85% or part of the 15%.

You'll need to read elsewhere about the fundamental concept of analyzing a sample of data to make inferences about the population it was drawn from.

Confidence interval and margin of error


Android library project "java.lang.NoClassDefFoundError"

Question: Ok, first of all, I know, that many users asked this question many times in stackoverflow. I looked through all possible solutions, but still have problem.
The problem:
My IDE:
Eclipse Standard/SDK
Version: Kepler Release
Build id: 20130614-0229
I have an android library project, called mb-fw-android. In this project properties -> android -> Is Library - checked;
I have another project called mb-revise-android, an it needs to use mb-fw-android. I'v tried :
1) Go to mb-revise-android -> properties -> Android -> add android library -> start projec
Result is:
<code>02-26 12:04:19.960: E/dalvikvm(11678): Could not find class 'ru.tsi.maksbm.android.config.AndroidFilePropsIOProvider', referenced from method ru.tsi.maksbm.android.revise.model.Model.<init>
02-26 12:04:19.976: E/AndroidRuntime(11678): FATAL EXCEPTION: main
02-26 12:04:19.976: E/AndroidRuntime(11678): java.lang.NoClassDefFoundError: ru.tsi.maksbm.android.config.AndroidFilePropsIOProvider
02-26 12:04:19.976: E/AndroidRuntime(11678):    at ru.tsi.maksbm.android.revise.model.Model.<init>(Model.java:117)
02-26 12:04:19.976: E/AndroidRuntime(11678):    at ru.tsi.maksbm.android.revise.model.Model.createInstance(Model.java:64)
02-26 12:04:19.976: E/AndroidRuntime(11678):    at ru.tsi.maksbm.android.revise.ReviseStartActivity.onCreate(ReviseStartActivity.java:70)
...
</code>
2) add android library project as a classic depencency project. mb-revise-android -> properties -> buildPath -> project -> add, then order and export -> check mb-fw-android project
Still the same error
3) Uncheck mb-fw-android IsLibrary checkbox, and try (2). The same result
4) Uncheck mb-fw-android IsLibrary checkbox, execute it like .apk, go to /bin folder and find mb-fw-android.jar. Paste this .jar to mb-revise-android "libs" folder, and mark "order and export" Android Private Libraries as checked.
The same result.
Summary: i've tried to add android library project as .jar, as classic dependency project and as properties -> android -> add android library, mark order and export as checked, when possible, but still not working.
Please help me, if you know solution.
I use Android SDK Platform-tools 19.0.1 and Android SDK Build-tools 19.0.2
Thank you.
Wow, I just find soluiton.
We can see there http://developer.android.com/tools/sdk/eclipse-adt.html#notes one interestiong thing about ADT 20.0.0 and higher:
Build System
Added automatic merging of library project manifest files into the including project's manifest. Enable this feature with the manifestmerger.enabled property.
I've tried to add "manifestmerger.enabled=true" to my project.properties file and all is done. The thing is that builder doesn't merge my library project manifest with apk project manifest
Comment: Did you try adding it as an external library already?
Comment: Do you speak about adding like standart external .jar library? I've tried it, but still the same result.
Answer: try importing the library project to the work space.
Go to your project rightclick->properties->Android
scroll down. In library add you library project
Comment: From post
1) Go to mb-revise-android -> properties -> Android -> add android library -> start project

Not working
Comment: After adding this you cleaned your project and rebuilt it right?
Comment: There should not multiple copies of the same library file.. If you importing library above mentioned way then remove the jar file from   1)build path 2) lib folder if it exists over there. Cause if the multiple copies exists you will get this kind of error
Comment: I know, that if i will try to multiple define one class dalvik can throw "multiple class define error". But when i add jar - i remove android library dependency, and when a try to add android library project dependency i remove .jar


Do I still need gctools with Ruby 2.2 even though its garbage collection has been upgraded?

Question: I am upgrading my app to use Ruby 2.2, and was going to remove gctools since I think it specifically supports Ruby 2.1's garbage collection. Any reason I should keep it?
Comment: "Any reason I should keep it around?" That depends. Was there any reason you wanted it in the first place? The project's github page says it is "built on new apis and events offered in ruby 2.1", which to me means that it will likely work with any version of Ruby >2.1
Comment: It does seem to work, but since GC was revised heavily, didn't know if it became redundant.  Always looking to remove as much cruff when possible, and frankly this level of the system is a bit beyond my skills.  Thought maybe there was a gctools expert that could drop a thought or two and give so ideas on how it is still relevant.
Answer: So, after further review, it seems it is unnecessary according to the maintainer of gctools, Aman Gupta (tmm1):

"oobgc is unnecessary in Ruby 2.2, since it includes an incremental
  GC (RIncGC) and will not pause the world for a long
  time."

So, in case anyone else is seeing this error,
<code>listen loop error: unknown key: old_object (ArgumentError)
</code>
try pulling gctools out.
Comment: Nice. Deleting my answer then.
Comment: Thanks for the effort though Agis.  This question will be irrelevant soon anyway (hopefully).  There is a pull request to add it to the README.


Para que serve uma função especificamente em C?

Question: Para que serve uma função em C, qual sua utilidade?
Comment: Mais precisamente? Resumir o número de linhas de código! E garantir melhor eficiência e deixa o código mais limpo.
Comment: vlw,obrigado aí
Answer: Funções são elementos-chave da linguagem C. É o que permite que a linguagem seja modular.
Cada função é composta de linhas de enunciado, que realizam operações diversas ou declaram estruturas de dados em memória RAM.
Uma função tem:

um tipo de retorno
nenhum, um ou mais parâmetros
escopo próprio
Comment: obrigado pela informação


(Bayesian probability) Show that $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$

Question: The question, briefly
How does the calculation $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$ work?
Some background
I'm trying to work through the proof of the following theorem in Heinzelmann and Hartmann (2022):
Theorem 1. $P(H | E, \neg O ) > P(H|E) > P(H)$.
I don't quite follow the proof. I quote Heinzelmann and Hartmann's (2022) proof below, up to the step I find puzzling. Specifically, my problem is with the calculation $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$.

We consider the Bayesian network in Fig. 1 and use the machinery of Bayesian networks (..). With this, it is easy to see that $P(H) = op + \overline o q =: h$, where $\overline x := 1 - x$. Note that the above expression for $P(H)$ and condition (3) imply that $p < h <q$. **Next we use the product rule and calculate $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$.

Here is the Directed Acyclical Graph (DAG) relevant for the calculation.
And here's some notation and probabilities they use in the proof:

$o := P(O)$
$p := P(H|O)$
$q := P(H|\neg O)$
$c := P(c)$
$a := P(E|H, \neg C) = P(E|\neg H, \neg C)$
$P(E|H,C)=1$
$P(E|\neg H,C)= 0$
$P(E|H,\neg C)=a$
$P(E|\neg H, \neg C)=a$
Condition (3): $p < q$

Here is my understanding of how the proof goes. Firstly, they apply the Law of Total Probability to express the marginal probability P(H). So far, so good.
Next, they state they use the product rule it in calculating $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$. This is where I don't follow. My understanding is that the product rule (i.e., the chain rule) applies to joint probabilities, not conditional probabilities:
Chain rule. $P(A \cap B) = P(B|A)\cdot P(A)$
I didn't figure out where the product rule was used. So I tried (unsuccessfully) doing the calculation in detail myself.
My attempt at showing $P(H|E) = \frac{h (c +a \overline c)}{hc+a\overline c}$.
My unsuccessfull attempt follows.
Attempt. By definition of conditional probability, $$P(H|E) = \frac{P(E \cap H)}{P(E)}.$$ Then, by applying the law of total probability in the numerator we'd get $$\frac{P(E|H,C)\cdot P(H,C)+P(E| H\neg C)\cdot P(H,\neg C)}{P(E)}. $$ Now, we see that H and C are d-separated in the DAG, so $P(H, C) = P(H)\cdot P(C)$. We use this to get $$\frac{P(E|H,C)\cdot P(H)\cdot P(C)+P(E| H\neg C)\cdot P(H)\cdot P(\neg C)}{P(E)}. $$ Then we move the $P(H)$ outside the brackets like this: $$ \frac{(P(E|H,C)\cdot P(C)+P(E| H\neg C)\cdot P(\neg C))\cdot P(H)}{P(E)}. $$ Now we plug in the values, as specified above, which results in $$ \frac{(1 \cdot c+a\cdot \overline c)\cdot h}{P(E)} = \frac{h(c+a\overline c)}{P(E)}, $$  as desired. So, the numerator is done.
Next, I think I should expand $P(E)$ to $hc+a\overline c$. Namely, I should show $P(E) = P(H)\cdot P(C) + P(E| H, \neg C) \cdot P(\neg C)$. Perhaps the law of total probability (LOTP) was used at some point in the Heinzelmann and Hartmann calculation?  Applying the LOTP to $P(E)$ gets us: $$\frac{h(c+a \overline c)}{hc + ah \overline c + a \overline h \overline c},$$ which is not quite there yet, and I don't see how to proceed.  End of attempt.
What am I missing here? Could someone perhaps give me some pointers on how to proceed, or comments on where I've gone wrong? I'd very much appreciate it.
Answer: $\overline h= 1-h$ by definition, so: $$ah\overline c+a\overline h\overline c ~{= a(h+\overline h)\overline c\\=a\overline c}$$


Understanding proof that rationals of the form $\frac{p}{2^n}$ are dense in $\mathbb{R}$

Question:
Only the following definitions may be used in the proof:
1) A set $X$ is dense in $\mathbb{R}$ if the closure of $X = \mathbb{R}$.
2) The closure of $X$ is $X \cup X'$, where $X'$ is the set of all limiting points of $X$.
3) A limiting point $p \in \mathbb{R}$ is a point which a non-eventually constant sequence in $X$ converges to.

(Let $X$ be the set of rationals of the form $\frac{p}{2^n}$.)
My intuitive idea of density here is that between any two real numbers, there exists some rational number of the form $\frac{p}{2^n}$. But the given definition of density here is set equality, so I have no idea how this definition is equivalent or even remotely related to the intuitive notion of density I just mentioned.
So according to these definitions, I have to show that $X$ including all the convergence points of the non-eventually constant sequences that have terms of the form $\frac{p}{2^n}$, are all the members of $\mathbb{R}$. This seems difficult using only the given definitions but nothing else, but here is the proof that was provided:

For all $x \in \mathbb{R}$ and for all $\epsilon > 0$, it suffices to show that there exists a point in the open interval $(x - \epsilon, x + \epsilon)$ of the form $\frac{p}{2^n}$. (cont'd)

Why does this suffice for our proof?

(cont'd) There exists an $n > 0$ such that $\frac{1}{2^n} < \frac{\epsilon}{2}$. Let $p \in \mathbb{Z}$ be the last such that $\frac{p}{2^n} \leq x$. This means that $\frac{p + 1}{2^n} \geq x$. So either $\frac{p}{2^n}$ or $\frac{p + 1}{2^n}$ must be in the open interval $(x - \epsilon, x + \epsilon)$. Take either $x_n = \frac{p}{2^n}$ or $x_n = \frac{p + 1}{2^n}$. Then $x_n$ converges to $x$, so every point is a limit point. Thus the closure of $X = \mathbb{R}$.

I have no idea what is going on here. How do we know there exists an $n > 0$ such that $\frac{1}{2^n} < \frac{\epsilon}{2}$? How do we know if $\frac{p}{2^n} \leq x$, then $\frac{p + 1}{2^n} \geq x$? Isn't it possible that the rational also depends on $n$, not just $p$? Why are we only worried about $p$ here? How do we know either $\frac{p}{2^n}$ or $\frac{p + 1}{2^n}$ must be in the open interval $(x - \epsilon, x + \epsilon)$? I don't see any conditions restricting both from being less than $x - 2\epsilon$ and greater than $x + 2\epsilon$, so that neither is in $(x - \epsilon, x + \epsilon)$. Then it says we take a sequence to be either of these points, and they converge to $x$ somehow, which I don't see. And then finally it says that every point of $X$ is a limit point, even though we haven't proven that all sequences in $X$ converge to a point in $X$, according to the given definition of limit point.
Answer: The closure of $X$ is $X \cup X'$, the union with the limit points as you mention. So fix some $x \in \mathbb {R}$. We want to show it is a limit point of rationals of the form $p/2^r$.
To do this, it suffices to show that for any $\epsilon > 0$, we can find a rational of the form $p/2^r$ within $\epsilon$ of $x$. This is because we can take $\epsilon \to 0$ to get a sequence of rationals converging to $x$, and thus $x$ is a limit point.
There exists an $n$ such that $2^{-n} < \epsilon$ because $2^{-n} \to 0$. Alternatively, and more basically, there is no largest positive integer and for any real number $y$, there is a positive integer $m$ such that $m > y$. This is sometimes called the Archimedian property, and is an axiom of the real numbers (which is sometimes encoded in ordering axioms of the real numbers).
The integers have the well-ordering principle, which says that any set of integers bounded below has a least element (or equivalently, that any set of integers bounded above has a greatest element). This is one of the axioms of the integers (also sometimes encoded in ordering axioms, for what it's worth). So once we've fixed an $n$ such that $2^{-n} < \epsilon$, the integers $p$ such that $p/2^n < x$ is bounded above, and thus has a largest element. Denoting this largest element by $p$, we see that $p+1$ is not in this set, and thus $(p+1)/2^n > x$.
Then the distance between $p/2^n$ and $(p+1)/2^n$ is less than $\epsilon$ and $x$ is in the middle, so that both are at most $\epsilon$ from $x$ (I notice here that you have used $\epsilon/2$ in some places, which I did not. But this changes almost nothing).
Thus for any $\epsilon > 0$, there exists a rational of the form $p/2^n$ within $\epsilon$ of $x$. A sequence of these rationals as $\epsilon \to 0$ gives a convergent sequence of rationals to $x$. As this can be done for every $x \in \mathbb{R}$, we see that $\mathbb{R}$ is contained in the closure of the rationals of the form $p/2^n$. Of course, the real numbers are complete (yet another axiom of the real numbers), so no sequence of real numbers will converge to a nonreal number. Thus $\mathbb{R}$ is the closure of the rationals of the form $p/2^n$.
Comment: @user130018 We know that because the difference is exactly $1/2^n$, which is less than $\epsilon$. There is no reason why either $p/2^n$ or $(p+1)/2^n$ would be less than $\epsilon$ on their own.
Comment: How do you know that the distance between $p/2^n$ and $(p+1)/2^n$ is less than $\epsilon$? We only know that $1/2^n < \epsilon$, so it would seem that $p/2^n > \epsilon$ and $(p+1)/2^n > \epsilon$. Not sure how to deduce that both $p/2^n$ and $(p+1)/2^n$ are $< \epsilon$
Comment: Oh, I just noticed I missed such simple arithmetic. Thank you
Answer: You ask why this is true:

For all $x \in \mathbb{R}$ and for all $\epsilon > 0$, it suffices to show that there exists a point in the open interval $(x - \epsilon, x + \epsilon)$ of the form $\frac{p}{2^n}$.

Suppose that we've shown this; then for each $n\in\Bbb Z^+$ there is an $x_n\in\left(x-\frac1n,x+\frac1n\right)\cap X$. If $\epsilon>0$, there is an $m\in\Bbb Z^+$ such that $\frac1m\le\epsilon$, and it's clear that $|x-x_n|<\frac1m\le\epsilon$ whenever $n\ge m$. Thus, $\langle x_n:n\in\Bbb Z^+\rangle$ converges to $x$. There are now two possibilities.

Suppose that $\langle x_n:n\in\Bbb Z^+\rangle$ is eventually constant. Then there is an $m\in\Bbb Z^+$ such that $x_n=x_m$ for all $n\ge m$. Show that this is impossible unless $x_m=x$, in which case $x\in X$.
Otherwise, $\langle x_n:n\in\Bbb Z^+\rangle$ is not eventually constant, and $x\in X'$.

In either case $x$ is in the closure of $X$.
Now let's look at the rest of the argument:

There exists an $n > 0$ such that $\frac{1}{2^n} < \frac{\epsilon}{2}$. Let $p \in \mathbb{Z}$ be the last such that $\frac{p}{2^n} \leq x$. This means that $\frac{p + 1}{2^n} \geq x$. So either $\frac{p}{2^n}$ or $\frac{p + 1}{2^n}$ must be in the open interval $(x - \epsilon, x + \epsilon)$.

Let me stop here for now. We're trying to find a member of $X$ in $(x-\epsilon,x+\epsilon)$. Without worrying for a moment about what $n$ is, consider the possible values of $\frac{p}{2^n}$: they're evenly spaced in $\Bbb R$ at intervals of $\frac1{2^n}$. If $\frac1{2^n}$ is too big, they could miss the interval $(x-\epsilon,x+\epsilon)$ entirely. This part of the argument is a way to show how to choose $\frac1{2^n}$ small enough so that this doesn't happen. Specifically, we choose $n$ big enough so that $\frac1{2^n}<\frac{\epsilon}2$. This is actually overkill: his argument works just fine if we take $n$ big enough so that $\frac1{2^n}<\epsilon$, so that's what I'm going to do. (In fact, taking $\frac1{2^n}<2\epsilon$ is good enough, but it requires a little more work.)
Let $X_n=\left\{\frac{p}{2^n}:p\in\Bbb Z\right\}$, the set of multiples of $\frac1{2^n}$. The idea is that $x$ splits $X_n$ into a left part $X_n^L$ and a right part $X_n^R$: $X_n^L=\{y\in X_n:y\le x\}$, and $X_n^R=\{y\in X_n:y>x\}$. The left part has a biggest element, $\frac{p}{2^n}$. Because this is the biggest element of the left part, the next larger multiple of $\frac1{2^n}$, which is $\frac{p+1}{2^n}$ must be in the right part:
$$\frac{p}{2^n}\le x<\frac{p+1}{2^n}\;.$$
Then $$0<\frac{p+1}{2^n}-x<\frac{p+1}{2^n}-\frac{p}{2^n}=\frac1{2^n}<\epsilon\;,$$
so $$x<\frac{p+1}{2^n}<x+\epsilon\;,$$
and $\frac{p+1}{2^n}\in(x-\epsilon,x+\epsilon)$, as desired. For that matter,
$$0\le x-\frac{p}{2^n}<\frac{p+1}{2^n}-\frac{p}{2^n}=\frac1{2^n}<\epsilon\;,$$
so $\frac{p}{2^n}\in[x,x+\epsilon)\subseteq(x-\epsilon,x+\epsilon)$ as well: we took $\frac1{2^n}$ small enough to get both of these points of $X_n$ inside $(x-\epsilon,x+\epsilon)$. You might like to try showing that if $\frac1{2^n}<2\epsilon$, we can still show that at least one of the two points is in the interval $(x-\epsilon,x+\epsilon)$.
(The author could have been more rigorous about the assertion that $X_n^L$ has a biggest element, but he appears to be willing to use basic consequences of the Archimedean property of $\Bbb R$ without going through the details.)
Now for his conclusion:

Take either $x_n = \frac{p}{2^n}$ or $x_n = \frac{p + 1}{2^n}$. Then $x_n$ converges to $x$, so every point is a limit point. Thus the closure of $X = \mathbb{R}$.

This is very poorly stated; I would simply ignore it and use the argument that I gave to explain 'it suffices'.
Answer: For a direct proof that the rationals of the form $\frac{p}{2^k}$ are dense in $\mathbb R$, here is a simpler proof.
I will denote the integer part of $x$ by $\lfloor x \rfloor$. If $x \in \mathbb{R}$ and not in $X$ the sequence
$$
a_{n} =\frac{\lfloor 2^nx \rfloor }{2^n}
$$
satisfies
$$
\frac{ 2^nx -1 }{2^n} < a_n \leq \frac{2^nx  }{2^n}
$$
and hence converges to $x$. Since $a_n \in X$ and $x \notin X$ it follows that $x \in X'$.


openvpn dns server not resolving forwarded DNS lookups after connecting, only local

Question: I am using OpenVPN server (on an Ubuntu server 14.04) with Mac OS X Yosemite client (using TunnelBlick v 3.50 build 4265).
It works well except for the DNS server from the VPN server which although it is being set on the client, it is only resolving the DNS queries for the local intranet and not being forwarded to the resolver for internet lookups. The same DNS server (bind) works fine in the local intranet and on the OpenVPN server.
Here is one  dig output once the vpn is connected.
<code>$ dig -x www.google.com

; <<>> DiG 9.8.3-P1 <<>> -x www.google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 12157
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;com.google.www.in-addr.arpa.   IN  PTR

;; Query time: 1884 msec
;; SERVER: 10.0.0.9#53(10.0.0.9)
;; WHEN: Fri May  8 10:32:22 2015
;; MSG SIZE  rcvd: 45
</code>
Answer: Another solution, add recursion to 10.1.0.0/24 net, by adding this line in /etc/bind/named.conf.options, as follow:
<code>allow-recursion { 10.1.0.0/24; };
</code>
Answer: Solutions (from comments)
add allow-recursion in the bind (which was changed from the default permissive settings around bind 9.4)
Possible solution:

Try using public DNS server like google famous 126.96.36.199/184.108.40.206.
Push route of 10.0.0.9 IP to VPN client by adding this line in your server.conf:

push "route 10.0.0.9 255.255.255.255"

Another alternative: add/allow dns recursion for VPN IP on bind config.
I hope it worked.
Comment: I am already using google forwarders (both 8.8 and 4.4) and pushing the following route:
push "route 10.0.0.0 255.255.255.0"
Comment: So the problem could be your DNS/Bind/Named setting. From your dig result it can be seen that your DNS server (10.0.0.9) didn't resolve google.com domain correctly.
Comment: That's what I'd like to know. This same server resolves google.com without any trouble from the 10.0.0.x network but not on the 10.1.0.x VPN network.
Comment: Have you added allow recursion from 10.1.0.x net?
Comment: Will try tonight and confirm ...though I think this must be it ...didn't know bind changed something (and if I'm not wrong this used to work a long time ago)...can you make this a part of answer


Programação Java para cartões

Question: Olá,
Eu tenho um leitor de cartões magnéticos KDE KT-2280 e esse leitor é programável.
Só que eu não sei como programar cartões, porque nunca mexi em programação para cartões.
Existe alguma biblioteca de Java para programar cartões?
Podem-me ajudar, por favor?
Obrigado
Answer: Chama se Javacard
Oracle Javacard
Segundo a wikipedia:

Java Card é uma tecnologia que permite que pequenos aplicativos
  (applets) baseados em plataforma Java sejam executados com segurança
  em smart cards e dispositivos similares com limitações de
  processamento e armazenamento, como o Java Ring.
O Java Card é amplamente utilizado em cartões SIM (usados em celulares
  GSM) e em cartões para caixas eletrônicos. O primeiro Java Card foi
  apresentado em 1997 por várias empresas, incluindo uma divisão da
  extinta Schlumberger Limited (divididas em Axalto e Gemplus, que
  terminaram por se fundir).
Os produtos Java Card são baseados nas especificações da Plataforma
  Java Card desenvolvidas pela Sun Microsystems, e suas principais
  características são portabilidade e segurança.

Link para o Artigo aqui
Segue um Hello World! em Javacard criado pelo Igor Medeiros.
<code> /*
 * Package:  br.com.igormedeiros
 * Filename: HelloWorldJC.java
 * Class:    HelloWorldJC
 * Date:     [[8 de maio]] de [[2005]] 14:55:52
 */
 package br.com.igormedeiros;
 import javacard.framework.*;

 /**
 * Class HelloWorldJC
 */
 public class HelloWorldJC extends javacard.framework.Applet {

 // CLA Byte
 final static byte HELLO_CLA = (byte) 0xB0;

 // Verify PIN
 final static byte INS_HELLO = (byte) 0x20;

 public static void install(byte[] bArray, short bOffset, byte bLength) {
  (new HelloWorldJC()).register(
   bArray,
   (short) (bOffset + 1),
   bArray[bOffset]);
 }

 // processa o comando APDU
 public void process(APDU apdu) {
  byte[] buffer = apdu.getBuffer();
  if ((buffer[ISO7816.OFFSET_CLA] == 0)
   && (buffer[ISO7816.OFFSET_INS] == (byte) (0xA4)))
   return;

  // Validate the CLA byte
  if (buffer[ISO7816.OFFSET_CLA] != HELLO_CLA)
   ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);

  // Select the apropriate instruction (Byte INS)
  switch (buffer[ISO7816.OFFSET_INS]) {
   case INS_HELLO :
    getHello(apdu);
    return;
   default :
    ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
  }
 }
 /**
  * @param apdu
  * @author Igor Medeiros
  * Get user id attribute
  */
 private void getHello(APDU apdu) {
  // cadeia de bytes com a mensagem: "hello world Java Card"
  byte[] hello =   {
    'h',
    'e',
    'l',
    'l',
    'o',
    ' ',
    'w',
    'o',
    'r',
    'l',
    'd',
    ' ',
    'J',
    'a',
    'v',
    'a',
    ' ',
    'C',
    'a',
    'r',
    'd' };

  // informa ao JCRE que será enviado uma resposta
  short le = apdu.setOutgoing();
  short totalBytes = (short) hello.length;

  // informa ao JCRE o tamanho da mensagem em bytes
  apdu.setOutgoingLength(totalBytes);

  // envia a mensgem para o host
  apdu.sendBytesLong(hello, (short) 0, (short) hello.length);

  }
 }
</code>
Comment: ué.. respondi a pergunta do cara e recebo negativo? o que você que deu negativo esperava? rs

Programação Java para cartões


$X \sim U(0,\theta)$. Find the distribution of $X_1\mid \max (X_i)$

Question: The problem is to find the distribution of $X_1\mid M$ where $M$ is the maximum of the i.i.d. random variables $X \sim U(0,\theta)$. I have a complete solution but am having trouble justifying one step. We use Bayes' Theorem for CDF's to get started:
$$ P(X_1 < x_1 \mid M < m) = \frac{P(M < m \mid X_1 < x_1) P(X_1 < x_1)}{P(M < m)} $$
The cdf's for $M$ and $X_1$ are $(m/\theta)^n$, by independence, and $x_1/\theta$. The cdf for $M\mid X_1$ is $(m/\theta)^{n-1} {\bf 1} [x_1 \leq m]$. The justification I have is that if the observed value $x_1$ is greater than $m$, then $m$ cannot be the maximum. So, I threw the indicator on the cdf in order to justify that $M\mid X_1$ is just the distribution of the maximum excluding $X_1$. So,
$$ \frac{P(M < m \mid X_1 < x_1) P(X_1 < x_1)}{P(M < m)} = \frac{(x_1/\theta) (m/\theta)^{n-1}}{(m/\theta)^n} = \frac{x_1}{m} $$
It follows that $X_1\mid M \sim U(0,m)$.
Is my justification for the distribution of $M\mid X_1$ correct? I believe my final answer is intuitive.
Comment: Then I think it is wrong. There must be a **positive probability** for $X_1$ to take value $m$ under the condition: $P(X_1=m\mid M=m)>0$. This because there is a positive probability that $X_1$ will be the maximum.
Comment: "It follows that $X_1|M\sim U(0,m)$" What is $m$ in this statement?
Comment: Are you sure the problem is to compute $P(X_1 \leq a \mid \max X_i \leq b)$? It seems like it should be $P(X_1 \leq a \mid \max X_i=b)$.
Comment: $m$ was the observed value of $M$. Perhaps I should write this as $U(0,M)$ or $X_1 | M = m \sim U(0,m)$.
Comment: That is fair. Since we know that one of $X_1, \dots, X_n$ takes on the value $m$, it should be that there is a positive probability that $X_1 = m$ given that $M =m$. Perhaps it is similar to a multinomial distribution. Nonetheless, I still don't know how to handle $P(M < m | X_1 < x_1)$.
Comment: @Ian that might be the case. The problem was written without specifying. I chose to interpret it as $M < m$ since we were dealing with a continuous distribution, namely $X$ is uniform.

Does $P(M=m)$ make sense? Or is $P(M=m) = 0$. I thought that $M$ would have a continuous distribution.
Comment: $M$ does have a continuous distribution, but you can still condition on null sets. (Of course if you do then Bayes' rule doesn't do you any good.)
Comment: I'm still not seeing how this can help. Perhaps I could condition on the event $M \in (m, m + dm)$. Then given that $x_1 < m$, we would have to deal with the probability that one of $X_2, X_2, \dots, X_n$ are in $(m, m + dm)$? Finally, we could take the limit as $dm$ goes to 0. That might be doable.
Comment: Isn't the conditional CDF $X|Y=y$ defined as $$F_{X|Y}(x|y)=\int^x_{-\infty} \frac{f_{X,Y}(u,y)}{f_Y(y)}\,du$$ Can you find the joint PDF of $X_1$ and $M$ and the PDF of $M$?
Comment: The accepted answer is not quite correct. The conditional distribution is mixed (partially discrete and partially absolutely continuous). Related: https://math.stackexchange.com/a/1007778/321264.
Answer: Suppose you're asking for $P(X_1 \leq a \mid \max X_i=b)$. Consider $n=2$. Then the relevant set is the intersection between the line segments between $(0,b)$ to $(b,b)$ and $(b,0)$ to $(b,b)$, with the half-plane $X_1 \leq a$. Assuming of course that $0<a<b$, then you're looking at the ratio of the lengths of the segment $(0,b)$ to $(a,b)$ and the whole pair of segments. So that's $\frac{a}{2b}$. The results for $a \leq 0$ and $a \geq b$ are clearly $0$ and $1$ respectively.
For general $n$, what happens? Well, for $0<a<b$ again, you're missing one "face" which is the face where $X_1$ is actually the biggest one; this face has probability $1/n$. Other than that, the fraction of the "area" on each face where $X_1 \leq a$ is $a/b$. So you're looking at a general result of $\frac{a}{b} \left ( 1 - \frac{1}{n} \right )$. Note that this can be interpreted as $P(X_1 \leq a \mid X_1 \leq b) P(X_1<\max X_i)$.
Of course this approach is geometric, but you can use the general formulae for conditional CDFs/PDFs to do it analytically.
Answer: We want the CDF of $X_1|M=m$. One knows that:
\begin{align}
F_{X_1|M}(x|m)=\int^x_{-\infty} \frac{f_{X_1,M}(u,m)}{f_M(m)}\,du
\end{align}
It is easy to find
\begin{align}
F_{X_1,M}(x,m)=P(X_1<x, M<m)=
\begin{cases}
\left(\frac{m}{\theta}\right)^n & \text{ if } & 0\leq m \leq x \leq \theta\\
\frac{x}{\theta}\left(\frac{m}{\theta}\right)^{n-1} & \text{ if } & 0\leq x < m \leq \theta\\
\end{cases}
\end{align}
Note that $F_{X_1,M}$ is not differentiable everywhere. But differentiating where it is differentiable yields:
\begin{align}
f_{X_1,M}(x,m)=\frac{(n-1)m^{n-2}}{\theta^n}\mathbf{1}_{0\leq x<m\leq\theta}
\end{align}
We also know that $f_M(m)=\frac{nm^{n-1}}{\theta^n}$, just differentiate the CDF you already have. So we get:
\begin{align}
F_{X_1|M}(x|m) =
\begin{cases}
0 & \text{ if } &  x<0\\
 \frac{x(n-1)}{mn} & \text{ if } & 0\leq x<m\\
1 & \text{ if } &  m\leq x\\
\end{cases}
\end{align}
Comment: Indeed. Thank you for spelling that out for me!
Comment: Hi Shashi, thank you for your response. This method makes sense. I should have considered to use the definition earlier! (facepalm)

One question. For $0 \leq m \leq x \leq \theta$, did you compute $P(X_1 < x , M < m)$ as $P(X_1 < x \mid M < m) P(M < m)$ where $P(M < m) = (m/\theta)^n$ and $P(X_1 < x \mid M < m) = 1$ since $m \leq x$? Or is there a more intuitive method to compute this using the joint?
Comment: @JohnPortin there is no need to all that, \begin{align} P(X_10$. So the starting definition of $F_{X_1\mid M}$ is not valid.
Comment: @StubbornAtom wow, never thought about this! Thanks for pointing that out. At this moment I don't have time to correct it and I don't even know how so I'll delete it. If it turns out to need a small fix you can edit it!


How to use ctrl + click to show super or implementation methods in Intellij Idea?

Question: In Intellij Idea, I should use CTRL + ALT + B to turn into implementation method, use CTRL + U to turn into super method, it's not convenient and not easy to remember so many shortcut keys, so how to use CTRL + click to forward that like in Eclipse??
Answer: You can change your key map in intellij-idea exactly like ECLIPSE by following steps.
Move to File -> Settings -> Keymap and change Keymaps settings to your keymap,for Example : ECLIPSE,so that you can use the short cut keys like in ECLIPSE.
Comment: You can set your shortcut here [John](https://stackoverflow.com/users/8275347/john-chou) This CTRL+ click works in this keymap.
Comment: If so, the Ctrl + click default to facade method will be overrided.


Multi Threaded Application with (Spring) ThreadPoolTaskExecutor

Question: I need to implement Multi Threaded background process.  My project is spring , hibernate based I tried with below code which uses org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor to perform the
below background operation in multi threaded manner.
I need to know

If I use Spring ThreadPoolTaskExecutor is this multi threaded?
Will there be overlapping issues like multiple threads acqure the same user object ?
If "YES" Should I need to use synchronize the method upgradeUserInBackground() to avoid
such a situations ? Alternative solution ?
<code>public class UserUpdateProcessor implements InitializingBean {
private ThreadPoolTaskExecutor executor;
public void afterPropertiesSet() throws Exception {
    executor.execute(new UserBackgorundRunner ());
}
}

private class UserBackgorundRunner extends Thread {

public UserBackgorundRunner() {
    this.setDaemon(true);
    this.setPriority(MIN_PRIORITY);
}
</code>
public void run() {
<code>    List<User> users = getUserList();;

    for (User user : users) {
        try {
            upgradeUserInBackground(user);
        } catch (Exception e) {
            LOGGER.warn("Fail to upgrade user");
        }
    }

}
</code>
Answer:
Yes, it is multi threaded, all submitted tasks will be executed at the same time. Spring takes care of thread starvation as well so there will be parallel execution always until you try some hacks.
Yes, there may be overlapping issues like multiple threads acqure the same user object.
For your scenario i would advice you to use Spring Batch FMK and configure/hack it for not  saving any data in database. It will give you concurrency, speed, reliability and solution of overlapping objects using tasklet "scope".

If you use synchronization in threads, it is considered to be a bad design, rethink your problem.


Ubuntu Firewall Disable Through PHP

Question: Is there a way I can execute a command line in PHP. I want to have a hidden file on my servers so If I lose access to them I can disable the firewall through the website by loading a secure .php file through my browser. The command I use to disable the fire wall is
<code>sudo ufw disable
</code>
I'm running Ubuntu Server with apache2. I'm not sure how to execute that through PHP.
Thank you
Comment: no good will come from this - remotely executing system scripts thru sudo is dangerous. u should find another way to solve this.
Answer: What you need to do is setup SSH on your server. Log into the server, and disable the server that way.

Ubuntu Firewall Disable Through PHP


How to adjust bar's widht of 3D bar graph using matplot lib

Question: How can I adjust  width of a bar graph's bars. An image has been attached with this post, which shows the actual condition.  As we can see the labels, showing years, from  2011 to 2015.
I am finding a solution to reduce down  the width of respective bars along the yaxis. Many random solutions were tried by me which is available here and there on line but nothing has worked.
The given image is actually a 3D graph but due to clear view only 2D picture  has been shown.
Please help:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

data = np.array([[0,6,3,0,0,0,0,0,0,0,0,2,2,3,0,2,2,3,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,2,2,0,0,0,0,0,0,0,2],
                 [3,3,5,3,3,0,0,0,0,0,0,0,0,0,3,4,0,0,4,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,0,2,0,0],
                 [0,0,7,5,0,10,5,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,2,4,3,3,2,0,0,0,0,0,3,2,3,2,3,0,0,0,0,0,0,0,0,3,0],
                 [0,0,0,4,0,2,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0],
                 [5,0,2,2,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0], ])

#data = data.transpose()

row_names = ['Ch','Bi','Ba','Ho','Ja','Pu','N','Ga','Ke','Ma','Me','Ti','Ka','Th','Di','Wa','Ha','My','Tu','Ma','Bi','Ut Ka','Ra','Da','Ch','Ko','B','Bid','Gu','D&N','Ra','Pu','San','Dhu','Jal','Gon','Gand','Alw','Jal','SAS','Gur','Pat','Hos','Lu','Pan','Kur','Jan']

column_names = ["2011","2012","2013","2014","2015"]

fig = plt.figure()
ax = Axes3D(fig)

xpos = np.arange(0,lx,1)
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.5, ypos+0.5)

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.ones(lx*ly)*1e-10

dx = 1. * np.ones_like(zpos)
dy = dx.copy()
dz = data.flatten()
print dz
cs = ['r', 'g', 'b', 'y', 'c'] * ly

values = np.linspace(0.2, 1., xpos.ravel().shape[0])
colors = cm.rainbow(values)

ticksx = np.arange(1, len(row_names)+1,1)
plt.xticks(ticksx, row_names)

z_data = np.random.rand(0,10)

ticksy = np.arange(0.5, len(column_names),1)
plt.yticks(ticksy, column_names)

#ax.tick_params(width=2, colors='r')

ax.w_xaxis.set_ticklabels(row_names,rotation=90,size=12)

ax.w_yaxis.set_ticklabels(column_names,rotation=40,size=12)

ax.bar3d(xpos,ypos,zpos, dx, dy, dz,   alpha=0.7, zsort='max',color=colors)
plt.ion()

plt.show()
raw_input(" " )

update:
Reducing the "dx" value by 1 to 0.5, reduces the bar width but now its showing the huge padding between the bars which i want to  remove completely.

Last Update:
I have attached one more Image. I am expecting this kind of 3D bar graph with reduced bar width (its done), and minimised gap between bars.
Comment: Question is identical to http://stackoverflow.com/questions/43954511/how-to-format-3d-bar-size-width-and-length-and-z-axis-value Please delete one of them.
Comment: [This question](http://stackoverflow.com/questions/43869751/change-bar-color-in-a-3d-bar-plot-in-matplotlib-based-on-value) seems to be related in that it uses the same data and already has the problem of bar widths solved.
Comment: deleted the previous one thanks
Answer: The call signature or bar3d is
ax.bar3d(xpos,ypos,zpos, dx, dy, dz,...)

where dx and dy are are the width and depth of bars. Changing the width is therefore done by supplying a different array or number to dx.  E.g. to have a 0.5 wide bar, use
ax.bar3d(..., dx=0.5, ...)

If instead you want to change the width of the axis, you may look at this question. Implementing this solution here,
ax.bar3d(xpos,ypos,zpos, 1, 1, dz,   alpha=0.7, zsort='max',color=colors)
ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([1,0.4, 1, 1]))

would give:
Comment: Hey,, its a  great solution, worked when,  I change the value by 0.5. But one problem still exist now its showing the reduced bar width but huge padding between two bar is there any method to reduced this padding size i tried with set_padding but its not working. I have updated one more image. thanks
Comment: There is no padding! If `dx` is `1` The bar is one year wide, if `dx` is less than `1`, the bar is a fraction of a year wide. Can you explain exactly what the desired plot should look like?
Comment: As you can see in second image a hug gab between bars, i want to remove this gap,  bar should be connected to each other without gap
Comment: Yes to remove this gap, use the original case, where `dx  = 1`.
Comment: But using original case  bar size will increase again. I have posted one more, probably last image (created with power point cut and past) which shows what I am expecting from matplotlib.
Comment: Can you explain this  particular line in your answer Little bit more "ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([1,0.4, 1, 1]))"
Comment: There is a good explanation in [this answer](http://stackoverflow.com/a/30419243/4124317).


How to reference a variable in regex URL?

Question: router.get("/(A|B)/account/", async (req, res) => {});

How to do I reference the (A|B) inside of the async function?
Comment: You should be using parameters. http://expressjs.com/en/guide/routing.html
Comment: But with parameters it will match anything, not just A or B
Answer: I guess your route responsibility is getting account information of only A or B. So  let's change your router path to /account/:name(A|B), then your express router will look like this:
router.get("/account/:name(A|B)", async (req, res) => {
    const name = req.params; // A or B
});

Only 2 kinds of requests are handled by this router:
GET /account/A
or
GET /account/B


Comparing the same song sung in different key

Question: I am not sure if my question makes sense to the most learned musicians, I still would like to get one simple thing clarified, and I must admit that I did search about this everywhere but there was no clear answer, or better, I did not understand.
Let us take Queen's Bohemian Rhapsody. It is based on A# sharp major (or B flat major?) key. So if a new singer who cannot sing as the original version tries to sound similar by singing at a lower key. Can he sing the same song in let us say key D sharp major?
The second example is from "The Lonely Shepherd" by Gheorghe Zamfir which is in D minor scale. Can it be played in G minor? How will it sound?
Answer: Transposing is the term for changing the key of a song as your describe.
Theoretically the music will be the same. The same in terms of the relative relationships of rhythm and the intervals that make chords and the melodic line.
But as a matter of orchestration, of timbre, range does matter. It matters a lot. As chords are played in lower and lower ranges they become "muddier." Acoustic guitar in the open string range is fairly deep and resonant, but put a capo on even the fifth fret to raise the pitch a fourth and it can start to sound thinner and bright, sort of like a mandolin or autoharp. Each instrument has certain "colors" associated with different ranges and those are often important choice in a song arrangement/recording.
Imagine a pop song by a singer with a high range, like Mariah Carey, sung in a lower octave by a bass. It probably would not have the same effect as sung in a high range. It could even sound like a comic parody!
Transposing down a fifth - what you described going from Bb to Eb or Dm to Gm - is roughly the difference between the four basic voice types, so it's like dropping a tenor to a bass. That probably isn't too big a change for the vocal part. Chord voicings in the accompaniment could be adjusted to keep things in roughly the same range for guitar or keyboard. (Example, a bass of G3 up to D4 could be transposed down a fifth by playing C4 down to G3, the letters transpose a fifth down, but the octaves are juggled to stay within the same general range to maintain timbral color.)
You might consider if dropping a third would be enough to make it comfortable to sing. That would be a change sort of in between vocal ranges, like tenor to baritone which is between tenor and bass.
Comment: Another example: think about the impact that the line "And the rocket's red glare" has in "The Star-Spangled Banner" because of its high register. If you transposed the song down, it would still be a jump from the previous line, but not be as spectacular if people didn't have to stretch to sing it.
Answer: It's called transposing. There's a system called the Nashville System where they write down key information irrespective of key, so when new singers with different ranges come along, it's easy for the band to transpose for them. It is commonly adjusted for the range of the singer, because that varies a lot between singers, and singers' voices tend to drop in pitch over time.
Most of the time? It's fine. We all know songs like "Bohemian Rhapsody" in one key because we all know that same recording, but as long as the intervals are correct, it should be identifiable and work for everyone.
(I read once that the Dave Brubeck Quartet usually played "Take Five" in Eb minor, but once played with a guest and changed the key to accommodate, and all decided it sounded wrong, but I haven't heard it.)
Answer: Any song can be (and sometimes is) played in any key. I've played many well-known songs in many different keys, with many different bands/groups of players. Really, it matters not.
With good players, any song which is in an 'original key' - whatever that may be recognised as - could get played in any of the 12 available keys. In fact, for a laugh, we often played song xyz in key whatever. Sometimes it worked really well - better than the original - others, it just worked. In fact, one ought to be capable of playing anything in any key, to help the vocalist.
In reality, and my opinion, any key will work for any song, with good players. There are certain songs which are guitar orientated, though, that need certain (open) chords to sound authentic. But take any standard, and it'll work.
The bug in the system may be those blessed (?) with absolute pitch, but why that should be a problem to them still needs clarification.


Save image from URL to a field from a custom module

Question: With a custom module, I'm trying to create a new node, save an image to a node's image field from URL and save the node as well. However when I'm trying to save the node, this error messages comes up

Notice: Trying to get property of non-object in file_field_presave()
  (line 220 of
  /var/www/clients/client1/web20/web/modules/file/file.field.inc).
Notice: Undefined property: stdClass::$uri in file_save() (line 566 of
  /var/www/clients/client1/web20/web/includes/file.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '' for key 'uri': INSERT INTO {file_managed} (filesize, status,
  timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0
  [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] =>
  1373886933 ) in drupal_write_record() (line 7136 of
  /var/www/clients/client1/web20/web/includes/common.inc).

This is the code I wrote for saving the image into a folder, saving it into a node field and save the node:
      $node = new stdClass();
      $node->type = "flickr_image";
      node_object_prepare($node);

      $node->title    = $photo['title'];
      $node->language = LANGUAGE_NONE;

      $node->uid = 1;

      $url = $image[10]['source']; //URL of the image
      $directory = file_build_uri('flickr_images/');

      $file = system_retrieve_file($url, $directory, TRUE, $replace = FILE_EXISTS_REPLACE);
      file_save($file);

      $node->field_image[LANGUAGE_NONE] = $file;

      if($node = node_submit($node)) {
          node_save($node);
      }

What am I doing wrong? I've looked up several similar questions here, but I don't understand what's the problem. The messages only come up when I use node_save(). When I comment it out, the messages disappear.
Answer: Hope this will help  you,
In Drupal 7,  for your requirement I made some changes.

As system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

$node = new stdClass();
$node->type = "node_type";
node_object_prepare($node);
$node->title    =  'your title here';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$url = 'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png';
//I have used picture folder to store images using image field settings
$file_info = system_retrieve_file($url, 'public://pictures/', TRUE);
if($file_info->fid){
    $node->field_image[LANGUAGE_NONE]['0']['fid'] = $file_info->fid;//assign fid
}
$node->field_test_field[LANGUAGE_NONE]['0']['value'] = 'test';//other fields
if($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('submitted successfully');
}

Make changes as per your requirement.


Let $A$ be a torsion abelian group. Then $A$ has no $p$-torsion iff $A \otimes \Bbb Z_{(p)} = 0$.

Question: Let $A$ be a torsion abelian group, $p$ a prime. Then $A$ has no $p$-torsion iff $A \otimes \Bbb Z_{(p)} = 0$.
I could prove one directioin $\Rightarrow$. But how does one prove the converse?
Answer: Lets consider the exact sequence $0\rightarrow T\rightarrow A\xrightarrow{\times p} A\rightarrow Q\rightarrow 0$, where $T$ is our $p$ torsion, and $Q$ is the quotient. Tensoring with $\mathbb{Z}_{(p)}$ is exact, so we have the following exact sequence:
$0\rightarrow T\otimes \mathbb{Z}_{(p)}\rightarrow A\otimes \mathbb{Z}_{(p)}\xrightarrow{\times p} A\otimes \mathbb{Z}_{(p)}\rightarrow Q\otimes \mathbb{Z}_{(p)}\rightarrow 0$.
Since $T$ is $p$-torsion, every $n$ coprime to $p$ already acts invertibly on $T$, so this left term is just $T$. So we see that if $A\otimes \mathbb{Z}_{(p)}$ is zero, then $T$ must be zero by exactness, giving the other direction.
Comment: So I was wondering if omit the hypothesis that $A$ is torsion to begin with. Do we get that $A \otimes \Bbb Z_{(p)}=0$ implies $A$ is torsion?
Comment: That is correct, since the property of being torsion is saying that we admit no injective maps from $\mathbb{Z}$. So if we had $A$ being nontorsion, there exists an injective map $\mathbb{Z}\rightarrow A$, so since tensoring is exact, this map remains injective, giving that $A\otimes \mathbb{Z}_{(p)}$ is nonzero.


Executing CScript scripts from an ASP script fails

Question: Context: Windows Server 2003; IIS 5
I'm trying to launch a JScript file from within an IIS application. I keep getting
<code>Permission denied 70 0 Microsoft VBScript runtime error
</code>
Just in case you're thinking that it's because I'm having a JScript/VBScript senior moment, I'm using the VBScript tool in a third party CGI to execute the JScript, using the following bit of VBScript:
<code> ans = CreateObject("WScript.Shell").Run("c:\windows\system32\cscript.exe //B ..\js2\script3.js group-name 1004041814
</code>
So the error appears to be happening either in the call to cscript or in cscript itself reporting back that it can't do what it's been told.
I've done a lot of digging around for an answer, but so far none of the suggestions given have worked. If nothing else, I'd just like to know what's going on, even if a fix isn't possible. I have come up with a couple of workaround since, but it's a drag that the thing doesn't work in the first instance.
Answer: The IUSR account, or whatever account your IIS application is running under, doesn't have NTFS permissions to cscript.exe, script3.js, some resource that the script3.js is trying to access or a combination of the aforementioned.
I would start by seeing if you're able to launch a blank version of script3.js using the same process. If that doesn't throw the error, then start checking permissions on resources that your script is trying to access or write to.


Views Search Terms not working correctly for taxonomy terms with multiple words

Question: I'm having a bit of an odd issue. I have a Search Terms filter set up on a view and it's not working quite correctly for taxonomy terms in the view.  For example, if one of the Terms is 'International Harvester' and it returns the correct results if I enter International or Harvester or "International Harvester", but if I put in International Harvester without quotes then no results are returned. Any ideas?
using Drupal 7.41, Views 7.x-3.7
Answer: This turned out to be a bug with the search score feature discussed here https://www.drupal.org/node/1615438.
This comment details that checking the "Remove search score" checkbox under the Search: Search Terms filter fixes that problem.


Como mudar a cor do texto de uma coluna de uma JTable

Question: Tenho um formulário para pagamento de parcelas, e este formulário possui uma tabela onde mostro tanto as parcelas pagas quanto as que ainda deveriam ser pagas.

Para popular esta JTable, faço uma consulta no banco de dados e trago as informações necessárias.
public void preencherParcelas(String SQL) {
    ArrayList dados = new ArrayList();
    String[] colunas = new String[]{"Data Pagamento", "Valor Parcela", "Status Pagamento"};
    conecta.conexao();
    conecta.executaSQL(SQL);
    String status;
    try {
        conecta.rs.first();
        dataVenda = conecta.rs.getString("data_venda");
        idParcelamento = conecta.rs.getInt("id_parcelamento");
        do {

            if (conecta.rs.getInt("status_pagamento") == 0) {
                status = "PAGAMENTO PENDENTE";
            } else {
                status = "PAGAMENTO EFETUADO";
            }

            dados.add(new Object[]{conecta.rs.getString("data_pagamento"), "R$ " + conecta.rs.getString("valor_parcelas"), status});

        } while (conecta.rs.next());
} catch (SQLException ex) {

        JOptionPane.showMessageDialog(rootPane, "ERRO AO LOCALIZAR PARCELAS" + ex);

    }

ModeloTabela modelo = new ModeloTabela(dados, colunas);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(0).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(0).setResizable(false);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(1).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(1).setResizable(false);

    jTableInformaVencimentos.setModel(modelo);
    jTableInformaVencimentos.getColumnModel().getColumn(2).setPreferredWidth(150);
    jTableInformaVencimentos.getColumnModel().getColumn(2).setResizable(false);

    jTableInformaVencimentos.getTableHeader().setReorderingAllowed(false);
    jTableInformaVencimentos.setAutoResizeMode(jTableInformaVencimentos.AUTO_RESIZE_ALL_COLUMNS);
    jTableInformaVencimentos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    conecta.desconecta();

Modelo usado na Tabela
    public class ModeloTabela extends AbstractTableModel{

    private ArrayList linhas = null;
    private String[] colunas = null;

    public ModeloTabela(ArrayList lin, String[] col){
        setLinhas(lin);
        setColunas(col);

    }
    public ArrayList getLinhas(){
        return linhas;
    }

    public void setLinhas(ArrayList dados){
        linhas = dados;
    }

    public String[] getColunas(){
        return colunas;
    }

    public void setColunas (String[] nomes){
        colunas = nomes;
    }

    public int getColumnCount(){
        //retorna a quantidade de colunas(conta a quantidade e retorna)
        return colunas.length;
    }

    public int getRowCount(){
        //retorna o tamanho do array(quantos letras tem)
        return linhas.size();
    }

    public String getColumnName(int numCol){
        return colunas[numCol];
    }

    public Object getValueAt(int numLin, int numCol){
        Object[] linha = (Object[])getLinhas().get(numLin);
        return linha[numCol];
    }

}

Gostaria de quando for identificado um "PAGAMENTO EFETUADO" essa String ficasse na cor vermelha de preferencia. Como posso fazer isso?
Comment: String? Você quer dizer celular da tabela ne?
Comment: Tanto faz o que for mais fácil... Se for só a String mesmo e inserir ela já com a cor nova.
Comment: Não é a mesma coisa colorir string e colorir célula. Você precisa definir o que você quer de fato para que a reposta seja condizente ao problema.
Comment: Quero colorir a String e inserir ela no jTable.
Comment: Somente o texto.
Comment: Somente da coluna pagamento ou o texto da linha inteira?
Comment: Só a palavra pagamento.
Comment: Adicione como você está preenchendo a jtable. Se tiver usando algum model ou renderer, adicione eles na pergunta também.
Comment: Está acima na pergunta, eu faço um select no banco e adiciono na tabela.
Comment: Não tem nenhum código que mostre como a jtable está sendo populada. Adicione na pergunta como vc esta populando a jtable.
Comment: Adicione o método getcolumnclass e getvalueat da sua classe modelotabela também.
Comment: O modelo que estou usando é esse.
Answer: Você precisa alterar a forma como o JTable renderiza a célula na tela, e para isso, use a classe DefaultTableCellRenderer, ou crie seu próprio renderer. A forma mais simples é usar a classe padrão citada:
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        String str = (String) value;
        if ("PAGAMENTO EFETUADO".equals(str)) {
            c.setForeground(Color.RED);
        } else {
            c.setForeground(Color.BLACK);
        }
        return c;
    }
};

E depois, aplique o renderer a coluna desejada, no seu caso, a coluna 2:
jTableInformaVencimentos.getColumnModel().getColumn(2).setCellRenderer(renderer);

Lembrando que este renderer, se for aplicado como default da JTable, irá efetuar a alteração de cor para todas as colunas, por isso apliquei apenas a coluna informada.
Se quiser aprender mais sobre renderers, você pode acessar o tutorial oficial da oracle.
Comment: Cara Perfeito... Funcionou exatamente como eu precisava. Obrigado pela atenção!
Comment: @Valdecir Disponha :)


Can't access to a iSCSI volume

Question: I have a iSCSI target on a customer place I'm using from an old Fedora (Core6) server. I configured it and formatted as ext3 (mistake, now I know) and I've been working with it for some time.
Now I need to access this volume from other machine. As far as I've read, I can't do it safely  from two machines at the same time (yep, that's the first thing I tried). So I've umount it from original server and tried to mount it on the new server (I did it at first with Ubuntu 10 LTS but when I was unable to do it I installed another Fedora with the same configuration) with no success.
The problem: I can see all target on NAS but when I do a "fdisk -l" to see all devices and know which mount I see all targets as SFS filesystem. From the original server I see all SFS (after all, they belong to my customer and don't know what he have in) except the one I manage which I see as 'Linux'.
Here it is the partition table as seen in the server (Fedora) which see it right. Spanish language, sorry. I hope it can be understood. My comments between [...]

[.. at beginning the real local drive ..]

Disco /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders
Units = cilindros of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000080

Disposit. Inicio    Comienzo      Fin      Bloques  Id  Sistema
/dev/sda1               1          26      204800   83  Linux
/dev/sda2              26        6400    51200000   83  Linux
[.. more local partitions ..]

[... then iSCSI drives ...]

Disposit. Inicio    Comienzo      Fin      Bloques  Id  Sistema
/dev/sdc1               1      130541  1048570551   42  SFS

Disco /dev/sdf: 2147.5 GB, 2147483649024 bytes
255 heads, 63 sectors/track, 261083 cylinders
Units = cilindros of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x2257d76f

[..... Other devices in between, and here it is the one I mind .....]

Disco /dev/sde: 2147.5 GB, 2147483648000 bytes
255 heads, 63 sectors/track, 261083 cylinders
Units = cilindros of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 262144 bytes
Disk identifier: 0x93afd446

Disposit. Inicio    Comienzo      Fin      Bloques  Id  Sistema
/dev/sde1               1      261083  2097149166   83  Linux

[ .... and ever more devices ....]

On the machine I'm trying to configure, the one which should access the drive (but don't) I see the offending target as:
[....]

Disk /dev/sdc: 2147.4 GB, 2147483649024 bytes
255 heads, 63 sectors/track, 261083 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1               1      261083  2097149166   42  SFS

[....]

And I see rest of targets as SFS, the same as in first case.
Thank you in advanced,
Comment: Please post the output from `fdisk -l` so that we could see that the target in question is not visible. What's your iSCSI target? Am I correct that Fedora is an initiator in terms of iSCSI topology and the target is exported by some other device?
Comment: Hi Dmitri, I've just add the **fdisk -l** output on both machines. And right: Old Fedora (whoch works) and new Ubuntu (don't work) and both initiators. Targets are on a NAS device but don't know the brand and model but almost sure a QNap.

Thank you!
Answer: fdisk reported labels don't mean much nowadays -- in fact as MS-DOS partition tables fall out of use, it even can be entirely misleading. If you want to know what's on a partition, better use file -s /dev/sdXX:
 file -s /dev/sda1
/dev/sda1: Linux rev 1.0 ext2 filesystem data (mounted or unclean), UUID=ebf12615-9c1a-4aca-9111-bebd1eaf4ed3 (large files)
file -s /dev/sda3
/dev/sda3: Linux rev 1.0 ext4 filesystem data, UUID=7322a490-8814-4f0b-92a7-a6f4287acadc (needs journal recovery) (extents) (large files) (huge files)

Comment: I never knew about `file -s`...  That would have come in handy recently!  My current method of discovering the file system is with `blkid`.  eg. `/dev/sda1: UUID="c7f00876-a631-41c4-bf78-4cd18cce4041" TYPE="ext3"`
Comment: Didn't knew that, thank you wazoox for your info. Anyway, I can't access iSCSI target as **file** command reports it as 'data'  so cannot mount it. Any hint?
Comment: @jmiguel.rodriguez, this is definitely strange. What are you exporting from the iSCSI target? is it a fileIO or a blockIO device? You should give more details on the target type (lio, iet, tgt; etc) and configuration.
Comment: Well, "file" has the advantage of working for about anything, block devices, media files, etc :)
Answer: SFS (0x42) partition type in fdisk -l output may be a sign of a partition that existed before it was formatted as ext3.
According to Wikipedia this partition type may correspond to Windows 2000/XP dynamic volume. If the partition was simply reformatted as EXT3, the type code could be left unchanged.
In order to check what partition type is there you could issue
TMPFILE=$(mktemp --tmpdir=/tmp)
dd if=/dev/sdc1 bs=512 count=2048 of=$TMPFILE
file $TMPFILE
rm $TMPFILE

on a ext4 filesystem, for example, this sequence would produce
2048+0 records in
2048+0 records out
1048576 bytes (1.0 MB) copied, 0.0291348 s, 36.0 MB/s
/tmp/tmp.QLD5XhZOYn: Linux rev 1.0 ext4 filesystem data (needs journal recovery)
(extents) (large files) (huge files)

That indicates that whatever the partition type specified in the partition table, the partition itself is an EXT4. One Megabyte is usually enough to identify the true partition type.
If /dev/sdc1 indeed is an EXT3 partition as you expect, you could mount it safely. I would suggest though to mount it via Device Mapper multipath mount point to avoid problems if the device enumeration over iSCSI changes.
Comment: Good point. Thank you. I've tested it, and on first machine (where it's well mounted):

[root@scancia ~]# file /tmp/test
/tmp/test: Linux rev 1.0 ext4 filesystem data (needs journal recovery) (extents) (large files) (huge files)

On second machine (SFS system):
[root@scanciaprodj2ee ~]# file /tmp/test
/tmp/test: data

So.. bad news. :-(

I'll look the multipath parameter you mention, I presume it will solve the problem I also have (althouth didn't mind a lot) with /dev/sd?1 names on every reboot.

Can't access to a iSCSI volume


Converting $\frac{\sqrt{2-\sqrt{3}}}{2}$ into $\frac{\sqrt{3}-1}{2\sqrt{2}}$

Question: A few days ago I had a quiz question on calculating the sine of $15^\circ$. Using the half-angle identity for sine, I did the following:
$$\sin15^\circ=\sqrt{\frac{1-\frac{\sqrt{3}}{2}}{2}}=\frac{\sqrt{2-\sqrt{3}}}{2}$$
But the lecturer give this:
$$\frac{\sqrt{3}-1}{2\sqrt{2}}$$
This is also the first answer given by WolframAlpha.
So my question is: how does one convert between the two forms?
$$\frac{\sqrt{2-\sqrt{3}}}{2}=\frac{\sqrt{3}-1}{2\sqrt{2}}$$
Edit: and why would one prefer the second over the first, if the the first is so straightforward to reach?
Comment: Observe,$$(\sqrt{3}-1)^2=2(2-\sqrt{3})$$
Comment: I think you have improved your question, and so I have voted to reopen.
Answer: $$\frac{\sqrt{2-\sqrt{3}}}{2}=\frac{\sqrt{2}\sqrt{2-\sqrt{3}}}{2\sqrt{2}}=\frac{\sqrt{4-2\sqrt{3}}}{2\sqrt{2}}=\frac{\sqrt{3-2\sqrt{3}+1}}{2\sqrt{2}}=\frac{\sqrt{3}-1}{2\sqrt{2}}$$
Comment: Please refrain from answering very low quality PSQs, as written in the Enforcement of Quality Standards.
Comment: Please refer to [the guidelines for enforcing quality standards](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards). Thank you.
Comment: Thanks. I should've asked _why_ the lecturer and [WolframAlpha](https://www.wolframalpha.com/input/?i=sin+15) would opt for the second form, when it seems to require more steps if one uses the half-angle identity.


Find whether vector w belongs in the span

Question: $$v_1=[1,0,1,2]$$
$$v_2 = [0,1,1,3]$$
$$v_3 = [2,1,3,7]$$
$$w = [1,2,3,4]$$
We are supposed to determine if $w$ is in $\operatorname{span}(v_1,v_2,v_3)$.
Comment: Form the matrix $\begin{bmatrix} v_1|v_2|v_3|w\end{bmatrix}$ and then use row reduction to see if the corresponding linear system is consistent.
Comment: Yes, you want to use Gaussian elimination, and you didn't need to check to see if $v_1,v_2,v_3$ were linearly dependent first.
Comment: What have you done so far?
Comment: First I checked if v1,v2,v3 are linearly dependent.  Without calculation I figure they have to be because in Gaussian elimination there would be a free column which would imply linear dependence.  To check if w is in the span would I just have to apply Gaussian elimination again?
Answer: Create a matrix $A=[v_1 | v_2 | v_3 | w]:$
$A =\left[\begin{array}{cccc}
1 & 0 & 2 & 1 \\
0 & 1 & 1 & 2 \\
1 & 1 & 3 & 3 \\
2 & 3 & 7 & 4
\end{array}\right]$
Now just calculate the rank of $A$.
If the rank comes out to be $4$, then $w$ cannot be written as a linear combination of $v_1,v_2,v_3$.
Otherwise, we can say that w is in the span of $v_1,v_2,v_3$.
Correct me if wrong.
Answer: The vector $w$ will be in the span of the given set of vectors if you can write $w$ as a linear combination of the vectors. That is, provided that $w$ is in the span, you will have
$$w=c_1v_1+c_2v_2+c_3v_3$$
$w$ will be in the span if you can find at least one set of solutions for the coefficients.
Comment: I don't understand the edit. Aren't we only concerned whether $w$ is a linear combination of the vectors $v_i$? And surely $w\neq\mathbf0$.
Answer: Let us take the vectors $v_1$, $v_2$ and $v_3$ and perform elementary row operations until we get reduced row echelon form.
$$
\begin{pmatrix}
  1 & 0 & 1 & 2 \\
  0 & 1 & 1 & 3 \\
  2 & 1 & 3 & 7
\end{pmatrix}\sim
\begin{pmatrix}
  1 & 0 & 1 & 2 \\
  0 & 1 & 1 & 3 \\
  0 & 1 & 1 & 3
\end{pmatrix}\sim
\begin{pmatrix}
  \boxed{1} & 0 & 1 & 2 \\
  0 & \boxed{1} & 1 & 3 \\
  0 & 0 & 0 & 0
\end{pmatrix}$$
Since elementary row operations do not change the row space, the non-zero rows of the last matrix span the same subspace. So now we have a rather simple basis consisting of the vectors $u_1=[1,0,1,2]$ and $u_2=[0,1,1,3]$ and we are asking whether $w\in\operatorname{span}(u_1,u_2)$.
Now it suffices to look at the numbers in the first and second position in the vector $w$, since this is where the pivots are in the rref.
So $w$ can only be a linear combination of $u_1$ and $u_2$ if it is equal to
$$u_1+2u_2=[1,2,3,8].$$
Therefore we see that $w\notin \operatorname{span} (u_1,u_2)= \operatorname{span}(v_1,v_2,v_3)$.
See also this similar question: Finding whether a vector is in the span of a set of vectors
Answer: The row reduced form:
$$
\begin{align}
  \mathbf{A} &\to \mathbf{E}_{\mathbf{A}} \\
%
\left[
\begin{array}{ccc}
 1 & 0 & 2 \\
 0 & 1 & 1 \\
 1 & 1 & 3 \\
 2 & 3 & 7 \\
\end{array}
\right]
%
 &\to
%
\left[
\begin{array}{ccc}
 1 & 0 & 2 \\
 0 & 1 & 1 \\
 0 & 0 & 0 \\
 0 & 0 & 0 \\
\end{array}
\right]
%
\end{align}
$$
Therefore the matrix rank is $\rho = 2$.
We have two elementary columns, 1 and 2. If $w$ is in the span of the column space then we must have
$$
  \left[
\begin{array}{c}
 1 \\
 2 \\
 3 \\
 4
\end{array}
\right]
=
\alpha
  \left[
\begin{array}{c}
 1 \\
 0 \\
 1 \\
 2
\end{array}
\right]
+
\beta
  \left[
\begin{array}{c}
 0 \\
 1 \\
 1 \\
 3
\end{array}
\right]
$$
The first two elements reveal the answer: $w$ is not in the span.
The vector $w$ can be resolved into $\color{blue}{range}$ and $\color{red}{null}$ space components
$$
\begin{align}
  w &=
   \color{blue}{w_{\mathcal{R}(\mathbf{A})}} +
   \color{red}{w_{\mathcal{N}(\mathbf{A})^{*}}} \\
%
\left[
\begin{array}{c}
 1 \\
 2 \\
 3 \\
 4
\end{array}
\right]
&=
\frac{1}{17}
%
\color{blue}{\left[
\begin{array}{c}
 21 \\
 50 \\
 71 \\
 56 \\
\end{array}
\right]}
+
\frac{1}{17}
\color{red}{\left[
\begin{array}{r}
 -4 \\
 -16 \\
 -20 \\
 12 \\
\end{array}
\right]}
%
\end{align}
$$