Find a left ideal of $\mathbb{H}[X]$ that is a maximal, but not a ideal.

Question:
Find a left ideal of $\mathbb{H}[X]$ that is a maximal, but not a ideal.

$\mathbb{H}[X]$ is just the polynomial extension.
$$\mathbb{H}=\{a+bI+cJ+dK \mid a,b,c,d \in \mathbb{R} \} .$$
$$\mathbb{H}[X]=\{\alpha_0+\alpha_1X+\cdots+\alpha_nX^n: \alpha_0,\alpha_1,\dots,\alpha_n\in \mathbb{H}\}$$
First thought is something like $\mathbb{H} \times (XI)$. However, sort of stuck. I know you have to use the non-commutativity of quaternions somewhere.
Second thought is that you have to use something about inverses. Well, it can't have $1$ in it. Since you would get itself. So, ... I'm pretty sure $\mathbb{H} \times (XI)$ is the left ideal. However, can't see how you would get not a right ideal.
Comment: $\mathbb{H}[X]=\{\alpha_0+\alpha_1X+\dots+\alpha_nX: \alpha_0,\alpha_1,\dots,\alpha_n\in \mathbb{H}\}$. It's the ring consisting of polynomials with coefficients in $\mathbb{H}$, not quite what you said.
Comment: @simplicity: I have edited the question. Please check the edits to make sure this is what you intended.
Comment: @BrunoStonek Thanks for that. Silly of me to think that.
Comment: @Srivatsan: I think simplicity may be trying to say $\mathbb{H}[X]IX$ as in the left ideal of $\mathbb{H}[X]$ generated by $IX$. As a side comment, I think using capital letters to denote the "imaginary units" of the quaternions is a bit confusing. ($I$ seems an ideal; plus, you never write $a+bI$ for a complex number, and these sit inside $\mathbb{H}$...)
Comment: @BrunoStonek well, definition of I is 4x4 matrix rings. Has nothing to do with imaginary number. I don't think of I as i.
Comment: @Bruno: Ah, I had a hunch I could be making some mistake (which is why I left that comment). Thanks for pointing it out. I will leave it to the OP to fix the post as necessary.
Comment: @BrunoStonek I'm confused about what you do.
Comment: @BrunoStonek I understand the Quaternions really well. Just can't do this question. It just you was talking about imbedding i in I, which is a question I asked about a month ago, well two months ago.
Comment: @simplicity: Oh, I believe you *should* think of $I$ as the complex number $i$. I suggest that, before doing this exercise, you prove that the quaternions as a subring of $M_4(\mathbb{R})$ (which I think is what you meant) are isomorphic as a ring to $\mathcal{H}$. Here, let $\mathcal{H}=\mathbb{R}^4$ as a set, and denote $1=(1,0,0,0), I=(0,1,0,0), J=(0,0,1,0), K=(0,0,0,1)$. Addition is pointwise, and multiplication is given by considering the laws $i^2=j^2=k^2=ijk=-1$. See that this turns $\mathcal{H}$ into a ring, and prove it is isomorphic to $\mathbb{H}$....
Comment: ...then, identify $\mathbb{C}$ as a subring of $\mathcal{H}$. This may help in getting some familiarity with the quaternion ring.
Comment: Ah, I guess what you mean by your last comment is this question: http://math.stackexchange.com/questions/94640/how-is-mathbbh-a-mathbbr-algebra-but-not-a-mathbbc-algebra . However, IMHO getting familiar with thinking of the quaternions as the ring $\mathcal{H}$ described above, whence seeing easily that $\mathbb{C}\subset \mathcal{H}$ as a subring (and whence $I$ having *everything* to do with the imaginary unit), should be your first concern.
Comment: @BrunoStonek Yeah, I can see what you are saying. However, to be honest I'm more worried about passing exams at the moment. That question came up with exam two years ago. The exam is tomorrow.
Answer: New answer
Let $\mathbb H$ be the $\mathbb R$-algebra generated by the symbols $i_0$ and $j_0$ subject to the relations
$$
i_0^2=-1=j_0^2,\quad i_0\ j_0=-j_0\ i_0.
$$
Let $X$ be an indeterminate and define the $\mathbb R[X]$-algebra $\mathbb H[X]$ by
$$
\mathbb H[X]:=\mathbb R[X]\underset{\mathbb R}{\otimes}\mathbb H.
$$
We must find a maximal left ideal $\mathfrak a$ of $\mathbb H[X]$ which is not an ideal.
Put
$$
\mathbb C:=\frac{\mathbb R[X]}{(X^2+1)}
$$
and denote by $x\in\mathbb C$ the canonical image of $X$.
Note that the left ideal $\mathfrak b\subset\mathbb H[X]$ generated by $X^2+1$ is an ideal. In particular
$$
A:=\frac{\mathbb H[X]}{\mathfrak b}
$$
is a $\mathbb C$-algebra.
If $\pi:\mathbb H[X]\to A$ is the canonical projection, and if $\mathfrak c$ is a maximal left ideal of $\mathbb H[X]$ which is not an ideal, then $\mathfrak a:=\pi^{-1}(\mathfrak c)$ fits the bill.
Let $M$ be the $\mathbb C$-algebra of two by two matrices with entries in $\mathbb C$, and let $i,j\in A$ be the canonical images of $1\otimes i_0,1\otimes j_0\in\mathbb H[X]$.
One easily checks that there is a unique $\mathbb C$-algebra morphism $\phi:A\to M$ satisfying
$$
\phi(i)=\begin{pmatrix}x&0\\0&-x\end{pmatrix},\quad
\phi(j)=\begin{pmatrix}0&-1\\1&0\end{pmatrix},
$$
and that $\phi$ is bijective.
It is also easy the verify that the left ideal of $M$ generated by
$$
e:=\begin{pmatrix}1&0\\0&0\end{pmatrix}=\phi\left(\frac{1-ix}{2}\right)
$$
is maximal, and that it is not an ideal.
This implies that we can put
$$
\mathfrak c:=A\ \frac{1-ix}{2}\quad,
$$
or, in other words, that
$$
\pi^{-1}\left(A\ \frac{1-ix}{2}\right)
$$
is a maximal left ideal of $\mathbb H[X]$ which is not an ideal.
Old answer
Let $\mathfrak a$ be the ideal of $\mathbb H[X]$ generated by $X^2+1$, let $A$ be the quotient $\mathbb H[X]/\mathfrak a$.
It suffices to find a maximal left ideal of $A$ which is not an ideal.
Write $x\in A$ for the canonical image of $X$. Let us identify $\mathbb R[x]$ to $\mathbb C$. Then $A$ is isomorphic, as a $\mathbb C$-algebra, to $M_2(\mathbb C)$.
(See the very beginning of the text of Gaëtan Chenevier named Lecture 6 on this html page. Here is a direct link to the pdf file.)
As a result, $A$ contains an idempotent $e$ with $1\neq e\neq0$, and $Ae$ is the sought-for maximal left ideal.
EDIT. One can put
$$
e:=\frac{1+ix}{2}\quad.
$$
(I use the traditional notation $i,j,k$ instead of the $I,J,K$ in the question.)
Answer: I am assuming that in the polynomial ring $R=\mathbb{H}[X]$ the indeterminate $X$ commutes with all the constants, for otherwise what is $Xq$ for some $q\in\mathbb{H}$?
Unless I am very wrong, there is a one-sided division algorithm in $R$. So if we consider the left ideal $R(X-I)$ then the quotient space $R/R(X-I)$ is a 1-dimensional space over $\mathbb{H}$, because all the cosets of $R(X-I)$ contain a constant polynomial (divide any polynomial from the right by $X-I$ and take the remainder). Hence the left ideal $R(X-I)$ is maximal, because it is of 'codimension one'.
However, $R(X-I)$ is not an ideal of $R$. We have
$$
J(X-I)-(X-I)J=(JX-JI)-(JX-IJ)=-JI+IJ=2K.
$$
So any ideal containing $(X-I)$ must also contain the unit $2K$, and hence is equal to all of $R$.
We need to be careful here. Because $\mathbb{H}$ is not commutative, we don't get a ring homomorphism from $\mathbb{H}[X]$ to $\mathbb{H}$ by evaluating polynomials at a selected element $q\in\mathbb{H}$.


PCA on a rank-deficient matrix using SVD of the covariance matrix

