Equality-constrained QCQP — what to do next?

Question: I am studying the following problem. I want to obtain all the local minima of
$$
\min_{x\in D} x^Tx \quad \quad \quad \quad \quad \quad (P.1)
$$
where $x\in\mathbb{R}^n$ and $D = \{x: x^TA_ix = 1, \forall i=1,\dots,m\}$ and $A_1,\dots,A_m$ are a collection of $m<n$ positive definite $n\times n$ matrices. According to the Lagrange multiplier theorem ("Nonlinear programing" by Dimitry Bertsekas):

Proposition 3.1.1 (Lagrange Multiplier Theorem - Necesary Conditions) Let $x^*$ be a local minimum of $f$ subject to $h(x)=(h_1(x),\dots,h_m(x))=0$ and assume that the gradients $\nabla h_1(x^*),\dots,\nabla h_m(x^*)$ are linearly independent. Then, there exists a unique vector $\lambda^*=(\lambda_1^*,\dots,\lambda_m^*)$ called Lagrange multiplier vector such that
$$
\nabla f(x^*) + \sum_{i=1}^m\lambda_i^*\nabla h_i(x^*)  =0 \quad \quad \quad \quad \quad \quad (3.3)
$$

Thus, the set of ALL local minima can be divided in two, the ones which have $\{\nabla h_i\}_{i=1}^m$ linearly independent (regular points), and such points may be found using (3.3), and other minima which have $\{\nabla h_i\}_{i=1}^m$ linearly dependent (nonregular points).
My question is: I already know how to find the regular points. My interest is regarding the nonregular ones. Can those nonregular points be studied (obtained) in my case? For reference, note that $h_i(x) = x^TA_ix-1$ and $\nabla{h_i}(x) = 2A_ix$.
From this point, let me explain what I have found up to now:
Suppose $\hat{x}$ is one of such points. I can partition the set of vectors $\mathcal{A}=\{A_i\hat{x}\}_{i=1}^m$ into two disjoint sets $\mathcal{B}=\{B_i\hat{x}\}_{i=1}^s\subset \mathcal{A}$ and $\mathcal{C}=\{C_i\hat{x}\}_{i=1}^r\subset \mathcal{A}$ with $r+s=m$ such that the vector in $\mathcal{B}$ are linearly independent and the ones in $\mathcal{C}$ are a linear combination of the ones in $\mathcal{B}$.
Then, there exists real constants $\{\alpha_{ij}\}_{j=1}^m$ such that
$$
C_i\hat{x} = \sum_{j=1}^s \alpha_{ij}B_j\hat{x}
$$
And for this point to lie in $D$ I require that $\hat{x}^TC_i\hat{x} = 1$ but also $\hat{x}^TB_j\hat{x}, j=1\dots,s$. Hence, it must be the case that $\sum_{j=1}^s \alpha_{ij}=1$ for $i=1,\dots,r$ and $j=1,\dots,s$. (is this useful?).
My original intention was to cast this as another (reduced) nonlinear program in which the gradients $\{\nabla h_i\}$ are linearly independent. My attempt was to try to show that $\hat{x}$ will be a local minimum of $(P.1)$ ignoring the "linearly dependent components". This is, if I solve (P.1)  for all combinations of $\{A_i\}_{i=1}^m$, for example building $D$ only with the $A_i$ for separate, then by pairs, etc... then $\hat{x}$ would show up as a solution of one of those, in which the corresponding $\{\nabla h_i\}$ are linearly dependent. Is this true? The more I think about it the more I convince myself it is not the case. But what do you think? As an example of what I mean here, is the following. Consider $m=2$, $n=3$ and $A_1 = \text{diag}(1,1,0.1)$, $A_2 = \text{diag}(1,1,0.5)$. The constraints $x^TA_1x=1$, $x^TA_2x=1$ look like the red and blue surfaces here:

Their intersection is the yellow circle. Note that points in such intersection will have linearly dependent gradients, basically since $A_1x=A_2x$ for $x$ in such interection. However, if I study (P.1) just by taking into account $A_1$, I could still find those points. Of course this is just an example that motivated my idea, but It seems not to generalize.
My other attempt was to try to find explicitly all points that have $\{A_i\hat{x}\}_{i=1}^m$ linearly dependent. This is, find coeficients $\alpha_1,\dots,\alpha_m$ such that the matrix $H(\alpha)=\sum_{i=1}^m\alpha_iA_i$ is singular, and then look for $\hat{x}$ in the kernel of $H(\alpha)$ and see if such set of points intersect the problem constraints, etc... However, I haven't been able to obtain anything new from here.
What do you suggest me to do next? Do you think is possible to obtain such points? Actually any suggestion, advice, comment would be helpful for me.
Comment: Without looking at the proof, I can't be certain, but your first question regarding Prop. 3.1.1 looks like the answer is no. This only states that "linearly independent gradients at a local min $x^*$ implies (3.3)." It does not say that (3.3) implies you are a local minima with linearly independent gradients.
You can certainly still partition the minima into {$x^*$ with linearly independent gradients} $\sqcup$ {$x^*$ without linearly independent gradients}. It's just that the former are not entirely characterized by (3.3).
Comment: I totally agree with you. Do you have a suggestion regarding the other part of the question? thanks
Comment: I'll let you know if I find some time to sit down and really think about the other questions. By the way, this problem is nonconvex, but you could numerically solve the convex relaxation (obtained by replacing $x^\top Ax=1$ with $\leq 1$) pretty easily using a quadratic programming software package.
Comment: Thanks for the feedback. Do you think is ok now?
And yes, thats one way to put it. However, I have been able to obtain all regular points (the ones that comply with (3.3)) my question is regarding the nonregular ones.
Comment: For the case where $m=1$ and $n=2$, take a look at [this](https://math.stackexchange.com/a/2090988/339790).
Comment: Thanks @RodrigodeAzevedo! Actually I have a very similar solution for the case with $m>1$ in other to find all other points which comply (3.3), this is all regular points. Moreover, when $m=1$, there are no nonregular points, so I think I have that case completely understood. My complications come when I have $m>1$, when the nonregular points may exist.
Answer: $$\begin{array}{ll} \underset{\mathrm x \in \Bbb R^n}{\text{minimize}} & \mathrm x^\top \mathrm x\\ \text{subject to} & \mathrm x^\top \mathrm A_1 \mathrm x = 1\\ & \qquad\vdots\\ & \mathrm x^\top \mathrm A_m \mathrm x = 1\end{array}$$
where $m < n$. We define the Lagrangian
$$\mathcal L ({\rm x}, \mu) := \mathrm x^\top \mathrm x + \mu_1 \left( \mathrm x^\top \mathrm A_1 \mathrm x - 1 \right) + \cdots + \mu_m \left( \mathrm x^\top \mathrm A_m \mathrm x - 1 \right)$$
Taking the partial derivatives and finding where they vanish,
$$\begin{aligned} \left( \mathrm I_n + \mu_1 \mathrm A_1 + \cdots + \mu_m \mathrm A_m \right) \mathrm x &= 0_n \\ \mathrm x^\top \mathrm A_1 \mathrm x &= 1 \\ &\vdots\\ \mathrm x^\top \mathrm A_m \mathrm x &= 1 \end{aligned}$$
I have no idea how to solve this system of $n+m$ equations in $n+m$ unknowns. Since we are not looking for the solution ${\rm x} = 0_n$, from the first $n$ equations, we have
$$\det \left( \mathrm I_n + \mu_1 \mathrm A_1 + \cdots + \mu_m \mathrm A_m \right) = 0$$
but I do not know what to do with this. Suggestions are most welcome.
Comment: Thanks! I obtained something similar before. Actually, the problem can be studied using duality analysis, and the Lagrange multipliers can be found by solving a set of polynomial equations (showing zero duality gap is easy). So I already know how to obtain those. However, as I described before, those regular points (which have $\nabla \mathcal{L} = 0$) are not so much of my interest. I'm interested in the nonregular ones, those which may not comply with $\nabla \mathcal{L} = 0$ due to linear dependency in the gradients of the constraints, but still being local minima.


What are the consequence of $\limsup_{x\to x_0}f(x)\leq \ell$ or $\limsup_{x\to x_0}f(x)\geq \eta$?

Question: I'm always confuse with this limsup (especially of the form $\limsup_{x\to x_0}$.
What are the consequence of $\limsup_{x\to x_0}f(x)\leq \ell$ or $\limsup_{x\to x_0}f(x)\geq \eta$ ? Which information do we have ?
Answer: $\lim \sup_{x \to x_0} f(x) \leq l$ is equivalent to: for every $\epsilon >0$ there exists $\delta >0$ such that $f(x) <l+\epsilon$ whenever $|x-x_0| <\delta$.
$\lim \sup_{x \to x_0} f(x) \geq l$ is equivalent to: for every $\epsilon >0$ there exists a sequence $x_n \to x$ with $ f(x_n) >l-\epsilon$ for all $n$.


Constructing $\mathbb{R}$ from $\mathbb{Z}$?

Question: I have been told that the real number line $\mathbb{R}$ can be constructed from the cartesian product $\mathbb{Z} \times [0,1)$.
How exactly is that true? Surely, the cartesian product $\mathbb{Z} \times [0,1)$ would give a set of ordered pairs of numbers? How is this equivalent to $\mathbb{R}$?
Comment: Integer part and fractional part. The integer is whatever's to the left of the decimal point; and the fractional part is everything to the right.
Comment: I'd say it is the opposite : $[0,1)$ is constructed by quotienting $\mathbb{R}$ by $\mathbb{Z}$
Comment: Why do you think "constructed from" means "equivalent" and why do you think "equivalent" means "is the exact same thing" and why do you think "constructed from" means "leave alone exactly as is"?  (a,b) in Z x [0,1) is an ordered pair.  But f(a,b) = a + b is a real number.  For any real number r and can find an integer n so that n <= r < n+1 so (n, r-n) in Z x[0,1), and f(n,r-n) = r.  So clearly R can be constructed from Z x [0,1) by "putting them all through" f.
Comment: @user1952009 it depends on what "constructed" means.  To create f(a,b) = a + b one has to assume R already exists so in that sense you are right; finding a function that maps Zx[0,1) isn't "contruction"-- defining and proving the existence of a number system.  On the other hand if "contruction" simply means finding a way to "convert" Zx[0,1) to R than f(a,b) = a + b certainly does that.
Answer: There is a bijection $f((x,r)) = x + r$, so $x$ is the integer part of the real number (before the digital point) and $r$ is the part after the digital point. Of course this assumes we write $1$ as corresponding to $(1,0)$ etc.
This is a bijection but not a homeomorphism (as the product is disconnected as a topological space).
Answer: If you had $\mathbb{R}$, a natural map from the set you have to $\mathbb{R}$ would be
$$\mathbb{Z} \times [0,1) \to \mathbb{R}$$
$$(x,y) \mapsto x+y.$$
This is a bijection, as you can verify. However, since we "do not have" $\mathbb{R}$, we must "define":
$$\mathbb{R}:=\mathbb{Z} \times [0,1).$$
But... I think that by any reasonable meaning of "construct", you are entailing at least the operations and ordering of $\mathbb{R}$. And I see no easy way to do this in the set above without using explicitly (or at least "implicitly explicitly") the operations and ordering in $\mathbb{R}$, which would turn out to be circular.

If you admit as given the "structure" inherited by $[0,1)$ (although this is unclear, since it is not a good algebraic structure. It is an ordered set in a natural way, but the operations are not defined on all elements), we can proceed as follows to get the operations:
We use the lexicographic order on "$\mathbb{R}$". From the order, we already have the topology.
To do addition, if $x+y$ is defined, then
$$(n,x)+(m,y):=(n+m,x+y).$$
Now, before defining addition in the whole set, we define what it means to multiply by two in $[0,1)$, a unary operation which we will call $d$.
If $x<1/2$, we define $d(x)=2x$. If $x \geq 1/2$, we define $d(x)=x-(1-x)$*. Now we can define addition everywhere as follows:
if $x+y$ is not defined, then
$$(n,x)+(m,y):=\left(n+m+1,d\left(\frac{x}{2}+\frac{y}{2}\right)\right).$$
Having defined addition, we have a natural way to define multiplication by integers (we can verify that, indeed, our set with addition is an Abelian group).
Now, to define multiplication, we do
$$(n,x)\cdot(m,y):=(nm,0)+n(0,y)+m(0,x)+(0,xy).$$

*- $(1-x)$ can be defined as $\sup\{y \in [0,1) \mid x+y \text{ is defined}\}$ (with regards to what "is defined" means if it is not clear, see Ian's comment below). For $x \neq 0$ this is well-defined. Hence, it is well-defined for all $x \geq 1/2$, as is needed for our definition.
Comment: I'm not sure what you mean. For the ordering it is easy, once you have the ordering on $[0,1)$, to compare $(a,b)$ with $(c,d)$, first compare $b$ and $d$. If they're the same, compare $a$ with $c$. For the operations, you can make sense of "let $a$ be the bigger of $a$ and $c$, if $a>1-c$ then...else..." That gets you addition and subtraction. Can we do something similar to get multiplication?
Comment: @Ian You're right, but I (maybe mistakenly) thought about purging away any structure on $[0,1)$, including its ordering, since constructing such a structure would be something similar to using an already constructed $\mathbb{R}$ (that's what I meant by "implictily explicitly"), but this was silly I think. I will add information to the answer.
Comment: @Ian I've updated the answer. Please tell me if there is any issue : ).
Comment: It's a bit messy because you haven't characterized when $x+y$ fails to be defined. Yet there is basically a simple answer: $\max \{ x,y \} \geq 1-\min \{ x,y \}$. (Issues: 1. we don't have $1$, so we need to get $1-x$ from somewhere. 2. 1-0 isn't in $[0,1)$. But then, we could handle that case separately.) Otherwise it looks good.
Answer: Define
$$
f:\mathbb{Z} \times [0,1)\to\mathbb R
$$
as follows: for any $(m,x)\in \mathbb{Z} \times [0,1)$, $ f(m,x)=m+x$. Then $f$ is a bijective map. I don't know if that is what you mean with 'contructed'
Answer:
I have been told that the real number line $\mathbb{R}$ can be constructed from the cartesian product $\mathbb{Z} \times [0,1)$.

"constructed from" is perhaps relatively vaguely defined, but I assume you mean "has the same cardinality as" or, equivalently, "a bijection exists to".
$$ f((n, r)) = n + r $$ is exactly such a bijection.

How exactly is that true? Surely, the cartesian product $\mathbb{Z} \times [0,1)$ would give a set of ordered pairs of numbers? How is this equivalent to $\mathbb{R}$?

"Equivalent" makes no sense in this case. One could define equivalence in many distinct ways. When you say "constructed from" I assume you are searching for a bijection.


How to import a datetime data to sqlite3?

Question: I have a CSV file containing a timestamp in the following format:
 Datetime, Outdoor, Indoor
 01/01  01:00:00,24.5,21.3
 01/01  02:00:00,24.3,21.1
 01/01  03:00:00,24.1,21.1
 01/01  04:00:00,24.1,20.9
 01/01  05:00:00,25.,21.
 01/01  06:00:00,26.,21.
 01/01  07:00:00,26.6,20.3
 01/01  08:00:00,28.,21.
 01/01  09:00:00,28.9,21.5
 01/01  10:00:00,29.4,22.1
 01/01  11:00:00,30.,22.
 01/01  12:00:00,29.,23.
 01/01  13:00:00,28.4,22.9
 01/01  14:00:00,27.8,22.7
 01/01  15:00:00,27.3,22.3
 01/01  16:00:00,27.,22.
 01/01  17:00:00,26.,21.
 01/01  18:00:00,26.,21.
 01/01  19:00:00,26.3,21.4
 01/01  20:00:00,26.,21.
 01/01  21:00:00,25.9,21.1
 01/01  22:00:00,25.8,21.3
 01/01  23:00:00,25.6,21.4
 01/01  24:00:00,25.5,21.5

That is the datetime format is "%m/%d  %H:%M:%S". How can I import this into sqlite3?
Answer: "01/01" isn't a date. If you mean "21.0", output "21.0", not "21.".
Edit your csv file (or better yet, fix the program that outputs that junk) so it looks like this.
2011-01-01  01:00:00,24.5,21.3
2011-01-01  02:00:00,24.3,21.1
2011-01-01  03:00:00,24.1,21.1
2011-01-01  04:00:00,24.1,20.9
2011-01-01  05:00:00,25.0,21.0
2011-01-01  06:00:00,26.0,21.0
2011-01-01  07:00:00,26.6,20.3
2011-01-01  08:00:00,28.0,21.0
2011-01-01  09:00:00,28.9,21.5
2011-01-01  10:00:00,29.4,22.1
2011-01-01  11:00:00,30.0,22.0
2011-01-01  12:00:00,29.0,23.0
2011-01-01  13:00:00,28.4,22.9
2011-01-01  14:00:00,27.8,22.7
2011-01-01  15:00:00,27.3,22.3
2011-01-01  16:00:00,27.0,22.0
2011-01-01  17:00:00,26.0,21.0
2011-01-01  18:00:00,26.0,21.0
2011-01-01  19:00:00,26.3,21.4
2011-01-01  20:00:00,26.0,21.0
2011-01-01  21:00:00,25.9,21.1
2011-01-01  22:00:00,25.8,21.3
2011-01-01  23:00:00,25.6,21.4
2011-01-01  24:00:00,25.5,21.5

Then set the separator and import the file.
sqlite> .separator ','
sqlite> .import filename tablename


Json Array para Array de string C#

Question: Preciso somente pegar os nomes da moderators e viewers desse json:
{
  "_links": {},
  "chatter_count": 16,
  "chatters": {
    "moderators": ["gumagames", "juliavidoto", "nightbot", "pinkpanthersz_", "victoriia66"],
    "staff": [],
    "admins": [],
    "global_mods": [],
    "viewers": ["andreschramm", "anotheruselessbot", "barbosza", "brancoxp", "froydz1515", "hurato2", "luiz522", "phoenixlabella", "rockmam", "sumarilion1988", "xoverxkill"]
  }
}

Estou usando JSON.Net mas não consegui um resultado satisfatório.
Comment: O que você já tentou?
Comment: Olhe se é [**isso**](https://dotnetfiddle.net/WzSBx3) o que você precisa.
Comment: @Brunno Estava fazendo assim mesmo Brunno, estava declarando as classes de maneira errônea, mesmo assim agradeço pela solução!
Comment: @MarcosBarbosa legal, postei como resposta.
Answer: Você precisa criar uma classe de acordo com o seu Json, e após isso basta usar:
JsonConvert.DeserializeObject<SeuObjeto>(stringJson);

Que ele fara o parse do Json para sua classe e retornara o objeto instanciado.
Segue o fiddle.
Gerando as classes do Json em C#: json2csharp
Answer: Usando o comando de linha jq:
jq ".chatters.moderators,.chatters.viewers" ex.json

produz:
[
  "gumagames",
  "juliavidoto",
  "nightbot",
  "pinkpanthersz_",
  "victoriia66"
]
[
  "andreschramm",
  "anotheruselessbot",
  "barbosza",
  "brancoxp",
  "froydz1515",
  "hurato2",
  "luiz522",
  "phoenixlabella",
  "rockmam",
  "sumarilion1988",
  "xoverxkill"
]

ou
jq ".chatters.moderators+.chatters.viewers" para obter um único array

Json Array para Array de string C#


Bijective coding of general graphs (like Prüfer code but not for trees)

Question: I'am trying to find some way to effectively enumerate all possible graphs without repetition. I know there are Prüfer codes for trees, but what about other graphs? And if there is some coding, are there also codings for directed graphs or multigraphs? It would be ideal if all isomorphic graphs had the same code.
Comment: Your last wish is very ambitious. The graph isomorphism problem is very hard: https://en.wikipedia.org/wiki/Graph_isomorphism
Comment: labelled or unlabelled graphs?
Answer: As pointed out by @EthanBolker, the problem of describing all  graphs upto isomorphism is not even known to be NP-hard. But, in case you want to just enumerate the number of graphs of order $n$, then as the graphs are nothing but binary non-reflexive, symmetric relations on a set of $n$ elements, their number is $2^{\frac{n(n-1)}{2}}$. As for directed graphs, since these needd not be symmetric, therefore, we have their number of $n$ vertices equals $2^{n(n-1)}$. Also see here
Comment: Correction: graph isomorphism is not known to have a polynomial-time algorithm, but it is not known to be NP-hard either. (Of course, we can't *prove* that it's not NP-hard, because that would be proving that P≠NP.)
Comment: @MishaLavrov thanks! edited the post


Como abrir uma imagem em nova guia ao clicá-la e bloquear página sem parâmetro?

Question: Estou com a pesquisa do CSE no meu site, e até fiz essa pergunta: Como alterar objetos do URL via JavaScript?, e queria saber se tem como criar um script que as imagens da página abram em nova guia quando forem clicadas.
E queria que o usuário fosse redirecionado para a página inicial do site quando a página de pesquisa estivesse com o parâmetro ?q= vazio (sem pesquisa).
Comment: Quanto mais detalhes você der na pergunta, mais fácil fica para responder de primeira. Mas, atenção, detalhes importantes, detalhes superfluos só atrapalham.
Answer: Para abrir uma nova janela pode ver esta resposta. No fundo precisa de usar o window.open('url da imagem'), ou pode simplesmente usar o atributo target="_blank" no HTML usando no href da ancora o URL da imagem:
Texto ou Imagem aqui

Para fazer o redirecionamento pode fazer assim (colocando dentro de tags  preferencialmente na head da página:
var query = window.location.search;
if (query == '?q=') window.location.href = "http://pt.stackoverflow.com";

Comment: Funcionou! Obrigado, valeu!
Comment: Marquei! Valeu!!!
Comment: Blz. Precisa ter o Id das imagens?
Comment: @GustavoPonte depende de como o HTML está feito, e como faz o redirecionamento. Qual é o HTML que o utilizador clica? É uma ancora? ``
Comment: Olha, eu sei que, quando são exibidos resultados de imagens e o usuário clica, em vez de abrir a imagem, abre um link. Veja: https://www.google.com/cse/publicurl?cx=012244706173914607628:ivy1g9qzid0
Comment: E o "location.search", na verdade, o link de busca é:
Comment: E sobre o "locarion.search": O link de pesquisa do meu site é: www.site.com/busca/?q=pesquisa. O que eu faço?
Comment: @GustavoPonte coloque o javascript que dei na resposta dentro da sua página, ele vai ler o URL e fazer o redirecionamento.. Em relação a como abrir uma imagem respondi ao que perguntou na pergunta.


Get access to node titles and nid's only

Question: there are two content types on my site: Projects and Employees. Employees has a user reference field, Projects have several node reference fields to Employees (according to different project roles). I grant rights to users with Node access user reference and Node access node reference modules so they can view and edit only the nodes they are referenced to (either directly or indirectly).
Certain referenced users (project managers) should be able to add other Employees in Project nodes but in the same time they must not see their personal data. Therefore they haven't got any referencable Employee nodes.
Would it be possible to grant access to the node titles (and nid's for referencing) only and hide other fields?
Answer: Yes you can, with  field_permissions module  you can set permissions according to the fields.
Comment: Do you mean to hide all other fields with this module and make the Employees content type viewable for authenticated users?
Comment: @StG yes, it can do it ,of course it did not hide them( disable access to them)
Comment: I'd gladly avoid this because there are lot's of fields in this content type but it seems to be a suitable solution nonetheless. Thanks a lot.
Comment: @StG your welcome, also if you have a development knowledge maybe there are another ways but need more time :)


Prevent Default Not Working

Question: I am working on a music player and i believe my prevent default is not working. When I hit play everything works fine. The button switches to the pause button and the music plays. However when I hit pause the page refreshes. Any ideas?
Thanks!
play.on('click', function (e) {
    e.preventDefault();
    song.play();
    $(play).replaceWith('');
    container.addClass('containerLarge');
    cover.addClass('coverLarge');

});

pause.on('click', function (e) {
    e.preventDefault();
container.removeClass('containerLarge');
    cover.removeClass('coverLarge');
    song.pause();
    $('#pause').replaceWith('');

});

Answer: You're replacing the elements with new ones. The event handlers are bound to the old elements, not the new ones, and the references stored in variables play and pause will be the old detached DOM elements as well.
You need to leave the elements alone, and programatically hide/show them, rather than completely removing them and replacing them with the other element:
play.on('click', function (e) {
  e.preventDefault();
  play.hide();
  pause.show();
});

Comment: Or use on like this: `$('body').on('click','#pause',function(e){`
Comment: While I provided an answer below, I can't see why you would need to removed the DOM elements entirely. So @Meagar's answer is better. You should simply hide the elements not removed them from the DOM. However if you NEED to remove them and add them back, adding the listener to the body element and seeing where the event took place would be an option.
Answer: $('body').on('click','#pause',function(e){
$('body').on('click','#play',function(e){

You didn't provide HTML but these should work.

Prevent Default Not Working


Spivak Calculus Chapter 3 Question 6

Question:
If $x_1,\cdots,x_n$ are distinct numbers, find a polynomial function $f_i$ of degree $n−1$ which is $1$ at $x_i$ and $0$ at $x_j$ for $j\not=i$.

Forgive my complete ignorance, but I do not understand what this question is asking. Can someone please explain the following basics to me or suggest where I might learn to comprehend such questions?
My attemp: The $i$ in $f_i$ serves only to distinguish $f_i$ as the polynomial function in question from some random polynomial function. It does not mean $f(x_i)$, nor does it have any relationship to $x_i$, but rather there is some value for $f_i$ of any $x$. If so, why not just call it $f$. If otherwise, what does it mean?
What is the significance of "degree $n-1$"? Must the $x_1,...,x_n$ be ordered such that $x_i$ can be found from any $x$?
How can I learn to comprehend these questions? Should I be studying at a lower level? I was top in my calculus class at the University of Illinois in the 1980s, but I cannot even figure out what this question is asking.
As an aside, where can I learn to use the math editor on this site?
Comment: There will be different polynomial functions for each $x_i$.  $f_i$ is the polynomial function corresponding to $x_i$.  For example, if the points are $1, 2, 3$ then $f_2$ is the polynomial where $f_2(2) = 1$ and $f_2(1)=f_2(3)=0$.  Since there are three points, $n=3$ and the degree of $f_2$ is 2.
Comment: About learning to use the math editor, here's a useful link https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Useful reference: [Lagrange polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial). Note this is just an outgrowth of the fact that two points determine a line, three non-colinear points determine a parabola, etc.
Comment: There are some missing universal quantifiers that readers are assumed to fill in. See if this helps. Instead of $n$ (what's missing is saying at the beginning "for each positive integer $n$ let $\ldots"),$ use $5,$ and instead of $i$ (what's missing is saying "for each $i$ in the set $\{1, \, 2, \, \ldots, \, n\}$ find $\ldots")$ use $3.$ Then you have $5$ numbers (all different from each other) and you're supposed to find a polynomial, which we'll denote by $f_3,$ of algebraic degree $4$ such that $f_3(x_1) = 0$ and $f_3(x_2) = 0$ and $f_3(x_3) = 1$ and $f_3(x_4) = 0$ and $f_3(x_5) = 0.$
Comment: About your attempt, the function does have a relationship with  $i$. A way of writing $f_i$ in a way that makes this clearer is $$ f_i(x_j)=\left\{
\begin{array}{c}
1, {\ \ \ } i=j \\
0, {\ \ \ }i \neq j
\end{array}
\right.$$
Answer:
Preliminaries

Degree means the order of the polynomial, e.g. the function $g(x) = x^2 - 3x + 2$ is degree $2$ (the highest power of $x$). Note the function $g$ can also be written as
$$
g(x) = \underbrace{(x - 1)(x - 2)}_{\text{2 factors}}
$$
A couple of things to realize here

The number of factors is the order of the polynomial
$g(1) = 0$ and $g(2) = 0$, so at least we understand now how to get one the requirements of the problems solved, the other one is easy, it is just a matter of dividing by the right number

Now the problem

Consider an arbitrary $i$ and define the function
$$
h(x) = (x - x_1) (x - x_2) \cdots (x - x_{i-1})(x - x_{i + 1}) \cdots (x - x_n) \tag{1}
$$
This function has $n-1$ factors (note that the factor $x - x_i$ is missing). Since this function is tied to the selection of $i$ it makes sense to label it with this value, so let's rename this function $h_i$
$$
h_i(x) = (x - x_1) (x - x_2) \cdots (x - x_{i-1})(x - x_{i + 1}) \cdots (x - x_n) \tag{2}
$$
Note that this function satisfies
$$
h_i(x_i) = (x_i - x_1) (x_i - x_2) \cdots (x_i - x_{i-1})(x_i - x_{i + 1}) \cdots (x_i - x_n) \not = 0
$$
since all numbers are distinct. However if you evaluate this function at $x = x_j$ one of the terms must be $(x_j - x_j) = 0$ so the function will vanish
$$
h_i(x_j) = (x_j - x_1) (x_j - x_2) \cdots (x_j - x_{i-1})(x_j - x_{i + 1}) \cdots (x_j - x_n)  = 0 ~~~ i \not = j
$$
Now define the function
$$
f_i(x) = \frac{h_i(x)}{h_i(x_i)}
$$
and that's it

Spivak Calculus Chapter 3 Question 6


Data Mining / ML applications in hydrodynamics?

Question: I have a question about Scientific Data Mining.

Do you know successful case studies of applying Data Mining / Machine Learning techniques in hydrodynamics?
In general, does it make actually sense to try to apply DM/ML techniques to such deterministic systems as gas/fluid flows which are described by Navier-Stokes equations?

I guess that answer is 'no' in the case of very simple flows. But maybe it makes sense if we have a deal with complex data from turbulent/multiphase/... flows?

What could be the problem formulation in this area?

I will appreciate to your opinion, links to the papers and web-pages.
Answer: There has been quite a lot of work done regarding the statistical description of turbulence, trying to find correlations between certain quantities (pressure, velocity components) and the autocorrelation (in time) of these quantities.
There has been some research done on the spectral analysis of turbulence as well.
But there isn't that much insight to be gained from this statistical description of turbulence, and it has little application in terms of computing turbulent flows.
There has been some data mining work done with ships to try and find the drag coefficients of ships hulls depending on the ships parameter and speed. This results in methods for approximating a ship's drag such as the Hollenbach method. But these regressions have their limits and are only good for very rough estimations.


pip can't install new packages

Question: We have a strange bug in our project, on our server a newly added package can't be installed with the following error message:
ERROR: Could not find a version that satisfies the requirement minify-html==0.6.8 (from versions: none)
ERROR: No matching distribution found for minify-html==0.6.8

This is in a docker container and doesn't make any sense, as all other packages were installed previously and even after pruning the docker system and trying to install without pip cache. The same thing happened with a colleague with another one of our other recently added packages.
It seems that pip can't install new packages. After deleting the virtualenv on colleagues computer the same thing still happens.
This is the docker file:
FROM python:3.10.0rc2-alpine3.14
WORKDIR /src
COPY requirements.txt /src/
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN apk update \
    && apk add build-base gcc python3-dev musl-dev mariadb-connector-c-dev libffi-dev
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY src/ /src/

The complete output log is:
Skipping link: none of the wheel's tags (cp38-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/40/93/fbde0f7c68f324622932dc5f471f96941b76b70507b05c97ade605786cbb/minify_html-0.6.5-cp38-none-win_amd64.whl#sha256=420c26667b5d1a830badaf43f23812b1119929a5c695628610d1084637161981 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/35/d8/e6356a7ee9f43dc821cac3a9411d02a1fc1be3089cdf93a8b5459c88e632/minify_html-0.6.5-cp39-cp39-macosx_10_7_x86_64.whl#sha256=fe23bd8762fbf5837886af2936d63bc10c4588276945f161d755c75878cd752c (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/c5/56/28edcfeb4c16ede54358870244fa2cf067528a43733b509e31f80841332b/minify_html-0.6.5-cp39-cp39-manylinux2010_x86_64.whl#sha256=5dfe7530d7a164e12ff69fd250970466a519feb3b73e19860dfe9eda031f01fb (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/96/38/ea6e2d63ed11c1c8df16073abfdf7642f25041aa3eca60bfb3633921dd20/minify_html-0.6.5-cp39-none-win_amd64.whl#sha256=a5bd94f91fde1776e8a7f341ad15639ebd2d27a1604c6901491b19f186037993 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-cp37m-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/fb/d9/92fb1842f5d6ad1667ee6f15f20dfda770adee4f7a2f8eac165fa2ca0c21/minify_html-0.6.6-cp37-cp37m-macosx_10_7_x86_64.whl#sha256=0fc30834af647c67afbee5230cac046aafcf052333518d88645bcdd0791fb87a (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-cp38-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/d6/46/b12784385efc996682b34f97a3c18666f8f30d256f8b7f975c2b5715eee5/minify_html-0.6.6-cp38-cp38-manylinux2010_x86_64.whl#sha256=3705fd23cb8863ddd9b38e7030a07cfe211b4818efa0a3d82b4047d7afc321a7 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-cp37m-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/1c/b0/9d071ae4e8aee76d6eff7f11228b93cf1c99d8fccc420e392518da6a8475/minify_html-0.6.7-cp37-cp37m-macosx_10_7_x86_64.whl#sha256=3c42784dad3efd892b78fdb8d2b600161cf69937abeb31c7122dac460970dfec (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-cp37m-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/88/db/8bde23363a9073df07b113798341c5a5f419560843a16be1e79760704dce/minify_html-0.6.7-cp37-cp37m-manylinux2010_x86_64.whl#sha256=feeb8bd97623c82975003706c95679a1a558ac7b306a68fbde23278ce8171f3c (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/ae/da/4eef42c5c23c5def297c4b56e91f0c5f2ee7939fa045cea8116e96035102/minify_html-0.6.7-cp37-none-win_amd64.whl#sha256=dedb68a9de8d099bbbcc35aa2321457bb8ae36bed5e09fa42b1f932676fb434a (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-cp38-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/97/6e/2c048fd2348f1e38d35baf3857411adbd0a26f27b0a1b97cb0e35c109e81/minify_html-0.6.7-cp38-cp38-macosx_10_7_x86_64.whl#sha256=4ea81762ad9af1e6fae2bbc7d7286c3d85445c2afb76485d4adcae678232633e (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-cp38-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/e4/90/e96dc296eb84a3281ae5a84998a7429ea833cdb1878be32ce762925658c6/minify_html-0.6.7-cp38-cp38-manylinux2010_x86_64.whl#sha256=52a603da3735e75aad835a06e7372bc676ced3727053654cf7f62f1fd6117ac1 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/e2/08/fad195b197de8af9ec51ea73f5f8eda80a94fd76f625673e0e29a60cb5ca/minify_html-0.6.7-cp38-none-win_amd64.whl#sha256=f0b715ee807685526f71348b7b247f3b2c7c32de899b5b3dc6d7db9e7d19c6ca (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/77/43/2fb8fc0cddbc63cb1890dd7340a3747b4800bf5ddc14e52db136c3763dc5/minify_html-0.6.7-cp39-cp39-macosx_10_7_x86_64.whl#sha256=f7f965e2213c08a8c32070cda813b9f09bff2b617195a4fb3c84012b8297c49d (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/35/f8/e64ae6b24aaa7981471b78721b093a503c634ec166c09582368aff132d7e/minify_html-0.6.7-cp39-cp39-manylinux2010_x86_64.whl#sha256=9f2a886400084e2fe176a77df7729f53f676b849c01e3b0202387e6de8ad2079 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/eb/bc/34cc8876d499615a5b2abcf432c7a871372724e5052a6abc1cddbd3f8e4f/minify_html-0.6.7-cp39-none-win_amd64.whl#sha256=64e67da68a72690962ede804683317b098683f77bcfa1821990a47c87b405594 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-cp37m-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/41/19/30e86456fd868bcb4d5d668cc1858257421b0b947e4bf590cf36cbb3cf01/minify_html-0.6.8-cp37-cp37m-macosx_10_7_x86_64.whl#sha256=102951dd7bf9edb3d5a4b1cf61a2f8d1288bb78d65d271d755066eef15470deb (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-cp37m-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/d5/be/30cf2f514bb99adecff12192a0fad1a83346080ad2a3d31fff70afffb9f7/minify_html-0.6.8-cp37-cp37m-manylinux2010_x86_64.whl#sha256=d5c5e2dea59fe8126255e19440986fa4efda0c90257d4ca969cf2dcf3d71f6dd (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp37-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/d6/0f/63fe4933ffbcdf541378bde81088b7b6249c7d7ce1ef7262d9a3de248095/minify_html-0.6.8-cp37-none-win_amd64.whl#sha256=0b65ce125e067a1f09330a57d8f8258e4b129b0a3e59da280c17418e6ca93851 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-cp38-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/27/ef/d3273e182f6702ff18d9096e731ddfa50f08b4216fa6916d01cb3f993bf9/minify_html-0.6.8-cp38-cp38-macosx_10_7_x86_64.whl#sha256=7592755e8443797eb4f9318cc6210bd7d41ed9b1b3bbb8cd4f6b6d3cd70d8b49 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-cp38-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/c6/c2/69bbf7954acdddc721662f0633244ed4a338c35e69d19c1e04d797216653/minify_html-0.6.8-cp38-cp38-manylinux2010_x86_64.whl#sha256=6f71d394e0716308d2ee071dbefa0610c5b41470d84530c19ed6e24b5fb4ad37 (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp38-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/54/c0/9eb12d5d1b784e5c9abc211e09cf3450c44bb51b81250a0ba5534c2c87e8/minify_html-0.6.8-cp38-none-win_amd64.whl#sha256=bf80e98af59da582b9284da973d8500795597db2c8c77b8ca4ce5cebc3ce2d5c (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-macosx_10_7_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/cc/ea/d780084e64e0d4077ceaf1a463a8c2f21987861bde5e02a4806d59013e37/minify_html-0.6.8-cp39-cp39-macosx_10_7_x86_64.whl#sha256=17e7c0049671662e65bdfc962bb30b0274243f06d9f763c60e18ce5664a7f5df (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-cp39-manylinux2010_x86_64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/9b/d1/0c35e014c195abb93721486abf99fc0d990c9de5781f7cdfba0b41d6e1ae/minify_html-0.6.8-cp39-cp39-manylinux2010_x86_64.whl#sha256=4ae273af47975dfb3ecd15ff210663cce0fef053286aa083bfb820b7b8db8faa (from https://pypi.org/simple/minify-html/)
  Skipping link: none of the wheel's tags (cp39-none-win_amd64) are compatible (run pip debug --verbose to show compatible tags): https://files.pythonhosted.org/packages/0c/b8/a6cf5dee3994de4b38b3970b25988dc87542524aeffa54f7b1a62e391e62/minify_html-0.6.8-cp39-none-win_amd64.whl#sha256=6057732b03fa4ee995b72cf3a3cabfbd8d590a8bdc09a97c431ffa861e23a703 (from https://pypi.org/simple/minify-html/)
Skipping link: not a file: https://pypi.org/simple/minify-html/
Given no hashes to check 0 links for project 'minify-html': discarding no candidates
ERROR: Could not find a version that satisfies the requirement minify-html==0.6.8 (from versions: none)
ERROR: No matching distribution found for minify-html==0.6.8
Exception information:
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 341, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "/usr/local/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 173, in _add_to_criteria
    raise RequirementsConflicted(criterion)
pip._vendor.resolvelib.resolvers.RequirementsConflicted: Requirements conflict: SpecifierRequirement('minify-html==0.6.8')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 94, in resolve
    result = self._result = resolver.resolve(
  File "/usr/local/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 472, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "/usr/local/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 343, in resolve
    raise ResolutionImpossible(e.criterion.information)
pip._vendor.resolvelib.resolvers.ResolutionImpossible: [RequirementInformation(requirement=SpecifierRequirement('minify-html==0.6.8'), parent=None)]

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 173, in _main
    status = self.run(options, args)
  File "/usr/local/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 203, in wrapper
    return func(self, options, args)
  File "/usr/local/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 315, in run
    requirement_set = resolver.resolve(
  File "/usr/local/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 103, in resolve
    raise error from e
pip._internal.exceptions.DistributionNotFound: No matching distribution found for minify-html==0.6.8
Removed build tracker: '/tmp/pip-req-tracker-dgj5z89h'
Service 'web_dev' failed to build: The command '/bin/sh -c pip install -vvv -r requirements.txt' returned a non-zero code: 1
Makefile:7: recipe for target 'build-dev' failed
make: *** [build-dev] Error 1

Comment: Try a stable Python release. 3.10 is not released yet
Comment: Build on roman_ka's comment: you can also use `python3 -m pip`. This ensures that `pip` is installing into the correct python version (for example, 3.8.10).
Comment: @Vinay Thanks for reminding me of this. No I didn't figure this out, we switched the container image.
Comment: Try to run pip in verbose mode and add the output to your question - `pip install -vvv ...`
Comment: Maybe you need to use pip3? On some distos 'python' and 'pip' are reserved for the python2 versions and 'python3' and 'pip3' for python3?
Comment: alternatively, don't use alpine. It has weird behavior with some `pip` packages.
Comment: @DeepSpace We ran into the issue in python:3.8.3-alpine and upgraded because we thought it might help.
Comment: @roman_ka No the python container only has pip3 installed.
Comment: If you're curious, check out my preferred image for python [here](https://gist.github.com/rnag/4e845ea85c79493978944998bdb1aa4f). It uses ubuntu base image which is similarly optimized for container size.
Comment: Why not to use alpine for Python images: https://pythonspeed.com/articles/alpine-docker-python/
Comment: @kmaork Thanks for the tip! Added it to the question.
Comment: I switched our project to debian now really quick and everything works again. Still am interested in a solution, as building takes a lot longer now.
Comment: Currently the problem is that `minify-html` did not release a source distribution for version 0.6.8, and also did not release python3.10 wheels for that version. You can go back to a stable python version and show us the logs, but the problem is probably the missing source distribution and the fact that you are using alpine, which reduces the chance to find a matching wheel.
Comment: There is no [3.10](https://pypi.org/project/minify-html/0.6.8/#files) wheel. I also see similar error when I forget that I'm on an unsupported version - for ex. 3.5 which most libs don't support nowdays.
Comment: @creyD Long shot but did you figure out the root cause for this? Facing the same issue: https://stackoverflow.com/questions/76918323/pip-cannot-install-some-python-packages-due-to-missing-platform-tag-in-m1-mac
Answer: Make sure that the version of the package is still maintained or available.Or try installing the packages individually without installing using requirements.
It worked for me.
Comment: https://pypi.org/project/minify-html/ This project ist still maintained
Comment: it's the latest version, so this is wrong facts

pip can't install new packages


Many-to-many relationships with several fields in Django

Question: I have the following model:
class Trip(models.Model):
    driver = models.ForeignKey(User)
    trip_cost = models.IntegerField(blank=True, null=True)
    passenger = models.CharField(max_length=50, blank=True, null=True)
    shared_cost = models.IntegerField(default=0, blank=True, null=True)

Each Trip can have a driver alone, or a driver with several passenger. For each passenger the driver can set the percentage of the trip_cost each passenger is going to pay.
What I need is to have:

the field passenger to be listing all Users
several passenger + shared_cost for each Trip.

I guess I should use Many-to-many but I cannot make it work. Also when I try to set the passenger to models.ForeignKey(User), I get an error.
Any help or direction highly appreciated.
Answer: Use related_name when refer to same models using 2 fields.
class Trip(models.Model):
    driver = models.ForeignKey(User,on_delete=models.CASCADE, related_name='driver')
    trip_cost = models.IntegerField(blank=True, null=True)
    passenger = models.ForeignKey(User,on_delete=models.CASCADE, related_name='passenger')
    shared_cost = models.IntegerField(default=0, blank=True, null=True)


Como criar objetos dinamicamente com base em vetor? (VBA/Excel)

Question: Criei duas Labels dinamicamente com base em um vetor conforme o código abaixo, porém, no formulário só permanece a última Label criada (NewLabel1), tanto a primeira (NewLabel0) como a Label que usei de base para a criação das outras duas (Label1) não permanecem.
Preciso criar várias Labels conforme o número de itens que quero trabalhar (uma para cada produto de certa linha de cosméticos, por exemplo), por isso a necessidade de usar um vetor. Como posso resolver isso?
Dim NewLabel(1) As Object

Set NewLabel(0) = Label1 'Label1 existe no formulário
Set NewLabel(1) = Label1

With NewLabel(0)
 .Caption = "NewLabel0"
 .Top = 0
 .Left = 0
End With

With NewLabel(1)
 .Caption = "NewLabel1"
 .Top = 20
 .Left = 20
End With

...
...
...

NewLabel(0).Delete
NewLabel(1).Delete

Answer: Numa altura que precisei usei este código, verifica se consegues adaptar para ti.
Private Sub UserForm_Initialize()
i = 1
maxBoxes = 3
    For idx = 1 To maxBoxes
            Set newBox = Me.Controls.Add("Forms.TextBox.1")
            With newBox
                .Tag = "new" & .Name
                    .Left = 55 * idx
                    .Top = 10
                    .Width = 50
                    .Text = "Exemplo" & i
            End With

            Set newBox1 = Me.Controls.Add("Forms.TextBox.1", "txt-" & i)
            With newBox1
                .Tag = "new" & .Name
                    .Left = 55 * idx
                    .Top = 25
                    .Width = 50
            End With
            i = i + 1
        Next
End Sub

Answer: Funcionou muito bem! Abaixo a adaptação sugerida para o meu caso (usando vetor). Grato!
Dim i As Integer
Dim NewLabel(3) As Object

For i = 0 To 3
 Set NewLabel(i) = Me.Controls.Add("Forms.Label.1")
 With NewLabel(i)
  .Tag = "NewLabel" & i 'Usar no lugar de "Name"
  .Caption = .Tag 'Name inicia do Label2 pois existe o Label1 no formulário
  .Top = 50 * i
  .Left = 50
End With

Next i


Is this a lattice of $6$ elements?

Question: I am reading "Set Theory & General Topology" by Fuichi Uchida.
In this book, the author wrote all lattices($15$ lattices) of $6$ elements.

I wonder the following is also a lattice of $6$ elements, but the following is not in the list written by the author.
Is the following a lattice or not?
Answer: Call the two atoms (elements in the lower row) $a$ and $b$, and the two co-atoms (in the upper row) $x$ and $y$.
This is not a lattice because $a$ and $b$ do not have a supremum (join). In particular, $x$ and $y$ are both upper bounds for $a$ and $b$, but are incomparable.
Comment: Elliot G, Thank you very much!

Is this a lattice of $6$ elements?


Views aggregation summary

Question: I am creating a stats page for a football (american) team in Drupal 7 and I am having issues summarizing the data.  I have the following fields aggregated in a views table. Each is a summary of the individual players for each game.
Game 1 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc
Game 2 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc
I want to print a summary line at the bottom that totals up the season.
I have tried the views_calc module, but I would rather print the summary as one line instead of a separate line for the sum and max fields.
Any help would be greatly appreciated
Answer: Late but might be useful for someone, you can use views_summarize module.
Note: If you want to take export of your views using views_data_export module than views_summarize will create issues.
Answer: You have two options that works for Drupal 7 and Drupal +8:

https://www.drupal.org/project/views_summarize (create a summary, you can use the views default aggregation feature)
https://www.drupal.org/project/views_aggregator (aggregate data without using DB function, witch open more feature. Also create a summary)

Views aggregation summary


Help showing derivative is compact

Question: I'm struggling with proving the following theorem:
$\textit{Let }A:U\subset X\rightarrow Y\textit{ be a completely continuous operator from an open subset U of a normed}$
$\textit{space X into a Banach space Y and assume A to be Fréchet differentiable at }\psi\in U.\textit{ Then the}$
$\textit{derivative }A'_{\psi}\textit{ is compact.}$
I'm not sure how to go about this. I was thinking of trying to do it by contradiction, i.e., assuming that $A'_{\psi}$ is not compact, but I'm not really sure how to proceed from there... I guess what I am asking for is a hint or a strategy for trying to prove $A'_{\psi}$. Any help is highly appreciated.
Thanks in advance.
Answer: Let $T=A'_\psi$. By the assumption, we have for some $\delta>0$,
$$
A(\psi + h) = A(\psi) +T h + \epsilon(h),\quad \forall |h|<\delta
$$ where $\frac{\|\epsilon(h)\|}{\|h\|}\to 0$ as $\|h\|\to 0$. Without loss of generality, we may assume that $\psi =0$ and $A(\psi)=0$. Let $(x_n)\subset X$ be a sequence with $\sup_n \|x_n\|\le 1$. Our goal is to show that there exists a subsequence $n(k)$ such that $
Tx_{n(k)}
$ is convergent. By the assumption on $\epsilon(\cdot)$, for any given $\eta >0$, there exists (sufficiently large) $M\in\mathbb{N}$ such that$$\Big\|\epsilon\left(\frac{1}{M}x_n\right)\Big\|\le \eta\Big\|\frac{1}{M}x_n\Big\|$$ for all $n\ge 1$. This impiles that$$
M\Big\|\epsilon\left(\frac{1}{M}x_n\right)\Big\|\le \eta\|x_n\|\leq \eta.
$$
Now, observe that by the assumption that $A$ is completely continuous, (i.e. every bounded sequence $(u_n)$ admits a subsequence that makes $A(u_{n(k)})$ norm-convergent in $Y$) the diagonalization method gives us a subsequence $n(k)$ such that for each $j=1,2,\ldots$, the sequence
$$
A\left(\frac{1}{j}x_{n(k)}\right)
$$ converges to some $y_j\in Y$.
From the fact that$$
A\left(\frac{1}{M}x_n\right) = \frac{1}{M}Tx_n+\epsilon\left(\frac{1}{M}x_n\right),
$$ it follows
$$\begin{eqnarray}
\|Tx_{n(k)}-My_M \|&=& \Big\|MA\left(\frac{1}{M}x_{n(k)}\right)-My_M-M\epsilon\left(\frac{1}{M}x_{n(k)}\right)\Big\|\\
&\le&M\Big\|A\left(\frac{1}{M}x_{n(k)}\right)-y_M\Big\|+\eta.
\end{eqnarray}$$ By taking $k\to\infty$, we get
$$
\limsup_{k\to\infty}\|Tx_{n(k)}-My_M \|\le \eta
$$ and
$$
\limsup_{k,l\to\infty}\|Tx_{n(k)}-Tx_{n(l)} \|\le 2\eta.
$$Since $\eta>0$ was arbitrary, This proves that $Tx_{n(k)}$ is Cauchy in $Y$. Thus $Tx_{n(k)}$ is convergent, and the compactness follows as a result.
Comment: @GiuseppeNegro I'm sorry for the confusion, sir ... I've looked up precise definition of completely continuous operators, and it turns out that I used the wrong definition that $A$ sends weakly converging sequence to norm convergent sequence. Now, I edited my answer according to the correct definition that you gave. I appreciate your comment!
Comment: Very good answer, but can you please spend a couple more words on the fact that $A(x_n)\to 0$? To me, a completely continuous operator is a continuous operator that maps bounded sets to compact sets. Is it the case that this operator is weak-norm continuous? Thank you.
Comment: The previous version of the answer was also very good, I was asking out of my ignorance.
Comment: @James Note that $A$ is not assumed to be a linear map. We are dealing with a possibly non-linear, Frechet differentiable function $A:U\to Y$. But its derivative $A'$ is of course linear. About the definition: if $A$ linear (which is not suitable for our case), '$A$ sending weakly convergent sequence to norm-convergent sequence' is the definition of completely continuous function. And it is in general stronger than the compactness of $A$ which is saying 'every bounded set is mapped to a relatively  compact via $A$'.
Comment: @James However, for a non-linear map $A$, I found in https://link.springer.com/chapter/10.1007%2F978-94-015-9986-3_3
that the definition of complete continuity is more like that of compactness of a linear operator. It probably is more universally accepted definition, but I'm not sure.
The proof I gave is based on this weaker assumption, and should also be true under the alternative definition.
Comment: @Song Thank you for the help! It's funny you mention the possibility of $A$ not being a linear map, because the theorem is from a section about nonlinear operators so what you have found is very useful!

Would you mind if I ask you some questions regarding the proof you just provided?
Comment: @James I don't mind :)
Comment: @Song Cool! It's been a while since I've encountered them, but is $\epsilon(h)$ an epsilon function? Furthermore, I get that you can assume $\psi=0$, but how can you assume $A(\psi)=0$? I have more questions, but I believe they come from me not knowing the answer to these questions :)
Comment: @James Umm .. I'm not very familiar with this terminology, but $\epsilon(h)$ can be seen as a formal expression of $A(\psi+h) = A(\psi) +A'_\psi h + \mathcal{o}(h)$. ($o(h)$ is $Y$-valued.) I don't know if it is sometimes called epsilon function .. We may assume $A(\psi)=0$ by considering $B(x) = A(x) -A(\psi)$ istead of $A$. Then $B'_\psi=A'_\psi$ is not influenced while we get $B(\psi)=0$.
Comment: @Song I'm not sure I follow why the $\epsilon(h)$ is needed and how it works when you use it throughout the proof. I get the idea of how you are trying to show $A'_{\psi}$ is compact, but I just can't connect the pieces.
Comment: @James Umm ... $\epsilon(h)$ is an error happening when we approximate $$A(\psi+h) \sim A(\psi) + A'_\psi h.$$ You can recall the the formula from multivariate calculus : for differentiable $F:\mathbb{R}^m\to\mathbb{R}^n$, $$F(x+v) = F(x) + DF_x v +\epsilon(v)$$ where $\epsilon(v) = o(|v|)$. This error cannot be removed completely, but the idea is that if we "telescope"(I'm not sure this terminology is appropriate) by selecting large $M$, we can make it as small as we want.
Comment: @Song Thanks for the response! I think I need to read more into $\epsilon(h)$, cause I haven't seen nor used that before. But I think see the idea in your proof of showing $A'_{\psi}$.

Help showing derivative is compact


List of length $x$, with letters $A$ and $B$, how many ways? (Basic Combinatorics Question)

Question: I was tasked with finding the number of possible ways of writing a sequence with the following conditions:

Sequence has a length $x$, where $x$ is even
Sequence consists of the letters $A$ and $B$
The number of $A$s must equal the numbers of $B$s

For example, for $x=4$, these are all the valid sequences:
<code>AABB, ABAB, BABA, ABBA, BAAB, BBAA
</code>
I was able to quickly find out that the answer was $\binom{x}{x/2}$ just by pattern (in this case $\binom{4}{2}=6$), but am having trouble understanding why that is the solution i.e expression for phrasing the solution.
There are $x$ slots to fill, which are to be filled with two letters, but $\binom{x}{2}$ would just give me the number of lists of length two. Here I'm trying to find the number of lists of length $x$ with the same number of $A$s and $B$s.
I guess to rephrase my question, how could you translate the phrase "$x$ choose $x/2$" in the context of this problem?
Follow-up question I was thinking about: if $x$ is an odd number, how would we have to modify our expression? For example, if we must use three $A$s and two $B$s, and our $x=5$.
Answer: Let me rephrase the original question slightly: for each $n\in\Bbb N$ you want to count the sequences of $n$ $A$'s and $n$ $B$'s. (In other words, your $x$ is my $2n$.) There are $2n$ positions in such a sequence, and any $n$ of them can be filled with the $n$ $A$'s. Once you know which $n$ positions hold the $A$'s, you know that the remaining $n$ positions must hold the $B$'s, so you actually know the whole sequence. Thus, you can count the sequences by counting the ways to place $n$ $A$'s in a string of $2n$ positions. That's just the number of ways of choosing $n$ of the $2n$ positions, which is given by the binomial coefficient $\binom{2n}n$.
Comment: Thank you for the answer, very succinct and more clear. The expression nA's in a string of 2n positions helped a lot (for the odd question, I can replace 2n with 2n+1). I also just realized that 5 choose 3 = 5 choose 2 etc, very cool result and I understand it now.
Comment: @NoobCoder: Excellent! You're welcome.


psql, display column that is not in the group by clause

Question: i'm having problems with a query. I have two tables: country and city and i want to display the city with the highest population per country.
Here's the query:
select country.name as coname, city.name as ciname, max(city.population) as pop
    from city
    join country on city.countrycode=country.code
    group by country.name
    order by pop;`

Error

column "city.name" must appear in the GROUP BY clause or be used in an aggregate function.

I don't know how to solve this, i tried to make a subquery but it didn't work out.
How can i make it work?
Comment: To resolve your error, you have to add `city.name` to the `group by`. But i don't know if it will give you the correct result, you have to show the two tables definition, and some data sample
Comment: If i add city.name to the group by it will show all ciites of a country
Comment: You can easly use: [rank](http://www.postgresql.org/docs/9.4/static/tutorial-window.html) window function to get it
Answer: You can easly get it using rank function:
select * from
(
select country.name as coname,
 city.name as ciname,
 city.population,
 rank() over (partition by country.name order by city.population desc) as ranking
from
    city
join
    country
on city.countrycode=country.code
 ) A
 where ranking = 1

Comment: Thanks this worked, what does the fourth column "ranking" mean?
Comment: It is a caluclated column ( `ranking` is just an alias name), it gives the rank of the country's cities depending on its population. Please see the documentation for more detail


Perform Github action to automatically merge when I create a pull request

Question: I'm setting up Github actions for a few of my projects. The flow I'd like to achieve is:

A developer opens a new pull request
The branch is automatically merged with the main branch

My question is, is it possible to achieve this kind of workflow? If not, what are the other possible alternatives?
Answer: You could use the GitHub Action "Merge branch", for instance for any feature/xxx branch pushed (you can change the naming convention as you want).
name: Merge any release branch to uat
on:
  push:
    branches:
      - 'feature/*'
jobs:
  merge-branch:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Merge feature/xxx -> main
        uses: devmasx/merge-branch@master
        with:
          type: now
          target_branch: main
          github_token: ${{ github.token }}


Masking the values in a textbox using jQuery

Question: I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:

    <input type="text" id="txtCCN" maxlength=19 />

But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
Comment: You want to make it using other plug in?try http://digitalbush.com/projects/masked-input-plugin/
Answer: No need of any condition of length, substring and replace can be directly used on the string of any length safely.

$(document).ready(function() {

  $("#txtCCN").keyup(function(e) {
    var CCNValue = $.trim($(this).val());

    $(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
  });
});

<input type="text" id="txtCCN" maxlength=19 />

val can also be used

$(document).ready(function() {

  $("#txtCCN").keyup(function(e) {
    $(this).val(function(i, v) {
      return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
    });
  });
});

<input type="text" id="txtCCN" maxlength=19 />

The same can be done in VanillaJS

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('txtCCN').addEventListener('keyup', function() {
    var value = this.value.trim();

    this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
  }, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Answer: Try It: Its 100% workable...
$(document).ready(function () {

    $("#txtCCN").keyup(function (e) {
        var CCNValue = $(this).val();
        CCNValue = CCNValue.replace(/ /g, '');

        var CCNLength = CCNValue.length;
        var m = 1;
        var arr = CCNValue.split('');
        var ccnnewval = "";

        if (arr.length > 0) {
            for (var m = 0; m < arr.length; m++) {
                if (m == 4 || m == 8 || m == 12) {
                    ccnnewval = ccnnewval + ' ';
                }

                if (m >= 6 && m <= 11) {
                    ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
                } else {
                    ccnnewval = ccnnewval + arr[m];
                }
            }
        }

        $("#txtCCN").val(ccnnewval);
    });
});

Answer: One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)

to
if(CCNLength >= 8)

This seems to maintain the functionality while cutting out some repetition in your code.
Answer: Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.

$(function () {
    $("#cardnum").keyup(function (e) {
        var cardNo = $(this).val();
        //Add the indices where you need a space
        addSpace.call(this, [4, 9, 14], cardNo );
        //Enter any valid range to add mask character.
        addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
    });

    function addSpace(spacePoints, value) {
        for (var i = 0; i < spacePoints.length; i++) {
            var point = spacePoints[i];
            if (value.length > point && value.charAt(point) !== ' ')
                $(this).val((value.substr(0, point) + " "
                                   + value.substr(point, value.length)));
        }
    }

    function addMask(range, value) {
        $(this).val(value.substring(0, range[0])
            + value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
            + value.substring(range[1]));
    }
});

<input type="text" id="cardnum" maxlength="19" />


Proof By Induction Divisibility Question: $12\mid 3^n + 7^{n-1} + 8$

Question: Prove that $3^n + 7^{n-1} + 8$ is divisible by $12$ for all positive integers $n$.
I have proved it is true for $n=1$ and I have done the 'assume $n=k$' step, but after getting $3^{k+1} + 7^k + 8$, I am stuck. Where do I go from here?
Answer: HINT: $3^{k+1}+7^{k}+8=7(3^{k}+7^{k-1}+8)-4\cdot3^{k}-6\cdot8=7(3^{k}+7^{k-1}+8)-12(3^{k-1}+4)$
Clarification of where this comes from:
$3^{k+1}=3\cdot3^{k}=7\cdot3^{k}-4\cdot3^k$
similarly $8=7\cdot8-6\cdot8$
Comment: Much better than my expression. +1!
Comment: And since we assume that 3^k + 7^(k-1) +8, the first term is divisible by 12, and the second term is divisible by 12 due to its coefficient anyway, that answers the question. May I ask where the '4.3^k-6.8' comes from?
Comment: @Rich -- I have added a clarification of where these come from.
Answer: Hint: Show that $3^{k+1}+7^k+8 = 3\cdot\left(3^{k}+7^{k-1}+8\right)+4\cdot \left((3\cdot 2+1)^{k-1}-3-1\right)$ is divisible by $3$ and $4$.
Answer: Your next step is to relate the expression you have for $k+1$ to the expression for $k$ (no need, incidentally, to change notation from $n$ to $k$)
Since the expression involves powers, you probably need to multiply by something, and $3$ and $7$ are the obvious candidates.
So let $f(k)=3^k+7^{k-1}+8$ then we have $$f(k+1)=3^{k+1}+7^k+8=3f(k)+g(k)$$ where $g(k)$ is to be found by putting in what we know for $f(k)$. We know that $12|f(k)$ and if we can prove that $12|g(k)$ we are done.
This knocks out the power of $3$, but doesn't immediately get you the whole way. But go confidently, one step at a time.
Answer: It might be easier to split into the two cases: $\pmod 3$ and $\pmod 4$ then combine using the Chinese Remainder Theorem.
I.e., we prove:

$3^n+7^{n-1}+8 \equiv 0 \pmod 4$ for all $n \geq 1$

and

$3^n+7^{n-1}+8 \equiv 0 \pmod 3$ for all $n \geq 1$.


Running / Cumulative total in GridView column

Question: I was looking for a way to add a cumulative total column to my GridView that would show a cumulative total of one of the numeric columns in the row.  So basically:
Points | Running Total
2      | 2
1      | 3
-0.5   | 2.5
1.5    | 4

I saw some questions on cumulative totals using SQL Server and other databases, but I found nothing about strictly using GridView without changing any SQL, so I thought I would post my solution here.
Answer: The solution simply handles RowDataBound and adds the value from the given field to a member variable of the class.  Then the value in that member variable is displayed in the Running Total column, which holds a label for that purpose.
In the GridView aspx code:
<asp:GridView runat="server" ID="gvHistory" datasourceid="dsHistory" AutoGenerateColumns="false" AllowSorting="false"
    onrowdatabound="gvHistory_RowDataBound">
        <Columns>
            <asp:BoundField HeaderText="Date" DataField="Date"  SortExpression="Date" DataFormatString="{0:d}" />
            <asp:BoundField HeaderText="Points" DataField="nPoints" />
            <asp:TemplateField HeaderText="Running Total">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblRunningTotal" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView>

And here is the code for the RowDataBound handler
Protected m_runningTotal As Double = 0

Protected Sub gvHistory_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim pointsString As String = e.Row.DataItem("nPoints")
        Dim points As Double
        If Double.TryParse(pointsString, points) Then
            m_runningTotal = m_runningTotal + points

            Dim lblRunningTotal As Label = e.Row.FindControl("lblRunningTotal")
            lblRunningTotal.Text = m_runningTotal.ToString
        End If
    End If
End Sub


An interesting geometry problem about incenter and ellipses.

Question: Let $I$ be the incenter of a triangle $ABC$. A point $X$ satisfies the conditions $XA+XB=IA+IB$, $XA+XC=IA+IC$. The points $Y,Z$ are defined similarly. Show that the lines $AX,BY,CZ$ are concurrent or parallel to each other.
My friend discovered this problem when he was drawing random ellipses for fun. But we have no idea how to solve such a problem because we literally know nothing about ellipses (except its definition). So I can't post where I'm stuck here. We're just curious to see the solution, whether or not it's elementary.
We do not know what kind of tags we should add because we do not know what methods are to be used. Please edit the tagging.
Comment: Now it is - X(46705)
Comment: nice question (+1)
Comment: same opinion (+1)
Comment: it's not listed in the ETC.
Answer: For the moment, I will just sketch an approach, and develop the calculations later.
It will be clear soon that this approach has to work, so we may also leave the non-interesting computation part to a CAS. The key idea is highlighted.

Concurrency and collinearity are straightforward to check through Ceva's theorem, hence we just have to compute the trilinear coordinates of $X,Y,Z$, then check that an associated determinant vanishes;

The ellipses $\Gamma_A$ with foci at $B,C$ and $\Gamma_B$ with foci at $A,C$ are two conics meeting at two points. We may write down their
  trilinear equations and exploit Vieta's theorem to get the trilinear
  coordinates of $Z$, since the trilinear coordinates of $I$ are just
  $[1;1;1]$;

In order to write down the trilinear equation of our ellipses it is enough to recall that $$ AI^2 = bc-4rR $$ and so on. By Vieta's theorem we do not even need all the coefficients of the trilinear equation, so computations are not that painful.
Comment: Thanks for your solution. But I wonder if there is any solution without tedious calculations?
Comment: @YuxiaoXie: that is a good question. Maybe there is a tricky way for exploiting Marden's theorem, but a pure synthetic solution still eludes me. It would be interesting also to understand which points of $ABC$ lead to a concurrency as above, since the incenter is not the only one.
Comment: that would be interesting to know. But we haven't found another one yet.


Using lame as library

Question: I have already compile lame for android as static library.
How can I use lame for convert a wav file to mp3?
What I have to call? There is some tutorial of how use lame as library?
Answer: You can see this developer.samsung.com tutorial for porting or how we use LAME on Android with JNI
Porting and using LAME MP3 on Android with JNI

Using lame as library


How this categorical variable have no reference value?

Question: I'm reading the vignette for fixest
After fitting this model for trade between countries:
$E\left(Trade_{i,j,p,t}\right)=\exp\left(\gamma_{i}^{Exporter}+\gamma_{j}^{Importer}+\gamma_{p}^{Product}+\gamma_{t}^{Year}+\beta\times
\ln Distance_{ij}\right)$
where $\gamma$ are fixed effects, we extract the fixed effects and we discover that Origin has no reference value.
How is that possible?
I thought the model included the fixed effects as a one dummy variable per category.
Then you have to drop one of the variables, otherwise they would be perfectly multi-collinear.
Answer: It's safe because there's no separate "intercept" term here.
When the model contains an intercept term, dropping a level of a dummy variable is necessary, otherwise it's impossible for the model to distinguish the intercept from the dummy variable. It's kind of like collinearity, but specifically collinearity with the constant intercept term.
But in this case there's no separate intercept term in the model. So the fixed effects add up to act like a separate intercept term for each group.
Comment: Didn't realize there was no intercept. Thanks!


XDMP-PARENTLINK error on Fragment Root with xsi:noNamespaceSchemaLocation

Question: I am trying to insert a document having a element which is a fragment root:
xquery version "1.0-ml";

let $doc :=
<doc>
  <frag-root xsi:noNamespaceSchemaLocation="test.xsd"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  </frag-root>
</doc>

return xdmp:document-insert("/test.xml", $doc)

This xquery throws following error:
XDMP-PARENTLINK: xdmp:eval(...) -- Invalid parent link node doc("/test.xml")//doc

I've found this email which is kind of the same behavior but he has a schemaLocation instead of a noNamespaceSchemaLocation attribute.
In my case the element frag-root is indeed a fragment root. Might this be a similar bug ?
If i change noNamespaceSchemaLocation to schemalocation, the insertion does not fail, so my guess is the bug is fixed for schemaLocation, but not for noNamespaceSchemaLocation.
Comment: I would take this up with MarkLogic support.
Answer: I reported this error to MarkLogic and they filed a bug for it.
Will update as soon as it is fixed.


Getting all classes with Javassist using a pattern

Question: How can I get all classes using a pattern like "com.stackoverflow.*" with Javassist?
i found only 2 methods :
1/ Find a class by full name
CtClass ClassPool.getDefault().getCtClass("com.stackoverflow.user.name")

2/ Find a list of classes with fullnames :
CtClass[] ClassPool.getDefault().get(String [] arg0)

Answer: You could use some library like :
https://github.com/ronmamo/reflections
I don't think you can do that just with JRE classes.
Example from the doc :
Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeType>> subTypes =
           reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated =
           reflections.getTypesAnnotatedWith(SomeAnnotation.class);

Comment: Thanks but i want to do it with javassist library if possible
Answer: Michael Laffargue's suggestion is the best way to go. The Reflections library uses javassist under the covers. Basically, javassist provides a means of reading raw byte code from class or jar files and extracting the class meta-data from it without actually class loading it, where as Reflections provides a richer API around locating (via classpath specifications) and filtering the set of classes you're looking for.
You can do the same thing yourself using javassist only, but you will be recreating some portion of the Reflections library. You could look at Reflections' source code to see how it works, but very generally speaking, it looks like this:

Locate the classpath you want to scan. This will usually be a group of directories with a tree of class files, or a group of Jar files, but could also include more complex structures like WARs or EARs (which Reflections supports quite nicely).
Add the root of the file system where the class files live, or the JAR file reference to your ClassPool instance.
Using a file system iteration or a JarInputStream, iterate through each class file or JarEntry. You can filter out any files or entries that do not match "com/stackoverflow/**.class"
For the remaining, using the name of the file or entry, derrive the class name and load it from the javassist class pool.
Use the loaded CtClass to apply any further search criteria.
Now you have your class reference list, release the ClassPool for garbage collection.


How can I bind a specific key to different launch configurations in Eclipse?

Question: I have several launch configurations for the code I work on.
One configuration (#1) means "run the unit tests for the file in the frontmost editor (i.e. selected resource)".  I would really like to be able to always make this be bound to a key.
Another configuration (#2) means "run the server that I am working on (in the frontmost project) so I can test it interactively".
Yet another (#3) means "run some automated acceptance tests against the server".
I always want to have #1 close at hand, easy to run from a single keystroke.  Plus, I want to be able to run #2, watch it start up in a console, and when it's ready (since it's not entirely trivial to automate this) hit the key for #3.
This is possibly similar to the question for binding a key to a specific build configuration, but the answers there look very specific to builds, and as I'm using PyDev, I don't have a "build" step at all.
Also, given that I'm using PyDev, an answer in the form of a pyedit_* script would be appreciated just as much as a "native" answer for eclipse.
Comment: You don't need run configuration for #1 as there is standard one for this `CTRL+F9`. See [Keybindings quick-reference](http://pydev.org/manual_adv_keybindings.html)
Answer: Maybe Eclipse Runner plugin could make it easier for someone to handle launch configurations. It doesn't allow to assign key binding to launch configurations currently but I opened a feature request Key bindings for launch configurations
Comment: Sadly, this project doesn't seem to be actively maintained, so shortcuts may not be available in the foreseeable future. It still is a useful plugin though.
Answer: Not to a specific launch Configuration , but you can bind a key to run Last run Configuration ,
Windows->preferences->General->Keys->Run last launched external Tool

Answer: You can do the following (for #2 and #3), after having those run configurations created:
Go to Run > Run Configuration > Select the run configuration you want > Common > Display in Favorites Menu > Check Run/Debug. This will make it always appear as the first on the menu.
This will make it appear in the menu in Run > History and Run > Debug History, then, you can access it through Alt+R, T, 1 (and 2 and 3) to run your configurations or Alt+R, H, 1 (and 2 and 3) to debug.
And for #1, as Piotr Dobrogost said, you can just use Ctrl+F9 in the current editor and choose which test-cases you want to run (if you select a unit-test -- usually with Ctrl+Shift+Up or Ctrl+Shift+Down -- it'll be pre-selected for you) -- then, if you configured to always relaunch the last launch, as explained in http://www.pydev.org/manual_101_run.html, you can use Ctrl+F11 to relaunch the last launch.


Tem como pegar o valor de uma coluna autoincrement antes que seja salva no banco de dados?

Question: Eu tenho três tabelas: preco, estabelecimento e precoXestabelecimento. O id do preço é autoincrement e existe um relacionamento N:N entre as duas primeiras tabela, que é representado pela terceira tabela precoXestabelecimento.
Para que um preço seja salvo é preciso ter um estabelecimento ligado à ele, então no momento em que um preço é salvo eu preciso pegar seu ID, junto com o ID do estabelecimento e salvar na 3ª tabela. O problema é que eu não sei como pegar o ID do preço uma vez que seu valor é autoincrement e não foi salvo no banco de dados ainda.
Answer: Use algo assim (depende do seu código):
INSERT INTO precoXestabelecimento (precoID, ...)
    VALUES ((SELECT last_insert_rowid()), ...);

Coloquei no GitHub para referência futura.
O last_insert_rowid() te dará o último ID inserido. Obviamente o INSERT que o gera deve vir logo antes desse INSERT e tudo deve estar dentro de uma transação única.
Tem que tomar um cuidado para não usar em ambiente multithread. Também é importante verificar se a inserção anterior ocorreu sem problemas, se ela não ocorrer, o que será pego é um ID inserido anteriormente, que não é o que deseja. A forma de fazer isso depende de como está implementando tudo isso, da tecnologia usada. Talvez seja com um execute() que retorne um código indicado o sucesso, talvez lance uma exceção, talvez tenha que fazer uma query para conferir.
Answer: Use last_insert_rowid(). Ele retorna o último INSERT. É importante que você use essa função imediatamente após a inserção para evitar pegar o valor errado.
Sua query ficaria apenas:
SELECT last_insert_rowid()


Composition relation of R1 ∘ R2

Question:
Let $R_1$ and $R_2$ be the relations on $\{1, 2, 3, 4, 5\}$ defined by
$$R_1 = \{(1,1),(2,3),(2,4),(3,5),(5,2),(5,5)\}$$
$$R_2 = \{(1,1),(2,2),(2,3),(2,5),(4,3),(5,5)\}$$

The answer for this is below but I'm not sure how they arrived at this answer.
Answer:
$$R_2 \circ R_1 = \{(1,1),(2,3),(2,4),(2,5),(4,5),(5,5)\}$$

What I got:
$$R_2 \circ R_1 = \{(1,1),(2,3),(2,4),(2,5),(2,2),(4,5),(5,5)\}$$
Comment: I must also be doing it wrong because I got what the answer is supposed to be except I got $(2,2)$ in addition.
Answer: $$1\to1\to1$$
$$2\to2\to3$$
$$2\to2\to4$$
$$2\to3\to5$$
$$2\to5\to2$$
$$4\to3\to5$$
$$5\to5\to5$$
But, as pointed out by @Rag in the comments, there is one additional:
$$5\to5\to2$$
And, as pointed out by @MithleshUpadhyay, a second way to obtain $(2,5)$ is
$$ 2\to5\to5$$
Comment: Thanks allot! My tutor had wrote down the wrong answer by the looks of it, had this answer initially :)
Comment: is there not another relation 5 -> 2 -> 5 for R2 o R1 given R1 has (5,2) and R2 has (5,5)
Comment: @Rag Yes, you are correct. I will edit my answer. Thanks.
Comment: @JohnWaylandBales sir , isn't $2→5→5$ , also ?
Comment: @MithleshUpadhyay Yes, that is a second way to get $(2,5)$.
Answer: An alternative is through matrix representations of relations ($a_{ij}=1$ if $(i,j)$ is present in the relation, $0$ otherwise) with composition of relations replaced by matrix product (in the same order as in the composition, with boolean addition convention: $1+1=1$). This can be very useful on a computer. Here, we have :
$$\begin{pmatrix}1&0&0&0&0\\0&1&1&0&1\\0&0&0&0&0\\0&0&1&0&0\\0&0&0&0&1\end{pmatrix}
\times \begin{pmatrix}1&0&0&0&0\\0&0&1&1&0\\0&0&0&0&1\\0&0&0&0&0\\0&1&0&0&1\end{pmatrix}=\begin{pmatrix}1&0&0&0&0\\0&1&1&1&1\\0&0&0&0&0\\0&0&0&0&1\\0&1&0&0&1\end{pmatrix}$$
Comment: Somehow we both missed the $(5,2)$ as pointed out by @Rag in the comment above. There should be a $1$ in row $5$ column $2$ in your product.
Comment: @John Wayland Bales Corrected. Thanks !
Answer: Here is how to think about RoS: (not a definition, just a way to think about it.) You have a subway system with stations {1,2,3,4,5}. It is served by the R-line and the S-line. (This is much simpler than NYC, where we old-timers can't find the BMT any more.) But the rules of travel are bit confining. You must first take the S line one stop, transfer to the R-line and go one stop. If you can start at a and get to b under these rules of travel, (a,b) belongs to RoS. Otherwise it doesn't.
Take R={(1,1),(2,2), (2,4),(2,5),(4,3), (5,5)} and S to be your first relation. Let's start at 2. You could take the S-train from 2 to 3, but unfortunately 3 is not served by the R-line, and the rules are that you must take the R-line one stop. But there is still hope, you can take the S-line from 2 to 4 and then take the R-line from 4 to 3. Thus, the one pair belonging to RoS is (2,3).
The answer to the obvious question, why is RoS defined backwards to mean you must first take the R-line and then take the S-line, is that the crazy analysts got there first and defined the composition of two functions fog, to mean first "do" g and then "do" f.

Composition relation of R1 ∘ R2


Class getting parameter from Game.cs

Question: I am writing a short program. What I need is that I want to set "correct" parameter in Game.cs, and in my advTry.cs, I want to use this "correct" parameter to determine the output.  with my class advTry.cs like:
public bool correct { get; set; }

if (correct)
{
    solveButton = new MenuButton(contentManager.Load<Texture2D>("solve"),
      buttonCenter, GameState.AnswerNo);
   Console.WriteLine("OK");
}
else
{
    solveButton2 = new MenuButton(contentManager.Load<Texture2D>("solve"),
                  buttonCenter, GameState.AnswerYes);
    Console.WriteLine("Not OK");
}

While in my GAME.cs, I define correct as:
if (messageString == "18")
{
    Console.WriteLine("Main OK");
    advTry.correct = true;
}
else
{
    advTry.correct = false;
    Console.WriteLine("Main not OK");
}

I use the Console.WriteLine to check the passing of boolean parameter "correct". While the result is originally "Not OK", then when I start to input "18", it gives out"Main not OK" first, then "Main OK" (easy to understand, because input"1" then "8").
However, the biggest problem is "OK" never comes out, the state "GameState.AnswerNo" can't be fulfilled, Why is that please? How to fix it please?
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Comment: Thanks for reminding. Will do it in the future.
Answer: Your question is not at all clear. You haven't given any idea of the structure of the code apart from those two conditionals. It's just impossible to answer right now. However, my best guess from what you've written here is that you've set the value of "correct" to true in your advTry class, but you haven't run the code inside that class to output OK to the console. That code won't run automatically just because you set the value of "correct". You need to do something like this in advTry.cs:
private bool _correct;
public bool correct
{
    get { return _correct; }
    set
    {
        _correct = value;
        output();
    }
}
private void output
{
    if (_correct)
    {
       //output "OK"
    }
    else
    {
       //output "Not OK"
    }
}

Comment: Or even use a SetCorrect(bool) method, as setters should do nothing beyond set variables (generally used to set multiple things at once, otherwise a setter wouldn't be needed at all).
Comment: Hello all. Thanks for all your reply. Sorry about the confusion. What I need is that I want to set "correct" parameter in Game.cs, and in my advTry.cs, I want to use this "correct" parameter to determine the output. May I ask that why many people use _correct by putting _ in the front please?
Comment: The underscore is a just a convention that is used to indicate that the variable is private. So you have a public property 'correct' with a getter, and a setter which sets the value of the private variable _correct. Did you try the code? If you change advTry.cs as suggested and leave Game.cs as it is, you should see the output you're looking for.

Class getting parameter from Game.cs


MobileFirst Java Adapter backend server URL

Question: Is it possible to load backend server URL from properties file in MobileFirst 7.1 Java Adapter, without reading properties every time? What will happen if someone changes the URL while the adapter is already deployed?
The target is to build adapter for for all environments(DEV, TEST, PROD etc.) and keep backend URLs outside .adapter file.
Comment: You need to mention your MobileFirst Platform version...
Comment: @IdanAdar MobileFirst platform 7.1
Answer: You cannot keep the URL the adapter is meant to connect to outside of the adapter implementation.
In Java adapters you define and create the connection in Java code.
Comment: I am confused about life cycle of adapter, when will be the init method of AdapterApplication class is called? Is it possible to load properties file from init and then use it in resource class? Pardon my knowledge of MobileFirst Java adapters/JAX-RS implementation
Comment: The init method is called once the adapter is deployed (or if already deployed and you restart the server). In theory you could possibly load a file to memory and read its contents and then run some backend logic to decide which address to use, but why? Just hard-code all of them, why mess with loading external files...
Comment: The project deployment team insists that the configuration part be in properties file instead of hard coding, so they can reuse .adapter file without re-building the code by just changing the properties file. Thanks for the answer @Idan.


cannot find -lmysqlclient collect2: ld returned 1 exit status

Question: Invoking: Cygwin C++ Linker
g++ -nostartfiles -L"E:\cygwin\lib\mysql\lib" -lmysqlclient -lz -shared -o"final.so"  ./src/one.o ./src/two.o ./src/three.o ./src/four.o ./src/five.o
/usr/lib/gcc/i686-pc-cygwin/4.3.4/../../../../i686-pc-cygwin/bin/ld: cannot find -lmysqlclient
collect2: ld returned 1 exit status
Comment: this is not google, and yours is not a question but an error message
Comment: error msg is for reference ... I dont know whats the problem here..why this error is coming
Answer: The error message states that the mysqlclient library cannot be found. Since you're using Cygwin the issue might be that you're using a Windows-style path -L"E:\cygwin\lib\mysql\lib". I believe the GNU C++ Linker expects a Unix-style path, such as -L"/lib/mysql/lib".
Without more specific information it's hard to say though.
Comment: @ERIK Some more details >
libmysqlclient.so is present under E:\cygwin\lib\mysql\lib n somehow that is not getting linked properly.
I dont think its path prb coz compilation phase excuted properly with the same path.
can u plz tell how to do it
Comment: Under Project->properties->C++ Build->settings->Cygwin c++ Linker->Libraries

Added following

Libraries (-l)
mysqlclient.so

Library search path (-L)
E:\cygwin\lib\mysql\lib
Comment: I don't think g++ tries to use the -L paths during compile phase, so you won't notice the problem there.
Comment: Even after path changes ----> Building target: final.so Invoking: Cygwin C++ Linker g++ -o"final.so" ./src/one.o ./src/two.o ./src/three.o ./src/four.o ./src/five.o -nostartfiles -L/cygdrive/e/cygwin/usr/local/lib -lmysqlclient -lz -shared /usr/lib/gcc/i686-pc-cygwin/4.3.4/../../../../i686-pc-cygwin/bin/ld: cannot find -lmysqlclient collect2: ld returned 1 exit status make: * [final.so] Error 1


How to add support for custom android compiler in cmake?

Question: Am using a Customized Android Compiler. That compiles cpp code and generates the .so file.  From Command Prompt it is working fine but when I try to Build using Cmake then Cmake always picks wither Clang or GNU Compiler for Android compilation even after setting the compiler name in toolchain file.
My Analysis and Findings are as below.
I am working towards creating a toolchain file for an ANDROID compiler
I understand that the flow in CMAKE, when CMAKE_SYSTEM_NAME is specified in Android is different when compared to specifying CMAKE_SYSTEM_NAME as IOS or LINUX
Please validate my current understanding when a toolchain file or command-line option sets CMAKE_SYSTEM_NAME to "Android"
CMakeDetermineSystem.cmake loads this file:   Android-Determine.cmake
Next is the platform-specific initialization step:   CMakeSystemSpecificInitialize.cmake which loads Android-Initialize.cmake to select the sysroot.
A "determine" step also runs for each language when it is first enabled in a new build tree:
Android-Determine-C.cmake
Android-Determine-CXX.cmake

The language files go here:
Determine-Compiler.cmake
Determine-Compiler-NDK.cmake

The latter file is where we parse a bunch of information from the NDK.
The results persist in CMakeFiles/$v/CMake${lang}Compiler.cmake for future runs.
Next is the language-specific initialization step. For  Example – in case {lang} is C :     CMakeCInformation.cmake
That loads one of these:
Android-GNU-C.cmake
Android-Clang-C.cmake

which loads one of these:
Android-GNU.cmake
Android-Clang.cmake

Determine-Compiler-NDK.cmake is where cmake looks for versions of clang or gcc or llvm toolchains and sets the appropriate compiler.
Our Requirement and Problem statement
When I tried manually setting a c and cxx compiler from a toolchain file, cmake would not allow me to point to my custom compilers. Ideally, I would want my toolchain file to tell cmake the libraries to include/link and the compilers to use. But once System has been determined as android, cmake goes through the above sequence of events and expects toolchains to be specified for either clang, gcc or llvm compilers.
I believe I would probably need to make changes in the following files to accommodate cmake to use custom compilers.
Determine-Compiler-NDK.cmake  - We would need to add support for an "NewCompiler Toolchain" which would contain android libraries and compilers.
New Android-{NewCompiler}-C.cmake, Android-{ NewCompiler }-CXX.cmake, Android-{ NewCompiler }.cmake and another appropriate toolchain file to set target architecture and compiler flags.
Any comments on the process or how to go about this would be appreciated.
Answer: Toolchain files can set the path to compilers on the host, but
target-platform-wide information like the set of libraries and
include directories to use typically belongs in platform information
modules (e.g. Platform/Android-... and the like).
Since your compiler doesn't come with the NDK, perhaps you could look
at using the standalone toolchain mode.
Comment: After some research i found the same thing.


Call a JS function when a views ajax request completes?

Question: I want to run some JS stuff on the exposed filters of a view which uses ajax. How can I know every time the view is reloaded by ajax, and run some JS?
Answer: You can find ahah/ajax success by this function.
Not a Drupal Way.
<code>$(document).ready( function () {
 $('body').bind('ajaxSuccess', function(data, status, xhr) {
  alert('Ajax Success');
 });
});
</code>
This function will get invoked on every ajax success.
Answer: Drupal Way
Create own module
Implement hook_views_ajax_data_alter() in it
For ex. if your module has name 'mymodule', code will be
<code>function mymodule_views_ajax_data_alter(&$commands, $view)
{
    $commands[] = array('command' => 'customCommand');
}
</code>
and add your JS stuff to this command
<code>(function ($) {
  if (Drupal.ajax) {
    Drupal.ajax.prototype.commands.customCommand = function (ajax, response, status) {
//JS stuff
console.log(response);
    };
  }

}) (jQuery);
</code>