Converting infinite base-k expansions into base-j expansions

Question: I understood the method of transforming a finite sized base-k numbers to another base (j) through the use of successive divisions
For example
$$12_{10} = 12/2 + 0*2^0 = 6/2 + 0*2^1 + 0*2^0 = 3/2 + 1*2^2 + 0*2^1 + 0*2^0 =  1100_2$$
But what about generalizing this to consider infinite expansions in some base?
I can't seem to reason a good strategy involving remainders for this problem.
Answer: You can never write down all of an infinite expansion -- the best you can hope for is to approximate the number as closely as you need for a particular purpose, or, in some cases, to specify a pattern that repeats ad infinitum in the digits.
With this in mind, converting an infinite expansion from base $k$ to base $j$ is no more problematic then writing down the expansion in the first place. You can determine it up to any given digit after the radix point by performing your procedure for finite expansions on a truncation of your base $k$ expansion.
Let me elaborate: say that you have a number $x$, represented in base $k$ by a possibly infinite expansion, which you can compute to any finite number of digits after the radix point (for instance $(.3333....)_{10}$ represents the number $\frac{1}{3}$, and given any natural number $m$ you can compute its base $10$ expansion to $m$ digits after the radix point).
To approximate $x$ in base $j$, you first truncate the base $k$ expansion of $x$ to include $m$ places after the radix point. That is, you approximate $x$ by a string of digits $(a_na_{n-1}.. a_0.b_1...b_m)_k$. Note that the number $y$ represented by this approximation differs from $x$ at most $k^{-m}$.
Now, suppose that you convert your expansion for $y$ from base $k$ to base $j$. How many digits of $y$ in base $j$ match those of $x$ in base $j$? To answer this, suppose that $l$ is the maximal natural number so that $j^l$ divides $k^m$. It's easy to see that your base $j$ expansion of $y$ matches that of $x$ at least up to the $(l-1)$-st digit after the radix point. You can run this argument backwards to get as many digits as you like of the expansion for $x$ in a given base, if that's what you are looking to do.
Note that numbers with finite expansions in one base need not have finite expansions in another, and vice versa:
$$(.3333333....)_{10} = (.1)_{3}.$$
So, really, the only way to avoid this "infinity problem" when converting between basis is to restrict yourself to whole numbers.


find $A_0$, $x_0$ such that the Gauss integration formula $\int_{-1}^{1} f(x)|x| \,dx\, \approx$ $A_0 f(x_0)$ will be with maximum accuracy degree

Question: Hint: the formula will calculate the true value integrals of the form $\int_{-1}^{1} x^n |x| \,dx$ for all $n=0,1,...k$
such that $k$ is the accuracy degree.
How can I approach this?
An easy guess : $k=0$,$A_0 =1$  and $x_0 = 0$.
However, I don't know if the maximum value for $k$ is 0.
Comment: Your easy guess has $k=1$ in fact.
Answer: Each $n$ yield an equation
$$
\int_{-1}^1 x^n |x| dx = A_0 x_0^n.
$$
On the other hand,
$$
\int_{-1}^1 x^n |x| dx = \begin{cases}
\frac{2}{n+2}, &n \text{ is even}\\
0, &n \text{ is odd}
\end{cases}
$$
So we have the following system of nonlinear equations for $A_0$ and $x_0$:
$$
1 = A_0, \quad n = 0\\
0 = A_0 x_0, \quad n = 1\\
\vdots\\
\int_{-1}^1 x^k |x| dx = A_0 x_0^k, \quad n = k.
$$
The first two equations immediately require $A_0 = 1, x_0 = 0$. If we truncate system at $n = 1$ then $A_0 = 1, x_0 = 0$ will be the solution. So $k$ is at least 1.
Let's check that $k$ cannot be greater than 1. If $k > 1$ then for $n = 2 \leq k$ the integration should be exact:
$$
\frac{2}{4} = A_0 x_0^2.
$$
But it is not true, so $k$ cannot be greater than $1$.


Turn a file into dictionary

Question: I'm really new into Python and I have a question. I need to convert a file containing morse code alphabet. It's a file with a single string and it looks like this (A2.-B4-...C4-.-.D3-..). I'm thinking that I should be able to create a dictionary out of this file but I'm not sure how. Do you guys have any idea?
Comment: Welcome to Stackoverflow! Would you like to post some data formatted as they are in your file and give us an example of desired output?
Comment: I can't see your screen from here, can you post what you have tried, what the file looks like, what you want the output to be, what you want the directory to be?
Answer: This approach uses regular expression to parse your entire string and convert it to dict directly:
import re

with open('yourfile.txt') as f:
    data = f.read()

morse = dict(re.findall(r'(\w)\d+([-.]+)', data))
print(morse)

The results for your example data:
{'A': '.-', 'C': '-.-.', 'B': '-...', 'D': '-..'}

Here's a short explanation of the regular expression:

(\w) parens means we want to capture this part, \w means any alphanumeric
\d+ here, \d means any digit and the + sign means one or more
([-.]+) parens again means we want to capture this part, [-.] means we want . or - and the + again means we want one or more of those.

For more regular expression explanation I suggest reading "Regular Expression HOWTO" by A. M. Kuchling, excellent read.
Comment: Wow, this looks really elegant! I've never heard about regular expression... but it looks like a really good tool to handle different patterns in text. I've tried google to understand what r'(\w)\d+([-.]+)' means but I don't fully understand it. Could you please explain what different parts of mention code mean? I'm really thankful for your help :)
Comment: @gdom I have added a short explanation of the regular expression, and a link to a more detailed regular expression text for beginners. If my answer is good for you, please consider marking it as accepted to close the question.
Answer: When you open files in Python, they can be read line by line like so:
d = {} # Init empty dict
with open("file.txt", "r") as file: # This manages the open/close, IO mode, et cetera
    for line in file: # Iterates through the file line by line
        # Now the variable line represents a string for that line
        sline = line.split("-")
        d[sline[0]] = sline[1]

In the last two lines of this example I assume that you want a dict where the key (lookup) always sits before "-" on each line, and the value (to be looked up) is always after. On this assumption I line.split("-") and then assign those keys and values to dict d with d[sline[0]] = sline[1]. If you adopt this solution but have problems with this part of the solution, I think that might warrant a separate question.

Turn a file into dictionary


session to show message and back button

Question: i have 3 jsp's :-

a.jsp
b.jsp
c.jsp

From a.jsp i am going to b.jsp to show some result. And when the user update one of the record i call c.jsp which actually update it. So after updation it forward to a.jsp with a message saying "Successfully Updated"  . And i set this message in session . And in a.jsp after showing this message. i invalidate the session.
The problem is , when i press the browser back button it still show the message.
How can i solve this.
Please help me.
Thanks
Comment: Could you share some source code? However I suspect you're putting java code in a jsp which is an anti-pattern.
Comment: Maybe [this][1] will help...

  [1]: http://stackoverflow.com/questions/8785682/preventing-user-to-got-back-after-logout-in-jsf
Answer: I would suggest few steps to do that...
As you click on back button browser will get the page from cache... so set the JSP page Expires date to some previous day/time to get it from server(origin) instead of cache. This can be done by writing a Custom tag and in that tad set Expires header on HttpServletRequest object and adding that tag to JSP page is enough.
To invalidate the page and redirect to a.jsp when there is no valid session, write a Filter to  that job.
Tag can be written like this
public class ExpiryTag extends SimpleTagSupport{

    @Override
    public void doTag() throws JspException, IOException {

        PageContext pageContext = (PageContext) getJspContext();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, -1);
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
        response.addHeader("Expires", instance.getTime().toString());

    }

}

Map tag in tld file like this
<tag>
            <name>expired</name>
            <tag-class>com.analysis.mvc.tags.ExpiryTag</tag-class>
            empty
        </tag>

Then use the tag in JSP like this
<prefix:expired/>

For session handling you can go through this for basic understanding.
Answer: If a.jsp, b.jsp and c.jsp are a part single process, try putting them on single page (say abc.jsp). Now using some attributes show contents of either a.jsp/b.jsp/c.jsp, something similar to a wizard.

session to show message and back button


Why hook_preprocess_html() isn't working?

Question: Why hook_preprocess_html() isn't firing in my module file? Is it only works in theme_hook?
EDIT:
function my_module_preprocess_html(&$variables) {
  if (current_path() == 'user') {
    $variables['head_title'] = implode(' | ', array(drupal_get_title(),  variable_get('site_name')));
  }
}

Comment: You cleared cache and put an exit or debug statement in? How can you tell it isn't hitting that function?
Comment: can you provide more info please? Some piece of code from module file and theme file
Comment: @AdrianCidAlmaguer
`function my_module_preprocess_html(&$variables) {

  if (current_path() == 'user') {

    $variables['head_title'] = implode(' | ', array(drupal_get_title(),
variable_get('site_name')));

  }

}`
Answer: Try the general preprocess hook, like:
/**
 * Implements hook_preprocess().
 */
function my_module_preprocess(&$variables, $hook) {
  if ($hook == 'html') {}
}

Comment: Unfortunately it doesn't work too.
Comment: can you show your module file structure, list all files you created, and name the file you have the above code in. what's your module name ? is your module enabled ?


"Peakedness" of a skewed probability density function

