Proving $\tan^{-1}\frac{1}{2\cdot1^{2}}+\tan^{-1}\frac{1}{2\cdot2^{2}}+\cdots+\tan^{-1}\frac{1}{2\cdot n^{2}}=\frac{\pi}{4}-\tan^{-1}\frac{1}{2n+1}$

Question:
By using Mathematical Induction, prove the following equation for all positive integers $n$:
  $$\tan^{-1}\frac{1}{2 \cdot 1^{2}} + \tan^{-1}\frac{1}{2 \cdot 2^{2}} +\cdots+\tan^{-1}\frac{1}{2 \cdot n^{2}} = \frac{\pi}{4}-\tan^{-1}\frac{1}{2n+1}$$

I am able to prove the statement for n=1 and I got the assumption statement when $n = k$ as follows:
$$\tan^{-1}\frac{1}{2 \times 1^{2}}+\tan^{-1}\frac{1}{2 \times 2^{2}}+\cdots+\tan^{-1}\frac{1}{2 \times k^{2}}=\frac{\pi}{4}-\tan^{-1}\frac{1}{2k+1}$$
The problem is when I have to prove the case for n=k+1. I'm supposed to prove the following:
$$\tan^{-1}\frac{1}{2 \times 1^{2}}+\tan^{-1}\frac{1}{2 \times 2^{2}}+\cdots+\tan^{-1}\frac{1}{2 \times (k+1)^{2}} = \frac{\pi}{4}-\tan^{-1}\frac{1}{2k+3}$$
I simplified the left hand side - with the assumption - into
$$\frac{\pi}{4}-\left(\tan^{-1}\frac{1}{2k+1}-\tan^{-1}\frac{1}{2(k+1)^{2}}\right)$$
I understand that I am supposed to use the identity
$$\tan^{-1}a-\tan^{-1}b=\tan^{-1}\left(\frac{a-b}{1+ab}\right)$$
However, I still am unable to obtain the right-hand side from the expression I have right now.
Is there something I am missing?
Comment: https://math.stackexchange.com/questions/2153365/how-to-calculate-the-series-sum-limits-n-1-infty-arctan-frac2n2
Comment: that would work... however, I am required to use this induction to prove this identity, which is why I need to know where I went wrong in the induction
Answer: I don't know what you did wrong but you should get the required result using the given identity:
$$\begin{align}
\arctan{\left(\frac{1}{2k+1}\right)}-\arctan{\left(\frac{1}{2(k+1)^2}\right)}
&=\arctan{\left(\frac{\frac{1}{2k+1}-\frac{1}{2(k+1)^2}}{1+\left(\frac{1}{2k+1}\right)\left(\frac{1}{2(k+1)^2}\right)}\right)}\\
&=\arctan{\left(\frac{2(k+1)^2-(2k+1)}{(2k+1)(2(k+1)^2)+1}\right)}\\
&=\arctan{\left(\frac{2(k^2+2k+1)-(2k+1)}{2(2k+1)(k^2+2k+1)+1}\right)}\\
&=\arctan{\left(\frac{2k^2+4k+2-2k-1}{2(2k^3+4k^2+2k+k^2+2k+1)+1}\right)}\\
&=\arctan{\left(\frac{2k^2+2k+1}{2(2k^3+5k^2+4k+1)+1}\right)}\\
&=\arctan{\left(\frac{2k^2+2k+1}{4k^3+10k^2+8k+3}\right)}\\
&=\arctan{\left(\frac{2k^2+2k+1}{(2k+3)(2k^2+2k+1)}\right)}\\
&=\arctan{\left(\frac{1}{2k+3}\right)}\\
\end{align}$$
Comment: Thanks a lot! Turns out I made a slight expansion error which messed everything up ... Appreciate it tho
Answer: All you need to do is to prove
$$ \tan^{-1}\dfrac{1}{2k+1}-\tan^{-1}\dfrac{1}{2(k+1)^{2}} = \tan^{-1} \dfrac{1}{2k+3}.$$
You can use the formula you mentioned in this way:
$$ \begin{align}\tan^{-1}\dfrac{1}{2k+1} - \tan^{-1} \dfrac{1}{2k+3} &= \tan^{-1} \dfrac{\frac{1}{2k+1}-\frac{1}{2k+3}}{1+\frac{1}{2k+1}\frac{1}{2k+3}}\\
&= \tan^{-1} \dfrac{2}{(2k+1)(2k+3)+1}\\
&= \tan^{-1} \dfrac{1}{2(k+1)^2}.
\end{align}$$


Expectation with respect to a transformed random variable

Question: Problem
Suppose I have a random variable $z$ following a distribution $p(z)$. Suppose I have a transformation
$$
f(z) = x
$$
that transforms the random variable $z$ into a new random variable $x$ with distribution $p(x)$. I have often seen the following result
$$
\mathbb{E}_{p(x)}[g(x)] = \mathbb{E}_{p(z)}[g(f(z))].
$$
In other words, the expectation with respect to a distribution $p(x)$ can be written in terms of the original distribution $p(z)$.
Is there proof of this? I think this should work even if $f(z)$ is not invertible and/or differentiable.
My Set-Up for a Solution
I will describe my measure theory set up.
Distribution of Z
Suppose we have two measurable spaces $(\Omega, \mathcal{F})$ and $(\mathsf{Z}, \mathcal{Z})$. The random variable $Z$ is a measurable mapping
$$
Z: \Omega \to \mathsf{Z}
$$
such that the pre-image $Z^{-1}(B)$ of any $\mathcal{Z}$-measurable set $B\in \mathcal{Z}$ is also $\mathcal{F}$-measurable:
$$
Z^{-1}(B) = \{\omega\in \Omega \, :\, Z(\omega) \in B \} \in \mathcal{F} \qquad \forall \, B \in \mathcal{Z}
$$
Now the distribution of $Z$ is a push-forward measure. Suppose we have a probability space $(\Omega, \mathcal{F}, \mathbb{P})$. This means we can measure sets in $\mathcal{F}$. The push-forward or distribution for $Z$ is a way of measuring sets in $\mathcal{Z}$ via $\mathbb{P}$.
Basically, the distribution $Z_*\mathbb{P}$ assigns to sets $B\in\mathbb{Z}$ the same value as if we map $B$ back to $\mathcal{F}$ via $Z^{-1}$ first, and then we find its measure using $\mathbb{P}$.
$$
(\mathbb{P} \circ Z^{-1})(B) = Z_*\mathbb{P}(B) \qquad \forall \, B\in \mathcal{Z}
$$
Distribution of X
Now, the new random variable $X$ is basically a function of the random variable $Z$ and therefore $X$ is also a random variable.
Consider the probability space $(\mathsf{Z}, \mathcal{Z}, Z_*\mathbb{P})$ for $Z$. Consider also a measurable function
$$
X: \mathsf{Z} \to \mathsf{X}
$$
where $(\mathsf{X}, \mathcal{X})$ is a measurable space. This essentially defines the random variable $X$. Since we can measure sets in $\mathcal{Z}$ using $Z_*\mathbb{P}$ we would like to measure sets in $\mathcal{X}$ too. To do this, we define the distribution of $X$ to be a push-forward measure. Essentially, to give a measure to a set $C\in \mathcal{X}$ it maps it to $\mathcal{Z}$ via $X^{-1}$ and then measures it with the distribution $Z_*\mathbb{P}$.
$$
(Z_*\mathbb{P} \circ X^{-1})(C) = X_*Z_*\mathbb{P}(C) \qquad \forall \, C\in\mathcal{X}
$$
Expected Value with respect to $Z$
I am using this definition.
$$
\mathbb{E}_{p(Z)}(Z) = \int_{\mathsf{Z}} Z(\omega_z) \,\,d Z_*\mathbb{P}(\omega_z)
$$
Expected Value with respect to $X$
$$
\mathbb{E}_{p(X)}[X] = \int_{\mathsf{X}} X(\omega_x) \,\, d X_*Z_*\mathbb{P}(\omega_x)
$$
Comment: @Euler_Salter: This is the so-called [law of unconscious statistician](https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician), exactly. (The proof in Wikipedia is alas unnecessarily limited to the case of $g$ being invertible. The only constraint is actually that the transform $f$ is measurable in order for $X$ to be a random variable.)
Comment: Could the [law of unconscious statistician](https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician) be not applied here? As in, if define a function $h(z)\equiv g(f(z))$ and then use the law?
Comment: @Dayne Mmm Interesting.. but here there's an additional change: the expectation on the right-hand side is taken with respect to $p(z)$, while on the left-hand side is taken with respect to $p(x)$.
Answer: Let $Z$ be a random variable with distribution $P^Z$, meaning that for any measurable set $A$,$$\mathbb P(Z\in A)=P^Z(A)$$
Then, for any measurable transform $f$, $X=f(Z)$ is a random variable with distribution $P^X$ such that, for any measurable set $A$,$$P^X(A)=\mathbb P(X\in A)=\mathbb P(f(Z)\in A)=\mathbb P(Z\in f^{-1}(A))=P^Z(f^{-1}(A))$$
where
$$f^{-1}(A)=\{x;\ f(x)\in A\}$$
(which applies even when $f$ is not invertible).
This means that, when $g(\cdot)$ is an indicator function, $\mathbb I_A$, the equality
\begin{align}\mathbb E^{P^X}[g(X)]&=\mathbb E^{P^X}[\mathbb I_A(X)]\\
&=\mathbb P^X(A)\\
&=\mathbb P^Z(f^{-1}(A)]\\
&=\mathbb E^{P^Z}[\mathbb I_{f^{-1}(A)}(Z)]\\
&=\mathbb E^{P^Z}[\mathbb I_A(f(Z))]=\mathbb E^{P^Z}[g(f(Z))]
\end{align}
stands. The conclusion follows (as usual) when writing any measurable function $g$ as a limit of weighted sums of indicator functions. The expectation under the push-forward measure $P^X$ is indeed the expectation of the $f$-transformed variate under the initial measure $P^Z$:
$$\mathbb E^{P^X}[g(X)]=\mathbb E^{P^Z}[g(f(Z))]$$
Comment: That's fine, but it strikes me that you are asking a non-measure-theoretic question framed in terms of *distributions* rather than random variables: "the expectation with respect to a distribution $p(x)$ can be written in terms of the original distribution $p(z).$"  Although introducing random variables is natural, the way you have asked the question strongly suggests you were looking for more direct proofs.
Comment: (I cope with such situations by deleting my partial answer.  Later I can edit it and undelete it.)
Comment: Thank you! I can see that you've used the definition of a push-forward measure. But how does this prove the equality between the expected values? The definition of expected value that I am using is [this](https://en.wikipedia.org/wiki/Expected_value#General_case)
$$
\mathbb{E}_{p(X)}[g(X)] = \int_{\mathsf{X}} g(X(\omega_x)) d P^X(\omega_x).
$$
How does this relate to the other expected value?
$$
\mathbb{E}_{p(Z)}[g(f(Z))] = \int_{\mathsf{Z}} g(f(Z(\omega_z))) dP^Z(\omega_z)
$$
Comment: @whuber I've added some more measure theory to ease the path towards a proof.
Answer: Here's a simple case using random variable transformation. Assume $p_Z(z) = p_X(f(z)) \frac{df(z)}{dz}$ holds. Then we have,
$$
\int g(f(z)) p_Z(z)dz = \int g(f(z)) p_X(f(z)) \frac{df(z)}{dz} dz
= \int g(x) p_X(x) dx
$$