Question: I have a high-dimensional data matrix X where sample size is smaller than the variable size. I want to use PCA as a dimensionality reduction method, but I cannot call it directly in R since the matrix X is rank-deficient. I saw below technique in an R code to get the principal component representation from a rank-deficient matrix:
1) Get U from svd(XXT)
2) Get the principal component representation C by solving X = UC
I am new to PCA, and I have no idea how that makes sense. Could someone clarify how those 2 steps is equivalent to applying PCA on X?
Comment: Note that since `XX'` (as well as `X'X`) is square symmetric its svd() = its eigendecomposition().
Comment: Probable duplicate, at least closely related: http://stats.stackexchange.com/q/147880/3277.
Comment: There are many questions asked about the relation between PCA and SVD, but my specific question is that I would expect the 1st step to be `svd(X)` rather than `svd(XX^T)`.
Comment: What do you mean you cannot call it directly? Just use `prcomp` and not `princomp`.
Comment: Principal component analysis (PCA) is usually explained via "an eigen-decomposition of the covariance matrix (`XX^T`)" or via "a singular value decomposition (SVD) of the data matrix itself (`X`)". That's what confuses me. Is it okay to use either `svd(X)` or `svd(XX^T)` in the 1st step?
Comment: Yes. (http://stats.stackexchange.com/q/79043/3277), you may use both.
Comment: Thanks, this helps a lot! Also, is there a problem with the 2nd part? It calculates the principal components using `U^T * X`, but what is explained in the link you sent is to calculate principal components using `U * S`, where S is the matrix of the singular values.
Answer: PCA amounts to finding and interpreting a singular value decomposition  (SVD) of $X$ (or any closely-related matrix obtained by various forms of "standardizing" the rows and/or columns of $X$). There are direct connections between any SVD of $X$ and any SVD of $XX^\prime$.  I will exhibit the connections in both directions, by obtaining an SVD of one from an SVD of the other.

1. Any SVD of $X$ determines a unique SVD of $XX^\prime$.
By definition, an SVD of $X$ is a representation in the form
$$X = U\Sigma V^\prime$$
where $\Sigma$ is diagonal with non-negative entries and $U$ and $V$ are orthogonal matrices.  Among other things, this implies $V^\prime V = \mathbb{I}$, the identity matrix.
Compute
$$XX^\prime = (U\Sigma V^\prime)(U\Sigma V^\prime)^\prime= (U\Sigma V^\prime)(V\Sigma U^\prime) = U\Sigma V^\prime V \Sigma U^\prime = U\Sigma \mathbb{I} \Sigma U^\prime = U (\Sigma^2) U^\prime.$$
Since $\Sigma^2$ is diagonal with non-negative entries and $U$ is orthogonal, this is an SVD of $XX^\prime$.

2. Any SVD of $XX^\prime$ gives (at least one) SVD of $X$.
Conversely, because $XX^\prime$ is symmetric and positive-definite, by means of an SVD or with the Spectral Theorem it can be diagonalized via an orthogonal transformation $U$ (for which both $UU^\prime$ and $U^\prime U$ are identity matrices):
$$XX^\prime = U\Lambda^2 U^\prime.$$
In this decomposition, $\Lambda$ is an $n\times n$ diagonal matrix ($n$ is the number of rows of $X$) with $r = \text{rank}(X)$ non-zero entries which--without any loss of generality--we may assume are the first $r$ entries $\Lambda_{ii}, i=1,2,\ldots, r$.  Define $\Lambda^{-}$ to be the diagonal matrix with entries $1/\Lambda_{ii}, i=1,2,\ldots, r$ (and zeros otherwise).  It is a generalized inverse of $\Lambda$.  Let
$$Y = \Lambda^{-}U^\prime X$$
and compute
$$YY^\prime = \Lambda^{-} U^\prime XX^\prime U \Lambda^{-} = \Lambda^{-} \Lambda^2 \Lambda^{-} = \mathbb{I}_{r;n}.$$
(I have employed the notation $\mathbb{I}_{r;n}$ for an identity-like $n\times n$ matrix of rank $r$: it has $r$ ones along the diagonal and zeros everywhere else.)  This result implies $Y$ must be a block matrix of the form
$$Y = \pmatrix{W^\prime & 0 \\ 0 & 0}$$
with $W$ an $r\times r$ orthogonal matrix.  The zeros are matrices of appropriate dimensions to fill out the rest of $Y$ (which has the same dimensions as $X$).  Let $p$ be the number of columns of $X$.  Certainly $r \le p$.  If $r \lt p$, we may extend $W$ to a $p\times p$ orthogonal matrix $V$.  This can be done in many ways, but a simple one is to put $W^\prime$ in the upper left block, an identity matrix of dimensions $p-r\times p-r$ in the lower right block, and zeros everywhere else.
Since (by construction) $V^\prime V = \mathbb{I}_p$,
$$U^\prime X V = \Lambda Y V = \Lambda (V^\prime V) = \Lambda.$$
Upon left-multiplying by $U$ and right-multiplying by $V^\prime$ we obtain
$$U\Lambda V^\prime = (UU^\prime) X (VV^\prime) = X,$$
which is an SVD of $X$.
$$XX^\prime = (U\Sigma V^\prime)(U\Sigma V^\prime)^\prime= (U\Sigma V^\prime)(V\Sigma U^\prime) = U\Sigma V^\prime V \Sigma U^\prime = U\Sigma \mathbb{I} \Sigma U^\prime = U (\Sigma^2) U^\prime.$$
Since $\Sigma^2$ is diagonal with non-negative entries and $U$ is orthogonal, this is an SVD of $XX^\prime$.


Quero usar ajax para simplesmente atualizar uma tabela que reflete o banco, sem atualizar a página

Question: Tenho a index.php, que tem lado a lado um formulário de inserção e uma tabela que reflita o banco, nao precisa ter timeout, só quero que quando faço um novo registro na tabela, ele vai aparecer na tabela ao lado, sem fazer refresh na pagina, olha como esta o metodo até agora:
 function atualizarTabela(){
                xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", "select.php", false);
                xmlhttp.send(null);
                document.getElementById("tabela").innerHTML=xmlhttp.reponseText;
            }

a div:

por enquanto estou tentando fazer assim, mas retorna "undefined"
essa pagina select.php até agora só tem um echo dizendo que funcionou, para teste, mas ela vai fazer select no banco e retornar em echo, os resultados da tabela.
Answer: No submit do formulário você faz um ajax para salvar e caso positivo adiciona o registro na tabela. O retorno pode ser apenas o valor do registro ou o html da nova linha.
Segue exemplo:
$("#form").submit(function(e) {
  e.preventDefault();
  var $form = $(this);
  $.ajax({
    url: "select.php",
    type: "GET",
    data: $form.serialize(),
  })
  .done(function(novoRegistro) {
    $("#tabela table").append(novoRegistro);
  })
  .fail(function() {
    console.log("erro ao salvar");
  });
});

E em sua div você teria algo como:

E seu select.php retornaria o html da nova linha para a tabela por exemplo

   Registro 1


Inserir conteúdo de um arquivo HTML em uma DIV - jQuery/Ajax

Question: Estou fazendo um Sistema GED aqui para a empresa onde trabalho (bem simples, apenas para organizar melhor).
Estou desenvolvendo as telas primeiro, pra depois conectar com o BD e fazer as coisas funcionarem.
Eu tenho um menu que fica a esquerda com os links para navegar entre as páginas. A direita eu insiro o conteúdo das páginas em uma DIV chamada #conteudo, pra isso estou utilizando a função load() do jQuery. Conforme abaixo:
// Carrega o conteúdo das páginas dentro da div#conteudo
$('.carrega_pagina').click( function(){

    var href = $(this).attr('href'); // pega o valor do atributo href da âncora clicada
    $('#conteudo').load(href);
    return false;
});

Isso tem funcionado bem, porém, ao clicar nos links umas 8-10 vezes ou mais, a tela solicitada demora a aparecer (é como se o navegador tivesse travando), além disso, o navegador chega a consumir até 70% da CPU quando solicito uma página (lembrando que isso tudo só ocorre após navegar várias vezes entre as páginas, quando dou um refresh na página tudo volta ao normal).
Queria saber se existe uma maneira melhor de inserir o conteúdo das outras páginas nessa DIV.
Comment: Provavelmente você está carregando um `javascript` que adiciona a função nos itens do menu. Conforme mais cliques você fizer, mas funções você adicionará aos itens e mais requisições esses itens irão fazer. O ideal é você utilizar uma requisição simples (pode ser `$.GET`) e carregar somente o que precisa. (Sem os JS já adicionados).
Comment: Tenta usar `html()` no lugar de `load()`
Comment: @ValdeirPsr, é exatamente o que está acontecendo! Coloquei um alert no success do $.ajax e vi que cada vez que clico em um link a requisição é feita outra vez e vai incrementando...
Comment: @ValdeirPsr Poderia me dar um exemplo de como fazer com $.get? Outra dúvida, eu estou inserindo meu arquivo de script junto as páginas porque tentei fazer antes sem inserir e não funcionou as funções que tenho nas páginas solicitadas. Fazendo com $.get mesmo sem inseri-los novamente as funções irão funcionar?
Answer: Um alternativa é usar o próprio Ajax para fazer isso. O segredo é setar o dataType como "html", assim:
$('.carrega_pagina').click(function () {
    var href = $(this).attr('href');
    $.ajax({
        url: href,
        dataType: 'html',
        success: function (html) {
            $('#conteudo').html(html);
        }
    });
    return false;
});

Agora faça os testes com múltiplos clicks e veja se atende melhor que o .load()
Comment: Ricardo, obrigado pela resposta. Eu fiz exatamente como você mencionou, mas continuou da mesma forma :(
Answer: Isso acontece pois durante do .load( URL ) você está trazendo alguns códigos JavaScript repetidos. Isso faz com que os elementos do menu fiquem adicionando mais e mais eventos de clique.
Esses eventos são adicionados tantas vezes, que ao invés de fazer uma requisição, você pode chegar a fazer 100 requisições de uma só vez. Claro que vai depender da quantidade de vezes que você clicar.
Para corrigir isso, é necessário que você filtre o que vai adicionar, por exemplo:
page1.html
<!DOCTYPE hml>

        <title>Title of the document</title>

Page 1

Page 2

Page 3

Page 4

The content of the document...

page2.html
<!DOCTYPE hml>

        <title>Title of the document</title>

Page 1

Page 2

Page 3

Page 4

Tudo certo

            <button type="button" id="btnTest" data-msg="O JavaScript está funcionando.">Alerta</button>

Comment: Opa, muito obrigado! Funcionou tudo perfeitamente, agora sem engasgos. =)


TypeError: can only concatenate list (not "str") to list - pandas dataframe

Question: I know a similar question has been posted and I have exhausted them all. I have a dataframe with the fields below:
import pandas as pd

df = pd.DataFrame([[0, 1021, 0.00, ["C2"]],
    [1, 1023, 0.00, ["C2"]],
    [2, 1024, 2.00, ["C1", "C4"]]],
    columns=["index", "id", "revenue", "campaign"])

print(df)

Resulting in
   index    id  revenue  campaign
0      0  1021      0.0      [C2]
1      1  1023      0.0      [C2]
2      2  1024      2.0  [C1, C4]

I just want to create a new column 'path': end of path is Null if revenue is 0 and revenue if revenue is >0.. start of the path is 'Start'
  index  id    revenue campaign       path
   0    1021    0.00    [C2]       ['Start', 'C2', 'Null']
   1    1023    0.00    [C2]       ['Start', 'C2', 'Null']
   2    1024    2.00    [C1, C4]   ['Start', 'C1', 'C4', 'Revenue']

If I do something below it works.. but i have a billion rows to process so doesnt seem efficient.
for i in range(0,len(df)):
    if(df['revenue'][i] == 0):
        df['path'][i] = ['Start'] + df['campaign'][i] + ['Null']
    else:
        df['path'][i] = ['Start'] + df['campaign'][i] + ['revenue']

But if i work at a column level like this it works sometimes but sometimes it breaks with the erroe that i can only concatenate list to a list.
df['path'] = np.where(
   df['revenue'] == 0,
    ['Start'] + df['campaign'] + ['Null'],
    ['Start'] + df['campaign'] + ['revenue'])

Can someone help me sort this issue? I would be really grateful.
Comment: Use `.str.cat(...)`
Comment: Hi idelaney.. I tried to create one.. but the dtypes i am getting and the dtypes of my original df are coming out different.. i didnt want to mislead and gave up..
Comment: @thealchemist - yeah, that can be a problem. I added one that I think is right.
Comment: @tdelaney: cant thank you enough.. really appreciate your support
Comment: Since `pandas` omits quotes for string elements, it's hard to tell whether a column entry contains a list or a string that looks like the list display (or even array).  And the column dtype will be `object`.  So if there's a chance of mixing, your code has to take that into account.
Answer:
You can use the python .extend list method and the pd.Series.tolist:

list1.extend(list2.tolist().extend(list3))
So:
df['path'] = np.where(
   df['revenue'] == 0,
    ['Start'].extend(df['campaign'].tolist().extend(['Null'])),
    ['Start'].extend(df['campaign'].tolist().extend(['revenue']))
)

Comment: Hi vendant.. I get a 'TypeError: 'NoneType' object is not iterable'
Comment: @thealchemist It seems like one of your rows has data that does not match.
Comment: I think that's because `.extend()` actually returns None (it appends to the first iterable the elements of the second iterable, but returns nothing). Even if you run `a = ['Start'].extend(['banana'])` you will see that `a` is None
Answer: It looks like your column campaign is of mixed types: in the examples you are showing the values are lists, but from the error it looks like maybe somewhere in your dataframe you have a string, and possibly other types as well. That's why the "list addition" is not working, as it expects to add lists as [list1] + [list2] + [list3], but in some specific row the df["campaign"] actually evaluates to a string.
One way to go about this is to first try to guarantee that the column (pd.Series) is of a homogenous type. I would do the following:
def to_list(item):
    """Maps anything that is not a list to a list"""
    return item if isinstance(item, list) else [item]

df["campaign"]= df["campaign"].apply(to_list)

EDIT:
I originally suggested that you should continue by using np.where(), but I'm not sure it will work. In the examples of the documentation, we're only seeing numerical transformations of the existing variables. And also when trying it out with dummy data it's not working.
What I would go instead (after transforming everything to a list) if write a short function and map the dataframe to it.
def concat_cols(row):
    if row["revenue"] == 0:
        return ['Start'] + row['campaign'] + ['Null']
    else:
        return ['Start'] + row['campaign'] + ['Revenue']

df.apply(concat_cols, axis=1)

This isn't necessarily faster (or even different than looping through the dataframe, so you might need to experiment with smaller samples.
Comment: Hi Tania.. really appreciate your response.. now i am getting a TypeError: can only concatenate str (not "list") to str.. if i take out the '[]' from 'Start' I get a giant string in the path column which is again bad..
Comment: the to_list function actually turns my list into this:  [[, ', C, 1, 1, ', ]] .
Comment: Hi @thealchemist, take a look at my revised answer. I think the `np.where` solution wouldn't work anyhow (at least it didn't for me). The `to_list` function should work... see example df: `df = pd.DataFrame(dict(banana=[['a', 'b', 'c'], None, 1, [], 'c', ['d']]))`
 (with various data types, just in case you have those in the "campaigns" column) and then `df.banana.apply(to_list)`