Question: I would like to describe the "peakedness" and tail "heaviness" of several skewed probability density functions.
The features I want to describe, would they be called "kurtosis"? I've only seen the word "kurtosis" used for symmetric distributions?
Comment: Indeed, the measures of kurtosis are typically applied to symmetric distributions. You can calculate it for skewed ones as well but the interpretation changes since this value varies when the asymmetry is introduced. In fact, these two concepts are difficult to separate. Recently, a skewness-invariant measure of kurtosis was proposed in [this paper](http://amstat.tandfonline.com/doi/abs/10.1198/tast.2011.10194).
Comment: High kurtosis is associated with peakedness and with heavy tailedness (it's also characterized as 'lack of shoulders'). One of the volumes of Kendall and Stuart discuss these issues at some length. But such interpretations, are, as you note, generally given in the situation of near-symmetry. In nonsymmetric cases, the standardized 4th moment is usually highly correlated with the square of the standardized third moment, so they're mostly measuring much the same kind of thing.
Comment: Indeed, given the particular way I phrased it in my earlier comment, it's true even of symmetric distributions - the square of the sample standardized third moment (squared moment skewness) is highly correlated with the sample standardized fourth moment ('kurtosis'), even at say the normal.
Answer: The main issue here is, what is "peakedness"? Is it curvature at the peak (2nd derivative?) Does it require standardization first? (You would think so, but there is a stream of literature starting with Proschan, Ann. Math. Statist. Volume 36, Number 6 (1965), 1703-1706, that defines peakedness in a way that normal with smaller variance are more "peaked"). Or is it probability concentration within a standard deviation of the mean, as implicit in Balanda and Macgillivray (The American Statistician, 1988, Vol 42, 111-119)? Once you settle on a definition, then it should be trivial to apply it. But I would ask, "why do you care?" Of what relevance is "peakedness", however defined?
BTW, Pearson's kurtosis measures tails only, and does not measure any of the above mentioned "peakedness" definitions. You can change the data or distribution within a standard deviation of mean as much as you want (keeping the mean=0 and variance=1 constraint), but the kurtosis can only change within a maximum range of 0.25 (usually much less). So you can rule out using kurtosis to measure peakedness for any distribution, even though kurtosis is indeed a measure of tails for any distribution, no matter whether the distribution is symmetric, asymmetric, discrete, continuous, discrete/continuous mixture, or empirical. Kurtosis measures tails for all distributions, and virtually nothing about peak (however defined).
Answer: With variance being defined as the second moment $\mu_{2}$, skewness being defined as the third moment $\mu_{3}$ and the kurtosis being defined as the fourth moment $\mu_{4}$, it is possible to describe the properties of a wide range of symmetric and non-symmetric distributions from the data.
This technique was originally described by Karl Pearson in 1895 for the so-called Pearson Distributions I to VII.  This has been extended by Egon S Pearson (date uncertain) as published in Hahn and Shapiro in 1966 to a wide range of symmetric, asymmetric and heavy tailed distributions that include Uniform, Normal, Students-t, Lognormal, Exponential, Gamma, Beta, Beta J and Beta U.  From the chart of p. 197 of Hahn and Shapiro, $B_{1}$ and $B_{2}$ can be used to establish descriptors for skewness and kurtosis as:
$\mu_{3} = \sqrt {B_{1}\ \mu_{2}^{3}}$
$\mu_{4} = B_{2}\ \mu_{2}^{2}$
If you just wanted simple relative descriptors then by applying a constant $\mu_{2} = 1$ the skewness is $\sqrt {B_{1}}$ and the kurtosis is $B_{2}$.
We have attempted to summarize this chart here so that it could be programmed, but it is better to review it in Hahn and Shapiro (pp 42-49,122-132,197).  In a sense we are suggesting a little bit of reverse engineering of the Pearson chart, but this could be a way to quantify what you are seeking.
Answer: A possible very practical approach could be calculate the ratio of the survival function of the distribution $\Pr\left(\tilde X \gt  1- \alpha \right)$ against the normal one, showing it is quite far greater. Another approach can be calculating the ratios of percentiles $w_1=\frac{\tilde{x_{99}}-\tilde{x_{50}}}{\tilde{x_{75}}-\tilde{x_{50}}}$ of the distribution $\tilde x$ under interest and dividing it against the normal one quantile values, $w_2=\frac{\tilde{\Phi_{99}}-\tilde{\Phi_{50}}}{\tilde{\Phi_{75}}-\tilde{\Phi_{50}}}$, $\tau=\frac{w_1}{w_2}$.
Answer:
I would like to describe the "peakedness" and tail "heaviness" of several skewed probability density functions.

See BigBendRegion's answer. Also read his relevant paper.

The features I want to describe, would they be called "kurtosis"?

What's in a word? The excess kurtosis is given by
$$g_2 = \frac{\frac{1}{m} \sum_{i=1}^m (x- \bar x)^4}{\left[ \frac{1}{m} \sum_{i=1}^m (x_i - \bar x)^2 \right]^2} - 3$$
and has the upper bound
$$g_2 \leq \frac{1}{2} \frac{m-3}{m-2} g_1^2 + \frac{m}{2} - 3 = B$$
where $g_1$ is the similarly-defined skewness. Finding a dataset which minimized $\frac{g_2}{B}$ I found:

And finding a similarly maximal example:

These patterns are unusual, and not what I would intuitively agree to call minimal or maximal "peakedness".

I've only seen the word "kurtosis" used for symmetric distributions?

(Pearson's) kurtosis requires that the fourth moments exist, which is true of many distributions. Some of them even have a really clean expression, such as the excess kurtosis for a gamma distribution.
Answer: I am not sure I get your understanding of peakedness and heaviness. Kurtosis means "Excess" in German, so it describes the "head" or "peak" of a distribution, describing whether it is very wide or very narrow. Wikipedia states that the "peakedness" is actually described by the "kurtosis", whereas peakedness does not to appear to be a real word and you should use the term "Kurtosis".
So I think you might have gotten everything right, the head is the Kurtosis, The "heaviness" of the tail might be the Skewness":
Here is how you find it:
$$
a_3 = \frac{\Sigma^{N}_{i=1}(x_i - \overline x)^3}{N * s^3_x}
$$
with s as the standard deviation for x.
The values indicate:
Negative Skew:
$$
a_3 < 0
$$
Positive Skew:
$$
a_3 > 0
$$
No Skew
$$
a_3 = 0
$$
You can get a value for the kurtosis with:
$$
a_4 = \frac{\Sigma^{N}_{i=1}(x_i - \overline x)^4}{N * s^4_x}
$$
The values indicate:
Platycurtic:
$$
a_4 < 3
$$
Leptocurtic:
$$
a_4 > 3
$$
Normal:
$$
a_4 = 3.0
$$
Did that help?
Comment: I'm afraid this answer in its current form may be less than helpful due to errors in it.  Skewness is a standard measure of *asymmetry*. It is not closely related to heaviness of tails: it is possible for the tails to be extremely heavy and the skewness to be zero (which is the case for any symmetric distribution, for instance). Please note, too, that it is impossible for $a_4$ to be negative, so the second half of this answer makes little sense. (Perhaps you confused kurtosis with *excess kurtosis*?)
Comment: Thank you for clarifying. There might indeed be some errors in the formulas, I just copied them from the scripts they provide at uni. I oversaw the fact that a4 can't be negative.
Comment: I looked up why my answer is wrong - it is a translational error, I apologize for that. My slides are all in German, mixing [Kurtosis and Excess](http://de.wikipedia.org/wiki/W%C3%B6lbung_(Statistik)).
Comment: @Peter As Peter Westfall keeps pointing out, your comment is incorrect: "peakedness" (of any mode), thought of vaguely as pointiness or height, has absolutely nothing to do with the tails of any distribution, nor is it measured by any finite combination of moments (such as the kurtosis).  It may happen to be connected to heaviness of tails for a *family of distributions,* but that's a completely different matter.


Lock removable drives to domain/network with BitLocker

Question: I have a network/domain of PCs that users use and don't have administrative privileges. Occasionally, they copy some data to USB drives to move between machines.
I need to prevent data written to those drives from being accessible outside of the domain/network.
I know I can force BitLocker encryption onto all USB drives. But this doesn't prevent the user from taking the USB drive home and unlocking it there to copy the data to an unsecure machine.
I want the drive to only be unlockable using machines that are on the network.
Is this possible? Seeing as how all user accounts are regular non-administrator users, it sounds like it should be as simple as keeping the encryption key on some domain server and using it to unlock drives without ever letting the users access the key.
Answer: Be glad, I wrote an article for that exact scenario:
A new aspect to securing USB data: SID protectors
Comment: Can you explain, why that comment was rated negatively? It addresses exactly your problem, we use it.
Comment: I didn't rate it negatively, your article was helpful and answered the question I had.
Comment: Thank you for following up.


Questões de multipla escolha em php e banco de dados

Question: Olá, estou montando um sistema de busca com filtro para buscar questões de múltipla escolha em um site, de acordo com a disciplina, banca, cargo, ano, etc. Para isso cadastrei as questões em uma tabela no banco de dados e as alternativas em outra tabela. Agora eu preciso que a questão e suas alternativas apareçam juntas. Como faço isso? segue o código:
'
//////////////////////DISCIPLINAS//////////////////////////////////////////////
$sql_disciplina = "SELECT * FROM tabela_disciplina ORDER BY Disciplina ASC";
$pega_disciplina = mysqli_query($connection, $sql_disciplina);

    ////////////////////////////////////////BANCAS/////////////////////////////////
    $sql_banca="SELECT * FROM tabela_banca ORDER BY Banca ASC";
    $pega_banca = mysqli_query($connection,$sql_banca);

////////////////////////////////////////INSTITUIÇÃO/////////////////////////////////
$sql_instituicao="SELECT * FROM tabela_instituicao ORDER BY Instituicao ASC";
$pega_instituicao = mysqli_query($connection,$sql_instituicao);

////////////////////////////////////////CARGO/////////////////////////////////
$sql_cargo="SELECT * FROM tabela_cargo ORDER BY Cargo ASC";
$pega_cargo = mysqli_query($connection,$sql_cargo);

////////////////////////////////////////ANO////////////////////////////////////
$sql_ano="SELECT * FROM tabela_ano ORDER BY Ano ASC";
$pega_ano = mysqli_query($connection,$sql_ano);

//////////////////////NÍVEL//////////////////////////////////////////////
$sql_nivel = "SELECT * FROM tabela_nivel ORDER BY id_nivel ASC";
$pega_nivel = mysqli_query($connection, $sql_nivel);

////////////////////////////////TRAZ AS QUESTÕES DE ACORDO COM O CRITÉRIO/////
if(!empty($_POST['bt_enviar']))
{
$disciplina = (empty($_POST['Disciplina']))? 'null' : $_POST['Disciplina'];
$banca = (empty($_POST['Banca']))? 'null' : $_POST['Banca'];
$instituicao = (empty($_POST['Instituicao']))? 'null' : $_POST['Instituicao'];
$cargo = (empty($_POST['Cargo']))? 'null' : $_POST['Cargo'];
$ano = (empty($_POST['Ano']))? 'null' : $_POST['Ano'];
$nivel = (empty($_POST['Nivel']))? 'null' : $_POST['Nivel'];
$sql_questao="SELECT * FROM tabela_questao WHERE id_disciplina = $disciplina OR id_banca = $banca OR id_ano = $ano OR id_nivel = $nivel OR id_instituicao = $instituicao OR id_cargo = $cargo";
$seleciona_questao = mysqli_query($connection,$sql_questao);
}

////////////////////////////////TRAZ AS ALTERNATIVAS DE ACORDO COM AS QUESTÕES/////

$query = "SELECT Q.Questao, A.Alternativa
FROM Tabela_questao AS Q
LEFT JOIN tabela_resposta AS A
ON Q.id_questao = A.id_questao";

$executar_query = mysqli_query($connection, $query);

while($resultado = mysqli_fetch_array($executar_query)) {?>

<?php echo $resultado['Alternativa']; ?>

<?php
}
mysqli_close($connection);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta charset="utf-8" />
<title>Busca</title>

<form action="" method="post" enctype="multipart/form-data">

<select name="Disciplina">
<option value="" selected="selected">Selecione a disciplina</option>
<?php
if(mysqli_num_rows($pega_disciplina) == 0) {
echo '<option value="">Não foram encontradas disciplinas</option>';
}else{
while($linha = mysqli_fetch_array($pega_disciplina)){
echo '<option value="'.$linha['id_disciplina'].'">'.utf8_encode($linha['Disciplina']).'</option>';
}
}
?>

</select>

<select name="Banca">
<option value="" selected="selected">Selecione a banca</option>
<?php
if(mysqli_num_rows($pega_banca) == 0) {
echo '<option value="">Não foram encontradas bancas</option>';
}else{
while($linhaB = mysqli_fetch_array($pega_banca)){
echo '<option value="'.$linhaB['id_banca'].'">'.utf8_encode($linhaB['Banca']).'</option>';
}
}
?>

</select>

<select name="Instituicao">
<option value="" selected="selected">Selecione a instituição</option>
<?php
if(mysqli_num_rows($pega_instituicao) == 0) {
echo '<option value="">Não foram encontradas instituições</option>';
}else{
while($linhaD = mysqli_fetch_array($pega_instituicao)){
echo '<option value="'.$linhaD['id_instituicao'].'">'.utf8_encode($linhaD['Instituicao']).'</option>';
}
}
?>

</select>

<select name="Cargo">
<option value="" selected="selected">Selecione o cargo</option>
<?php
if(mysqli_num_rows($pega_cargo) == 0) {
echo '<option value="">Não foram encontrados cargos</option>';
}else{
while($linhaD = mysqli_fetch_array($pega_cargo)){
echo '<option value="'.$linhaD['id_cargo'].'">'.utf8_encode($linhaD['Cargo']).'</option>';
}
}
?>

</select>

<select name="Nivel">
<option value="" selected="selected">Selecione o nível</option>
<?php
if(mysqli_num_rows($pega_nivel) == 0) {
echo '<option value="">Não foram encontrados níveis</option>';
}else{
while($linhaC = mysqli_fetch_array($pega_nivel)){
echo '<option value="'.$linhaC['id_nivel'].'">'.utf8_encode($linhaC['Nivel']).'</option>';
}
}
?>

</select>
Ano
<select name="Ano">
<option value="" selected="selected">Selecione o Ano</option>

<?php
if(mysqli_num_rows($pega_ano) == 0) {
echo '<option value="">Não foram encontrados</option>';
}else{
while($linhaB = mysqli_fetch_array($pega_ano)){
echo '<option value="'.$linhaB['id_ano'].'">'.utf8_encode($linhaB['Ano']).'</option>';
}
}
?>

<input type="submit" name="bt_enviar" value="buscar" />

</form>

<?php
if(!empty($_POST['bt_enviar']))
{
if(mysqli_num_rows($seleciona_questao) == 0)
{
echo '
Desculpe, mas sua busca, não retornou resultados
';
}
else
{
echo "
";
while($linhaquestao = mysqli_fetch_array($seleciona_questao)){
echo '
'.utf8_encode($linhaquestao['Questao']).'
';
}
echo "
";
}
}

?>

'

Comment: O seu banco de dados é MySQL?
Comment: É sim @EduardoAlmeida
Comment: Pode ser mais especifica quando se refere a questões e suas alternativas?
Comment: CArolina, poderia da uma organizada no código? Fica quase impossivel entender do jeito que está, nem organizei porque não entendi bem sua organização.
Comment: Desculpa, eu tentei colocar como código, colocando ' ' mas eu não consegui
Comment: Oi, Carolina! Desculpa ter-me afastado. Bem, gostaria de saber se conseguiste resolver essa questão. Como está o andamento de tudo?
Comment: oi @EduardoAlmeida, ainda estou na mesma. Usando o left join como vc indicou, aparece na tela todas as alternativas que foram cadastradas na minha tabela de alternativas, isso sem eu ter feito a busca pelas questões. E quando faço a busca continua aparecendo apenas as questões sozinhas e as alternativas todas juntas, que já apareciam antes da busca.
Answer: ATUALIZAÇÃO
Você poderá imprimir os valores da seguinte forma, então.

<?php
//sua query: se ficar muito grande passe pra uma variável, só por questão de visualização

$query = "SELECT Questao.Questoes AS questao, Alternativa.Alternativas AS alternativas
FROM TABELA_DE_QUESTOES AS Questao
LEFT JOIN TABELA_DE_ALTERNATIVAS AS Alternativa
ON Questao.ID_Questao = Alternativa.ID_Questao";

$executar_query = mysqli_query($con, $query); //primeiro sua conexao, depois sua query

//iteração pelos resultados
while($resultado = mysqli_fetch_array($executar_query)){ ?>

<?php echo $resultado['questao']; ?>

<?php echo $resultado['alternativa']; ?>

<?php

}

mysqli_close($conn);

?>

Perceba: eu escapei o HTML no loop while().
Use sempre as funções mysqli e não as mysql, porque estão obsoletas.
Posta os resultados pra gente ver como tá indo.
------------------------------------*
É bem simples, Carolina. Use o LEFT JOIN pra associações 1:N (um registro de uma tabela - questão - pra vários registros de outra tabela - escolhas/alternativas).
Um exemplo do uso seria o seguinte:

SELECT Questao.Questoes, Alternativa.Alternativas
FROM TABELA_DE_QUESTOES AS Questao
LEFT JOIN TABELA_DE_ALTERNATIVAS AS Alternativa
ON Questao.ID_Questao = Alternativa.ID_Questao

Explicando:
Na primeira linha da query, eu coloquei Questao.Questoes e Alternativa.Alternativas: a primeira palavra é um apelido que eu dei pra cada tabela usando a palavra AS a segunda palavra é o nome do campo.
Na segunda linha, fica explícito onde eu dou o apelido pra tabela de questões e, na terceira linha, eu dou um apelido pra tabela de alternativas e me refiro a ela por meio das palavras-chave LEFT JOIN.
Na última linha, eu termino o LEFT JOIN, que usa a palavra ON pra agrupar os valores das duas tabelas por meio de um campo comum, no caso do exemplo, o campo é ID_Questao que deve existir nas duas tabelas, por isso o sinal de igual (pode ser qualquer sinal de comparação, mass é mais comum procurar por igualdades, uma vez que há outros tipos de JOIN pra outros tipos de associações ou junções).
Bem, tenta e manda os resultados pra galera aqui!!!
Comment: humm legal, quando eu coloquei isso no banco de dados deu certo. Mas como e onde eu coloco isso no meu código, para aparecer no site? e como fica o echo? ficou assim:
'SELECT Q.Descricao, A.Descricao
FROM Tabela_questao AS Q
LEFT JOIN tabela_resposta AS A
ON Q.id_questao = A.id_questao'
Comment: Eu editei a questão com um exemplo de aplicação do código.
Comment: hummm, nesta parte:

 a questão e a alternativa seriam os campos da tabela? pq nas minhas tabelas estes dois campos estão com o mesmo nome: Descricao. Não deu certo, deve ser por isso. Vou tentar mudar.
Comment: Sim, são os campos da tabela. Na verdade, se você olhar na query do exemplo, eu dei apelidos aos campos retornados do banco de dados usando a palavra `AS`. Suponha: `SELECT campo_questao FROM tabela_questao` e `echo $resultado['campo_questao']`, eu estou imprimindo o campo que é retornado na query. O que eu fiz foi: `SELECT campo_questao AS questao...` e `echo $resultado['questao']`, chamando o campo pelo apelido que eu dei.
Comment: certo, isso eu entendi.. mas estou fazendo alguma coisa errada, pois imprimi todas as alternativas da minha tabela na tela sem eu ter filtrado as questões no filtro que criei. vou editar o primeiro código que postei para ver como está
Comment: Tirei essa parte:  pq já tinha acima, no meu filtro.


envio de e-mail em java não mostra o erro quando não consegue enviar o mesmo

Question: Criei um sistema onde o próprio usuário se cadastra e a senha é enviada por email.
Caso não consiga enviar o email , gera um erro e não cria o usuário, notificando o mesmo.
Estava funcionando enquanto estava utilizando servidor de email próprio.
Recentemente passei a utilizar uma conta do Gmail para enviar os emails.
A partir daí a função não gera mais erro quando o Gmail não consegue entregar a mensagem.
Com isso o usuário não sabe que ocorreu um problema e não recebe a senha.
import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

// ... Demais imports

@ViewScoped
public class Mailer implements Serializable{

    private static final long serialVersionUID = 1L;

    @Inject
    private PropriedadesEmail propriedadesEmail;

    private String mailTo;
    private String mailCC;
    private String mailSubject;
    private String mailBody;

    public void sendMail() throws NegocioException {

        try{
            MimeMessage generateMailMessage = propriedadesEmail.mineMessage(); // new MimeMessage(getMailSession);

            generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(this.mailTo));
            if(this.mailCC != null)
                generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(this.mailCC));

            generateMailMessage.setSubject(this.mailSubject);
            generateMailMessage.setFrom(propriedadesEmail.getMailUsername());

            generateMailMessage.setContent(this.mailBody, "text/html");

            Transport transport = propriedadesEmail.getMailSession().getTransport("smtp");

            transport.connect( propriedadesEmail.getMailServerHost()
                                  ,propriedadesEmail.getMailUsername()
                                  ,propriedadesEmail.getMailPassword()
                                 );

            transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            System.out.println("-------- ERRO AddressException e "+e.getMessage());
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("-------- ERRO MessagingException e "+e.getMessage());
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        }

    }

    // ... Demais metodos e clases
}

Classe PropriedadesEmail
@ApplicationScoped
public class PropriedadesEmail implements Serializable{

    private static final long serialVersionUID = 1L;

    private String  mailServerHost;
    private String  mailServerPort;
    private String  mailEnableSsl;
    private String  mailEnableStarttls;
    private String  mailAuth;
    private String  mailUsername;
    private String  mailPassword;
    private Session mailSession;

    @PostConstruct
    private void init(){
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));
            mailServerHost      = props.getProperty("mail.server.host");
            mailServerPort      = props.getProperty("mail.server.port");
            mailEnableSsl       = props.getProperty("mail.enable.ssl");
            mailEnableStarttls  = props.getProperty("mail.enable.starttls");
            mailAuth            = props.getProperty("mail.auth");
            mailUsername        = props.getProperty("mail.username");
            mailPassword        = props.getProperty("mail.password");

            mailSession             = Session.getDefaultInstance(mailServerProperties(), null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador");
        }
    }

    public MimeMessage mineMessage() {
        return new MimeMessage(this.getMailSession());
    }

    private Properties mailServerProperties() {
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));

            Properties mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.port", this.getMailServerPort());
            mailServerProperties.put("mail.smtp.auth", this.getMailAuth());
            mailServerProperties.put("mail.smtp.starttls.enable", this.getMailEnableStarttls());

            return mailServerProperties;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador");
        }
    }