Função COUNT do PostgreSQL não funciona

Question: O problema é simples porém não consigo entender onde estou errando, preciso verificar a quantidade de resultados da seguinte sql:
SELECT

f.id,sum(p.valor) as valor_fatura, f.valor_desconto as desconto,
(f.numero || '/' || f.ano_fatura ) as numero,
(sum(p.valor) + f.valor_desconto + f.valor_acrescimo)as
valor,f.valor_acrescimo as acrescimo, f.emissao_em,
f.vence_em, f.situacao, f.juros_acrescimo, hb.dt_hr_inclusao::date AS
vencimento_ultimo_recalculo,
f.multa_acrescimo, f.is_gera_boleto, f.qtd_taxa_recalculo,
f.valor_taxa_recalculo, f.is_confianca,
(sumid(p.is_baixado) = sumid(true)) as is_baixado

FROM parcels p
JOIN sales s ON (p.sale_id = s.id)
JOIN faturas f ON (p.fatura_cobranca_id = f.id)

LEFT JOIN (SELECT (array_agg(dt_hr_inclusao order by dt_hr_inclusao
desc))[1] as dt_hr_inclusao,
(array_agg(cod_mov_remessa_id order by dt_hr_inclusao desc))[1] as
cod_mov_remessa_id,
hb.fatura_id FROM historico_remessa_boleto hb GROUP BY hb.fatura_id
) hb ON (f.id = hb.fatura_id and hb.cod_mov_remessa_id = 6)

WHERE p.is_baixado = false AND f.vence_em is not null AND is_gera_boleto
AND consignatario_id = 6512

GROUP BY f.id, f.numero, f.ano_fatura, f.emissao_em, f.vence_em,
f.situacao, f.juros_acrescimo, f.multa_acrescimo, f.is_gera_boleto,
f.valor_desconto, f.valor_acrescimo, hb.dt_hr_inclusao::date

O problema é que quando eu executo essa sql ela me trás 6 resultados, para saber a quantidade agora eu faria isso :
SELECT
count(p.id)
FROM parcels p
JOIN sales s ON (p.sale_id = s.id)
JOIN faturas f ON (p.fatura_cobranca_id = f.id)
LEFT JOIN (SELECT (array_agg(dt_hr_inclusao order by dt_hr_inclusao
desc))[1] as dt_hr_inclusao,
(array_agg(cod_mov_remessa_id order by dt_hr_inclusao desc))[1] as
cod_mov_remessa_id,
hb.fatura_id FROM historico_remessa_boleto hb GROUP BY hb.fatura_id
) hb ON (f.id = hb.fatura_id and hb.cod_mov_remessa_id = 6)

WHERE p.is_baixado = false AND f.vence_em is not null AND is_gera_boleto
AND consignatario_id = 6512

Agora ela me retorna 11 resultados no count.
Não sou bom em sql meu foco é front-end então estou meio perdido de onde posso está errando, caso alguém precise de alguma informação que eu não coloquei só pedir nos comentários.

Quando deixo a query com o group by ela me retorna 6 linhas de resultados onde só posso ter um resultado com a quantidade total.
Answer: Pelo visto, quando você deixa com o group by retorna 6 linhas, com o resultado 6 em cada uma delas, correto ?
você pode usar o distinct para isso.
ps. Tente identar o código pra ajudar na leitura.
SELECT
count(DISTINCT p.id)
FROM parcels p
JOIN sales s ON (p.sale_id = s.id)
JOIN faturas f ON (p.fatura_cobranca_id = f.id)
LEFT JOIN (SELECT (array_agg(dt_hr_inclusao order by dt_hr_inclusao
desc))[1] as dt_hr_inclusao,
(array_agg(cod_mov_remessa_id order by dt_hr_inclusao desc))[1] as
cod_mov_remessa_id,
hb.fatura_id FROM historico_remessa_boleto hb GROUP BY hb.fatura_id
) hb ON (f.id = hb.fatura_id and hb.cod_mov_remessa_id = 6)

WHERE p.is_baixado = false AND f.vence_em is not null AND is_gera_boleto
AND consignatario_id = 6512

GROUP BY f.id, f.numero, f.ano_fatura, f.emissao_em, f.vence_em,
f.situacao, f.juros_acrescimo, f.multa_acrescimo, f.is_gera_boleto,
f.valor_desconto, f.valor_acrescimo, hb.dt_hr_inclusao::date

Comment: Funcionou com uma pequena alteração, coloquei assim : count(DISTINCT f.id)
Comment: Isso! perfeito, já alterei na resposta
Comment: Obrigado pela ajuda!
Answer: Na primeira query você tem um agrupamento (GROUP BY). Na segunda query não. Isso altera o formato do resultado. Comparar a quantidade de registros de uma query para a outra é como comparar maçãs com laranjas.
Se você quer contar a quantide de registros da primeira query programaticamente, o ideal é fazer isso na camada de aplicação. Se você absolutamente precisa fazer isso de forma agnóstica, a maneira "suja e rápida" é encapsular a sua query e fazer assim:
SELECT COUNT(*) FROM (x) T

Onde T é um nome qualquer arbitrário e x é toda a query que você já colocou na pergunta.
Comment: Quando deixo com o group by ele simplesmente me trás vários resultados, onde só posso ter 1 com o total,  porém tas 6 linhas de resultado que seria 'correto' só que com o count deveria ter 1 linha com 6 de quantidade, não sei se expliquei bem.
Comment: Editei a pergunta, ao final expliquei isso.

Função COUNT do PostgreSQL não funciona


Why does it print out 0?

Question: Why is the answer 0 and not 1? I know it has something to do with the boolean sentence, but I can't figure out how it works. From my understanding, the while loop stops when i and j are both equal to 1.
public void random(){
    int i = 0;
    int j = 2;
    int k = 0;
    boolean keepGoing;
    keepGoing = i<j;
    while (keepGoing && k<2) {
        i++;
        j--;
        k++;
    }
    System.out.println(j);
}

prints out 0
Comment: Debug / step through your code and it will be clear what is happening.
Answer: You are probably saying that because you think the keepGoing variable will stop the loop...
Well the keepGoing variable won't change at all! You instantiated your variable with this:
boolean keepGoing;
keepGoing = i<j;

This expression will look at the values of i and j at that moment in the code, replace these variables with their values (respectively 0 and 2 at that moment), and just process the comparison. As i is less than j at that moment in the code it will return true and set keepGoing to true. After that, keepGoing won't change itself each time i or j changes. That is not how it works. The value of keepGoing will only change if you set another value in it! In general, a variable will only change if there is an explicit line (or method) encountered that tells it to change. So if in your case you want keepGoing to change each time you change i or j, you'll have to explicitely recalculate keepGoing each time that happens. In your case this will be at the end of your while block:
    while (keepGoing && k<2) {
        i++;
        j--;
        k++;
        keepGoing = i<j;  //explicitely recalculate value of keepGoing
    }

Answer: It's because you are decreasing the integer j and increasing the integer k.
The while steps look like:

i = 0, j = 2, k = 0
i = 1, j = 1, k = 1
i = 2, j = 0, k = 2

Why does it print out 0?


How to accommodate specflow step definition to accept deferent number of parameters from specflow feature file with one method

Question: Hi I have below Specflow feature files
First scenario
<code> Scenario outline:
    Given Add two numbers <num1> <num2> <num3>
    Then divide by <num4>
    Examples:
    |TestCase|num1|num2|num3|num4|
    |Add     |1   |2   |3   |4   |
</code>
Second Scenario:
<code> Scenario outline:
    Given Add two numbers <num1> <num2>
    Then divide by <num4>
    Examples:
    |TestCase|num1|num2|num4|
    |Add     |1   |2   |4   |
</code>
below is the code which I want in Step definition method
<code>[Given(@"Add two numbers (.*) (.*) (.*)")]

[Given(@"Add two numbers (.*) (.*)")]

public void Testtheconditionwith(string a, string b, string c = null)

{

}
</code>
this is not working. I don't want to write different methods with different parameters.
Is there any way to achieve this?
Thanks.
Comment: Please format you code using the format code icon in the question editor. It is too difficult to read.
Comment: Please do not post images of code. Copy and paste it into the question editor.
Answer: SpecFlow doesn't support optional parameters in the step definition methods.
You have to write two methods, but you can simply call one from the other.
<code>[Given(@"Add two numbers (.*) (.*) (.*)")]
public void Testtheconditionwith(string a, string b, string c)
{

}

[Given(@"Add two numbers (.*) (.*)")]
public void Testtheconditionwith(string a, string b)
{
    Testtheconditionwith(a,b,null)
}

</code>
Better would be to use the Driver pattern. More about it at: https://docs.specflow.org/projects/specflow/en/latest/Guides/DriverPattern.html


SQLAlchemy boolean value is None

Question: I have this table in my Pyramid app
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    .....
    is_active = Column(Boolean, unique=False)
    def __init__(self, name, raw_password):
        is_active = True

When I did my test, it said is_active is None.
def test_register_user(self):
    user = User('user1', '1234')
    self.sess.add(user)
    self.sess.flush()

    #print user
    #self.assertTrue(user.is_active, True)
    user_db_record = self.sess.query(User).filter_by(name=user.name).first()
    self.assertEqual(user_db_record.is_active, True)

From my integration log I see when we are creating the row, is_active is set to None. Why?
Comment: If anybody has come here looking for an answer using SqlAlchemy and JetBrains' DataGrip, then do not use their visual editor to insert values into the table, it will ignore the `default` keyword and set the column's value to ``. Instead use a raw SQL statement from the console, then the value will be set correctly.
Answer: You have to set a default value otherwise None/NULL is used:
is_active = Column(Boolean, unique=False, default=True)