Insert nested object in multiple tables using Room

Question: I have a Json similar to below format:
{
      "gender": "male",
      "name": {
        "first": "Axel",
        "last": "Raab"
      }
}

I want to create 2 tables, say Person and Name and store this data in these 2 tables.
My Entity classes look like these:
@Entity
data class Person(
    @PrimaryKey(autoGenerate = true)
    var pid: Int,

    @SerializedName("gender")
    var gender: String?,

    @SerializedName("name")
    @Ignore
    var name: Name?,
)

@Entity(indices = [Index("pId")],
    foreignKeys = [ForeignKey(
        entity = Person::class,
        parentColumns = ["pid"],
        childColumns = ["pId"],
        onDelete = ForeignKey.CASCADE)])
data class Name(
    @PrimaryKey(autoGenerate = true)
    val mId: Int,

    @SerializedName("first")
    var first: String?,

    @SerializedName("last")
    var last: String?,

    var pId: Int
)

I have created corresponding Daos but unable to identify a way where I can write a transaction that would store this data into 2 tables and relate then using provided ids.
I have gone through many solutions that would either use @Embedded or @Relation or TypeConverter approaches but either they do not fit  my use case or the solution is about querying the data and not how to save or insert.
Thanks.
Answer: You can use Embedded
e.g
public class Coordinates {
       double latitude;
       double longitude;
   }
   public class Address {
       String street;
       @Embedded
       Coordinates coordinates;
   }

Insert example in your DAO
@Insert
fun insert(item: Coordinates)

you can pass Coordinates instance variable in your insert function
Address("your street", Coordinates(your_lat,your_lng))

Comment: Thanks Muhammad. But if I am not wrong, @Embedded is used to create a flat structure which is it would populate Coordinates columns inside Address table which isn't my requirement currently. I would like a separate Address table and Coordinate table wherein Address table primary key is a foreign key inside Coordinate table. Hope this further makes my requirement more clear.


Method to determine probability distribution

Question: I am planning an experiment to determine the frequency of a binary variable (valued 1 or 0).
Each day, there are 10,000 new events taking place
Each day, I get to draw 100 randomly out of the new 10,000 and see their outcome (either 1 or 0)
How do I estimate the frequency of 1 and 0 in the population with this data?
Answer: if the 10000 new events follow the same distribution each day, the estimator obtained with a sample of n=100 will be an estimator of the underlying distribution.
The underlying is a Bernoulli distribution with unknown parameter p, the only parameter for a Bernouilli.
Each day you obtain an estimator of p = (sum of ones in sample of 100)/100.
This estimators will follow a normal distribution with mean = the real p, and standard deviation sqrt(p*(1-p)/100).
Comment: So let's suppose I have 10 samples, each of 100 each. Can I combine these samples to estimate the population frequency? p = sum of all samples( (sum of ones in sample of 100))/(100*10)
Comment: Yes. You can combine the samples of the same day, and if each day the 10000 new events come from the same distribution, you can also combine the samples of different days.


Chord notation: a minor chord with a minor 6th

Question: This might be sort of a basic question, but I've been searching the internet for long enough and I thought I'd just ask:
I'm a guitarist, trying to create a tab on ultimate-guitar.com. In this tab, there is a certain chord which I'm not sure how to write down:
It's mostly a standard Am chord, but instead of the high E at the end you play F, so it looks like this:

    Fret: Note:
     X-----X
     0-----A
     2-----E
     2-----A
     1-----C
     1-----F

<code>%X/X.0/0.2/2.2/3.1/1.1/1
</code>
This would be Am with a minor 6th. I thought it would just be Am6, but apparently that implies a major 6th (F# instead of F). So how do I write it correctly?
The song I'm tabbing is in the key of Am (or C maybe). The progression goes Am, C, F, G, then this chord.
The answer I picked:
In the end I went with FM7/A, because it was the only thing I ever searched on google which actually listed the above as a variation. I would have given @Richard some credit because I believe he suggested that first, but he only put it as a comment. I might have also gone with Amaddb13, but ultimate-guitar didn't recognize that notation. Thanks a lot to @Fugu for not only giving both these answers in the end but also explaining them :)
Comment: Could you provide some context and also give the chords that precede and follow this mystery chord? Depending on the neighboring chords, this could be a few things.
Comment: @jdjazz I added some more info
Answer: So you've created a chord with the notes A C E F. There are three potential names for this combination of notes and it's good to be aware of all of them and what separates these names.
The first name you might call such a chord is AMib6, sometimes written AMiMi6. You would use this name when the E and F are not separated by an octave; the name, by exclusion, implies that these two notes are adjecent.
What do you do if they're separated by an octave? Well, then you call it AmiAddb13. This is an add chord because there is no 7th, 9th or 11th; if there was, you'd call it Ami11b13. Furthermore, it's 13 and not 6 to indicate that the F is to be separated from the triad by an octave.
Now here's where things get tricky. Generally speaking, the b6 (and the b13) aren't particularly common. The reason they aren't common has to do with the other name of this chord: F major 7 in first inversion. Fmaj7 consists of the notes F A C and E, which are simply the notes of the chord you've given in a different order. Why would you call a chord F major 7? Well, it comes down to function. Labeling the chord AMib6 in the key of A minor indicates a tonic function, whereas labeling it Fmaj7/A indicates a subdominant function. I won't go into chord function and how to determine which function a chord has (especially in the context of a relatively advanced case like this one), but I can tell you that most of the time - but certainly not all of the time - that you have this particular chord shape, you're actually looking at an inverted major 7th chord. The most common exception is when ACEF is followed or preceded by  ACEF# or ACEG (think Eleanor Rigby or the James Bond Theme). In most other cases, the correct labeling is maj7.
Comment: Never seen AMiMi6, or Amm6 before. Come to that Amb6 is pretty foreign. I still think we're barking,  - up the wrong tree looking for anything associated with Am
Comment: @Tim I have seen Mib6 before and I've heard it called a "minor minor sixth chord" although I will admit that I can't say with certainty that I've ever actually seen it written on the page. On principle, I agree with you that this is probably an FMaj7/A and that probably more than 90% of the time it's going to be correctly notated as a major 7th chord. But just this week I transcribed a solo piano piece which had the notes G Bb D Eb as a tonic functioning chord, and notating it as Eb would have been wrong. It's irregular, however, and I'd say generally this shape is an inverted major 7th.
Answer: There's a possible red herring here with the A note underneath. To me it looks more like F maj7, as the four notes are F,A,C and E. Obviously, with A under, it can be called Fmaj7/A or the first inversion of that chord.I wouldn't be thinking of it as any derivitive of A minor, even with that A underpinning the rest.
It's not a particularly harmonious sound - that's usually found by playing the F on string 4, and leaving the top string open to provide the maj7 part. This voicing is sometimes used as a 'stepping stone' chord to go between F major and F7.
I'm wondering why you chose this particular voicing. Is it just something in a list of chords, or does it belong to a specific song you have in mind?
Answer: I'd call the chord Am11b13 you spelled out Amb13
Comment: wouldn't an 11 chord require a fourth, for an `A` chord an added `D`?
Comment: doesn't 13 imply that the chord has 7, 9 and 11?
Comment: @coconochao -- the b13 would at least imply a b7 here; the 9th and 11th could be omitted and you could still call it a 13th chord (this is especially common with guitar). OP has spelled a possible **Am(add b13)** in the question; I don't know why this answer wants to add an 11th....


Can the non striking batsman be out if he blocks the field, having been injured

Question: Situation in a match was, the striking batsman hit the ball. It immediately hit the non striker, whilst the non striker was a few yards outside his crease. The ball fell to the floor, the non striker doubled up in pain, and the bowler picked up the ball and ran out the non-striker.

Was the ball dead after it hit the non-striker?
If not, would the ball have been dead if the non-striker had fallen to the ground, or was otherwise clearly unable to continue?
Had he fallen to the ground on top of the ball and blocked the fielder, could he have been out obstructing the field?
Answer:
No, the ball is not dead if it hits the non-striker. For perhaps the most famous incident of this, see this video where Andrew Symonds was caught off his teammate Michael Clarke's heel.
Yes. Law 23.4(b) states:

Either umpire shall call and signal Dead ball when [...] (ii) a serious injury to a player or umpire occurs.

No, even if the ball were not dead. Law 37 states

Either batsman is out Obstructing the field if he wilfully attempts to obstruct or distract the fielding side by word or action.

(my emphasis). An injured player is clearly not wilfully attempting very much at all.
While the above is what the Laws state, I'll say it is clearly against the spirit of the Laws to run out a player injured in this manner. I'd strongly hope that the captain of the fielding time would withdraw any appeal made.
Comment: Thanks. Yes it was clearly against the spirit of the game, but unfortunately the opposing captain and coach didn't see it that way.


How do you effectively clean rust from guitar pick-ups?

Question: The site recommended that I check both How do you care for you guitar? and Best method to clean guitar? before asking this question. But I couldn't find any information about this topic at all.
I have a very old stratocaster that has rust on the magnets of the pickups and I don't know what the most effective way to get the rust off is. Many people say it is a very tedious job and that attempting to clean the pickups is highly riskful and can result in broken electronics. How do you clean your pickups? Please help! If there are alternative options please write them down.
Question: How do you effectively clean guitar pick-ups?
Answer: I'm assuming you mean the individual pole pieces have rust on the top of them, as Stratocasters don't tend to have pickup covers (which can be easier to clean and polish)
First off, remember that removing rust isn't necessary to having the guitar sound good, and in fact that vintage aged look can be very desirable.
Second, most ways to clean them result in small metal shavings/flakes coming off, and you will never get these off your magnets, so your pickups may end up looking worse after cleaning.
But, if you do want to clean them, use some WD-40 or other penetrating oil on a rag or Q-tip and rub. This will get rid of the roughness. Then use a dry cloth to wipe up the excess. Dont get any on your paintwork though.
Personally I wouldn't bother, but if I got a guitar that had pickups that were so rusted they were flaking off everywhere - I'd just buy a new set of pickups :-)
Comment: Once again, Dr Mayhem with the good advice.
Answer: Try a dab of "Brasso" on a Q-tip. And I mean just a dab. Rub one end on a pole and then use the other end to clean it off. (I hope this lets you know just how little you need) Try not to let ANY drip into the pan, if you know what I mean.
Answer: You should be careful when cleaning pickups to not use steel wool or other ferrous material. Tiny metal pieces can be sucked in by the magnetic pull and ruin the copper wrapping inside the pickup, rendering it useless in some cases. I agree with the first answer, as well, but it may be best to take it to a professional, especially if you have valuable pickups.