mail.properties
mail.server.host=smtp.gmail.com
mail.server.port=587
mail.enable.ssl=false
mail.enable.starttls=true
mail.auth=true
email@example.com
mail.password=*******************

Email retornado com o erro no gmail.

Mail Delivery Subsystem
Endereço não encontrado A mensagem não foi entregue para
  email@example.com porque o endereço não foi
  encontrado. Verifique se há erros de digitação ou espaços
  desnecessários e tente novamente.
A resposta do servidor remoto foi: 550 5.1.1
  : Recipient address
  rejected: User unknown in virtual mailbox table
Final-Recipient: rfc822; firstname.lastname@example.com
  Action: failed Status: 5.1.1 Remote-MTA: dns;
  mail2.transportesalvorada.com.br. (188.8.131.52, the server  for the
  domain transportesalvorada.com.br.) Diagnostic-Code: smtp; 550 5.1.1
  : Recipient address
  rejected: User unknown in virtual mailbox table Last-Attempt-Date:
  Wed, 08 Mar 2017 05:53:40 -0800 (PST)
Comment: Edite a pergunta e inclui o e-mail que o gmail te enviou. Hoje em dia até pra configurar o Outlook pra usar o Gmail precisa ir no gmail e dar permissão. Com a sua aplicação não deve ser diferente.
Comment: Enquanto está recebendo sua requisição de envio de email, o Gmail não acusa que o email destinatário é inválido porque ele não é inválido - ele apenas não existe no provedor de destino; por isso não há nenhuma exceção. E o email de fato é enviado para o email destinatário! O que ocorre a seguir é que o provedor do email destinatário identifica que o email não existe lá e então responde com outro email. Se você tentar informar um destinatário inexistente de Gmail, como é o próprio Gmail que está enviando ele tem como verificar isso no ato e provavelmente haverá exceção.
Comment: @Marcelo Vai ter que mudar a lógica do teu sistema de acordo com os teus requisitos. Por exemplo: você poderia não enviar senha mas sim deixar que a pessoa informe uma; daí você envia um email com um link incluindo um hash onde a pessoa clicando confirma que o email é dela mesmo, e só então o email se torna confiável para você enviar novas senhas no futuro se for o caso. Você pode monitorar respostas ao email enviado para ver se o provedor rejeitou, mas veja que isso não serve pra muita coisa porque a pessoa pode entrar, mesmo sem querer, com um email existente mas que não pertence a ela.
Comment: Qual *e-mail* inválido você está utilizando para teste? O `AddressException` ocorre durante o *parse* da `String` para criar um objeto `InternetAddress` se o formato do *pattern* do *email* for inválido, ou seja, nesse momento você ainda não está conectado  ao *gmail*. A exceção lançada quando não se encontra o destinatário é `SendFailedException` durante a execução do método `sendMessage` da classe `Transport`.
Comment: Quando utilizei o gmail para enviar emails, o próprio gmail não deixava uma "aplicação menos segura" acessar minha conta, tive que ir no gmail e desabilitar uma opção de segurança para deixar minha aplicação acessar a conta e enviar os emails.
Comment: Eu estou conseguindo enviar os emails. Meu problema é se o usuário informa um email invalido e o gmail não consegue enviar o erro AddressException por exemplo não é gerado.
Comment: Coloquei o SendFailedException como sugerido mas continuo não recebendo a exceção no sistema.
Só recebo um e-mail no próprio gmail informando o erro.
Comment: Pergunta editada como sugerido.
Comment: E existe alguma forma de tratar isso?
Comment: Mas mesmo deixando o usuário informar a senha enviando um link para confirmar cairia no mesmo problema.
De qualquer forma obrigado.
Answer: O problema em questão é o e-mail ser digitado errado. ( não que o e-mail seja inválido, ele simplesmente é um e-mail válido que não existe)