You wanted to do this in __init__ but you used is_active = True (a local variable) instead of self.is_active = True.
Comment: @Hussain [Postgres docs](https://www.postgresql.org/docs/current/static/datatype-boolean.html) state a list of valid literals for True/False values and `'t'` / `'f'` are among them. I went with `server_default='t'` and it worked for me.
Comment: What should be the value of `server_default` for Boolean?
Comment: Oh... `self.` was missing. Embarrassing. Thanks!
Comment: Seriously, with South/Django migration background, sometimes I think writing raw SQL migrations is a better approach compared to Alembic - at least it works in a predictable way...
Comment: @havelock one of the main selling points of SQLAlchemy ORM is to abstract the actual server/driver implementation (otherwise why bother doing anything beyond iterating over the `Selectable` and `type(NamedTuple)`?). So setting `default` in the column def and assigning the default value in `__init__`  will create both the default constraint on the server and assign it upfront during ORM object instantiation.
Answer: If you're using Flask-SQLAlchemy, you can use this command to create a server side default.
from sqlalchemy.sql import expression
active = db.Column(db.Boolean, server_default=expression.true(), nullable=False)

This will create a default value on the database so anyone can write to it and the DB will have the default value.
Comment: how is that Flask related? because this seems to be regular SQLAlchemy thing, I think you may have mixed up the `db.TYPE` stuff with `server_default` arg of SQLAlchemy `Column`?
Answer: is_active = Column(Boolean, server_default='t', default=True)

Comment: Please add some explanation to your answer!
Comment: @ρss Alembic seems not to be generating SQL-level default value clauses in migration code from `default` alone, you have to supply `server_default` explicitly. As for the `'t'` value, please see [my comment above](http://stackoverflow.com/questions/12045698/sqlalchemy-boolean-value-is-none#comment69750602_12045897).
Comment: `server_default="true"` also works (note it is not the Python keyword `True` but a string `"true"`)
Comment: In my case alembic generate Column(Boolean, server_default=text("false")) and this was not working, I modified to Column(Boolean, server_default='f', default=False) as @far suggested and it worked properly.
Comment: One could use `expression.true()` rather than a literal `'t'` to assign `server_default` for portability.
Answer: If someone is looking for a solution and using Flask this is how you'd do it.
It is very important to note that server default should be used inside the migrations file, not on the model itself.
once you generate migrations using a
flask db migrate

you should see new migration in the folder ( migrations/versions/XXXXXX.py )
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('confirmed', sa.Boolean(), nullable=True, server_default='f'))
    op.add_column('users', sa.Column('confirmed_on', sa.DateTime(), nullable=True))
    op.add_column('users', sa.Column('is_admin', sa.Boolean(), nullable=True, server_default='f'))

This is the place where you'd want to add server_default.
Answer: Provided solutions here don't work for me (SQLAchemy 1.4.40)
def test_entity():
    class Entity(Base):
        __tablename__ = "test_entities"
        id = Column(BigInteger, primary_key=True)
        is_active = Column(Boolean, nullable=False, default=True)

    entity = Entity()
    assert entity.is_active is True

Expected :True
Actual   :None

Comment: yeah..same issue.  Have you found a solution?

SQLAlchemy boolean value is None


Patching .htaccess file

Question: I need to patch .htaccess file which is located in project's root (docroot in this case), my project is written using composer and I created a patch using git, added it to the /patches directory and wrote a composer.json entry:
"drupal/drupal": [
          {
            "title": "htaccess patch",
            "url": "docroot/profiles/laeg/patches/redirects.patch"
          }
        ]

Sadly after running composer update my patch doesn't appear in the patches list therefore it is not applied. I was told that I should patch drupal/drupal but it seems to not be a case, has some done anything like this and could suggest me something? Project is running Drupal 7.
Answer: For drupal 8, use the following.
In the 'scripts' section of your composer.json, add
"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]

Comment: I had to use -p1 instead of -p0 for it to work for me.
Comment: -p1 for me too! Thanks.
Answer: A little late, but check out https://github.com/drupal-composer/drupal-scaffold/issues/45. They give a few solutions for handling the issue.
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.

Patching .htaccess file


How can I add variables that are assigned during a loop?

Question: This might seem like a simple question, I have looked for solutions or just concepts behind this, but cannot find any.
How can I create a loop that asks for as many integers as the user wishes, and once the user types in the value 99 the loop will exit and will display the average of all the numbers inside of the loop?
Here is what I have so far:
#include <iostream>
#include <string>
using namespace std;

int main () {
  // Variables
  int numInput;
  int numOfIntegers;
  bool canContinue;

  cout << "Enter the amount of integers you would like to enter: ";
  cin >> numOfIntegers;

  int oldNums = new int [numOfIntegers];

  while (canContinue) {
    cout << "Enter a random integer: ";
    cin >> numInput;
    if (numInput != -1) {

    } else {
      canContinue = false;
    }
  }
}

Comment: Yes.  But you really only need two numbers to do that.  The sum of all the numbers, and how many numbers there are.  Do you see how you could just add the inputs into a running total and then divide that at the end?
Comment: `numInput != -1` should probably be comparing against 99
Comment: You don't need an array here at all.  What two pieces of data do you need to calculate the average of something?  So you see a why how you can get both of those by just taking each number in and doing something with them?
Comment: read a number from the user. If it is not 99, add it to the sum, increment a counter, and loop back to read another number. If it is 99, divide the sum by the counter, print the result, and exit the loop. You may have to watch out for integer division discarding the remainder of the division. No storage of anything other than the sum and the count is required.
Comment: `new int[]` returns a `int*` which can't be assigned to `int`. `oldNums` would need to be a pointer. However, please us a `std::vector` instead of managing your memory yourself. It's easier, cleaner and safer using `std::vector`.
Comment: `int oldNums = new int [numOfIntegers];` What makes you think this line is syntactically correct? Didn't the compiler tell you that it's wrong? BTW you should use a `std::vector` to represent an _array_.
Comment: Add your input values to a container ([std::vector](https://en.cppreference.com/w/cpp/container/vector) is a good default choice). And there's No need for manual memory management.
Comment: @NathanOliver It's not two numbers, I need the user to enter as many integer numbers and he/she would like and then find the average of all of these numbers.
Comment: @user4581301 - Thank you so much! I can't believe that this did not come to mind. I really appreciate your answer! :)
Comment: @NathanOliver You are right. I need the sum and the number of numbers that were used. I am going to create a counter inside a loop that tracks every loop and will divide the sum by the counter like user4581301 said. Thanks! :)
Answer: It's simple:
#include <iostream>
#include <string>
using namespace std;

int main () {
    int numInput;
    int sum = 0;
    int cnt = 0;

    while (true) {
        cout << "Enter a random integer: ";
        cin >> numInput;

        if (numInput == 99) {
            break;
        }

        sum += numInput;
        cnt++;
    }

    cout << "Average: " << ((double) sum / (double) cnt);

    return 0;
}

You don't need to save all the individual values in a array. Adding all values and then divide by the counter it's enough. Casting to double avoids losing precision in the average
Comment: It is best not to give concrete answers to questions like this as they are often tests of a programmer's abilities. If your answer is cut-and-pasted, it's your work being evaluated, not theirs.


Taxonomy Access Control

Question: I'm creating a site which will have multiple 'store' sections, with each store's staff needing to edit their own content, but not anyone else's.
The eventual layout will look something like this.

Store One

Page A
Page B

Store Two

Page C
Page D

This is fine - I figure I should have a vocabulary for 'Stores' and a term for each Store, and then use an access control module to limit page editing based on term.
Now, the complexity: we also need a certain amount of custom information displayed on the front page for each store (think opening hours, location etc). I figure the best place way to achieve this is to have a set of custom fields for each term, and then display them in a view that also lists the pages for the store.
Thus the problem: How do I allow a store to edit their term (and it's custom fields) but not others?
Will gratefully receive to any and all potential solutions.
Answer: I have a similar use case on my site.  I ended up making stores a content type for that very reason.  Entity reference is your friend cause you can create page a and b and link em to the store content entity.
Comment: Yeah I might have to go down that path - trying to teach users how to edit a taxonomy term is probably a bridge too far. Entity Reference certainly looks good!
Comment: It really does add a new wrinkle.
Answer: I think you would like the Workbench suite of modules. The Workbench Access module allows you to only allow certain users to edit sections of your website, so you could set the permission at the store level and it would cascade down to all of the pages associated with the store. It works well with taxonomies.
https://drupal.org/project/workbench
Comment: Thanks - Workbench Access is great, except it doesn't solve my particular issue of wanting to apply access control to a taxonomy as well as general content types.
Comment: If you look in the settings, you can use a taxonomy to enforce access control for taxonomies. "The module supports Taxonomy and Menu modules for the management of access hierarchies."

So it seems to fit with your statement: "vocabulary for 'Stores' and a term for each Store, and then use an access control module to limit page editing based on term"

You then put each user/role as an editor under each term for granular editing access. When you add content, you tag the appropriate section. Maybe I'm misunderstanding what you are asking for?

Taxonomy Access Control


Saving private key in application

Question: I want to create custom configuration for my application, not using the app.config.
So for example I want to make some ini file that stores the configuration itself and want to make it encrypted. So I want to encrypt connection string, passwords, etc that will be in this file.
I want to use RSACryptoServiceProvider. So i will create config file with a public key, and my application will decrypt those with private key. I need to store this private key inside the application somehow.
I can put is as const string value, but it's easy to see it when you reverse engineer the application.
So, what is the best way to store the private key inside my application?
How RsaProtectedConfigurationProvider does it?
Comment: The dilemma is that you are only adding a layer of complexity, not security, as there is a key in plain text in the end. The point is that the best way to protect the key doesn't pan out as it leaves you with the same problem as you start with. You have to make do with something that is second best, like obstruction.
Comment: The best way would be to encrypt it, but then you need to store the key for that somehow...
Comment: @anderhil: It uses an encryption key protected by the system at a user level. It's stored in the computer, not the application, so you need to encrypt the data on the same computer that is going to read it.
Comment: encypt the private key with other encryption and store as string?
Comment: How then RsaProtectedConfigurationProvider does it under the hood?
Comment: possible duplicate of [Encrypt connection string in app.config](http://stackoverflow.com/questions/11637348/encrypt-connection-string-in-app-config)
Comment: it's different question, cause I'm saying about separate custom configuration
Answer: You could use the Data Protection API, which is intended for this kind of use. It stores per-user secrets in Windows.
The key won't be as easy to retrieve, but bear in mind that this solution relies on Windows Security. The user for which you have stored the key will be able to retrieve it again easily (but other users cannot).
http://en.wikipedia.org/wiki/Data_Protection_API
To use it from .NET, start with the documentation for the ProtectedData Class.
Comment: But I need to have private key per application, cause it will be distibuted to lots of other computers.
Comment: It's the never-ending problem with cryptography, you need to store the keys somewhere you can retrieve them. Can you issue each user a different key, in use that key to ultimately decrypt the master key. Or redesign so individual clients don't need the master key. Ultimately, there is no *safe and 'good'* way to store the key, other than deriving it from something the user inputs, such as the password. The Windows DPAPI solution does this since it indirectly relies on the Windows user's password.
Comment: Yes I understand that, that's why I asked what is the best solution? I'd say even just acceptable solution, I want to be protected at least from simple reverse engineering - when you can read the strings that are stored as consts. So private key should be distributed with/in the application.

Saving private key in application


$\lim_{n \to \infty} \int_{0}^{1} e^{x^2} \sin(nx) dx$

Question: $$\lim_{n \to \infty} \int_{0}^{1} e^{x^2} \sin(nx) dx$$
I am trying to find above limit without using the concept of Lebesgue integration. I know that $e^{x^2} sin(nx)$ is not a uniformly convergent sequence of functions so i can not take limit inside integration. So give me any idea that is it really possible to evaluate the limit without using the concept of lebesgue integration. Thank you
Comment: Try Riemann-Lebesgue lemma.
Comment: Hint: let $z=nx$.
Comment: See [this post](https://math.stackexchange.com/q/3813759/743337).
Answer: You integrate by parts:
$$
\int^1_0 e^{x^2} \sin(nx)~\mathrm{d}x = - \frac{1}{n}(e \cos(n) -1) + \frac{1}{n} \int^1_0 2x e^{x^2}\cos(nx)~\mathrm{d}x
$$
Therefore, by using the triangle inequality, $\lvert \cos(nx) \rvert \leq 1$ and $\left \lvert 2xe^{x^2} \right \rvert\leq 2e$ on the domain:
$$
\left \lvert \int^1_0 e^{x^2} \sin(nx)~\mathrm{d}x \right \rvert \leq \frac{1}{n}\lvert e\cos(n) - 1\rvert + \frac{1}{n}\int^1_0 \left \lvert 2x e^{x^2} \right \rvert\lvert \cos(nx) \rvert~\mathrm{d}x \leq \frac{e-1}{n} + \frac{2e}{n}
$$
The right hand side tends to zero when $n \rightarrow \infty$ and thus so does your integral.
In general: If $f \in C^1([0, 1])$, then
$$
\int^1_0 f(x) \sin(nx)~\mathrm{d}x \overset{n \rightarrow \infty}{\longrightarrow}0.
$$
To prove this, you can use the same reasoning as presented above.
We can even allow $f \in L^p([0, 1])$ where $1 \leq p \leq \infty$. Because of density, for arbitrary $\varepsilon > 0$, we can choose $g \in C^1_0([0, 1])$ such that $\lVert f - g \rVert_{L^1([0, 1])} < \frac{\varepsilon}{2}$. Then:
$$
\left \lvert \int^1_0 f(x) \sin(nx)~\mathrm{d}x \right \rvert \leq \lVert f - g \rVert_{L^1([0, 1])} + \left \lvert \int_0^1 g(x)\sin(nx)~\mathrm{d}x \right \rvert < \frac{\varepsilon}{2} + \left \lvert \int_0^1 g(x)\sin(nx)~\mathrm{d}x \right \rvert
$$
With the usual integration by parts strategy, we can make $\displaystyle \left \lvert \int_0^1 g(x)\sin(nx)~\mathrm{d}x \right \rvert$ smaller than $\frac{\varepsilon}{2}$.
Comment: The general statement is also valid for any integrable function in $\mathbb{R}$. It is Féjer's formula.
Comment: @Meowdog Just to clarify what Oliver means is that $f$ need only be $C^0$, not $C^1$.
Comment: I reckon it even holds for $L^1$... I might have to make an edit...
Answer: These are the Fourier coefficents of the function $x \mapsto e^{x^2}I_{[0,1]}(x)$.  Invoke Riemann-Lebesgue:  these converge to zero.  Like the Ginzu knife man said on TV, there's more.  By Parseval's theorem they are square-summable, too!


How to display an option value of a GlusterFS server

Question: How can I display a value of an option for a GluserFS server. GlusterFS Documentation talks only about setting option values:
gluster volume set, e.g. gluster volume set test-volume performance.cache-size 256MB
There is no mention of inspecting option values currently in use. There were also several people asking similar question with no answer - is that really possible to not be able to display an option value in GlusterFS cli?
Answer: I had the same question when I was editing the docs for RHGS 3.1.2. :) The good news is, 'gluster volume get' has been implemented as of at least glusterfs version 3.7.9-7.
Docs for the Red Hat version are here: https://access.redhat.com/documentation/en-US/Red_Hat_Storage/3.1/html-single/Administration_Guide/index.html
Hope this helps!


Unconsistent entity object collection state

Question: I am having inconsistent object state when using Hibernate
I have class School that have a collection of student
<code>@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "LINK_SCH_STUDENT", joinColumns = @JoinColumn(name = "SCHOOL_ID"),
inverseJoinColumns = @JoinColumn(name = "STUDENT_ID"))
@LazyCollection(LazyCollectionOption.EXTRA)
private List<Students> associatedStudents;
</code>
I have a transactional method that links a student to a school:
<code>@Transactional
LinkStudentToSchool (schoolId, StudendID){
flush();
int result = getSession().createSQLQuery("INSERT INTO " + getSchemaName()
+ ".LINK_SCH_STUDENT(SCHOOL_ID, STUDENT_ID) " +
"Values (:recipient_group_id, :contentId)")
}
</code>
I am writing integration test for this method.
<code>@Transactional
TestLinkStudentToSchool {
school =new School ("GeorgiaTech", ....)
schoolId = saveOrUpdate (school)
studentID = saveOrUpdate (new Student ("LazyStudent", ....))

LinkStudentToSchool (schoolId, studentID)

Hibernate.initialize (school.getAssociatedStudent);
school.getAssociatedStudent // RETURN NULL !!!
}
</code>
Why is this happening, I already called a transactional method to add a student a school (update the link table), but the state of the collection of students
in the school did not get updated !!
Is this a caching issue ? is it because I have nested @transactional?
I will really appreciate any feedback
Thanks
Answer: You start by creating a Scool instance and saving it. It becomes associated to the Hibernate session. At this time, the list of students is null, because you neglected to initialize the list to an empty list (this should be the default state of a new school).
Then you execute a SQL query, like if Hibernate didn't exist and you were using JDBC. Hibernate doesn't know what this query does. It doesn't know that the query inserts a row to the join table. And it can't magically know that this corresponds to a new association between the student and the school. It can't magically initialize the field of your school in memory and replace it with a list containing the student. Don't bypass Hibernate by using SQL queries. Use the entities:
<code>// correct default state of a school:
private List<Students> associatedStudents = new ArrayList<>();

...

School school = new School("GeorgiaTech", ....);
session.save(school);
Student student = new Student("LazyStudent", ....);
session.save(student);
// now associate the student with the school:
school.getAssociatedStudents().add(student);

// done. Hibernate will insert the row in the association table for you.
</code>
Comment: Thank for your reply JB. the only reason I was not using Hibernate for the Link table is that it has a 'deleted' field for soft deleting the association. Using SQL query made easier to set the filed directly. I so know if I should change the design at this point.
Comment: Hibernate won't care at all about this additional column. If you want it to care about it, then the join table must be mapped as an entity, and the column should be mapped as a field of this entity.
Comment: Make sens, merci bien Jean-Baptiste.


Set up the limits and evaluate $\iiint ydv$

Question: Set up the limits and evaluate the integral.
$$\displaystyle\iiint ydv$$
$$G$$
G is the region enclosed by the plane $z = y$, $xy-plane$ and the surface $y = 1 - x^2$
I need help finding the limits of integration. I have this so far, but I don't think it is correct.
$$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} y\;dz\;dy\;dx$$
Comment: I think it's set up correctly because if you take antiderivative in terms of dz you would have yz and if you evaluate it from $F(y) - F(0)$ you would have $yy$ or $y^2$. then you take the antiderivative in terms of $y$ and you'll have $\frac{y^3}{3}$. Evaluate from $F(1-x^2) -F(0) $ and you'll have x terms remaining. Now take the antiderivative in terms of dx and evaluate from $F(1)-F(0)$

If the intergral was set up incorrectly, you wouldn't be able to take the antiderivative of whatever the letter was again.
Answer: $\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} y\;dz\;dy\;dx$
Taking the antiderivative in terms of $dz$, we have
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} yz\;dy\;dx$
Now, evaluate from $F(y) -f(0)$
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} yy\;dy\;dx$
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} y^2\;dy\;dx$
Taking the antiderivative in terms of $dy$, we have
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{y^3}{3}\;dx$
Now, evaluate from $F(1-x^2) -f(0)$
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{(1-x^2)^3}{3}\;dx$
We need to expand first
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{-x^6+3x^4-3x^2+1}{3}\;dx$
and simplify
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{-x^6}{3}+x^4-x^2+\frac{1}{3}\;dx$
Taking the antiderivative in terms of $dx$, we have
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{-x^7}{21}+\frac{x^5}{5}-\frac{x^3}{3}+\frac{x}{3}$
Evaluate from $f(1) -f(0)$
$\displaystyle\int_{0}^{1}\int_{0}^{1 - x^2}\int_{0}^{y} \frac{-1}{21}+\frac{1}{5}-\frac{1}{3}+\frac{1}{3}$
The final answer is $\frac{16}{105}$