Copy from select option to dynamic select option

Question: How can I get all the options of a select created dynamicly get from option from first,
i try with jquery but didnt work:
 for( j = 0; j < i; j++)
     $('#s1 option').clone().appendTo(IS+j);

HTML file:
<input type="button" value="Add" id="btn1" OnClick="f('dv1');">

    <select id="s1" name="select1">
        <option>
            1
        </option>

        <option>
            2
        </option>
    </select>

functions.js
var i = 1;
function f(x){
    var y = document.createElement('div');
    y.innerHTML = '
<Select id="IS"'+i+ 'name="NAME"'+i+' > </Select>';
    document.getElementById(x).appendChild(y);
    i++;
}

Comment: $('#s1 option').clone().appendTo('NAME'+j);
or
 $('#s1 option').clone().appendTo((#+'IS'+j));
didnt work too.
Comment: make sure you added the  first before adding the copy of
Answer: Since it seems you are creating multiple select objects, you need to fix your jquery selector and the id that you are generating for the selects. First of all, $('#s1 option').clone().appendTo(IS+j);
should be changed to:
$('#s1 option').clone().appendTo('#IS' + j);

Secondly, y.innerHTML = '
<Select id="IS"'+i+ 'name="NAME"'+i+' > </Select>';
should be changed to:
y.innerHTML = '
<select id="IS'+i+ '" name="NAME'+i+'"></select>';

Edit:
If you are just trying to clone your original dropdown, the following should work for you:
function f(x){
    // Create new select within its own div
    var y = document.createElement('div');
    y.innerHTML = '
<select id="IS'+i+ '" name="NAME'+i+'"></select>';
    document.getElementById(x).appendChild(y);

    // Fill new select with the options from the original
    $('#IS' + i).html($('#s1').html());

    i++;
}

Live DEMO
Answer: Here's another way if you need to iterate through the options for whatever reason to perhaps make a change
var newSelect = $("<select />");

$.each(primarySelect.options, function (i, opt)
{
   $(newSelect).append($('<option></option>', {
       value: opt.value, text: opt.text, selected: opt.selected }));
});

JS Fiddle Live Version
Be sure not to use $(primarySelect.options).each(...) because that won't work in IE propertly.

See also: What is the best way to add options to a select from an array with jQuery?


Is there any set in which exponents/powers can be used as a group operator.

Question: I am a student studying math who recently took an abstract algebra class that focused on group theory. Are there any sets such as maybe complex numbers that fulfill all of the group axioms using exponentiation?
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: If the set doesn't contain numbers, then what does "exponentiation" even mean? (Also we say group operation, not group operator.)
Comment: I don't think so. One of the essential group axioms is that every element has an inverse. If $G \subseteq \mathbb{C}$ is a group under the operation of exponentiation, then 1 would be the identity. As such, the inverse of any element $g \in G$ is 0. Unless the group you pick is pathologically small, this would contradict the fact that inverses are unique.
Comment: Don't forget that the group multiplication law has to be associative, and exponentiation generally isn't.  In the context of a course you tend to only work in groups where associativity comes for free, so it's an unappreciated restriction that is responsible for much of the structure of groups.  When you try to make up your own multiplication tables you start to see how rare associativity is if you stray from the well-worn examples.
Comment: What is true is that if $x$ is a fixed positive number, then the set of exponents $x^a$ ($a\in\mathbb{R}$) of $x$ form a group under multiplication: $x^ax^b=x^{a+b}$ (this is isomorphic to $\mathbb{R}$ under addition, via the logarithm map $y\mapsto\log_x(y)$ which you proved was a homomorphism in school before you know what a homomorphism was).
Answer: Another answer already points out that you are unlikely to find an example where proper exponentiation is the group law, except for trivial situations like $G = \{1\}$. You may find the following example compelling none-the-less: it sort of looks like exponentiation, and understanding the precise sense in which it is not exponentiation is worthwhile. The set $\mathbb R_+ = \{x \in \mathbb R \mid x > 0\}$ is a group under the operation $x \circ y = x^{\log(y)}$.
Answer: This heavily depends on what "exponentiation" means. The definition of the standard exponential map over reals, complex numbers or matrices heavily depends on their internal structure (Banach algebras). I don't really see how you can define an exponential map over other structures in an analogous way.
Note that typical exponential maps have this nasty property: $a^x=0$ has no solution regardless of $a$. And so it cannot induce a group operation, because group operations are always surjective.
This gets even worse: for some $a$ the $a^x$ is not even well defined, e.g. $-1^x$ fails to be well defined for $x\not\in\mathbb{Z}$. Even inside complex numbers $-1^{1/2}$ has two solutions, while say $i^i$ infinitely many. Of course you can apply an arbitrary choice here, but then you end up with an infinite number of exponential maps, with bad properties (none of them are continuous) and still none of them induces a group operation.
And finally the standard exponentiation is not associative, e.g. $3^{3^3}\neq (3^3)^3$.
The only set I can think of that is a group under the exponential map is the trivial $\{1\}$ set. Except for that, I suppose this cannot be done in a reasonable way.


Why is there no Men's T20I cricket at the 2022 Commonwealth Games?

Question: According to Wikipedia:

The matches are being played as Women's Twenty20 Internationals (WT20Is),
with only a women's tournament being part of the Games.

Why is there no Men's T20I cricket at the Birmingham 2022 Commonwealth Games?
Answer: Men's team from several countries were opposed to inclusion of Men's Cricket as it would coincide with already scheduled games. These games were scheduled in advance and maybe postponing isn't feasible from the business side of view and others.
Comment: Fixture congestion in men's cricket is apparently [the subject of ongoing controversy](https://www.bbc.co.uk/sport/cricket/62454761), with several top-level players believing there are too many matches being held. Throwing a Commonwealth Games tournament into the mix would have made things even worse, so it doesn't surprise me that the idea was rejected.


Using innerJoin() in TableSort

Question: In the examples modules I see a simple example of tableSort with one table.
Searching online I find a post where they claim Drupal 7 allowed a db_select() object to be created and then extended it with a join(), and then the final ->extend('TableSort');
https://www.drupal.org/forum/support/module-development-and-code-questions/2011-12-15/dbtng-tablesort-with-joins-any
I need to do an innerJoin() which appears to be a method of the SelectQuery class, and not necessarily a method of the Tablesort class. That's why the docs I see about extenders say it's critical to invoke the TableSort in the instantiation of the db_select object. Thus, my attempt:
$get_all_members = db_select('users', 'u')->innerJoin('members', 'm', 'u.uid = m.uid')->extend('TableSort');

Call to a member function extend() on string

is the response. Is there a way to convert a db_query into a TableSort object like it appears the extender is doing?
Or, could I find a way to combine the fields I need in these two tables to pass to the TableSort object?
Answer: The issue is addressed in the thread you referenced. Not all methods for the select class return the new query object. In particular, innerJoin() returns an alias string, not the query object.
Assign your query object so you can reference it outside of the method being called:
$query = db_select('users', 'u')->extend('TableSort')
$query->innerJoin('members', 'm', 'u.uid = m.uid');
//@TODO: add ->fields() ->execute() etc...

Using innerJoin() in TableSort


Issue with creating the instance of the model in EmberJS

Question: I'm writing simple app in EmberJS and trying to do some simple objects creation in the console. I'm trying to create PageModel and then retrieve it from the store (I use localstorage). Unfortunately it doesn't succeeded.
// creates the PageModel instance
page = store.createRecord(App.PageModel)
Class {id: "i1i67", store: Class, container: Container, _changesToSync: Object, _deferredTriggers: Array[0]…}

// tries to retrieve the object from the storage
store.find('page', page.get('id'))
// but doesn't work
Class {__ember1413471577603: null, __nextSuper: undefined, __ember_meta__: Object, constructor: function, _super: function…}

Can anyone is able to help with ?
Comment: What does "doesn't succeeded" mean?
Comment: `find` doesn't return the App.PageModel instance with given `id`
Comment: Are there errors in the console?  What does `find` return?
Comment: `Class {__ember1413471577603: null, __nextSuper: undefined, __ember_meta__: Object, constructor: function, _super: function…}`
which I interpret as blank collection/result.
Comment: `createRecord` doesn't save it, page.save() after creation
Comment: Unfortunately after `page.save()` it doesn't cause that object is visible by `store.find(id)`
Answer: If your model is called PageModel, then I'd expect the store to call it page_model.  It is unusual to call your model ThingModel- more common is Thing.  However, this works too:
store.find(App.PageModel, page.get('id'))


Combinatorics: How many solns to equation? (principle of inclusion / exclusion)

Question: So I'm having a lot of trouble understanding the logic in my Combinatorics class.  I've got this question for an assignment:
How many solutions are there to $x_1 + x_2 + x_3 + x_4 = 19$, $x_i \geq 0$ for $1\leq i\leq4$?
I don't think the Principle of Inclusion / Exclusion needs to be applied here.  As far as I know, the answer is $\binom{4+19-1}{19} = \binom{22}{19}$.  However, I don't understand why this choose with repetition formula is used.
I'm further confused with the second part of the question: How many solutions are there to $x_1 + x_2 + x_3 + x_4 = 19$, $0 \leq x_i < 8$ for $1 \leq i \leq 4$?
An example in the textbook shows that the Principle of Inclusion and Exclusion must be used at this point.  My understanding is that we consider four cases, $c_1, c_2, c_3, c_4$, which respectively represent the cases where $x_1, x_2, x_3, x_4$ each are greater than 7.  Then, the answer to the problem is the total number of solutions to $x_1 + x_2 + x_3 + x_4$ minus $S_1$ (the number of cases where one of the $x$ values is greater than 7) plus $S_2$ (the number of cases where two of the $x$ values are greater than 7) minus $S_3$ (the number..three of the $x$ values are greater than 7).
If someone could please confirm my understanding of the application of PIE, and  provide some inside as to WHY were using the choose repetition formula to solve these problems (I only know the choose formula as picking 4 people from 12 to form a committee, etc)
Cheers!!
Comment: You're right that incl.-excl. is not needed for the first problem, and you're right about how to use it for the second. There's a fairly decent explanation of the formula that should be used [here](http://en.wikipedia.org/wiki/Stars_and_bars_%28probability%29); try to make sense of that first, and see if you still have questions.
Answer: You could use generating functions to understand it a bit better or just apply the formula of $\binom{n+k-1}{k -1}$ like you did. Here is a link to a free pdf file that deals with combinatroics http://people.math.gatech.edu/~trotter/keller-wtt-book/keller-wtt-book.pdf. You should read section 2.5 on page 32.
Comment: Subtracting 1 from the subscripts? How can that affect the sum? What do you mean, "generating functions for 0, 1, 2, and 3"?
Comment: There is no need to substract $1$, since $i$ is only for the values of $x_i$. He could have used $x,y,z,w$ instead. His variables are already greater or equal than $0$
Comment: I meant since we subtract 1 from our constraints we must subtract it in our equation of $x_1+x_2+x_3+x_4=19$ as well. So subtract 1 from $x_1, ..x_4$ which will give us $x_1+x_2+x_3+x_4=15$. Is not that correct?
Comment: also, although I love generating function, and you should keep the answer, givent what is written in the question, I don't think @somekindarakus knows about these yet
Comment: @diimension read my comment if not done, the first one
Comment: Ah man, I was hoping to have given my first official answer here on SE. I make a better effort to understand the question next time. Hopefully my answer doesn't cause too much trouble.
Comment: Ah I see my mistake I didn't read it carefully I will make an edit to my answer! Thank you @Jean-Sebastien !
Comment: No trouble caused.  Generating functions are the next section and I actually tried to tackle the problem like that at first but couldn't figure out how to get the coefficient of $x^{19}$ in $(1 + x + x^2 + x^3 + .. + x^{19})^4$ (did I go about that right?)
Comment: Yup, that is right but generating functions isn't ideal for this particular problem because there isn't any constraints. If there were constraints then generating functions will work out perfectly. By constraints I mean, $x_1 < 3 , x_2 > 2$, etc. Here is a test bank you can use for reference. http://people.math.gatech.edu/~trotter/math-3012-Fa11/test10-1-solutions.pdf look at problem 3.
Comment: To find the coefficient of $x^{19}$ you will have to use the multinomial theorem.


Por que usar do "while (0)"?

Question: No código do Linux vi algumas macros com:
do
{

}while(0)

Existe motivo? Porque aparentemente não tem lógica um laço de repetição em que o código repete apenas uma vez.
Comment: Cara, vejo todo mundo questionando isso! O que tem a ver pergunta estar no SOen? Nem todo mundo sabe ler inglês :)
Comment: Essa pergunta no SOen é identica:[Why while(0)](http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for)
Comment: Relacionada: http://pt.stackoverflow.com/questions/78493/qual-%C3%A9-a-utilidade-e-import%C3%A2ncia-de-do-while
Comment: Esse não é o while infinito. O teste sempre dará falso. Por isso é um do..while, se não fosse, nem entraria. Pra infinito deveria ser while(1).
Comment: Normalmente omite-se o `;` no fim da macro; esse `;` vem do codigo propriamente dito.
Comment: É para efeito de declaração de macro.
Answer: Não existe provavelmente porque é pouco necessário e dá para resolver desta forma. De qualquer forma esta construção é usado essencialmente em macros (acho que você já sabia disto pelas tags originais da pergunta).
Ele serve para agrupar vários comandos sem causar erros quando o pré-processador expande o código.
Exemplo:
#define MACRO(x) do { funcao(x); x++; } while (0)

Pode ser usado em:
if (a > 0)
    MACRO(a);
else
    a++;

Isto causaria erro no mesmo uso:
#define MACRO(x) { funcao(x); x++; }

Porque seria expandido para:
if (a > 0)
    { funcao(x); x++; };
else
    a++;

Funcionaria se você não tivesse usado o ponto e vírgula na linha da macro, mas ninguém faz isto. E seria um erro obrigar o programador saber que esta macro deve ser usada assim.
Isto é pior ainda:
#define MACRO(x) funcao(x); x++

Expandiria para:
if (a > 0)
    funcao(x); x++;
else
    a++;

Coloquei no GitHub para referência futura.
Obviamente destruiria o uso do if como se imaginava e o else ficaria solto, gerando um erro de sintaxe.
Em alguns casos é possível usar isto em código normal, mas é raro ser útil e legível.
Comment: Além do que o Manero falou, tem também a questão do controle de fluxo com "continue" e "break" que requer escopos como o do "do/while". Não sei se essas macros usam para isso, mas serve para controlar mais livremente. Pode, por exemplo, definir condicionais onde se repete o loop e então botar "continue", bem como pode-se mudar a condição do loop para 1 ou true (C++) e definir condicionais onde o loop cessa usando "break.
Answer: É também uma forma de se evitar if's extremamente agrupados e simplificar a verificação de erros:
do {
  // faça algo
  if (error) {
    break;
  }
  // faça alguma outra coisa
  if (error) {
    break;
  }
  // etc..
} while (0);

Comment: Resumindo em poucas palavras: se tiver break neste bloco do ... while(0), é um "goto" disfarçado.
Comment: @epx exatamente, é a construção de estruturas complicadas só para dizer que não usou `goto`: http://pt.stackoverflow.com/q/20660/101

Por que usar do "while (0)"?


Get error "Class name (...) doesnt match path (...)" when trying to load library

Question: I have build a library, I have tried to load it (I have added the module to the sample app -> android gradle -> dependency), but when I compile the sample app, this is give me this error 16 times (every error have another file - anim/attrs/layout/id....):

Error:Gradle: com.android.dx.cf.iface.ParseException: class name
  (com/cld/ui/lib/R$anim) does not match path
  (com/cld/UI/lib/R$anim.class)

this is the project file structure:
Answer: Just read the error message: one case you have ui and the second one, UI. This is not the same thing. Put ui in uppercase.
Comment: You created the library right? Check all your paths and names, for example in your samples and in your lib folder you have UI and ui. try to always use UI to be sure to get rid of this problem.
Comment: Its partially worked. There is the same error about the BuildConfig which is still appears. Where is this file exists and How can I change his package from ui to UI?Thanks
Comment: I have searched for "ui", found that the package in BuildConfig.class used ui and not UI. changed it, cleaned project, and it still writing the error about this file. Any idea?
Comment: OK, after rebuild project, its working, thanks for you help


How does counting E twice explain the discrepancy between the 5th between C and G vs. the 3rd between C and E, 3rd between E and G?

Question: I still don't grasp the "source of the discrepancy". "the E got counted twice when we went C,D,E and then E,F,G, but only got counted once when we went C,D,E,F,G." — So what? How does this expound the discrepancy? All emboldings are mine.
Impaled on a Fencepost |

The music theorists of the Middle Ages committed a fencepost error that's too entrenched to dig up now. Consider the chord made of the notes C, E, and G (a C major triad). If music theory nomenclature for intervals made sense, the distance from C up to E plus the distance from E up to G would equal the distance from C up to G. And that's true if you measure the intervals by counting upward steps. The problem comes when you describe intervals with what I suppose might be termed "ordinal nomenclature": going from C to E is called going up by a third (because you count 1,2,3 when you play C,D,E) and going from E to G is called going up by a third for the same reason, but going from C to G is called going up by a fifth (because you count 1,2,3,4,5 as you play C,D,E,F,G).
The source of the discrepancy should be clear: the E got counted twice when we went C,D,E and then E,F,G, but only got counted once when we went C,D,E,F,G. So in music theory, when you stack a third on top of a third, you get a fifth. We musicians are stuck with nomenclature that essentially makes us say "3+3=5" so many times that we eventually stop noticing we're saying it. (Of course, saying "a third plus a third is a fifth" is confusing on a different level, since it sounds like "1/3 + 1/3 = 1/5". But I digress.)
Comment: I don't know for sure that it's the reason **in music**, but I do know that [inclusive counting](https://en.wikipedia.org/wiki/Inclusive_counting) (counting an interval by including the first item) was more common formerly than it is now. Seems it may have derived from Latin usage; the Romans had *nundinae* ("nine days") every eight days. Some Romance languages still use a "fifteen" word for a two-week period. Speculatively, I could link it to the lack of a zero in arithmetic back then.
Comment: The music theorists of the Middle Ages obviously weren't programmers, otherwise they would have started counting at zero! Then C would be the base note, E would be the second and G would be the fourth, solving your problem!
Comment: I can only give conjecture. I think the source of this issue could have been the desire to hear the unison (eg: C to C with no movement up or down) as perfectly harmonious, and thus as a kind of singleness or oneness. From that desire spawned the interval of the unison or "oneness" and therefore gets counted as one, not in the sense of moving by one step, but in the sense of being perfectly harmonious; nevertheless it still requires the next step (C to D) to be referred to as a second and so on.
Comment: "E got counted twice when we went C,D,**E** and then **E**,F,G" (emphasis mine). I count two E's in "C,D,**E** and then **E**,F,G" -- how many do you count? How is this not clear?
Comment: It is the concept in maths known as inclusive counting.
Answer:
"The source of the discrepancy should be clear"

Well, first things first, the discrepancy in question is that in musical terms, a third plus a third is a fifth. As the article mentions, 3 plus 3 equals 5 in interval speak, which is a discrepancy from the usual arithmetic idea of addition.
Now, the source of that discrepancy is that musical intervals are indexed ordinally - that is, two of the same note are a unison, or a first apart. There is no interval of a zeroth, and this is where the problem begins. Since the unison acts as the additive identity, it is possible to intervallically "add 1" to a note over and over again and still end up on the exact same frequency.
Had the music theorists of yore thought of zero-indexing their intervals, intervals would in fact be additive! Suppose instead that two notes of the same frequency were considered to be a perfect zeroth, and the doubling of frequency a logically-named heptave. In that case, we would be going up a major second from C to E, another (minor) second from E to G, and end up with C-G being a perfect fourth. The shoe fits: 2 + 2 = 4 in this case!
Side note: while intervals cannot be put together arithmetically, there is a way to count intervals that is zero-indexed: by converting frequency ratios into a number of semitones (or, for extra precision, cents), addition is preserved! Observe that C to E is 4 semitones, E to G is 3 semitones, and C to G is 7 semitones. 4 + 3 = 7, and thus the math works out right with half-step counting!
Comment: @ChieltenBrinke: The meaning is perfectly clear. Mathematical notation gets much more ambiguous than just exclamation points, and people still understand it.
Comment: The arithmetical statement `4 + 3 = 7!` is not correct. Don't mix punctuation and formula syntax.
Comment: The fact that some people use more ambiguous notation than this doesn't mean it is good practice.
Comment: @ChieltenBrinke If it bothers you, you have my permission to edit it to something more precise.
Comment: @user45266 I lifted the formula into the code span to remove the ambiguity.
Comment: @ChieltenBrinke Much appreciated, but generally code blocks on SE should only be used for actual code, since code blocks make it hard for accessibility tools to work properly. Here's my compromise!
Comment: This has nothing to do with the use of ordinal numbers and everything to do with inclusive counting.  If you count inclusively with cardinal numbers, you get the same result.
Answer: What the quotation is complaining about is that if you count the notes of the third from C to E ...

C = first note
D = second note
E = third note

Thus, three notes in total.

... and then you count the third from E to G ...

E = first note
F = second note
G = third note

Thus, three more notes.

Then the distance from C to G really ought to be a "sixth", because 3 + 3 = 6. However, C to G constitutes only five notes.

C = first note
D = second note
E = third note
F = fourth note
G = fifth note

The "problem" is that the E was counted twice when we added thirds.

C = first note
D = second note
E = third note and fourth note
F = fifth note
G = sixth note

What the quotation is missing is that intervals aren't additive. They only count notes from a given starting point.
Comment: "_They only measure distance...._" -- this seems to be the problem; distance as we usually think of it is additive, but intervallic distance is not the same thing (it is "counting" distance). If intervals were counted from zero instead of one, then thirds would be called seconds, and fifths would be called fourths, and two seconds would add to produce a fourth. Alternatively, you could think of intervallic distance in terms of _difference_, which is how we usually think of distance.
Comment: What the quote is missing is that intervals don't properly measure distance.  If they did, they _would_ be additive.
Comment: @LukeSawczak no, both C to E and E to G would be called a second. And if you add them you would get that C to G is a fourth. All of it would be perfectly consistent.
Comment: @Ootagu Well, some speculation, but not something I'd post as an answer: the term "fourth", for example, goes back at least to ancient Greece, before the acceptance of zero as a number. During the time modern theory was being developed, theorists adopted/adapted much of the terminology of ancient Greece. Perhaps the interval names just stuck (or were even in continuous use).
Comment: @leftaroundabout Indeed, and from C to D would be a 1st. The writer draws attention to the "twice-counted" E but fails to notice that they have to redefine 1st, 2nd and 3rd for the system to work at all.
Comment: I believe the poster understands the mathematics behind the issue quite clearly. Rather what I understand he is looking for is the "source of the discrepancy." And since he has already shown understanding of the mathematics I believe it's reasonable to read his question as a search for a deeper understanding as to why theorists opted for inclusive counting of intervals.
Comment: Of course, the original quotation's interpretation of why we count this way is mistaken. I mean, just look at your last table. As it demonstrate, if the medieval theorists "counted E twice" they wouldn't have called F the fourth, but they did. And what are they *supposed* to call E to G by the writer's logic? Presumably a second. But then the same distance would be called a third in one instance (C to E) and a second in the other. No, there's not much logic in it!
Comment: @Ootagu (Though it's not the poster being discussed here, but the quote and its writer's interpretation of the reason)
Answer: Musical intervals count ordinal start and end points not the actual "space" between tones:

ORDINAL: 1       2       3       4       5

TONES  : C       D       E       F       G

RULER  : 0       1       2       3       4
           --1--   --2--   --3--   --4--

If you treat musical intervals as spatial distances, then indeed it doesn't make sense. But, that is not what they are.
It might make more sense if you think of it in terms of ordinal numbers for the scale degrees above the tonic, and then extend that to ordinal numbers above any given tone in lieu of a tonic.
So, in C major the E is the third ordinal position. If you transpose that to start on E going up to G, think of the E as ordinal 1 and the G is the third ordinal above it.
It's kind of like saying in plain English "take a given tone and the third scale step above it" and then condensing it to just "a third" for convenience.
The tip off should be the "-nd", "-rd", "-th" ending of the interval names. Those are ordinal names. We have, for example, fifths, not fives. And of course it isn't a faction like "one fifth."
There are some oddities in the terminology. Musical intervals are very often referred to as distances, but if you really dig into it, we can see they aren't distances. Also, there isn't a musical interval of a first, it's called a unison. Those kinds of terminology inconsistencies aren't unique to music.
The whole 3+3 thing doesn't make sense. If you counted the "spaces", it would be 2+2=4, but because the ordinal numbers start with 1 you add 1 to get the musical interval, 2+2+1=5, a musical fifth. Taking two ordinal threes and then adding them together just doesn't make sense.
Comment: Yes, nicely summed up. They're ordinal in form, and we shouldn't be surprised if they're ordinal in function.
Answer: The problem is that this isn't a proper counting system starting with 0.  So every additional interval only adds "n-1" where "n" is the name of the interval.
An octave means "8," but it's only 7 notes up.  It's the 8th note.  The next octave is. . . 15ma, the 15th note.
Comment: Counting starts with 0.   No bananas, one banana, two bananas...    Maybe even negatives - I WANT one banana, I WANT two bananas...
Comment: @Tim Maybe it's my computer programming brain.  The first of anything is always 0-- the point of origin in a chart, the first byte of a sequence of memory (i.e. with an offset of 0), etc.  Calling an interval a "3rd" which is in fact an upward span of 2 notes is kind of goofy.  We're used to it in music, but it's goofy exactly BECAUSE it leads people to misunderstandings-- like 2*8 = 15 for octaves.  I remember seeing "16va" in a work by an impressionist-- Ravel maybe?
Comment: @LaurencePayne - counting might start with zero. But I've never heard anyone do it. 'Here's your change - no pounds, one pound, two pounds...' Farmer counting cows 'No cows, one cow, two cows...'  Crash survivors, maybe - 'None so far found...'
Comment: Note that the ancient convention of using inclusive counting for intervals wasn't specific to music theory.  After the Julian calendar reform of 45 BCE, the Roman pontifices misinterpreted the "add a leap day every four years rule" as adding a day every *three* years, since years 1-4, 4-7, 7-10, 10-13, etc. were counted as "four-year" intervals.  (And Julius Caesar himself was no longer around to check their math.)  Augustus had to fix this error decades later.
Comment: @Tim if you paid $10 for a $10 item, here is your change counted back: 0. It depends on _what_ is being counted, but natural numbers can start on _either_ 0 or 1. Time is a good example of zero starting.
Comment: How about this: "Someone gave me a stack of three bottles: one, two. . . done."
Comment: @MichaelCurtis - and I started to count out the $10 to pay - 1,2,3... and I've never been told 'Here's your change - nothing.' When it happens, the reply will be 'Well, keep the change.'
Comment: @MichaelCurtis - I know! Cardinal and ordinal *numbers* often get conflated, but it's not even that interals are ordinal. True, there's the inervals of thirds, fourths, etc, but the terms aren't really ordinal anyway. that's where the main problem lies.
Comment: Proper counting systems start with 1.  Proper measurements of distance start with zero.
Comment: Really?  I need to dig up Mrs. Henderson from grade one and tell her ghost that she had the number line all wrong.  Countdowns should go 3. . . 2. . . 1. . . Potato! :D  Anyway, I tested your theory by measuring distance on the piano, but strangely the black keys kept throwing off the measurements.
Comment: @Bennyboy1973 consider a digital clock counting down from five seconds to zero.  It illuminates a couple of (seeming) paradoxes: the seconds digit requires six distinct values for the countdown, not five, and the time expires one second after the seconds digit changes from 1 to 0, not at that moment.
Comment: @dan04 - and was there ever a year 0? We all fell for it with the millenium when new years eve 2000 arrived, I think.
Comment: I just realized we all have too much Corona time on our hands.  Oh well, it's all a bit silly, but a fun little diversion.  :D
Comment: @Tim   '...then there were NO green bottles, standing on the wall!'
Comment: @Tim, I'm trying to point out you're conflating ordinals and natural numbers, but more importantly natural number can start on _either_ 0 or 1 depending on what is counted. Just because _money_ counting starts at 1 doesn't necessarily mean anything about how other things are counted, or whether the situation is _actually_ dealing with _ordinal_ numbers. Flip the situation. Does anyone count money like "first dollar, second dollar..?" Not normally, but that's what's happening with musical intervals.
Answer:
I still don't grasp the "source of the discrepancy"

The discrepancy is between the fact that two stacked thirds form a fifth, and the OP's unfulfilled expectation that it should be expressed by addition of corresponding numbers, whereas in fact 3 + 3 ≠ 5. Possibly people who first named the intervals didn't consider performing such mathematical operations.

If music theory nomenclature for intervals made sense...

That's the key sentence. Music notation was first developed, to notate the music. Theoretical analysis came later. It could be compared to languages. For instance, in this site we use language in which the words "red" and "read" can be pronounced the same, while "read" and "read" can be pronounced differently. One can find more examples where conventions used for historical reasons don't follow simple expectations, both in languages, and in music notation.
There are some theoretical developments that fix the alleged "mistake". In particular, music set theory names intervals according to the number of semitones, with the root corresponding to 0, not 1; this allows for addition.
Answer: Put simply: C>E is a third (of some sort) as E is the third note from C, counting C as the first. E>G is also a third (of some sort) as G is the third note from E, counting E as the first. And, as we know, C>G is a fifth (of some sort), counting C as the first.
We could go more silly, and say that C>D is a 2nd, D>E is a 2nd, E>F is a 2nd, F>G is a second, G>A is a second, A>B is a second, and B>C is also a 2nd. That makes C>C a 14th, not what we know to be an 8th.
Even sillier, mathematically, we could say 1+2=3, 2+3=5, therefore 1+3= you work it out, I can't.
It's not quite as black and white (or grey!) as that.
We appear to use two distinct counting systems. One starts at O (think measuring with a rule, or timing with a stopwatch), the other at 1 (think counting money, counting sheep, but stay awake...), and I believe the two got interbred.
It all happened so long ago, that it really doesn't make sense to do anything about it. Apparently scientists found that positive and negative (electicity) really are the wrong way round. Should we all change them? Certainly not! It's taken this long for some of us to understand intervals as they are, please don't consider changing, for any reasons, let alone logic or pedancy...
Can't do any more, just been called back to the funny farm, where all is normal.


É possível instanciar uma conexão com o banco de dados manualmente usando o Entity Framework?

Question: Eu gostaria de gerenciar minhas conexões manualmente, para que os usuários pudessem informar o endereço do servidor, porém o Entity cria a string de conexão diretamente no arquivo de config, o único modo seria alterar aquele arquivo todas as vezes.
Porém eu queria fazer isso através de código, como se estivesse instanciando uma conexão manualmente ou apenas informando a string de conexão via código sem modificar o arquivo de configurações. É possível?
Answer: Sim, é possível.
Uma forma de se fazer isso é passando como parâmetro do construtor do contexto. Uma das sobrecargas do construtor aceita uma string.
Com esta abordagem é possível trabalhar de duas maneiras: 1) mantendo todas as conexões no arquivo web.config e construir o contexto passando o nome da conexão como parâmetro; e 2) passar como parâmetro do construtor a string de conexão completa.
public class SeuContexto : DbContext
{
    public SeuContexto(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }
}