Uma coisa simples que você pode fazer que não resolve completamente mas pode
  minimizar que as pessoas digitem e-mail errado é pôr pra digitarem duas
  vezes e dar erro se os dois campos não estiverem iguais, além da verificação com expressão regular sobre a validade do e-mail.

De acordo com o e-mail que o Gmail te enviou, o e-mail firstname.lastname@example.com não existe.
Não deu erro porque o e-mail foi enviado corretamente. Só que pra um endereço que não existe.
Quando seu e-mail chegou no servidor do domínio transportesalvorada.com.br esse servidor olhou na tabela de e-mails e viu que esse e-mail não existia e enviou a resposta pro gmail falando que o mesmo não existia. A resposta foi pro gmail pq o e-mail enviado saiu do servidor de lá.
Se o carteiro leva uma carta pra uma residência em que o endereço está errado ela retorna pro remetente. Perceba que a carta foi enviada e quem enviou só ficou sabendo que o endereço estava errado depois que a carta voltou.
Se apenas fazer a pessoa conferir se está digitando certo não é suficiente, você pode tentar procurar algum serviço para validar e-mails antes de enviá-los. Segue um serviço: http://www.verifyemailaddress.org/email-verification-api.html
Testando no site http://www.verifyemailaddress.org/ vi que o e-mail firstname.lastname@example.com não existia, mas email@example.com existe.
Esse site envia um e-mail e inicia uma conversa entre servidores para verificar se o e-mail existe.
MX record found: mail2.transportesalvorada.com.br (Priority 5)
MX record found: mail3.transportesalvorada.com.br (Priority 5)
Connecting to mail2.transportesalvorada.com.br
Connected to mail2.transportesalvorada.com.br
Dialog with mail2.transportesalvorada.com.br ok
------------------------------------------------------------
220 mail3.transportesalvorada.com.br running OSTec Mail Server 3000
HELO verifyemailaddress.org
250 mail3.transportesalvorada.com.br
MAIL FROM: <email@example.com>
250 2.1.0 Ok
RCPT TO: <firstname.lastname@example.com>
250 2.1.5 Ok
QUIT
221 2.0.0 Bye
------------------------------------------------------------
Email address firstname.lastname@example.com accepted

Assuntos relacionados:
Comandos SMTP:
http://www.samlogic.net/articles/smtp-commands-reference.htm
Páginas relacionadas de pessoas que tentaram fazer essa validação de existência de um e-mail com Java com algum sucesso:
https://stackoverflow.com/questions/13514005/how-to-check-mail-address-is-exists-or-not
http://www.rgagnon.com/javadetails/java-0452.html
Answer: Temo que o único jeito de resolver esse problema seja acessar periodicamente os e-mails do Gmail e procurar pela mensagem de retorno.
E-mail é um protocolo que foi mais ou menos estabilizado na década de 1970, e não é um protocolo de tempo real. Os MTA (Mail Transport Agent), como os do Gmail, têm a liberdade de segurar o e-mail por tempo indeterminado e fazer várias tentativas de entrega antes de desistirem. Eles podem até fazer uma entrega indireta, mandando para outro servidor de e-mail, e esse outro ser o encarregado de entregar para o destinatário final (embora eu duvide que algum sistema funcione dessa maneira nos dias de hoje). Se funcionava com o seu servidor de e-mail próprio, é porque ele fazia uma tentativa de entrega imediatamente, e já retornava o erro em caso de falha. O Gmail não é assim, e o aviso de falha deles é feito por e-mail.


The multi-part identifier could not be bound - GROUP BY

Question: I'm pretty new to SQL. I have this code that works without the final GROUP BY line. With it, I receive the multi-part identifier could not be bound. I need to GROUP BY L1_DESC, L2_DESC and L3_DESC, but cannot figure out where to put this in the code.
SELECT * FROM (
SELECT d.*
,c.COL_DESC
--,v.VAL_N
,an.CUST_ACCT_NBR
,s.L1_DESC, s.L2_DESC, s.L3_DESC
FROM dbo.ECL_SEG101_DATA d
INNER JOIN (
SELECT SITE_ID
,max(SRC_BATCH_ID) AS SRC_BATCH_ID
FROM dbo.ECL_SEG101_DATA d
WHERE SRC_ID = 'K12'
GROUP BY SITE_ID) d1
       ON d1.SRC_BATCH_ID = d.SRC_BATCH_ID
       AND d1.SITE_ID = d.SITE_ID
INNER JOIN dbo.ECL_SEG002_EXT_DATA_VAR v
       ON d.SRC_BATCH_ID = v.LIST_ID
       AND d.SRC_REC_ID = v.ROW_ID
LEFT OUTER JOIN dbo.INS_REF006_ACCT an
          ON d.SITE_ID = an.LOC_KEY
INNER JOIN dbo.ECL_SEG101_SEGMENT s
      ON d.SITE_SEG_LVLS_ID = s.LVLS_ID
INNER JOIN dbo.ECL_SEG002_EXT_COL c
       ON v.COL_ID = c.COL_ID
WHERE d.Site_Data_Ord = '1') p
GROUP BY c.COL_DESC, an.CUST_ACCT_NBR, s.L1_DESC, s.L2_DESC, s.L3_DESC

Answer: You have aliased the subselect as p yet your GROUP BY references c., an. etc. None of these are valid aliases - only p. is.
Also you can't return * as the columns returned from d.* in the subselect are not part of the GROUP BY. You will need these to be aggregated somehow (COUNT, SUM etc.).
So you need:
SELECT p.COL_DESC, p.CUST_ACCT_NBR, p.L1_DESC, p.L2_DESC, p.L3_DESC
--, SOME_AGGREGATE_FUNCTION()
FROM (
    SELECT d.*
    ,c.COL_DESC
    --,v.VAL_N
    ,an.CUST_ACCT_NBR
    ,s.L1_DESC, s.L2_DESC, s.L3_DESC
    FROM dbo.ECL_SEG101_DATA d
    INNER JOIN (
        SELECT SITE_ID
        ,max(SRC_BATCH_ID) AS SRC_BATCH_ID
        FROM dbo.ECL_SEG101_DATA d
        WHERE SRC_ID = 'K12'
        GROUP BY SITE_ID) d1
    ON d1.SRC_BATCH_ID = d.SRC_BATCH_ID
    AND d1.SITE_ID = d.SITE_ID
    INNER JOIN dbo.ECL_SEG002_EXT_DATA_VAR v
    ON d.SRC_BATCH_ID = v.LIST_ID
    AND d.SRC_REC_ID = v.ROW_ID
    LEFT OUTER JOIN dbo.INS_REF006_ACCT an
    ON d.SITE_ID = an.LOC_KEY
    INNER JOIN dbo.ECL_SEG101_SEGMENT s
    ON d.SITE_SEG_LVLS_ID = s.LVLS_ID
    INNER JOIN dbo.ECL_SEG002_EXT_COL c
    ON v.COL_ID = c.COL_ID
    WHERE d.Site_Data_Ord = '1') p
GROUP BY p.COL_DESC, p.CUST_ACCT_NBR, p.L1_DESC, p.L2_DESC, p.L3_DESC


Find a real number $x$ such that $x^5 − x − 1 = 0$.

Question: Find a real number $x$ such that $x^5 − x − 1 = 0$.
I have already proven that such a number exists, I now try to find which number it is.
Comment: A real polynomial with odd degree has at least a real root.
Comment: [You can write the root as a nice-looking series](https://en.wikipedia.org/wiki/Bring_radical#Series_representation)
Comment: Do you know the notion of "Galois group"?  That is the concept to use to answer whether or not the solution can be expressed in terms of radicals.
Comment: Iteration tells me its approximate value is $1.167303978$ (I iterated $x_{n+1}=\sqrt[5]{x_n+1}, x_1=1$)
Comment: I'm voting to close this question because it's essentially answered already: you know there is a root. The comments tell you how to find a numerical approximation. There is no way to express that root with an expression involving roots and other algebra.
Comment: @EthanBolker Can you prove that it is impossible to express that root with an expression involving roots and other algebra? That would be an interesting answer. Is it impossible to find $x$ in any closed form?
Comment: There's a proof in example 4.17 here: http://www.math.uconn.edu/~kconrad/blurbs/galoistheory/galoisaspermgp.pdf
Answer: You can use numerical methods such as Newtons method .
Define $h(x) = x^5-x-1$
$h'(x) = 5x^4-1$
$x_{n+1} = x_n-\dfrac{h(x_n)}{h'(x_n)}$
$x_1 = x_0 - \dfrac{h(x_0)}{h'(x_0)}$
With $x_0 = 1$ we get the following;
$\begin{pmatrix}n&&&&x_n\\0&&&&1\\1&&&&1.25\\2&&&&1.178459\\3&&&&1.167537\\4&&&&1.167304\\\vdots\end{pmatrix}$
Comment: Right, so this defines a Cauchy sequence $x_n$ that converges to a real number that is the solution of $x^5-x-1$. If we take equivalence class of this Cauchy sequence, we have now successfully constructed the real number we were looking for.
Comment: yes , thats correct.
Answer: You can use an iteration to find its approximate value:
Rearrange for:$$x^5=x+1\to x=\sqrt[5]{x+1}$$
Then iterate:
$$x_{n+1}=\sqrt[5]{x_n+1}, x_1=1$$
Calculator accuracy gives me $x\approx1.167303978$


image processing toolbox already installed still Undefined function 'extractHOGFeatures' for input arguments of type 'uint8'

Question: I am executing the following code in matlab.
ver
img = imread('/usr/local/MATLAB/coursera_svm/10.pgm');
[featureVector, hogVisualization] =extractHOGFeatures(img);

output:
MATLAB Version: 220.127.116.117246 (R2015b)
MATLAB License Number:
Operating System: Linux 3.16.0-51-generic #69~14.04.1-Ubuntu SMP Wed Oct 7 15:32:41 UTC 2015 x86_64
Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
MATLAB           Version 8.6         (R2015b)
Computer Vision System Toolbox                        Version 7.0         (R2015b)
Curve Fitting Toolbox                                 Version 3.5.2       (R2015b)
Database Toolbox                                      Version 6.0         (R2015b)
Global Optimization Toolbox                           Version 3.3.2       (R2015b)
Image Acquisition Toolbox                             Version 4.10        (R2015b)
Image Processing Toolbox                              Version 9.3         (R2015b)
Neural Network Toolbox                                Version 8.4         (R2015b)
Optimization Toolbox                                  Version 7.3         (R2015b)
Parallel Computing Toolbox                            Version 6.7         (R2015b)
Signal Processing Toolbox                             Version 7.1         (R2015b)
Statistics and Machine Learning Toolbox               Version 10.1        (R2015b)
Symbolic Math Toolbox                                 Version 6.3         (R2015b)

Undefined function 'extractHOGFeatures' for input arguments of type 'uint8'.

Can some one please help me in solving this issue. Thanks.
Answer: extractHOGFeatures is a part of the Computer Vision System Toolbox, which you seem to have installed...  What do you see if you do
>> which extractHOGFeatures

If it tells you that extractHOGFeatures is not found, do this:
>> rehash toolboxcache

and try it again. If that doesn't work, there maybe a problem with the license for the Computer Vision System Toolbox. You may want to contact your system administrator, or call Mathworks tech support.
See the documentation for rehash toolboxcache.
Comment: Yes. It sounds like your institution or company has a limited number of floating licenses and they are all being used at the moment. Definitely check with your system administrator.
Comment: Sorry, it's "rehash", not "reset".
Comment: @Dima This is the output:

    /usr/local/MATLAB/R2015b/toolbox/vision/vision/extractHOGFeatures.m  % Has no license available

Does it mean, image processing tool is installed on my machine but doesn't have license ?


Organizing messages in user chat activity

Question: i have created a custom view holder for my app to position sent messages to the right and received messages to the left which is working.
when messages are sent or received they are positioned as expected but when the chat activity is closed and reopened both the sent and received messages are positioned to the left and given the same color.
how can i make it remain as it is even when the app is closed and reopened?
below is my MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter {
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
private FirebaseAuth mAuth;

private Context mContext;
private List<Messages> mMessageList;

public MessageAdapter(List<Messages> mMessageList) {
    //mContext = context;

    this.mMessageList = mMessageList;

}

@Override
public int getItemCount() {
    return mMessageList.size();
}

// Determines the appropriate ViewType according to the sender of the message.
@Override
public int getItemViewType(int i) {

    mAuth = FirebaseAuth.getInstance();

    String current_user_id = mAuth.getCurrentUser().getUid();

    Messages c = mMessageList.get(i);

    String from_user = c.getFrom();
    String message_type = c.getType();

    if (from_user == (current_user_id)) {

        return VIEW_TYPE_MESSAGE_SENT;

    } else {

        return VIEW_TYPE_MESSAGE_RECEIVED;
    }
}

    // Inflates the appropriate layout according to the ViewType.
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
        View view;

        if (viewType == VIEW_TYPE_MESSAGE_SENT) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_sent, parent, false);
            return new SentMessageHolder(view);
        } else if (viewType == VIEW_TYPE_MESSAGE_RECEIVED) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_message_received, parent, false);
            return new ReceivedMessageHolder(view);
        }

        return null;
    }

    // Passes the message object to a ViewHolder so that the contents can be bound to UI.
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
        Messages c = mMessageList.get(i);

        switch (holder.getItemViewType()) {
            case VIEW_TYPE_MESSAGE_SENT:
                ((SentMessageHolder) holder).bind(c);
                break;
            case VIEW_TYPE_MESSAGE_RECEIVED:
                ((ReceivedMessageHolder) holder).bind(c);
        }
    }

    private class SentMessageHolder extends RecyclerView.ViewHolder {
        TextView messageText, timeText;

        SentMessageHolder(View itemView) {
            super(itemView);

            messageText = (TextView) itemView.findViewById(R.id.text_message_body);
            timeText = (TextView) itemView.findViewById(R.id.text_message_time);
        }

        void bind(Messages message) {
            messageText.setText(message.getMessage());

            // Format the stored timestamp into a readable String using method.
          //  timeText.setText(Utils.formatDateTime(message.getCreatedAt()));
        }
    }

    private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
        TextView messageText, timeText, nameText;
        ImageView profileImage;

        ReceivedMessageHolder(View itemView) {
            super(itemView);

            messageText = (TextView) itemView.findViewById(R.id.text_message_body);
            timeText = (TextView) itemView.findViewById(R.id.text_message_time);
        }

        void bind(Messages message) {
            messageText.setText(message.getMessage());

        }
    }
}