Programatically altering a field formatter in Views

Question: I'd like to create a new (date) field formatter in Views, but also keep the existing formatters intact. As of now, I've managed to use hook_field_views_data_alter() to entirely replace the exiting handler with mine. However I would prefer to have my custom formatter available in the dropdown below. Is it possible to append an option to this dropdown for my custom formatter?
Comment: If you have created a field formatter it should appear everywhere for the field, i.e. in "manage display" tab on the content type setting and in field options in views, etc. can you paste in the code you wrote for your field formatter?
Comment: I did not create a field formatter... I assumed I had to do this with views field handlers. Will look into it, thanks!
Answer: If you wish to display a field in a different way, there are a different ways to go about it.

Create a field template in your theme and change there. Just copying the field.tpl.php file would work changing the way the field is rendered on a node page. Note that field.tpl.php is a generic template which would be called on each field. You might want to try the specific template names like : field--article.tpl.php would get applied to all fields on article content type; field--body.tpl.php would get applied to body field on any content type; and field--body--article.tpl.php would only get applied to body field on the article content type.
Overriding the theme_field() function. E.g. Implementing the following functions in your theme's template.php file would do the same as with template copying THEMENAME_field__body__article(), THEMENAME_field__article(), THEMENAME_field__body(),
THEMENAME_field().
If the field is rendered in a view you could override it with the view template. To find out the specific template which you would need to override, click on "Theme: information" under the "Advanced" settings in the view to find the field template that applies to your field.
By creating your own custom field formatter by using this blog post. This will display the formatter in the dropdown as you intend.
There is also a module which helps your create custom formatters, which are ctools exportable. Which means you could easily featurize them. More about the module:

The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.
Comment: I want to have a date formatter that displays dates in the form of "Today, tomorrow, this week, this month, etc. The relative date format from date module uses the smallest granularity which could be minutes or hours. Altering that output seems like a bad idea, so defining a new field formatter would be the best option for this case I guess. But good to see the other options as well! :)


Expected Value of $X \sin(X)$ with $X$ normally distributed