E o uso poderia ser algo como
var context = new SeuContexto("uma string de conexao gigante aqui");


How many possible combinations in 8 character password?

Question: I need to calculate the possible combinations for 8 characters password. The password must contain at least one of the following: (lower case letters, upper case letters, digits, punctuations, special characters).
Assume I have 95 ascii characters (lower case letters, upper case letters, digits, punctuations, special characters).

lower case letters = $26$
upper case letters = $26$
digits = $10$
punctuations & special characters = $33$

The general formula for the possible passwords that I can from from these 95 characters is: $95^8$.
But, accurately, I feel the above formula is incorrect. Please, correct me.
The password policy requires at least one of the listed above ascii characters. Therefore, the password possible combinations = $(26)*(26)*(10)*(33)*(95)*(95)*(95)*(95)$
Which calculation is correct?
EDIT: Please, note that I mean 8 characters password and exactly 8. Also, There is no order specified (i.e. it could start with small letter, symbol, etc.). But it should contain at least one of the specified characters set (upper case, lower case, symbol, no., etc.).
Comment: Your second suggestion *seems* right - and can be shortened to `(26^2)*10*33*(95^4)` - but something feels just a little off about it. Regardless, this is off-topic for [security.se]. It *might* be on-topic for [math.se]. We'll see if they want it migrated.
Comment: Also of note, that password policy is ridiculously weak. 8-character passwords haven't been "strong enough" for quite some time. 12 is the new 8, but many are recommending 15, 20, or more. And please don't ever implement something that imposes a *maximum* length on the password. (Or at least, not a maximum that can be measured in two digits.)
Comment: 6.70 x 10^15 possible combinations
Comment: @Adnan That's the number of possible passwords *without* restrictions on any of the characters - not what's being looked for here.
Comment: @Iszi Please note the policy says "**at least** one of the characters should be...".
Comment: @Adnan Can you pleas explain more so I understand how this no. came?
Answer: Start with all $8$-character strings: $95^8$
Then remove all passwords with no lowercase ($69^8$), all passwords with no uppercase ($69^8$), all passwords with no digit ($85^8$) and all passwords with no special character ($62^8$).
But then you removed some passwords twice. You must add back all passwords with:

no lowercase AND no uppercase: $43^8$
no lowercase AND no digit: $59^8$
no lowercase AND no special: $36^8$
no uppercase AND no digit: $59^8$
no uppercase AND no special: $36^8$
no digit AND no special: $52^8$

But then you added back a few passwords too many times. For instance, an all-digit password was remove three times in the first step, then put back three times in the second step, so it must be removed again:

only lowercase: $26^8$
only uppercase: $26^8$
only digits: $10^8$
only special: $33^8$

Grand total: $95^8 - 69^8 - 69^8 - 85^8 - 62^8 + 43^8 + 59^8 + 36^8 + 59^8 + 36^8 + 52^8 - 26^8 - 26^8 - 10^8 - 33^8 = 3025989069143040 \approx 3.026\times10^{15}$
Comment: For reference to the OP: this is the *inclusion-exclusion principle*.
Comment: @Thomas Pornin the password must contains at least one of the (lower case, upper case, digit, symbol and punctuation). I do not understand why you assume passwords with no lower case, upper case, etc. as you explained.
Comment: @user2192774 I presume your policy means that you must have at least one of each character type. For four character types, there's 15 possible states of character inclusion/exclusion that a non-null password may be in and only 1 of those states is valid. Were the character distribution even (that is, if there were equally as many uppercase, lowercase, digit, and symbol characters to choose from) the formula would be simple - just raise the total possible characters to a power equal to the password length and divide by 15.
Comment: However, that is not the case. There are more symbols than there are letters of each class, and more than twice as many letters of each class as there are digits. Thus, we have to use more complicated methods like this.
Comment: A bit old question, was looking out of interest but my combinatorics would tell me $26^2\times10\times33\times95^4\times(8!)/((2!)\times(4!)) \approx 1.5 \times 10^{16}$.
Comment: Actually, no need to divide by 2! as the 26s represent two different things so I would get $26^2 \times 10 \times 33 \times 95^4 \times 8! / 4! \approx 3.05 \times 10^{16}$
Comment: Great application of inclusion-exclusion!
Answer: The answer I get is 0.3051925477389360000E+16 = 3,051,925,477,389,360.  This answer is taken from the answer at Derive an algorithm for computing the number of restricted passwords for the general case? .  This problem is more difficult than it appears.   $95^8$ is not the right answer.  (26)∗(26)∗(10)∗(33)∗(95)∗(95)∗(95)∗(95) is not the right answer and you can't just multiply this product by the number of permutations.  This is because if for example the punctuation special character first appears in the fifth position in the password with the first lower case letter, first upper case letter, and first digit appearing in the first 3 positions of the password then there are only $(95-33) = 62$ characters that can appear in the fourth position of the password.  Because of this problem a different approach is necessary.  An approach that gives the right answer is done by summing as follows:
The number of passwords for permutation $I_k$ with password positions j1, j2, j3, and j4 is
$$S(I_k,j1,j2,j3,j4)=f1*g_{I(1)}*(n_t-(g_{I(2)}+g_{I(3)}+g_{I(4)}))^{(j2-1-j1)}*g_{I(2)}*(n_t-(g_{I(3)}+g_{I(4)}))^{(j3-1-j2)}*gI_{(3)}*(n_t-g_{I(4)})^{(j4-1-j3)}*g_{I(4)}*n_t^{(n-j4)}$$  .
$$S(I_k)=\sum_{j4=4}^n \sum_{j3=3}^{j4-1} \sum_{j2=2}^{j3-1} \sum_{j1=1}^{j2-1} S(I_k,j1,j2,j3,j4)$$
gives the number of passwords corresponding to permutation, $I_k$.
$$Total=\sum_{k=1}^{24} S(I_k)$$
 gives the total number of passwords satisfying the requirement.