and my ChatActivity.java
 LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View action_bar_view = inflater.inflate(R.layout.child_custom_layout,null);
    actionBar.setCustomView(action_bar_view);

    mTitleView = findViewById(R.id.custom_bar_title);
    mLastSeenView = findViewById(R.id.custom_bar_seen);
    mProfileImage = findViewById(R.id.custom_appbar_image);
    mChatAddBtn = findViewById(R.id.chat_add_btn);
    mChatSendBtn = findViewById(R.id.chat_send_btn);
    mChatMessageView = findViewById(R.id.chat_message_view);

    mChatAddBtn.setVisibility(View.INVISIBLE);
    mChatAddBtn.setEnabled(false);

    mTitleView.setText(userName);

    mAdapter = new MessageAdapter(messagesList);

    mMessagesList = findViewById(R.id.messages_list);
    mRefreshLayout = findViewById(R.id.message_swipe_layout);
    mLinearLayout = new LinearLayoutManager(this);

    mMessagesList.setHasFixedSize(true);
    mMessagesList.setLayoutManager(mLinearLayout);
    mMessagesList.setAdapter(mAdapter);

  //  loadMessages();

    mImageStorage = FirebaseStorage.getInstance().getReference();

    mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);

    loadMessages();

Comment: If you consider at some point to try using [Cloud Firestore](https://firebase.google.com/docs/firestore/), here you can find a tutorial on how to can create a functional [Chat App](https://www.youtube.com/playlist?list=PLn2n4GESV0Ak1HiH0tTPTJXsOEy-5v9qb). However, you can take a look to see how the adapter and the holder class are created where such a problem does not exist.
Comment: When you are reopening the activity, did you check if your getItemViewType is returning correct value?
Comment: @Seeker how do i do that
Comment: @Eric Well, you will have to debug or at least print some logs using android.util.Log
Answer: Here is the problem in the code
if (from_user == (current_user_id)) {

    return VIEW_TYPE_MESSAGE_SENT;

} else {

    return VIEW_TYPE_MESSAGE_RECEIVED;
}

You are checking equivalency with ==. This is not the right way of checking string equivalency. If you want to check equivalency you need to call equals() method of string as mentioned in below code.
if (from_user.equals(current_user_id)) {

return VIEW_TYPE_MESSAGE_SENT;

} else {

return VIEW_TYPE_MESSAGE_RECEIVED;
}

Try this. Hope this will help you.


How to send monthly newsletter if the site is complex and has a lot of content types?

Question: I want to send monthly newsletter to subscribers via Drupal. The website has lots of content types (news, events, books, courses, blog posts etc.). If the site has only one content type it would be easy to prepare this newsletter with Simplenews module or Mailchimp etc.
Because the site is so complex and needed to create some specific views for each content type I wonder if is it better to prepare custom newsletter manually (without Drupal interface) or is there any solution to send newsletter via Drupal interface, "easily" and automatically?
Answer: There are a plethora of newsletter generation modules in various states of support. But if you want a first class newsletter that your audience reads you almost certainly want to take the time to write and layout the newsletter in a tool meant for the job (Mailchimp's interface or a competitor).
Newsletter generators are very appealing and can be effective if you have lots of very targeted segmentation of your list. But most of the time if you are sending one news letter to the entire list they are more overhead than value.
Most of the use cases people look to a generator to support are signs of a poor communications strategies. For example: I want to send a daily newsletter about XYZ and don't have the time to write it carefully every day -- does your audience want get and read that much auto-generated mail? Or Laying out my message is too hard to get it right every time -- use a better email newsletter tool that does the job better.


Is it possible or/and how to restrict access to the block on th certain page using route name?

Question: I am trying to restrict access to the block to be accessible only on the route:entity.user.canonical route.
Is it possible to define that on the block edit form?
Answer: There is no UI for it, but you can either write your own condition plugin to do that or implement hook_block_access() like this:
function yourmodule_user_block_access(BlockInterface $block, $operation, AccountInterface $account) {

  $hidden_blocks = ['yourtheme_block_id'];
  $hidden_routes = ['entity.user.canonical'];

  if ($operation == 'view' && in_array($block->id(), $hidden_blocks) && in_array(\Drupal::routeMatch()->getRouteName(), $hidden_routes)) {
    return AccessResult::forbidden();
  }
}


How do I generate a tweet with cell values and conditional statements in Google Sheets?

Question: I'm trying to generate a tweet using a bunch of values in google sheet.
My question is how do I put multiple cell values in a paragraph with conditional statements
This is my tweet format.
(newline)Trade Scalp =IF(E1 = 'LONG' OR 'LONG IDEA' THEN 'Long' ELSE IF E1='SHORT' OR 'SHORT IDEA' THEN 'Short) ${G1}
(newline)
(newline)Entry Price: ${H1}
(newline)Stop Loss: ${I1}
(newline)Take Profit: ${M1}
(newline)R/R Ratio: as much as {J1}
(newline)
(newline)#bitcoin #btc
Comment: Hi, this question is closed 6 hours ago due lack of [details or clarity](https://stackoverflow.com/help/closed-questions), Please take a look at [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), include your sheet or images of input and desired output, to make answers informed, precise and easy form the community.
Answer: Here is a formula that will format it how you are asking:
="Trade Scalp "&if(n(REGEXMATCH(upper(E1), "LONG"))>0, "Long", "Short")&" "&G1
&CHAR(10)&
""
&CHAR(10)&
"Entry Price: "&H1
&CHAR(10)&
"Stop Loss: "&I1
&CHAR(10)&
"Take Profit: "&M1
&CHAR(10)&
"R/R Ratio: as much as "&J1
&CHAR(10)&
""
&CHAR(10)&
"#bitcoin #btc"

CHAR(10) inserts a line break.
Comment: Works excepts for the regex
Comment: @JohnnyCash I fixed my formula to make the regex independent of case
Comment: It's still always Long even if E1 is Short. Possible values are Long, Long Idea, Short, Short Idea
Comment: @JohnnyCash ohhh my bad, I found my issue. Answer has been updated. Sorry about that!
Comment: Make sure to upvote [helpful questions](https://stackoverflow.com/a/73026320/19529694)
Answer: If you want to get a list of the tweets meanig in batch.
addition to the answer of @kaitlynmm569, but in this case no conditional statement no REGEXMATCH

paste this formula in H2 and drag down.

=IF(B2="",,CONCATENATE(CONCATENATE(B$1,": ",B2," ","g1"),CHAR(10),CHAR(10),JOIN(CHAR(10),TRANSPOSE(ArrayFormula(CONCAT(CONCAT(C$1:F$1,": "),C2:F2)))),CHAR(10),CHAR(10),CONCATENATE(G$1,": ",G2)))

You will get a result like this take a look at this sheet.

Steps...
1 - CONCATENATE the header in B1 "Trade Scalp" and a cell from the same column with ": " in between and "g1".
2 - CONCATENATE that with CHAR(10) which is a line break, and one more CHAR(10).
3 - CONCAT(CONCAT(C$1:F$1,": "),C2:F2) and JOIN it with CHAR(10) to get the tweet body.
4 - Add anther line breake with CHAR(10),CHAR(10).
5 - CONCATENATE the Header "Tags" with Cell of its columns like this CONCATENATE(G$1,": ",G2)
6 - Lastly CONCATENATE everything and wrap it with IF function to calculate only when not empty like this =IF(B2="",,CONCATENATE([ Previous formulas ]).
Comment: @JohnnyCash Make sure to upvote helpful questions, to benefit the responders.


What is a quantizing percentage?

Question: In certain DAWs  (such as Reason) and music production stations there's a quantization percentage.
I understand quantization, it's like auto-tune for rhythm.  That is, quantization adjusts the beats of a piece of music so that the beats regularly occur.
What I don't understand is the "percentage" aspect.  I get that quantization at 100% means that the beats will be exactly regular.  But what does 10%, 50% or 90% quantization mean exactly?
Comment: It's explained in the manual! :) I just checked it and there it is.
Answer: Quantizing percentage means how much closer to the quantization grid's perfect timing position the timing (position and/or length) of notes is moved.

0% : the timing is not changed at all. It's a no-change operation.
10% : the timing is moved 1/10 the way from its current position towards the exact quantization grid value closest to the current position.
50% : the timing is moved to halfway between where it is before quantization and the exact quantization grid value closest to the current position.
100% : the timing is moved all the way to the closest quantization grid value

Try it: quantize by 10%. Quantize again. Quantize again. Etc. You'll notice that the notes are nudged closer to the grid every time.
However, you might encounter the word quantization percentage (or Amount as it's called in Reason) in two different kinds of functions: destructive and non-destructive quantization.

Destructive quantization changes the stored data in the MIDI (or audio) tracks. It's a "Quantize this now" operation that the user performs, and which can usually be undone with an "undo" operation immediately after performing the operation. Usually this means that when you perform such a destructive operation, you see the notes move in the MIDI (or audio) editor.
Non-destructive quantization changes timing transparently, "on the fly", all the time as the sequence is playing. You can change the quantization amount to 100% and the notes will play back as if they had been quantized 100%, but they will still remain in their original timing locations in the stored MIDI data. You can change the amount to 0%, and the notes will start playing back in their un-quantized original way. Then to 50% ... and back to 0% etc. The note data will retain their original timing all the time. You probably won't see the notes move anywhere in the MIDI editor as you change the non-destructive quantize amount. (though it's possible that a sequencer could show the timing like it would sound when played back)

In Reason and Ableton Live there's a feature called Groove, which works as non-destructive quantization. In Ableton you can do an "Apply Groove" operation, which destructively bakes the groove into the note data.
Answer: notes that fall off the grid that are then quantized to 100% will then fall exactly on the grid.  If you quantize to less than 100% they will move closer to the grid but retain some of the, let's call it, character of the performance. The lower the percentage the closer to the original performance it will sound. The higher the percentage the closer to the grid it will be.

What is a quantizing percentage?


godaddy centos server nginx and apache running simultaneously

Question: Ive got a godaddy centos server running a few domains on apache.
I now need to install a new domain which will host an app and requires Nginx service.
Can I run both of these webservers off the same dedicated server? I would need 2 ips no?
How might I proceed? Any insight is appreciated.
thanks,
Comment: Remember to mark your questions as answered when you find the solution that works for you.
Answer: There are two options for this to work you will need to bind both apache and nginx to their own IP address.  So for instance in the httpd.conf file you will need to list a specific IP such as Listen 192.168.1.1:80
The article listed below explains how to bind both nginx and apache as well as explains using nginx behind apache by setting up virtual hosts
For more information check this site out
Answer: An alternative is to use VirtualHosts, and have apache proxy the new domain to Nginx, which listens on another port (eg 8080). This way, you don't necessarily need a second IP address.
Example config:
LoadModule proxy_module /path/to/mod_proxy.so
LoadModule proxy_http_module /path/to/mod_proxy_http.so

NameVirtualHost *
<VirtualHost *>
    ServerName some.existing.domain.com
    ProxyRequests Off
    # ... config for domain ...
</VirtualHost>
<VirtualHost *>
    ServerName new.domain.com
    ProxyRequests Off

    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/
</VirtualHost>


Relação 2 tabelas contas a pagar e a receber - Só aparece a soma de contas a pagar se recebido

Question: Estou com uma certa dificuldade em obter um resultado esperado via SQL.
Talvez o mesmo, só possa ser solucionado via linguagem de programação, mas resolvi postar na expectativa de que alguém possa me ajudar em uma falta de conhecimento da minha parte.
Eu tenho uma pagina de contas a receber e outra de contas a pagar.
Na pagina de contas a pagar, só pode aparecer na tela os registros de contas a pagar, caso a conta referente esteja como recebida na tabela de contas a receber, ou seja, não quero que aparece todos os registros de contas a pagar, pelo menos nesta pagina especifica.
Criei a seguinte SQL e o resultado é o esperado:
SELECT p.valor, p.id_imovel, p.data_vencimento
FROM contas_a_pagar AS p
INNER JOIN contas_a_receber AS r ON r.data_vencimento=p.data_vencimento
WHERE r.recebido=1

Porem gostaria de deixar este resultado mais enxuto, trazendo os valores de contas a pagar somados e com o valor de aluguel recebido, pois a intenção e subtrair os valores e mostrar o que sobrou(receita)
SELECT SUM(p.valor) AS despesas, r.valor AS valor_aluguel, p.id_imovel, p.data_vencimento
FROM contas_a_pagar AS p
INNER JOIN contas_a_receber AS r ON r.data_vencimento=p.data_vencimento
WHERE r.recebido=1
GROUP BY p.id_imovel

Estou usando o phpmyadmin para fazer os testes acima e o mesmo não causou nenhum erro, porem usando um editor/console online houve um erro ao utilizar a função SUM()
Mas blz, até ai tranquilo.
O problema é que o valor de aluguel que deveria ser de 4.000 no id_imovel=2 esta como 3.000.
Os valores de despesas estão corretos 1.500 para o id_imovel=1 e 1.700 para o id_imovel=2 o problema esta no valor de aluguel que esta errado.
O mesmo seria utilizado para fazer um calculo de subtrair EX: 1.500 - 4000 = 2.500
Imagem do resultado via phpmyadmin
https://postimg.cc/vc18xKqn
Paiza - Mysql Online
https://paiza.io/projects/hO4XodwbhL5xoN34BkteLg?language=mysql
Comment: não pode trazer um resultado "agregado" (`sum`) e outro não agragado, ou traz tudo com soma, media, etc ou o resultado não bate.
Imagina que na sua tabela tem 10 valores 1 a 10 por exemplo, e faz um `select sum(valor), valor from ... where ... group by campo` como o banco pode trazer hora uma soma agrupada por um campo, hora os valores separados?  isso gera confusão. Se tem `SUM(p.valor)` também deveria ter `SUM(r.valor)`, e a data assim como o id_imovel deveria estar no group by
Comment: Levei um tempinho para entender este 0 de despesa e receita, e o pq de fazer um union em uma subconsulta. Seu comentário foi perfeito, obrigado pela ajuda em me fazer enxergar o pq do problema, fico agradecido.
Comment: Você ainda pode melhorar gerando uma sequencia artificsl de datas com valores zerados para os casos de dias sem a duplak ocorrência.
Comment: Entendi. O mesmo esquema do zero de valores, porém para as datas. Obrigado
Answer: --tente algo assim
select sum(despesas) despesas, sum(receitas) receitas,id_imovel,data_vencimento
from
(
SELECT SUM(p.valor) AS despesas, 0 receitas,p.id_imovel, p.data_vencimento
FROM contas_a_pagar AS p
union all
SELECT 0 despsas ,SUM(R.valor) AS receitas, r.id_imovel, r.data_vencimento
FROM   contas_a_receber AS r ON r.data_vencimento=p.data_vencimento
WHERE r.recebido=1
) virtual
GROUP BY virtual.id_imovel,virtual.data_vencimento

Comment: Só tive um problema com a palavra virtual, me parece que a mesma é reservada, pela base de dados em alguma outra função, acabei por utilizar teste.


Actually calculating an Intersection of Variety and Divisor

Question: This has been bugging me for a while now.
Say I have a projective variety given by some polynomial $P$ and the canonical divisor of the projective space. How can I concretly calculate the Intersection of the two?
And by concretly I mean, actually get a result that is not purely abstract? (Like actual Intersection points, degree, etc...)
Comment: If I'm interpreting your question correctly, then you have two homogeneous ideals and can add them together to get the intersection of your two subschemes. Perhaps I am completely missing the point of your question though..
Answer: Unfortunately, you will run into a basic difficulty in your desire to make this example concrete, which is that the canonical bundle on projective space is anti-ample, and so the canonical bundle is not effective.  (Rather, it is its dual that is an effective divisor.)
More precisely, if $H$ is the linear equivalence class of a hyperplane in $\mathbb P^n$, then the canonical divisor $K$ is equal to $-(n+1)H$.
So if you want to intersect $K$ with $V(P)$ (the variety cut out by the polynomial $P$) you will have to use at least a little bit of theory, even if only to interpret what you are doing.
You might be better of starting with $H$ itself.  Then $H \cap V(P)$ is the linear equivalence class of a hyperplane section of $V(P)$.  Assuming that $V(P)$ is smooth, then Bertini's theorem says that a generic member of the linear equivalence class $H\cap V(P)$ will be smooth, and even irreducible if the dimension of $V(P)$ is at least two (i.e. if $n \geq 3$).
Then one way to write $K \cap V(P)$ is simply as $-(n+1) \bigl( H \cap V(P) \bigr)$.
Alternatively, one could consider the linear equivalence class $(n+1)\bigl( H \cap V(P)\bigr).$  This is the class of intersections of $V(P)$ with a degree $n+1$ hypersurface, and again a generic member is smooth (and irreducible if $V(P)$ is of dimension at least $2$).  Then you think of $K \cap V(P)$ as being
the negative of this class.
Comment: @FMN: Dear FMN, Yes, thanks for pointing out this misstatement!  Regards,
Comment: Thanks alot, once again! I was wondering, did you mean Bertini's Theorem instead of Bezout?
Answer: This is more of a comment than an answer (but I cannot comment yet). Isn't it the case that "the" canonical divisor is any divisor representing the linear equivalence class of the canonical bundle? We would get intersection points only after choosing a representative (and coordinates), and the points may depend on our choice. Only the intersection class (in a Chow ring) should be intrinsic, I think. I would appreciate hearing more on this too!
Comment: @jrajchgot: Dear jrajchgot, There is no "specific divisor"; no one member of the canonical divisor class is any more specific than any other.  What's worse (from the point of view of making things concrete), in the particular case of projective space, there are no effective members of this divisor class at all.   Regards,
Comment: @jrajchgot: Dear jrajchgot, You could say "a canonical divisor" (with "a" instead of "the" to indicate that it is just one of many possible choices), but to be safe I might write something like "let $D$ be a representative of the canonical divisor class" if I really needed a specific choice.  On the other hand, often people write "let $K_X$ be the canonical divisor" and treat $K_X$ as a specific divisor rather than a class of such (e.g. in Riemann--Roch calculations), but this is fine as long as everything that follows is invariant with respect to replacing a divisor by a linear equivalent ...
Comment: As far as I know, there are three types of objects to consider; sections of the canonical sheaf, canonical divisors, and canonical divisor classes. I think that you're right that often times people say "the canonical divisor" to mean the divisor class, but I think FMN's question is about the specific divisor, and not its class.
Comment: Dear Matt, What term would you use to refer to a specific representative of the class (in order to avoid ambiguity)? I have, until now, been using "canonical divisor" (vs. "divisor class") but perhaps this is dangerous..
Comment: ... one (but *only* if this invariance holds!).  Regards,


The probability of one Gaussian larger than another.

Question: For two Gaussian-distributed variables, $ Pr(X=x) = \frac{1}{\sqrt{2\pi}\sigma_0}e^{-\frac{(x-x_0)^2}{2\sigma_0^2}}$ and $ Pr(Y=y) = \frac{1}{\sqrt{2\pi}\sigma_1}e^{-\frac{(x-x_1)^2}{2\sigma_1^2}}$. What is probability of the case X > Y?
Comment: Are $X$ and $Y$ independent? And I don't agree when you write $Pr(X=x)=\dots$: the probability that a Gaussian random variable take a particular value is $0$ (but we can write $P(X\in A)=\int_A$ of the function you wrote).
Comment: What do you know about $X-Y$ ?
Comment: If $X > Y$ what can you say about $X-Y$?
Comment: Yes, do we have a name for this?
Comment: A name for *what*?
Comment: @Strin: [Probability density function](http://en.wikipedia.org/wiki/Probability_density_function)?
Comment: @DavideGiraudo: You are quite right, but this is a common abuse of notation.
Comment: @Nate: A common abuse of notation, to write $P(X=x)=f(x)$ to mean that $f$ is the density of $P_X$ with respect to Lebesgue measure? If you wish to indicate that we should not pay attention, I disagree. But this a too common **error**, yes.
Comment: @did: Many otherwise reputable textbooks use this notation deliberately.  I personally don't like it either since it is, as you say, also a common error.  But I just wanted to point out that someone who writes $P(X=x)$ for a density is not *necessarily* confused.
Comment: @Nate: *Many otherwise reputable textbooks use this notation deliberately*... OK. (But not in the part of the world where I live.) Any examples?
Answer: Suppose $X$ and $Y$ are jointly normal, i.e. no independence is needed. Define $Z = X - Y$. It is well known that $Z$ is Gaussian, and thus is determined by its mean $\mu$ and its variance $\sigma^2$.
$$
   \mu = \mathbb{E}(Z) = \mathbb{E}(X) - \mathbb{E}(Y) = \mu_1 - \mu_2
$$
$$
  \sigma^2 = \mathbb{Var}(Z) =  \mathbb{Var}(X) +  \mathbb{Var}(Y) - 2 \mathbb{Cov}(X,Y) = \sigma_1^2 + \sigma_2^2 - 2 \rho \sigma_1 \sigma_2
$$
where $\rho$ is the correlation coefficient. Now:
$$
    \mathbb{P}(X>Y) = \mathbb{P}(Z>0) = 1- \Phi\left(-\frac{\mu}{ \sigma}\right) = \Phi\left(\frac{\mu}{ \sigma}\right) = \frac{1}{2} \operatorname{erfc}\left(-\frac{\mu}{\sqrt{2}\sigma}\right)
$$
Comment: I believe the $\sqrt{2}$ should not appear in the standard CDFs, at the last line.
Answer: I assume that $X$ and $Y$ are independent. Let $Z=X-Y$ then $Z\sim\cal{N}(x_0-y_0,\sigma_0^2+\sigma_1^2)$. Accordingly
$$P(Z>0)=\int_0^\infty\frac{1}{\sqrt{2\pi(\sigma_0^2+\sigma_1^2)}}\exp\left(\frac{-(z-x_0+y_0)^2}{2(\sigma_0^2+\sigma_1^2)}\right)\mathrm{d}z$$
if we use the complementary error function
$$\operatorname{erf}c(x)=\frac{2}{\sqrt\pi}\int_x^\infty e^{-t^2}dt$$
with $t=\frac{z-x_0+y_0}{\sqrt{2(\sigma_0^2+\sigma_1^2)}}$, we have $\sqrt{2(\sigma_0^2+\sigma_1^2)}dt=dz$
$$P(Z>0)=\frac{2}{2\sqrt{\pi}\sqrt{2(\sigma_0^2+\sigma_1^2)}}\int_{t=\frac{y_0-x_0}{\sqrt{2(\sigma_0^2+\sigma_1^2)}}}^\infty e^{-t^2}\sqrt{2(\sigma_0^2+\sigma_1^2)}dt$$
and we get finally
$$P(Z>0)=\frac{1}{2}\operatorname{erfc}\left(\frac{y_0-x_0}{\sqrt{2(\sigma_0^2+\sigma_1^2)}}\right)$$
Comment: Which has the odd feature of not being $1/2$ when $x_0=y_0$. I suggest to review this answer, especially the change of variable.
Comment: Ok I found the mistake. Updating.
Comment: Well, there still seems to be something wrong.The odd feature noted by @did still persists: the probability is not $1/2$ when $x_0 = y_0$ and worse yet, the right side is negative when $x_0 > y_0$ and so definitely cannot be a probability. Did you mean to write erfc instead of erf in your final answer?
Comment: Yes it has to be erfc of course. It is obvious in the text. Proof is correct.


variable in ajax call holding old data

Question: I have the following code which I'm trying to use as an ajax load more feature on displaying wordpress / woocommerce posts but the value of 'cat' always seems to stay on the first value it gets.
Do i need to delete it each time or something similar so it starts holding the correct 'cat' ?
var ppp = 4; // Post per page
var pageNumber = 1;

$(".et-load-more").on("click", function(e) {
  e.preventDefault();
  var cat = $('.et-load-more').data('category');
  pageNumber++;

  $.ajax({
    cache: false,
    url: nanook_ajax_obj.ajaxurl,
    data: {
      'action':'more_post_ajax',
      'cat' : cat,
      'ppp' : ppp,
      'page' : pageNumber
    },
    success: function(html, data) {
      $(".products").append(html);
    },
    error: function(errorThrown) {
      console.log(errorThrown);
    }
  });
});
});

And the function from functions.php
function more_post_ajax(){

        $ppp = (isset($_POST['ppp'])) ? $_POST["ppp"] : 4;
        $page = (isset($_POST['page'])) ? $_POST['page'] : 2;
            $cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => $ppp,
            'cat' => $cat,
            'paged'    => $page
        );

        $loop = new WP_Query($args);
            $postcount = $loop->max_num_pages;
        $out = '';
            ?>

            <?php

            echo $postcount;
        if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
            $out .= wc_get_template_part( 'content', 'product' );

        endwhile;
            ?>

        <?php
        endif;
        wp_reset_postdata();
        die();
    }

    add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
    add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

And heres the visual composer element code :
// Product Grid
function productgrid_func( $atts ) {

 ob_start();
   extract( shortcode_atts( array(
  'nanook_extra_class' => '',
 ), $atts ) );

?>

         <?php
             $postsPerPage = 8;
                         $cat = '';
             $args = array(
                     'post_type' => 'product',
                     'posts_per_page' => $postsPerPage,
                     'product_cat' => $cat
             );

             $loop = new WP_Query($args);
                         $cat_id = $cat;

                         ?>

<?php echo 'All'; ?>
                            <?php $wcatTerms =
get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0));
                                            foreach($wcatTerms as
$wcatTerm) :
                                            ?>
                                                    <a class="cat-trigger" href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>"><?php echo $wcatTerm->name; ?>
                                            <?php endforeach; ?>

                                Filter

                        <?php
             while ($loop->have_posts()) : $loop->the_post();
                ?>
                        <?php $output .= wc_get_template_part( 'content', 'product' );
             endwhile;
                        ?>

                    <?php

          ?>

            Load More

add_shortcode( 'productgrid', 'productgrid_func' );
add_action( 'vc_before_init', 'productgrid_integrateWithVC' );

Comment: Are you updating the value of `$('.et-load-more').data('category')` anywhere?
Comment: What you are describing as the problem can't be the problem. The selector must be returning a collection of elements where the first element always has the same data value. Adding a .last() to the chain might bandaid the problem, but likely best option would be to properly remove old load more elements.
Comment: Yes the  $('.et-load-more').data('category')  is being updated and shows correct before pushing the load more button so im not sure why its still getting the old data
Comment: is it being updated, or replaced.
Comment: Updated i believe
Comment: Don't pick value from data-* attribute. You can use like this **var cat = $('.et-load-more').attr('data-category');**
Answer: You need to get the instance of that class that you are interacting with. Within an event handler this will be the element instance from the matching selector
Change
var cat = $('.et-load-more').data('category');

To
var cat = $(this).data('category');

What is happening is when you use $('.et-load-more').data('category'); it looks for all that class in page. But it can only return one value, so it takes it from the first
Comment: Thanks but its still stuck on the first value each time i click it. There is only one of them on the page. i will add the actual function to the post.

variable in ajax call holding old data


How do I find or set the apropriate form for base scheme fields?

Question: In my custom entity I want to set a base scheme field, which is an integer. The field has a minimum of 0, a maximum of 360 and a default of 180.
I tried this so:
<code>    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setSettings(array(
    'default_value' => 180,
    'min_value' => 0,
    'max_value' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'default',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
    'settings' => array(
      'default_value' => 180,
      'min' => 0,
      'max' => 360
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);
</code>
Neither the form is limited nor the input is limited when I post.
How can I get the correct type for my form and the correct settings? How can I look for them? Where?
Edit: solution is the following:
<code>    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setDefaultValue(180)
  ->setSettings(array(
    'min' => 0,
    'max' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'number_integer',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);
</code>
Comment: You should take the answer out of the question and add it as an answer.  This is a good answer.
Answer: You can always create a field with the desired settings in the field, widget and formatter settings in the UI. Then export the configuratio and use the settings from there. The field settings are in two files:

field.storage.entity_type.yourname.yml
field.field.entity_type.bundle.yourname.yml

For base fields, you can merge the settings together into a single array.


How to pass a matrix as a list of vectors in a cartesian product in python

Question: I'm trying to create a combinatorics matrix from a series of vectors. If I wanted all vectors to be included in the combination I would use:
CombinatoricsMatrix = list(itertools.product(vector1, vector2, ...)

or
CombinatoricsMatrix  = cartesian((vector1, vector2))

such that if
vector1 = [a]
vector2 = [1,2]
CombinatoricsMatrix  = cartesian((vector1, vector2))
CombinatoricsMatrix = [a,1; a,2]

However, there are some matrices that I want to pass as 'a list of vectors' so that the elements of those vectors are not included in the combination.
For example if
matrix3 = [w,x; y,z]

the desired output is
CombinatoricsMatrix  = cartesian((vector1, vector2, matrix3 ))
CombinatoricsMatrix = [a,1,[w,x]; a,1,[y,z]; a,2,[w,x]; a,2,[y,z]]

Any ideas? Note that the length and amount of vectors were kept short for the example.
Answer: There are likely more pythonic ways to do this but one solution is to zip the matrices such that
CombinatoricsMatrix  = list(itertools.product(vector1, vector2, zip(matrix3))


How to load a second user log in form?

Question: I have used default user login block on top navigation. I need to load another log in form on some pages.
I am trying to load the form by
drupal_get_form('user-login')

I get the following error:

Notice: Undefined index: user-login in drupal_retrieve_form() (line
  763 of /path/to/drupal/includes/form.inc). Warning:
  call_user_func_array() expects parameter 1 to be a valid callback,
  function 'user-login' not found or invalid function name in
  drupal_retrieve_form() (line 798 of
  /path/to/drupal/includes/form.inc).

Is it possible to load a second log in form? (Drupal 7)
Comment: Do you mean you want two log-in blocks/forms on the same page?
Comment: Yes, One is on top navigation on all pages. Second one will be on some pages where there is a password protected content.
Comment: You can use the LoginToboggan module if you want to show a login form when users do not have appropriate permission.  Just check the setting for "show login form on access denied."  http://drupal.org/project/logintoboggan
Answer: The key point in the error message is:

...expects parameter 1 to be a valid callback, function 'user-login' not
  found

You need to use:
drupal_get_form('user_login');

Where user_login is the form builder function in this case.
e.g:
print render(drupal_get_form('user_login'));

How to load a second user log in form?


calculate the pourcentage of the difference between two elements in array

Question: I want to render the percentage of the different data between two array elements (between two totals). How to do that?
//...
const [perc, setPerc] = useState(0);

const res = await userRequest.get("orders/income");
setPerc((res.data[1].total * 100) / res.data[0].total - 100);
console.log(res.data);

return(

{perc}%

)

clg res.data shows:
0: {_id: 11, total: 20}
1: {_id: 12, total: 60}

The expected percentage from this data is 33%
The actual percentage is 60%
Comment: Actually `60 * 100 / 20 - 100 = 200`. I think you need to swap `0` and `1` indices and remove `-100`.
Comment: didn't work @sagi
Answer: I think you only need to remove the -100 at the end of your setPerc
And if you want the % of the first element relative to the second you also need to swap to [0] and [1]
Comment: thank you so much,  i dont even remember from where -100 comes from!
Comment: hmm weird, i'm sure this should work , i swap [0] and [1] but i'm getting now 49% not 33%


Closedness of Finitely Generated Cones

Question: It is the exercise 4.37 from "Introduction to Linear Optimization" by Bertsimas.
Let $\textbf{A}_1$, ..., $\textbf{A}_n$ be given vectors in $\mathbb{R}^m$. Consider the cone $C=\{\sum_{i=1}^n \textbf{A}_ix_i\mid x_i\geq 0\}$ and let $\textbf{y}^k, k=1,2,\dots$ be a sequence of elements of $C$ that converges to some $\textbf{y}$. Show that $\textbf{y}\in C$ (and hence $C$ is closed), using the following argument. With $\textbf{y}$ fixed as above, consider the problem of minimizing $\parallel\textbf{y}-\sum_{i=1}^n\textbf{A}_ix_i\parallel_\infty$, subject to the constraints $x_1,\dots,x_n\geq 0$. Here $\parallel\cdot\parallel_\infty$, stands for the $\parallel\textbf{x}\parallel_\infty=\max_i\mid x_i\mid$. Explain why the above minimization problem has an optimal solution, find the value of the optimal cost, and prove that $\textbf{y}\in C$.
In other words, I have to prove that for $A\in\mathbb{R}^{m\times n}$ then the set $E=\{Ax\mid x\in\mathbb{R}_{\geq 0}^n\}$ is closed in $\mathbb{R}^m$.
I understand why the optimal value is $0$. But I have no idea about how to prove that the minimization problem has optimal solution.
I want to use the exercise to prove the Farkas' lemma and so the Strong Duality, so I do not want to use any of them in the exercise. Is it possible to use only the Wierstrass theorem about continuous functions and at worst the particular case of the Separating Hyperplane Theorem for point versus nonempty closed convex set? Given a $y$ in the closure of $E$, I tried to use the following continuous function $x\mapsto$ $\parallel y-Ax\parallel_\infty$ and to find a compact domain that is a subset of $\mathbb{R}_{\geq 0}^n$ to find a minimum point, but I was not able to solve it.
Comment: see also this thread https://math.stackexchange.com/questions/1165286/why-are-convex-polyhedral-cones-closed
Comment: and this https://math.stackexchange.com/questions/1831401/how-do-you-prove-that-ax-mid-x-geq-0-is-closed?noredirect=1&lq=1
Answer: If $P$ is a polyhedron, then set set $Q=\{Ax|x \in P\}$ is also a polyhedron.
Here our $P$ is $\{x \in \mathbb{R}^n|x \ge 0\}$ and our $Q$ is  $E$.
Polyhedron are intersection of  halfspaces, which are closed. Hence $E$ is closed.
Comment: Ok, but why is $Q$ a polyhedron? I know it looks like intuitive but a proof of it is not so trivial to me. I know a polyhedron is a set of the form $P=\{x\in\mathbb{R}^n\mid Ax\leq a\}$, where $A\in\mathbb{R}^{r\times n}$ and $a\in\mathbb{R}^r$, but if $M\in\mathbb{R}^{m\times n}$, what are examples of new $A'$ and $a'$ such that the set $Q=\{Mx\mid x\in P\}$ is of the form $\{x\in\mathbb{R}^m\mid A'x\leq a'\}$, or at least how to prove that $Q$ is a polyhedron?
Comment: I don't have the book that you mentioned with me now but from memory, flip to the summary page of chapter $2$, look at the page just before that. It is a theorem (or perhaps corollary)  proven in the book.

Closedness of Finitely Generated Cones


$\text{cis } 75^\circ + \text{cis } 83^\circ + \text{cis } 91^\circ + \dots + \text{cis } 147^\circ$

Question: The number
$\text{cis } 75^\circ + \text{cis } 83^\circ + \text{cis } 91^\circ + \dots + \text{cis } 147^\circ$
is expressed in the form $r \, \text{cis } \theta$, where $0 \le \theta < 360^\circ$. Find $\theta$ in degrees.
I tried to use this site for geometric sequences, How can we sum up $\sin$ and $\cos$ series when the angles are in arithmetic progression?.
Answer: Hint:
Let $\frac{75\pi}{180}=\alpha$. Since $\text{cis} \theta=e^{i \theta}$. Therefore the given series can be written as
$$e^{i \alpha}+e^{i \left(\alpha+\frac{8\pi}{180}\right)}+e^{i \left(\alpha+\frac{16\pi}{180}\right)}+ \dotsb + e^{i \left(\alpha+\frac{72\pi}{180}\right)}.$$
Let $\frac{8\pi}{180}=\beta$. Then we can write this as:
$$e^{i \alpha}\left[1+e^{i \beta}+e^{i2\beta}+ \dotsb + e^{i 9\beta}\right].$$
This is a geometric series with common ratio $e^{i\beta}$.
Answer: \begin{align}
   \text{cis }75^\circ +
      \text{cis }83^\circ +
      \text{cis }91^\circ + \dots +
      \text{cis }147^\circ
   &= \text{cis }75^\circ \left(
      1 +
      \text{cis }8^\circ +
      \text{cis }16^\circ + \dots +
      \text{cis }72^\circ \right)\\
   &= \text{cis }75^\circ \left(
      1 +
      \text{cis }8^\circ +
      (\text{cis }8^\circ)^2 + \dots +
      (\text{cis }8^\circ)^9 \right)\\
   &= \text{cis }75^\circ
      \dfrac{(\text{cis }8^\circ)^{10}-1}{\text{cis }8^\circ-1}\\
   &= \text{cis }75^\circ
      \dfrac{\text{cis }80^\circ-1}{\text{cis }8^\circ-1}\\
\end{align}


Yii2: How to add two fields and NULLS LAST in orderby() of Find() using mysql

Question: Trying to do something similar to this question, but need to sort NULLS LAST for MySQL
something like...
$query->MODEL_NAME::find();
$query->orderBy(['column_1' => 'IS NULL','column_1'=> SORT_DESC]);

though this syntax is wrong. Thanks!
When I try orderBy('column_1 IS NULL ASC, column_1 desc') i get the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column. The SQL being
  executed was: SELECT * FROM 'table' ORDER BY 'due_date IS NULL'

NOTE: had to replace backticks with single quotes in the error above in order for it to display here.
Comment: You have two columns or two order by on same column? I don't see two columns in your query.
Comment: Just by ordering column_1 in ascending order, you will get desired result.
Comment: primarily two order by same column in this example, but can be multiple. Ie. sort b y column 1 nulls last, column 2, column 3 nulls last, etc...
Comment: I need in descending order since column_1 is a date in this case and want to show most recent
Comment: use `\yii\db\Expression`, I edited my answer
Comment: awesome... thank you so much!
Answer: Use \yii\db\Expression
MODEL::find()
    ->where('1')
    ->orderBy(
        [
            new \yii\db\Expression('col_1 IS NULL ASC, col_1 desc')
        ]
    )
    ->all();

Comment: That results in `ORDER BY `column_1 IS NULL ASC`. Instead of `ORDER BY `column_1` IS NULL ASC`
Comment: Note: `$model::find()` is wrong, use `MODEL_NAME::find()`
Comment: what? I didn't understand your comment
Comment: sorry... difficulty editing comment...That results in the "backtick" key in the wrong place and an error... `ORDER BY **column_1 IS NULL ASC** Instead of ORDER BY **column_1** IS NULL ASC`
Comment: Also, am using... MODEL_NAME::find(). I mis-spoke in orig question
Comment: I still don't get it, orderBy can get string parameter too. is my code working? what is the result?
Comment: don't use backticks here.
Comment: I updated my orig question to show the error I get and refined my example code. Its putting the backticks in the wrong place for the generated sql
Answer: Sort In Ascending Order With NULLs Last
Using The Minus Operator:
In MySQL, NULL values are considered lower in order than any non-NULL value, except if a - (minus) character is added before the column name while sorting.
Query:
SELECT * FROM table
ORDER BY -date_login DESC

Using Yii framework
Model::find()->orderBy([new \yii\db\Expression('-column_1 DESC')])->all();

Using The IS NULL Comparison Operator:
We can rely on the fact that IS NULL returns 1 when an expression is NULL, and 0 otherwise. With that information, we could do something like this:
SELECT * FROM table
ORDER BY column1 IS NULL, column1 ASC

Using Yii framework
Model::find()->orderBy([new \yii\db\Expression('column_1 IS NULL, column1 ASC')])->all();

Using COALESCE Function
The COALESCE function can also be used, which returns the first non-NULL value in a specified list of arguments (or NULL if there are no non-NULL values). Therefore, to sort NULL last whilst ordering non-NULL values in ascending order, we could simply supply the highest possible value as a fallback (or substitute) for NULL values.
Query
SELECT * FROM table
ORDER BY COALESCE(name, 'zz') ASC

This works because zee is the last letter in the alphabet, and by default, MySQL sorts symbols and numbers first and then alphabets. Therefore, substituting NULL values with the highest possible sequence of the letter zee pushes NULL values to the bottom of the list.
Using Yii Framework
Model::find()->orderBy([new \yii\db\Expression("COALESCE(name, 'zz') ASC")])->all();

See Here for more details
Comment: its the minus operator, as i explained it in the first line,**`NULL` values are considered lower in order than any `non-NULL` value, except if a - (minus) character is added before the column name while sorting**
Comment: Thank you for the comprehensive response
Comment: what does the dash mean?
Comment: sorry @AlirezaFallah are you talking about the `-` operator that is used with the column name?
Comment: Yes, Exactly: `-`


For guitar sight reading, how do you not confuse between 3rd and 4th string?

Question: I am currently working on sight reading as a beginner guitar player.
I keep placing fingers wrongly between 3rd and 4th strings.
I try to keep my fingers near to the fretboard, have a steady hand.
But still this mistake keeps happening.
Is there a good way to fix this problem?
Comment: Add an example of what you are trying to play? It might be important because: maybe you use bad fingering, or the music is just too complex? Maybe there are specific chord voicings which you could change? Or anything else I can't even think about.
Comment: I'm not sure from the question if you have trouble making sense of the... tablature? (what kind of notation are you playing from? staff, tablature, chord symbols/diagrams?) in time, or you know exactly which string you should play but keep missing your aim with the hand (and if the latter, which hand).
Comment: You can [edit] your question to clarify.
Comment: When you say **sight-reading**, do you mean seeing unfamiliar music for the very first time and playing it as well as you possibly can, or do you mean playing whilst reading from sheet music? They are two different skills.
Comment: No real silver bullet I'm sorry. Just loads a practice, followed by loads more. Also, there's a lot of info. missing from the question - could you clarify at least the points noted in the comments.
Comment: Is it a proprioception issue? Also, be careful so you do not rest your arm on the guitar edge since the prolonged pressure it exerts on on the nerves and tendons in the forearm can cause issues in your arm.
Answer: Sounds like a case of "practice more" I'm afraid. Finger independence and muscle memory comes with time and practice, and there's no real way around this. Some general advice to make it easier:

Play the song a little slower - making sure you don't rush is key to encouraging best practices and discouraging bad technique.
Play to a metronome - to encourage consistency.
Film yourself - being able to play back what you're doing could highlight any habits which you don't realise you're doing (weird hand position, fingers floundering more than you realise, etc). It'll also be handy for figuring out if you're struggling with specific fingers more than others.
Play songs you already know - taking a break from practicing specific things gives you a chance to reset rather than getting too frustrated (and is generally more fun).
Practice general scales and finger independence exercises - personally I'm a big fan of John Petrucci's "Rock Discipline" book/video series. Doing the kinds of exercises that Petrucci outlines is excellent for getting more natural at finding the right strings/frets without issues.

If I have misunderstood your question and you are struggling with tablature (rather than literally struggling to play the 3rd/4th strings) - you may need to look for better tablature or make the tab bigger?
Answer: This is understandable because those are the two middle strings so they are farthest away from the edges of the fingerboard. It really doesn't matter whether you are sight reading or playing something you know. Here are a few tips that might be useful:
Keep in mind that the 3rd string is on the lower half of the fingerboard and the 4th is on the upper. Having this mental image will cause you to you reach higher towards the 4th and lower towards the 3rd.
Try and memorize the feeling of your hand position when playing each string. I'm referring to the thumb position (which actually should be fairly constant) and the curvature of your wrist and fingers.
Practice playing different scales on each individual string up and down the fingerboard. Also practice playing segments of scales back and forth between the two strings.