Question: I want to solve the following expected value problem. Let's say $X$ is normally distributed so that $X \sim N(m,s^2)$. I want to find the expected value,
$$E[X\sin(X)]$$
that is equal to
$$\frac{1}{\sqrt{2\pi s^2}} \int_{-\infty}^\infty \exp(\frac{_{-(x-m)^2}}{^{2s^2}})\,  x\,\sin(x)\, dx$$
Does anyone have an idea how to simplify this?
EDIT: thanks guys for helping me out!
Comment: @ Kodiologist I didn't want someone bitching at me for not having a nicely finished and formatted answer.
Comment: @mark My apologies. I was pretty careful actually, but I have replaced it by pasting a copy of the text you originally had (except it was necessary to reinsert the backticks \` \`; I forgot they wouldn't carry over)
Comment: For m=0, it evaluates to `s2*exp(-s2/2)`. It's messier if m is not zero, with the result `(1/2)*exp(-I*m-(1/2)*s2)*s2-((1/2)*I)*exp(I*m-(1/2)*s2)*m+((1/2)*I)*exp(-I*m-(1/2)*s2)*m+(1/2)*exp(I*m-(1/2)*s2)*s2` , in which the imaginary, `I`, terms will cancel out when evaluated.
Comment: @MarkL.Stone That seems like it should be an answer, not a comment.
Comment: Looper, please carefully examine all the edits made to your original question, in the grammar, spelling, capitalization, [formatting of mathematics](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) and so on. In particular note the necessity for distinction between the symbols for $X$, the random variable and $x$, the dummy variable in the integral.
Comment: The s2 in my comment above corresponds to what has now been edited in the question statement to be $s^2$.
Comment: @mark please check your comment is okay now. If you want to paste an answer, right click on the expressions in your comment, choose *Show Math As* --> *TeX Commands* and you should be able to copy the MathJax markup and paste the results between \$\$ signs to get a reasonably formatted answer.
Comment: @Glen_b I think your edit to my comment messed it up.  i don't have time to deal with it now.
Answer: Like many exercises involving trigonometric functions, the trick is to use complex numbers, i.e., $\int(\sin(x))\mathrm{d}x = \int Im(e^{ix})\mathrm{d}x = Im(\int e^{ix} \mathrm{d}x)$ here.
Knowing, the sum becomes
\begin{align}
 I \triangleq \mathbb{E}[X\sin(X)] = Im \left( \int_{\mathbb{R}} x e^{ix} e^{-\frac{1}{2\sigma^2} (x-\mu)^2} \mathrm{d}x \right) .
\end{align}
To compute this sum, we have to factorise the two exponential terms.
A rule of thumb for such calculation is that a gaussian stays gaussian when multiplied by an exponential term of the form $e^{ax}$.
I let you do the math, but one can write
\begin{equation}
-\frac{1}{2\sigma^2} (x-\mu)^2 + ix = -\frac{1}{2 \sigma^2}\big( x- (\mu+i\sigma^2) \big)^2 + i\mu - \frac{\sigma^2}{2} .
\end{equation}
Then, by recognising the expectation of a new gaussian distribution
\begin{align}
I =& Im \left( e^{-\frac{\sigma^2}{2} + i\mu} \int_{\mathbb{R}} \frac{1}{\sqrt{2\pi \sigma^2}} x e^{-\frac{1}{2\sigma^2}(x - \mu - i\sigma^2)^2} \mathrm{d}x \right) \\
=& Im \left( e^{-\frac{\sigma^2}{2} + i\mu} \times (\mu + i \sigma^2) \right) \\
=&e^{-\frac{\sigma^2}{2}} \times \left( \sigma^2 \cos(\mu) + \mu \sin(\mu) \right),
\end{align}
which corresponds to wolfies's answer.
Comment: did you miss the x in the last integral?
Comment: Thank you for pointing out this error, it has been corrected accordingly.
Comment: sorry for reopening, but x is still missing, right?
Comment: Sorry, yes $x$ was still missing, because it is an expectation. I only corrected the $\mathrm{d}x$.
Comment: Note that this can also be solved quickly using the same trick with the moment-generating function
Answer: Have you tried a computer algebra system? Here $X \sim N(\mu, \sigma^2)$ with pdf $f(x)$:

Here is the output from mathStatica / Mathematica:
Comment: I dont have Mathematica, is this also possible with Matlabs Symbolic Toolbox?


Cross scripting attack by appending link url in our web site

Question: Our site is facing problem of cross scripting attack in the form of
appending link url in our site pages
Previous attack was on near by 1 month month ago,
on that we have done following changes to our site :
1. parametrized queries
2. Use of Html Encode
3. RequestValidation="True" in web.config
and we successfully stop that attack by using above methods
Now After one month later we again get affected with same xss attack
if anyone have any suggestions about what we can do more to stop it?
Answer: xss is most often caused by allowing raw content (such as user-entered html, containing


I'm unable to install the Symfony var-dumper component

Question: I am having issues installing symfony/var-dumper package via composer
the command I ran is
composer require symfony/var-dumper

The result I get is
Your requirements could not be resolved to an installable set of packages.

Problem 1
   - Conclusion: remove drupal/core-recommended 8.9.1
   - Conclusion: don't install drupal/core-recommended 8.9.1
   - Conclusion: don't install symfony/var-dumper v5.1.2
   - Conclusion: don't install symfony/var-dumper v5.1.1
   - Conclusion: don't install symfony/var-dumper v5.1.0
   - Conclusion: don't install symfony/var-dumper v5.1.0-RC2
   - Conclusion: don't install symfony/var-dumper v5.1.0-RC1
   - Conclusion: don't install symfony/var-dumper v5.1.0-BETA1
   - Installation request for drupal/core-recommended (locked at 8.9.1, required as ^8.8) -> satisfiable by drupal/core-recommended[8.9.1].
   - Conclusion: don't install symfony/var-dumper 5.2.x-dev
   - drupal/core-recommended 8.9.1 requires symfony/console v3.4.41 -> satisfiable by symfony/console[v3.4.41].
   - symfony/console v3.4.41 conflicts with symfony/var-dumper[5.1.x-dev].
   - symfony/var-dumper 5.1.x-dev conflicts with symfony/console[v3.4.41].
   - symfony/var-dumper 5.1.x-dev conflicts with symfony/console[v3.4.41].
   - Installation request for symfony/var-dumper ^5.1 -> satisfiable by symfony/var-dumper[5.1.x-dev, 5.2.x-dev, v5.1.0, v5.1.0-BETA1, v5.1.0-RC1, v5.1.0-RC2, v5.1.1, v5.1.2].
   Installation failed, reverting ./composer.json to its original content.

My composer.json file is
{
  "name": "drupal/legacy-project",
  "description": "Project template for Drupal 8 projects with composer following drupal/drupal layout",
  "type": "project",
  "license": "GPL-2.0-or-later",
  "homepage": "https://www.drupal.org/project/drupal",
  "support": {
    "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
    "chat": "https://www.drupal.org/node/314178"
},
  "repositories": {
    "0": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
},
  "require": {
    "composer/installers": "^1.2",
    "drupal/core-composer-scaffold": "^8.8",
    "drupal/core-project-message": "^8.8",
    "drupal/core-recommended": "^8.8",
    "drupal/core-vendor-hardening": "^8.8",
    "phpmailer/phpmailer": "^6.1"
},
  "conflict": {
    "drupal/drupal": "*"
},
  "minimum-stability": "dev",
   "prefer-stable": true,
   "config": {
    "sort-packages": true
},
  "extra": {
    "drupal-scaffold": {
        "locations": {
            "web-root": "./"
        }
    },
    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        "libraries/{$name}": [
            "type:drupal-library"
        ],
        "modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "drush/Commands/contrib/{$name}": [
            "type:drupal-drush"
        ],
        "modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ]
    },
    "drupal-core-project-message": {
        "include-keys": [
            "homepage",
            "support"
        ],
        "post-create-project-cmd-message": [
            "<bg=blue;fg=white>                                                         </>",
            "<bg=blue;fg=white>  Congratulations, you've installed the Drupal codebase  </>",
            "<bg=blue;fg=white>  from the drupal/legacy-project template!               </>",
            "<bg=blue;fg=white>                                                         </>",
            "",
            "<bg=yellow;fg=black>Next steps</>:",
            "  * Install the site: https://www.drupal.org/docs/8/install",
            "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
            "  * Get support: https://www.drupal.org/support",
            "  * Get involved with the Drupal community:",
            "      https://www.drupal.org/getting-involved",
            "  * Remove the plugin that prints this message:",
            "      composer remove drupal/core-project-message"
        ]
    }
}
}

I haven't even customized it yet, this is pretty much out of the box at the moment and I am already having issues.
Answer: drupal/core-recommended 8.9.2 requires symfony/console v3.4.41 while the currently latest symfony/var-dumper requires symfony/console at minimum version 4.4. When you run composer require symfony/var-dumper without specifying any version it will try to install the currently latest version 5 of the var-dumper. Mismatched dependencies. Error. So simply install a version of the var-dumper that matches the dependencies and can be installed with Symfony 3.4 components.
composer require symfony/var-dumper:^4.4


Retornando dados selecionados para Razor em objeto anônimo

Question: Possuo um controller onde busco os aniversariantes do mês. Porém possuo mais de 1000 aniversariantes por mês, retornando uma tabela com mais de 50  atributos de cada um, tonando assim a consulta demorada.
    public ActionResult Aniversariantes()
    {
        var usuarios = usuarioRepository.Lista.Where(u => u.DtNascimento.Month == DateTime.Now.Month);
        var usuariosOrdenados = usuarios.OrderBy(u => u.DtNascimento.Day)ToList();
        return View(usuariosOrdenados);
    }

Para tentar resolver, tentei buscar apenas os campos que desejo mostrar em minha View.
public ActionResult Aniversariantes()
    {
        var usuarios = usuarioRepository.Lista.Where(u => u.DtNascimento.Month == DateTime.Now.Month);
        var usuariosOrdenados = usuarios.OrderBy(u => u.DtNascimento.Day).Select(x => new{x.DtNascimento, x.NmFuncionario, x.Descricao}).ToList();
        return View(usuariosOrdenados);
    }

Porém deste jeito recebo o seguinte erro ao acessar a View:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType23[System.DateTime,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PortalRH.DomainModel.Entities.Usuario]'.

Rastreamento de pilha
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType2`3[System.DateTime,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PortalRH.DomainModel.Entities.Usuario]'.]
   System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +378
   System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
   System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +614
   System.Web.Mvc.ViewDataDictionary`1..ctor(ViewDataDictionary viewDataDictionary) +37
   System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +98
   System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +425
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9715856
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

View
@model IEnumerable<PortalRH.DomainModel.Entities.Usuario>

@{
    ViewBag.Title = "Aniversariantes do Mês";
}

 @ViewBag.Matricula / @ViewBag.Contrato - @ViewBag.Nome

     Você está em: @ViewBag.Title

Aniversariantes do Mês

                        Nome do Funcionário
                        Secretaria
                        Data do Aniversário

                    @foreach (var item in Model)
                    {

                                @item.NmFuncionario

                                @item.Descricao

                                @item.DtNascimento.Day.ToString("00")/ @item.DtNascimento.Month.ToString("00")

                    }

Dúvida: Como retornar apenas os três campos que realmente necessito na consulta?
Lembrando que a forma que estou fazendo, ao debugar o código eu recebo o resultado correto, apenas os três campos. Porém ao listar na View recebo este erro.
Answer: Duas formas:
A forma recomendada
Crie um ViewModel tipado com os 3 campos que você precisa. Passe para o Razor uma coleção tipada:
@model IEnumerable<PortalRH.DomainModel.ViewModels.UsuarioViewModel>

A forma não recomendada
Funciona, mas tende a criar o caos. Faça o Razor aceitar um objeto dinâmico:
@model IEnumerable<dynamic>

Não é recomendado porque todos os campos são resolvidos em tempo de execução, o que dificulta na prevenção de erros.
Comment: Ao criar a **ViewModel** eu necessito realizar alguma alteração em meu Controller?
Comment: Na primeira forma, o Select ficaria assim: `.Select(x => new UsuarioViewModel {x.DtNascimento, x.NmFuncionario, x.Descricao}`.
Comment: Muito obrigado, resolveu o meu problema.
Porém da forma que colocou recebo erro de sintaxe, ai alterei um pouquinho o código, ficando assim: **.Select(x => new UsuarioViewModel ()
            {
                Descricao = x.Descricao, NmFuncionario = x.NmFuncionario, DtNascimento = x.DtNascimento
            }).ToList();**
Comment: @RenilsonAndrade Exatamente isso.


Comparing two lists according to specific properties

Question: how can i compare 2 lists and have the not matching items but according to the specifics properties
public partial class Cable : StateObject
{
    public int Id { get; set; }
    public int CablePropertyId { get; set; }
    public int Item { get; set; }
    public int TagNo { get; set; }
    public string GeneralFormat { get; set; }
    public string EndString { get; set; }
    public string CableRevision { get; set; }
}

I want to comparision accomplished accoring to the CablePropertyId,TagNo and CableRevision, if i use
var diffCables = sourceCables.Except(destinationCables).ToList();

the whole properties are compared to each other . how can i do that?
Comment: @BSoD_ZA: That does not suffice, you need to override `Equals` + `GetHashCode` or create and use a custom `IEqualityComparer` as mentioned below.
Comment: Have you tried overriding the Equals method?
Comment: You should check the following answer:
[Compare lists using LINQ and Join](https://stackoverflow.com/a/55138693/7606096) Works great!
Answer: Use Linq except method with custom EqualityComparer.
http://msdn.microsoft.com/en-us/library/bb336390(v=vs.110).aspx
class CableComparer : IEqualityComparer<Cable>
{
    public bool Equals(Cable x, Cable y)
    {
        return (x.CablePropertyId == y.CablePropertyId && ...);
    }

    public int GetHashCode(Cable x) // If you won't create a valid GetHashCode based on values you compare on, Linq won't work properly
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + x.CablePropertyID;
            hash = hash * 23 + ...
        }
        return hash;
    }
}

var diffCables = sourceCables.Except(destinationCables, new CableComparer());

Also, ToList() operation on the result isn't really necessary. Most of the time you can just operate on the result of Linq query IEnumerable without specifying the exact type; this way you won't waste performance on unneeded ToList() operation.
By the way, a couple of others proposed Where-based queries with simple lambda. Such solution is easier to read (in my opinion), but it's also less optimized: it forces n^2 checks, while IEqualityComparer allows Linq to be more optimal because of GetHashCode() method. Here's a great answer on importance of GetHashCode, and here's a great guide on writing GetHashCode() override.
Comment: what do you mean by  return x.CablePropertyId ...;
Comment: @nnmmss expanded this according with Jon Skeet's recommendations about `GetHashCode()` implementation for clarity.
Answer: You can create your own IEqualityComparer<Cable> like this:
public class CableComparer : IEqualityComparer<Cable>
{
    public bool Equals(Cable x, Cable y)
    {
        return x.CablePropertyId == y.CablePropertyId &&
               x.TagNo == y.TagNo &&
               x.CableRevision == y.CableRevision;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public int GetHashCode(Cable x)
    {
        return x.CablePropertyId ^
               x.TagNo.GetHashCode() ^
               x.CableRevision.GetHashCode();
    }
}

Then use this overload of Except:
var comparer = new CableComparer();
var diffCables = sourceCables.Except(destinationCables, comparer).ToList();

Alternatively, the MoreLINQ library (also available on NuGet) provides a convenient ExceptBy method:
var diffCables = sourceCables.ExceptBy(
        destinationCables,
        x => new {
            x.CablePropertyId,
            x.TagNo,
            x.CableRevision
        })
    .ToList();

Comment: I don't think that bitwise xor is a good way to write `GetHashCode()`. You'll get a collision on {1,2,4} and {2,1,4}, which seems a very likely combination.
Answer: You can override the Equals and GetHashCode methods of Cable if you will always compare this object in this manner.
Otherwise you can write a custom comparer and use the overload for .Except
List.Except Method
Answer: If you use LINQ with IQueryable<>, there may be solution with Where()
var destinationCablesAnon = destinationCables.Select(a=>new {a.CablePropertyId, a.TagNo ,a.CableRevision}); // add ToArray() if use IEnumerable<>

var diffCables  = sourceCables.Where(a=>!destinationCables.Contains(new {a.CablePropertyId, a.TagNo ,a.CableRevision})).ToList();

Answer: Essentially, when you want to compare your own types, you'll need to describe how they compare/differ from each other. Linq wouldn't know which properties in your Cable class are different right?
So you build a comparer which can be used generally to compare two types.
In this case, two Cable instances:
class CableComparer : IEqualityComparer<Cable>
{

    public bool Equals(Cable c1, Cable c2)//these represent any two cables.
    {
        if (c1.Height == c2.Height && ...)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(Cable c)
    {
        //this will work if each ID is unique
        return c.Id.GetHashCode();
        //otherwise you do this:
        //return (c.Id ^ c. CablePropertyId).GetHashCode();
    }
}

Then:
IEnumerable<Cable> except =
            sourceCables.Except(destinationCables, new CableComparer());

Answer: I think you can use something like this:
sourceCables.Where(sc => !destinationCables.Any(dc => dc.CablePropertyId == sc.CablePropertyId && ...));

Comment: I think that while lambda-based approach is more readable, it can be worse performance-wise, as it won't be able to use optimizations based on GetHashCode in IEqualityComparer.


How can I get real-time raw data using GoPro hero 5?

Question: I want to use camera for development.
Camera's model is GoPro hero 5.
But I can't find the way to get image data using GoPro.
Everyone use livestreaming using Wifi.
I want to get real-time raw image data using USB
How can I get the data?
Thanks

Connect USB to handle image in real-time
 -> Gopro's USB is only to charge
The only method offered by Gopro is the RTSP connection via the WIFI connection
Comment: Maybe try GoPro Tech Support?
Comment: yes. but nothing to solution.
Answer: What do you mean raw data? You could use HDMI or the MTP mount point of the HERO5 to get images
Comment: raw image data like mat to use image processing. I already success by using libvlc and I get the real-time image data.


Nested sql missing right parenthesis, but where?

Question: I´m trying to create a nested-sql that is suposed to show me all ID from table1 that also is in table2, but the thing is that if the row from table1 got the flag istask = 1 i want it to select the parentid instead of the ID.
There can be multiple ID with the same parentid
I know that this is simply done by a join but in IBM Maximo´s webinterface you are not alowed to create joins in a query and we can not create views that can be accessed within Maximo´s webinterface
I have tested with the following queries but i will only get the missing right parenthesis error.
If i try the queries as own queries they work.
Test 1
 SELECT * from table1
    WHERE id in(SELECT refid from table2 WHERE table1.istask = 0
                OR (SELECT DISTINCT table1.parentid from table1 WHERE
                    id in(select refid from table2 WHERE table1.istask = 1)))

Test 2
SELECT * from table1
    WHERE id in((SELECT refid from table2 WHERE table1.istask = 0 )
                OR (SELECT DISTINCT table1.parentid from table1 WHERE
                    id in(select refid from table2 WHERE table1.istask = 1))))

Comment: I'm confused by some of the wording - you state "following queries... missing right parenthesis error" and "if i try the following queries they work"  then you list two queries.  Are the queries working or not working?  Seems like you're providing conflicting information.  Why exactly are the queries being posted?  Do they give results you don't expect? What do you expect?
Comment: Sorry, i will edit and make it mor clear, but i mean that  if i run the two `SELECT` clauses within the `WHERE id IN` as own queries then it works.
The two tests are just different ways i have tested to nest them
Answer: My guess is that you're trying to do this:
SELECT * from table1
    WHERE id IN (SELECT refid from table2 WHERE table1.istask = 0)
    OR id IN (SELECT DISTINCT table1.parentid from table1
        WHERE id IN (select refid from table2 WHERE table1.istask = 1))

In the second part of the where clause, you need to repeat 'id IN'.
Comment: Tested it and it works! When i see it now it´s obvious. Thanks
Comment: Maximo is picky in that you need to insert extra right parenthesis or explicitly state the column you are selecting. Typically, the SQL is select * from table where and you fill in the where clause. There may be additional clauses if you've configured sorting (e.g. order by) in the Application Designer.


Popup Bottom Navbar in Bootstrap 4

Question: I'm trying to achieve this in Bootstrap 4:
https://jsfiddle.net/edz80vw5/
But:

Just produces a popup box in Bootstrap 4.
Answer: You're looking for the fixed-bottom Navbar in Bootstrap 4...
   ...

If you want a dropdown inside the fixed-bottom Navbar to also open upwards, use "dropup"...

          Dropup

          Action
          Another action

https://www.codeply.com/go/iNxFzV2H0J

Popup Bottom Navbar in Bootstrap 4


Select maximum across columns and identify column origin in R and/or ggplot

Question: I have several numeric columns in a data frame, I want to do the following:

Select maximum values across all the columns and return a column with the maximum values. This is easy.
The hard part: plot the returned column with different color segments identifying which column the part is from. For example, a red segment means those values are from column 1, a blue segment means from column 2.

A minimal example:
Olddata <- data.frame(X1=1:10,X2=5.5)

The returned data frame should be
Newdata <- data.frame(ColNew=c(rep(5.5,5),6,7,8,9,10)).

I am wondering how to plot Newdata as a line with the first part being red and the second part being blue. In addition, if this could be generalized to Olddata <- data.frame(X1,X2,X3,...), so Newdata will be plotted as a line of a number of color segments.
Thanks!
Comment: Add an example (showing what you already can do) if you want tested answers with code in them.
Comment: See `which.max`. It's just as easy as part 1.
Comment: Or possibly `max.col` although it's for numerical matrices..
Comment: Thanks. I see that max.col identifies the column where the max values are from, but how could I **plot** the new column ColNew=max(Column1,Column2,...ColumnN) as a line with different color segments?
Answer: # since it's all numeric, let's make it a matrix
# matrices are easier to apply functions by row
old = as.matrix(Olddata)
newdata = data.frame(max.value  = apply(old, MARGIN = 1, FUN = max),
                     max.column = apply(old, MARGIN = 1, FUN = which.max))
# alternatively, you could do max.column = max.col(old)
newdata

> newdata
   max.value max.column
1        5.5          2
2        5.5          2
3        5.5          2
4        5.5          2
5        5.5          2
6        6.0          1
7        7.0          1
8        8.0          1
9        9.0          1
10      10.0          1

It's really not clear what you want the plot to look like. Here's a start with points (below).
with(newdata, plot(max.value, col = max.column))

Here's another guess with ggplot, this way won't do too well as-is if your max.column alternates back and forth (though adding in a little rle logic for the group aesthetic would fix that).
library(ggplot2)
ggplot(newdata, aes(x = 1:nrow(newdata), y = max.value,
       group = max.column, color = factor(max.column))) +
    geom_line() +
    theme_bw()

Some questions for you to think about:

If you connect all the points, what color do you want the segment joining 5.5 to 6?
If you don't connect all the points, what do you want to do with points by themselves, like if max. column goes 1, 1, 2, 1, 1, what do do with the 2?
I've assumed you just want row number on the x axis, is this right?

I think it makes the most sense for the scope of this particular question to be on the data extraction. If you have trouble making the plot you want, you should specify it more completely in a new question. You can link back to this question, use the same or slightly modified sample data, and use the method from my answer to get the data for plotting.
Comment: You answer and the plots are exactly what I need. I now believe I do not really need a line, points with different colors are perfectly fine so long as readers know which column those points are from using possibly a legend. Thanks!


how can I merge single column dataframe to multicolumn dataframe?

Question: There's a multi columns dataframe like below
      x          y
      a     b    a     b
 1   21    54    4     7
 2   18    23    2     4
 3   10    54    8     9

and there's a single column dataframe to this
    alpa    beta
 1    9     5
 2    1     3
 3   10     7

how can I merge two dataframes like below??
      x          y        alpa   beta
      a     b    a     b
 1   21    54    4     7     9     5
 2   18    23    2     4     1     3
 3   10    54    8     9    10     7

Answer: You need join 2 DataFrame with MultiIndex or 2 Dataframes with no MultiIndex:
df2.columns = pd.MultiIndex.from_product([['new'], df2.columns])
df3 = pd.concat([df1, df2], axis=1)
print (df3)
    x      y     new
    a   b  a  b alpa beta
1  21  54  4  7    9    5
2  18  23  2  4    1    3
3  10  54  8  9   10    7

df1.columns = df1.columns.map('_'.join)
df4 = pd.concat([df1, df2], axis=1)
print (df4)
   x_a  x_b  y_a  y_b  alpa  beta
1   21   54    4    7     9     5
2   18   23    2    4     1     3
3   10   54    8    9    10     7

Else get tuples for MultiIndex:
df = pd.concat([df1, df2], axis=1)
print (df)
  (x, a)  (x, b)  (y, a)  (y, b)  alpa  beta
1      21      54       4       7     9     5
2      18      23       2       4     1     3
3      10      54       8       9    10     7

Answer: IIUC, you need to make a multiindex with blank first level:
df2.columns=pd.MultiIndex.from_product((df2.columns,['']))
pd.concat((df1,df2),axis=1)

    x      y    alpa beta
    a   b  a  b
1  21  54  4  7    9    5
2  18  23  2  4    1    3
3  10  54  8  9   10    7


Contradiction to $\sum_{n=0}^\infty n a_n(x_1-x_0)^{n-1}$ is convergent

Question: I have a limit $\lim_{n \to \infty} a_n|x_1-x_0|^n \ne 0$, and I want to prove that $\sum_{n=0}^\infty n a_n(x_1-x_0)^{n-1}$ is divergent.
We also know that $|x_1-x_0|>R \ge 0$.
I assumed towards a contradiction that the series converges, so $\lim_{n \to \infty} n a_n (x_1-x_0)^{n-1}=0$.
So after some cosmetic changes, we get that $\lim_{n \to \infty}a_n(x_1-x_0)^n=0$.
So I separeted in to 2 case:
If $x_1-x_0>0$, than we get an easy contradiction.
If $x_1-x_0<0$ we get that $\lim_{n \to \infty} a_n \cdot |x_1-x_0|^n=\lim_{n \to \infty} a_n \cdot (-1)^n(x_1-x_0)^n$
But I do not know how to get a contradiction here.
Any help?
Thanks a lot!
Answer: If$$\lim_{n\to\infty}a_n|x_1-x_0|^n\ne0,\tag1$$then$$\left|\lim_{n\to\infty}na_n|x_1-x_0|^{n-1}\right|=\lim_{n\to\infty}\frac n{|x_1-x_0|}|a_n||x_1-x_0|^n=\infty,$$due to $(1)$ and to the fact that $\lim_{n\to\infty}\frac n{|x_1-x_0|}=\infty$. So, the series $\sum_{n=1}^\infty na_n(x_1-x_0)^{n-1}$ diverges.
Comment: Amazing! Thanks a lot!
Comment: I'm just curious, what if $(1) \to -\infty$  or does not exists?
Comment: Simply consider the limit supremum $S$ of the sequence $\{|a_n||x_1-x_0|^n\}$. This is not $0$. Which implies that there exists a sub sequence  $|a_{n_k}||x_1-x_0|^{n_k}$ converging to $S$ (if $S$ is infinite, then this subsequence diverges). Now $n_k|a_{n_k}||x_1-x_0|^{n_k}$ goes to infinity!


Conditionally change the image field style and wrapping it in a div

Question: The Article content type has been classified by taxonomy vocab Topic, where each Article's node has one topic.
For some usability and design requirements, I want Articles belongs to a specific topic to render the image field in different image style when it is on the full display mode.
I used the code in node--article.tpl.php:
if ($node->field_topic['und'][0]['tid'] == 154){
     // In some preprocessor...
    $images = field_get_items('node', $node, 'field_image');
    if(!empty($images)) {
      $image = field_view_value('node', $node, 'field_image', $images[0], array(
        'type' => 'image',
        'settings' => array(
          'image_style' => '200x260',
          'attributes' => array('class'=>'center-text')
        )
      ));
    }
    // Testing wrapping the image
    $variables['image'] = "----".$image."----";

    // Now, in your .tpl.php
     $content['field_image'] =  $image;
     }
  print render($content)

The above code renders the image with HTML code like the following:

However, it works fine but has two limitations:
1- I could not able to figure out how to enclose  the image inside a div with css class to style it using CSS. The img tag is supplied only i.e without any wrapping divs or spans!
2- Using it from node--article.tpl.php is not recommended and I have a custom module, but I don't know the suitable node's hook that allows me to perform this task.
Comment: so the `center-text` div class does not get printed?
Answer: You can set wrapper for it with simple way
instead
print render($content);
just use
print '
'.render($content['field_image']).'
;
and for second limitation if you have not $node just need load it with node_load  ( if you have nid)
So before your code
  $node= node_load($nid);

Comment: Note that in node--article.tpl.php you should then `hide($content['field_image']);` so that it does not render twice if also using `render($content);`.
Comment: `render($content)` prints out all node's contents, so this wrapper will not be dedicated for the image only!
Comment: @sємsєм I update my answer
Comment: no first `render($content['field_image'])` then `hide($content['field_image']);` then `render($content);`, ok?


Finding the angle between the radius and vector

Question: I'm trying to find the angle between the radius vector produced and the tangent to the curve whose equation is $r = 4\cos\theta$ at the point where $\theta = \frac{\pi}{4}$.
My assumption was that I take the derivative, such that $\frac{dr}{d\theta}=-4\sin\theta$. Then substitute in the value for $\theta$.
Though, this isn't the right answers, for I expect $\frac{3\pi}{4}$.
I would appreciate your help, and if possible a pictorial example to help me understand this. The book i'm using is fairly terse and vague.
Answer: As $\theta$ increases the point on the curve moves from $(4,0)$ to $(2,2)$ counterclockwise.
The tangent and the produced radius vector form an angle $=135^{\circ}$.
Answer: Angle enclosed in a semicircle, other two for given condition are shown in isosceles right triangle.
Actually two correct answers. The angle radius vector makes to the outer tangent $\psi$ is $ 3 \pi/4$ but considering inner tangent it could be also $ \pi/4$ as shown... even with a consistent CCW convention.
The differential equation  determines the tangent. Its ode is $ \sin \psi =r/4 $. At the given radius, accordingly there are two arcsin $\psi$ values


AspNet mudar características do textBox dinamicamente

Question: Para teste criei um botão o qual chama uma função em javascript através do onclick(). Nessa função gostaria de mudar por exemplo a cor da borda do textBox, melhor ainda seria mudar a cor daquela borda azul padrão que tem quando o textBox está selecionado.
Answer: Você pode adicionar estilos dinamicamente para mudar as características do seu textbox. Exemplo:
<code> <html>
 <head>
 //Você pode usar classe
<style type="text/css">
    .borda {
        border: 1px solid red;
    }
</style>

  <script type="text/javascript">
    function mudarEstilo() {

        //exemplo sem usar classe, aqui eu adiciono uma borda de 1px de largura do formato solid e vermelha diretamente na propriedade css do input
        $('#txtTeste').css("border", "1px solid red");

        //aqui eu uso uma classe para o input, essa classe também tem borda de 1px de largura forma
        //prefiro essa solução
        $('#txtTeste').addClass("borda");
    }
</script>
</head>
 <body>
   <input type="button" value="Teste" onclick="mudarEstilo();" />
   <input type="text" id="txtTeste" />
 </body>
</html>
</code>
Comment: obrigado, deu certo. Eu havia tentado de forma parecida, não lembro direito do motivo de não ter dado certo. Você tem um site que tenha todas essas propriedades .css que o jquery usa?
Comment: na verdade, o que eu realmente queria mudar era a cor do textBox, cor azul padrão, de quando ele está selecionado. Você sabe como fazer isso? Eu andei vendo algo sobre pegar o elemento e usar alguma propriedade do mesmo para modificar algo, não consegui entender muito bem como faz isso ainda. Ah, e o textBox é em asp.
Comment: @HeyJoe site do jquery : http://jquery.com/download/  eu baixei o 2.2.3.
O css é nativo não usei nem um framework. Abraços
Comment: @HeyJoe Você pode mudar a cor do textbox quando está selecionado sem precisar usar javascript. No seguinte exemplo o css só será aplicado quando o campo tiver foco, estou pintando a borda do campo de vermelho e colocando uma sombra de azul:
 #txtTeste:focus {
            border-color: red;
            box-shadow: 0 0 10px blue;
        }


What kind of chord progressions am I using?

Question: I taught myself music theory mostly by playing with chord progressions and writing music based on what I like. (I've since learned music theory proper.) As a result, I prefer to use some chord progressions that I somewhat rarely see elsewhere over most typical chord progressions.
For example, when a music theory resource introduces chord progressions, the biggest idea that it uses is that chords are usually made up of notes in a scale. So, for instance, the most common chords for C Major are CMaj, dmin, emin, FMaj, GMaj, amin, and bdim.
In contrast, the chords I use the most don't follow that pattern. In major keys, I use almost exclusively IMaj, bIIMaj, bIIIMaj, IVMaj, bVIMaj, and bVIIMaj. I use the same chords for minor key songs, except I switch out IMaj with imin.
Neither of these sets of chords come from their keys, and they don't match any modes, either. My question is, is there any name or common way to describe the chord progressions I prefer to use? Or do I like some pretty unusual chords?
I know that some of these chords appear in common chord progressions. bVI-bVII-I, I-bIII-IV, and I-bII-bVII are three progressions that show up in pop, rock, and EDM and that I use frequently myself.
Answer: What you're doing is sometimes called modal interchange, i.e. you 'borrow' chords from other modes with the same tonic. The chords you mentioned when you play in major are taken from the major scale (I and IV), from the parallel minor key (bIII, bVI, bVII), and from the parallel phrygian mode (bII). When you play in minor you just borrow one chord from phrygian (bII). (Note that IV major is perfectly OK in minor, just think melodic minor or dorian). The technique of modal interchange is used a lot in pop/rock and in jazz. Its most frequent use is borrowing chords from the parallel minor key when playing in a major key. Once you start looking for it, you'll find it literally everywhere. There's also a short Wikipedia article about it.
Answer: You seem to be using a technique called 'planing' which exploits the fact that any set of chords of the same shape fit well together, particularly when they move by step.


What is C in Standard Form derived from?

Question: For Example $9x + 16y = 72$. What is $72$ derived from? Why does dividing $72$ by $9x$ get us to the slope? Why does dividing $72$ by $16y$ get us to the $y$ intercept?
Comment: What do you mean "derived from"?  You wrote it down...
Comment: I'm doing an exercise. I would like to know what 72 is based on and why dividing by that number makes sense. Your question makes no sense.
Comment: Do you mean: given an equation for a line, such as $y=mx+d$, how can you get the equation to have the form $ax+by=c$?
Comment: $72$ means that the line intersects the $x-axis$ at $x=72/16$.
Comment: Well in simple terms, what I mean is that if you take the equation in standard form, to convert it to slope intercept form, all it takes is solving the algebraic equation. Why does that make sense and where is the number 72 derived from. Hope you understand.
Comment: You asked earlier about the books by Blitzer; here are places to buy the sixth edition, one in England. https://www.abebooks.com/servlet/SearchResults?isbn=9780134469171&cm_sp=mbc-_-9780134469171-_-all  I am guessing you prefer English to German; however, there are surely similar books in German, and ABEBOOKS might easily have a version in Germany (I have purchased books that came from shops in Germany, through this site)
Comment: Thanks Jaggy, do you know why this one (loose leaf edition) only contains ~500 pages** and the 250$ edition over 1000?
Comment: No way of knowing; first, let me point out https://www.abebooks.de/   then I will check. Note that Blitzer has many editions, also a solutions manual, also a set of DVD's which are probably like the Khan academy except they are him giving lessons about this book (I think). Let me check that last part. Anyway, let me try to find out about your 500 and 1000 pages
Comment: here is the german site on Blitzer, many results, shipping assumed to be going to Germany: https://www.abebooks.de/servlet/SearchResults?sts=t&an=blitzer&tn=algebra+and+trigonometry&kn=&isbn=
Comment: To those voting to close/downvoting (I accidentally closed so I'm casting a reopen vote), this is a valid question IMO, and I believe it's best to approach this from the elementary perspective.
Answer: The "standard form" of a line is $Ax + By = C$ where $A$ and $B$ are not all zero. Usually we write lines in the slope intercept form $y = mx +b$. Here's how to go from standard form to slope-intercept form - I show all my students this.
From the standard form, divide by $B$ to allow the coefficient of $y$ to be $1$.
$$ \frac{A}{B}x + y = \frac{C}{B} $$
Now let's subtract $\frac{A}{B}x$ on both sides.
$$y = -\frac{A}{B}x + \frac{C}{B} $$
Now we do a thing called "equating coefficients." This process allows us to identify the slope and y-intercept of this line. The coefficient on $x$ is the slope, and the constant term the y-intercept. Hence we may identify $ m = -\frac{A}{B}$ and $b = \frac{C}{B}$.
Of course, you ask about $C$ in particular.  This is a parameter to help define other pieces of the line - namely, intercepts. Changing $C$ changes the location of these intercepts.
Comment: Thanks Sean, I might have phrased the question wrong.. but I tried to understand how they make an equation like this. Like how does Khan Academy come up with 9x + 16y = 72. Where did they take 9x, 16y and 72 from and what is the meaning of 72 itself (C). It sucks but we don't have German speaking forums so I just try to explain it in the best possible way that my English speaking abilities allow me to.
Comment: @EliS.: Can you refer us to the Khan link so we can now better what you are referring to?
Comment: https://www.khanacademy.org/math/algebra/two-var-linear-equations/standard-form/v/standard-form-for-linear-equations
Comment: @Eli It's just for the sake of exercise. In fact, you should know that two distinct points determine a line, so given the intercepts, one can describe a line by an equation those intercepts satisfy. The $C$ comes from possibly clearing fractions and making things a little more manageable. Not everything has a reason - I hate to give the "that's the way it is" cop-out, but, yeah.
Comment: @Sean Roberson Yeah I just like to dig into the why's, should probably let that go.


Books for algebraic geometry, algebraic topology

Question:
Possible Duplicate:
(undergraduate) Algebraic Geometry Textbook Recomendations

I am planning to self-study one of these  two subjects: Algebraic geometry , Algebraic topology. I can borrow books from library, but I don't know which books to borrow. Please suggest books for me.
Thank you
Comment: Related http://math.stackexchange.com/questions/1748/undergraduate-algebraic-geometry-textbook-recomendations/24443#24443

http://math.stackexchange.com/questions/998/best-algebraic-geometry-text-book-other-than-hartshorne/24447#24447
Comment: And another: http://math.stackexchange.com/questions/89843/learning-roadmap-for-algebraic-topology
Comment: @Seirios I never studied homological algebra. Do I need to study homological algebra before studying algebraic topology
Comment: You can study many subjets in algebraic topology without homological algebra. For example, Massey's book doesn't mention it.
Comment: @Seirios ,@Mohan Thanks everyone. Lets close the question!
Comment: You don't really need to study homological algebra before doing either. The deepest things you'll most likely use in AT are 5-lemma or snake lemma, but only for abelian groups. Can you clarify what level of AG you want to learn?
Comment: @John Stalfos I never studied AG before, thus I guess I am looking for an undergraduate book
Comment: @JohnStalfos However if there are good graduate AG books for beginners, then please mention them
Comment: Based on my experience I'd suggest Reid's Undergraduate Algebraic Geometry. You can probably do every problem in the book within a few months, and best of all it has some actual geometry in it. From there I don't really know. I took a first semester graduate class out of Shafarevich, but I found the book quite frustrating, as did most of my classmates. Hartshorne(what we moved too) is also frustrating at times, but for different reasons.
Answer: A very beautiful introduction to algebraic geometry is the book "Ideals, Varieties, and Algorithms: An Introduction to Computational Algebraic Geometry and Commutative Algebra" in the Springer undergraduate texts in mathematics series. (It only requires basic abstract algebra as a prerequisite).
The second "half" of Munkres' 2000 Topology textbook is an introduction to algebraic topology.
Comment: Is the book that you mentioned written for math students or CS students ?
Comment: Math students .
Answer: Algebraic Geometry
For algebraic geometry there are a number of excellent books.  Hartshorne's Algebraic Geometry is widely lauded as the best book from which to learn the modern Grothendeick reformulation of Algebraic Geometry, based on his Éléments de géométrie algébrique. This is also, however, considered one of the most challenging textbooks ever written on any mathematical subject ever. This makes it a poor first choice. He leaves critical and very much non trivial results as exercises and has very few motivating examples outside of the exercises. But it is well worth the effort.
Others are The Red Book of Varieties and Schemes by Momford which covers the topic from a more classical viewpoint. This is an excellent book. Also from the classical and historical view is Basic Algebaric Geometry I by Shafarevich which is well written and also an excellent book.
I would strongly reccoment reading one of the last two to get a grounding in the historical motivation and classical theory, then read Hartshorne. Be warned though, reading Hartshorne may, and should, take years.

Algebraic topology
There is an excellent book by Allen Hatcher called Algebraic Topology that is available for free on his website, and also as a hard copy on Amazon. This is an excellent geometrically oriented book on the subject that contains much of what you would learn in a graduate course on the subject plus a large number of additional topics. This is where I reccommend you first go.
A second excellent text on the subject is Topology and Geometry by Bredon. This book isn't titled as if it an Angebraic topological work but it is, and it is particularly well written, although requires a bit of maturity and knowledge of category theory.
Finally we have J.P. May's A Concise Cource in Algebraic Topology. This is probably the best text for a second exposure to the subject, or to be used along with one of the two I have just described. It doesn't give a lot of exaples and proceeds very quickly through the subject (hence concise) but it places the field in context and provides motivation for many of the objects of study. This one comes highly recommended as well.
Comment: I wonder why Hartshorne is still recommended. A better choice would be Liu, Görtz-Wedhorn or Bosch.
Comment: @Amr Absolutely. The first half covers general topology so well that it effectively has no competition as a book on general topology, and the second half is an excellent introduction to algebraic topology. Munkres is an excellent writer and teacher.
Comment: @DoctorBatmanGod Is Munkres topology good to study algebraic topology ?


Object: html insert takes up too much height

Question: I am working on a fairly simple HTML page for a JavaScript star-drawing program I've written and have run into some trouble. Since I want the top section of each page to be the same, I figured I could write an html file for that part of the page and insert that into the individual pages. I used <object> to do this and it basically works but takes up a lot of space in the page (I added a red border around the object to show this clearly):
code result
My page's code is:

  <object data="drawthestars-header.html" style="border: 1px solid red;">
    error loading file
  </object>

Draw a star?

      Points:
      <input type="text" value="15" id="deg" size="3" maxLength="3">

      Jump:
      <input type="text" value="6" id="jump" size="3" maxLength="3">

      <button id="redraw" onclick="addStar()">Draw</button>
      <button id="clear" onclick="clearAll()">Clear</button>

drawthestars-header.html, the inserted code, is just:
link???

Could someone point me to what's going wrong here?
Answer: That would be the default IFrame element size, which the object element actually is behind the scene.
Default width/height of an IFrame
You should set the width and height of the object element to change that.


Get Both Default locale translated value and Browser language translated value

Question: I'm trying to get Translated values for two locales for a given i18nkey.
Is there any way to pass required locales for a given key and get all values for the passed locales in ngx translate core translator service.
lets say Test key has de locale value as "Test DE" and Test key has EN locale value as "Test EN"
<code>TranslateService.get('Test');

TranslateService.instant('Test');

</code>
Answer: TranslateService.getTranslation('yourlocale')


How to get client service custom fields value in the whmcs hook?

Question: How do I get a client service custom Field value in whmcs hook?
I want to do something on AfterModuleCreate hook.
Answer: According to docs, the hook will receive the module parameters:
<code>add_hook('AfterModuleCreate', 1, function($vars) {

    $customFields = $vars['params']['customfields'];
    $fieldValue = $customFields['FieldName'];

});
</code>
Comment: Hello. I am trying to get the custom field value using `'chave' => $params['configoptions']["Chave"]`, but I am not getting it. Can you help me? See the image: https://prnt.sc/p04bdc
Comment: Did you try as in the answer above:
$customFields = $vars['params']['customfields'];
$chave = $customFields['Chave'];
Be careful with letters case,  $customFields['Chave'] is not the same as  $customFields['chave']
Comment: Can you tell me how do I get the value of the custom field, inside clientssummary.tpl?
Comment: https://whmcs.community/topic/302047-take-the-value-of-a-custom-field/?tab=comments#comment-1339825


Composer cannot delete .editorconfig

Question: I'm trying to install a third-party library in Drupal 8 by doing 'composer update'. I get this:

I have made it seemingly impossible for it not to be able to delete .editorconfig:

But I still get the same error. What should I try next?
Comment: `chown` that file to your own username, or whatever username you run composer as?
Comment: I did -- I run as administrator.
Comment: Out of frustration, I ran composer as root (yeah, I know, I shouldn't do that) and it ran successfully. I still figure why it won't complete as administrator.
Answer: From https://superuser.com/questions/373115/why-cant-i-delete-a-file-where-i-have-group-write-permissions-on

File deletion is based on directory perms, not file perms (*).

That said, check the directory <code>/var/www/html/drupal_2020</code> permissions.

Composer cannot delete .editorconfig