The algorithm for computing the number of passwords meeting the requirement is more completely described at the web site indicated above.
Answer: There's a simple flaw with the original equation:
It was stated that you have:

26 lowercase letters (a-z)
26 uppercase letters (A-Z)
10 digits (0-9)
33 punctuations and special characters

How many total choices can each character within the password use?
ADD the above numbers to answer that: $26+26+10+33 = 95$
How many characters is the password in question?
I believe we identified 8 in this scenario.
How many combinations for this password are there?
$$\text{(Possible choices)}^\text{(How many characters long)}=\text{(How many combinations)}$$
Or per this example, $96^8=6634204312890625$
Based on 8 characters of anything you can type, the answer is as simple as above.
As stated in a more convoluted, albeit more descriptively accurate, the number changes based on password requirements.
From a hacker / pentester perspective, entropy is stronger than mental complexity.
If people use all lowercase because rules don't force them to use something else, yes, their password is weaker being all lowercase, because I can probe the password based on just lowercase ($26^8$).
Wow, no rule against using humanly recognized words? (That was a common rule early-mid 2000s) The password rules themselves actually make a weaker password than the mathematically possible $96^8$.
Password entropy makes this even more fun as we demonstrate that the entropy of password

A#1WepOjII95&^2!

is actually weaker than the password

OMGmathMakesMyHeadWant2EXPLODE

If you're looking at this from a security standpoint, use a long run-on phrase for a more challenging time being cracked. Using rainbow tables, it's now possible to crack a 64-character password within 4 minutes on a single computer.
No, your $120 Atom laptop isn't likely to meet that kind of hacking efficiency. It's simply saying you don't need a cluster of computers anymore.
Comment: On creating a rainbow table for a 64 character password.  Lets assume all lower case letters: 26^64 = 3.6165483e+90.  Number of atoms in the universe 1.0e+83 atoms.  Assuming the single computer is able to leverage all the atoms in the universe each atom would need to store roughly 3.6e+7 entries.  A computer that can store 36 million hash table entries per atom and is able to use all the atoms in the universe.  Now THAT is a computer!  Do you think they might have them at Best Buy?


How to include book traversal links on a custom twig template page

Question:
I use the Book module to create books with chapters.
When I use the default twig template node.html.twig to display a book chapter, a section titled "Book traversal links" is included, with links to the previous chapter, the next chapter, and to the book. The debugger says these links come from the book-navigation.html.twig template.
Instead of the default template, I'm using a custom twig template node--chapter.html.twig to display chapters.

QUESTION:
How can I get the same book traversal links onto my custom page?
NOTES:

I checked for a block containing the book traversal links that I could just insert in my twig template, but I don't see one.
I have checked the $variables array in the twig template to see if maybe a list of the chapter's siblings is already there, but don't see one.
I'm already using HOOK_preprocess_node(&$variables) to find the book parent book's id, so I can use it to find the chapter's siblings, if that's the way to go.
Answer: Alas, there is no block for this; the book navigation links are hacked on to the node view in core.
From core/modules/book/book.module:
/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
      $build['book_navigation'] = [
        '#theme' => 'book_navigation',
        '#book_link' => $node->book,
        '#weight' => 100,
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
      ];
    }
  }
}

The good news is that this should work with custom templates as long as you are using the full view mode.
I have a custom node template and I still get the navigation links on my books at the bottom of the content.  (Unfortunately, whether I want them there or not-- as per the above code, they are forcibly added and there is no UI to control them.)
Answer: You can code the book navigation into your own block.
In this case, you will need to override book_node_view() so that the nav links are not displayed twice.
This may give you an idea (not complete code, cannot be used by itself; inspired by this post):
class BookNavigationBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $node = \Drupal::routeMatch()->getParameter('node');
    if (isset($node)) {
      if ($node->bundle() == 'book') {
        $build['book_navigation'] = [
          '#theme' => 'book_navigation',
          '#book_link' => $node->book,
          '#weight' => 100,
          // The book navigation is a listing of Node entities, so associate its
          // list cache tag for correct invalidation.
          '#cache' => [
            'tags' => $node->getEntityType()->getListCacheTags(),
          ],
        ];
      }
    }
    return $build;
  }


i create a bot can change my roles away but it get err

Question: i create a bot can change my roles away but it get err
when i am a roles
it can delete a roles
and change to b roles
and change back to a roles
myname.add_roles(rolesID)

i open dev mod and use my descord and set myname = myid
but i get
AttributeError: 'int' object has no attribute 'add_roles'

so i change myid to my discord username and #
i get
AttributeError: 'str' object has no attribute 'add_roles'

can someone help me ?
Answer: You need to actually get the member object from your id.
For example:
guild_obj = client.get_guild(Your Guild Id here)
member_obj = guild_obj.get_member(Your Member Id here)
await member_obj.add_roles(rolesID)


pip install pyinstaller no module named pyinstaller

Question: I wanted to install pyinstaller module with the following command:
pip install pyinstaller

But I always get the following error:
Answer: I tried everything, but finally i found the solution.
You just have to downgrade your pip from version 19 to 18.1 :
pip install pip==18.1

Then install PyInstaller :
pip install pyinstaller

.
As you see i managed to install it :

.
After that you can upgrade again your pip :
python -m pip install --upgrade pip

Comment: Thanks for putting this up, it definitely helped!
Answer: There seems to be a problem when using pip-19.0.1 because as the other answer suggests, using 18.1 works fine.
But also now pip-19.0.3 has been released and upgrading to that seems to fix the issue.
So I suggest you try to update pip and then install pyinstaller
python -m pip install --upgrade pip
pip install pyinstaller


Form submit in FieldFormatter

Question: I have a custom entity type with a "yield" field. I would like to allow users to see the custom entity (full content view-mode) and change "yield" value to regenerate it with calculated values from the yield changement.
I started with a new fieldFormatter for my "yield" (number_decimal) field. The formatter extends DecimalFormatter and builds a little form object instead of displaying a simple markup.
$element = [
  '#type' => 'form',
  '#tree' => TRUE,
];
$element['yield'] = [
  '#type' => 'number',
  '#title' => $this->t('Change yield'),
  '#default_value' => floatval($this->numberFormat($item->value)),
  '#value' => floatval($this->numberFormat($item->value)),
];

$element['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Change'),
  '#submit' => ['changeYield'],
];

Form is defined in the full content view, and a click on the submit button send the form. I think this is not the correct way to add a form because #submit callback is never called. I tried different syntax, with static or non-static callback, but it doesn't work.
I would like to find an elegant solution, not hacking and adding JavaScript custom code.
Now the ideal solution is attaching #ajax callback to rebuild the data without sending the page, but I don't know if it possible and if dependencies will be not to strong, because changes done on another fieldFormatter item's values.
Answer: You can't add a form field to an entity display. You have to approach this the other way. Build a form class with the field and the submit button and add the entity content to it. Then you can respond to the posted data in the submit method of the form class and save it to the entity.
For the ideal solution you can attach ajax to the submit button to avoid a page reload.
An alternative option is an entity form using a custom form mode containing one field. This could be set up without code by using blocks for both, the entity content and entity form or only one of them and the other as page. This depends on what the end result should look like. You need a module to control the form modes Form mode control and to put an entity form in a block Entityform block. The entity content can be placed in a block with Views. For a custom entity all of this can be done in code as well.
Answer: For my uses, I found a solution to embed forms in formatters.
Imagine that an entity type (type A) has a entity-reference field that holds another entity type (type B). Entities of type B holds a third entity type (type C).
Example:
A : an entity of type "collection"
B : an entity of type "album"
C : an entity of type "song".
A collection contains one or more albums, and each album contains some songs.
For the "collection" entity view, I would like to display each album as a little form with a table listing the songs, and allow reorder (draggable) and edit songs data.
In this case, and it work, I created a "album" formatter and a "song_list" form that contains the logic of the draggable/editable table.
The album formatter has a viewElements method like this:
public function viewElements(FieldItemListInterface $items, $langcode) {
    $base_entity = $items->getEntity();

    $elements = [
        '#theme' => 'item_list',
        '#items' => [],
        '#title' => $this->t('Albums listing'),
    ];
    /** @var \Drupal\my_module\Entity\Album $entity */
    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {

        $name = $entity->label();
        $name = Xss::filter($name, []);
        $item = [];
        $item['name'] = [
          '#type' => 'markup',
          '#markup' => '
'.$name.'
',
        ];

        $form = \Drupal::formBuilder()->getForm('\Drupal\my_module\Form\AlbumSongListForm', $entity);
        $item['form'] = $form;
        $elements['#items'][] = $item;
    }
    return $elements;
}

I used this formatter as "album" entity formatter in the "collection" view display mode.
When I go the the "collection" page, For each album in the collection is displayed a form listing each song. And off course, each form can be submitted to save values.
Be careful with multiple forms of the same class on the same page. Indicate explicitly the "form ID" to have unique identifier for each form. This can be done with
$form['#id'] = 'album-'.$album->id().'-song-list-form';

Finally, it's possible to use form's in formatters. I don't know if ajax or other behaviors can be used, but #states works with no problems.
Comment: Yes, this is because you are fetching a form array and setting it into the elements array, where it is rendered later. But I suspect that this is not a good place for it (inside `viewElements`).
Answer: Ok. Finally I found a solution based on 4k4 answer.
Instead of attaching ajax or simple submit to the formatter, I created a Form with my needs, and a Block that embed the form.
Form
namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;

class YieldChangerForm extends FormBase {

  public function getFormId() {
    return 'my_module_yield_changer';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

      // Attach some fields here.

      $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Change'),
      ];
      /*
      $form['submitAjax'] = [
        '#type' => 'button',
        '#value' => $this->t('Change'),
        '#ajax' => [
          'callback' => '::changeYield',
        ],
      ];
      */
    }

    return $form;
  }

  /*
  public function changeYield(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand(
      '#my-wrapper',
      '
Modified content here
'
    ));
    return $response;
  }
  */

  /**
   * {@inheritDoc}
   * @see \Drupal\Core\Form\FormInterface::submitForm()
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Handle submit here
}

Block
namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provide a Yield changer block to display
 * on recipes.
 *
 * @Block(
 *   id = "my_module_yield_changer_block",
 *   admin_label = @Translation("Yield changer"),
 * )
 */
class YieldChangerBlock extends BlockBase {

  /**
   *
   * {@inheritDoc}
   * @see \Drupal\Core\Block\BlockPluginInterface::build()
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('\Drupal\my_module\Form\YieldChangerForm');
    $renderArray = [
      'form' => $form
    ];
    return $renderArray;
  }
}

The block is placed before the entity content and display the Form. From now, I simply reload the page and set a "yield" key with user selected value in the URL.
In the sample, you can see commented code that use ajax callback to send modified data. I don't use it now because I think it's complex to render the data I want to change.

Form submit in FieldFormatter