Replacing items in JSON using Javascript

Question: I am new to javascript. I am trying to replace a JSON elements with a set values passed from another function. When i parse the object I am getting an error message  unexpected token at pos 0.
Thank you.
var defaultMessage = {
    "MTI": "1101",
    dataElements: {
        "DE01": "101",
        "DE02": "201",
        "DE03": "301",
        "DE04": "401",
        "DE05": "501",
        "DE06": "601",
        "DE07": "701"
    }
}

replaceDefaultElements: (testElements) => {
    console.info(testElements)
    console.info(defaultMessage);
    var messageElements = JSON.parse(defaultMessage.dataElements);
    Object.keys(testElements).forEach(function (key) {
        messageElements[key] = testElements[key];
    });
    return messageElements;
}

//Calling from JEST test function:

test('Should be ', () => {
    expect(functions.replaceDefaultElements('{"MTI":"1101",{"DE01":"XXX"}}')).toEqual({
        "MTI": "1101",
        dataElements: {
            "DE01": "XXX",
            "DE02": "201",
            "DE03": "301",
            "DE04": "401",
            "DE05": "501",
            "DE06": "601",
            "DE07": "701"
        }
    })

Answer:
When i parse the object I am getting an error message unexpected token at pos 0.

defaultMessage.dataElements is a JavaScript object. It isn't JSON.
Don't use JSON.parse there.
testElements, on the other hand, is JSON.
Answer: Replace JSON.parse(defaultMessage.dataElements) with  defaultMessage.dataElements
Replace Object.keys(testElements) with Object.keys(JSON.parse(testElements))
Hope it will work


Finding an angle involving two triangles inscribed in a circle

Question:
Since $\overline{OA} \parallel \overline{BC}$, we have that
So I know that $\angle COA=\angle BCO=40^\circ$. I'm trying to figure out how to make use of the facts that these triangles are inscribed in circles... help appreciated!
Comment: Use the fact that $\angle COA \cong 2 \angle CBA$.
Comment: $\angle{ABC}=\dfrac12\angle{COA}=20^{\circ}$ Then $\angle{ODA}=120^{\circ}$
Answer: We have
$$\angle OAD=\angle{ABC}=\dfrac12\angle{AOC}=20^{\circ}$$
because of Angle at the Centre Is Twice the Angle at the Circumference.
So, in $\Delta ODA$, we have
$$\angle AOC=40^\circ\\\angle OAD=20^\circ$$
So,
$$\angle ODA=180^\circ-40^\circ-20^\circ=120^\circ$$
Answer: $\angle O =\angle OCB = 40^°$ (alternate interior angles, $OA \parallel BC$)
$\angle B =\frac{\angle O}{2} = 20^°$ ($\angle$ of center=2$\angle$ circumference subtended same segment)
$\angle ODA=120^°$(sum of $\angle$ 's in a $\triangle$)


Irreducible components of an algebraic set

Question: I am totally stack in how to do this exercise :
How can I find the irreducible components of $ V(X^2 - XY - X^2 Y + X^3) $ in $A^2$(R)?
Given an algebraic set, what is the consideration I have to make to find them? I know the definitions of components and irreducible components but these don't help in to solve this kind of exercise in the end.
Can anyone suggest a good reference book also?
Thanks
Answer: Write your polynomial as a product of irreducible polynomials. The vanishing loci of these irreducible polynomials are then the irreducible components of your variety.
Answer: $V(f)$, the zero set of a polynomial $f \in R[x,y]$, is given as set of points such that $f(x,y) = 0$. If this polynomial is reducible, i.e. $f=gh$, the points $(x_0, y_0)$ in $V(f)$ are such that $g(x_0, y_0) = 0$ or   $h(x_0, y_0) = 0$. This means that $V(f)$ is a union of $V(g)$ and $V(h)$.
In your case, $f(x,y)=x^2-xy-x^2y+x^3=x(x+1)(x-y)$. Zeros of this polynomial are all the points for which any factor of $f$ is zero. Thus we see that $V(f) = V(x) \cup V(x+1) \cup V(x-y)$. Geometrically, we can imagine this in $\mathbb{R}^2$ as a union of three lines, the y-axis, diagonal line through the origin passing through the first quadrant and parallel to the y axis passing through the point $(-1,0)$.
As for the books, very nice introductory book about algebraic curves which is freely available is by Fulton: http://www.math.lsa.umich.edu/~wfulton/CurveBook.pdf.
Quick google search also turned up these notes which seem to contain some nice examples and theorems ilustrating what is going on: http://csclub.uwaterloo.ca/~mlbaker/get.php?name=LW-1135-pmath764notes.pdf.
Comment: Would this change if we consider $A^2(C)$? I don't think we have used anywhere the fact that we are in the field of real numbers
Comment: You are right, this will work in C as well. Actually I think this will work in any field (not just characteristic 0).


Equating the two equations of Ridge Regression

Question: I'm studying Ridge Regression now and I'm having a bit of trouble understanding how to relate the two equations that pop up when I read about it. There is the coefficient estimate:
$$\hat{\beta} = (X^TX + \lambda I)^{-1}X^TY$$
and then there is simply writing it out as Linear Regression such that $\beta^T\beta < t$.
My specific question is how do you relate $\lambda$ and $t$? As far as I know the equation with lamda is used for actual computation, while simply imposing a restriction on linear regression helps with conceptualizing the method, and relates to the graph given in page 271 of this journal article: http://statweb.stanford.edu/~tibs/lasso/lasso.pdf.
Any help/explanations would be very helpful, thanks!
Answer: The two equations are the same (I delete the $1/2$ though - it is not in Tibshirani either):
Write out the second expression:
$$Y^TY-2\beta^TX^TY+\beta^TX^TX\beta+\lambda\beta^T\beta$$
Finding the $\beta$ that minimizes this expression gives us the $\text{argmin}$, so let us set the first derivative to zero:
$$-2X^TY+2X^TX\beta+2\lambda\beta\stackrel{!}{=}0$$
Solving for $\beta$ yields the ridge estimator.
As for your interpretation, I would agree, yes.
Comment: So it appears I'm a little more tired than I thought. I edited my question, but what I really meant was BOTH those equations and simply writing linear regression such that $\beta^T\beta > t$
Comment: I see. You also mean $\beta^T\beta<t$, not more. Afaik, there is a 1-1 relationship between $\lambda$ and $t$ (there is for the LASSO, so I presume the same to be true for ridge), which is however typically always not easy to make explicit.
Comment: Yes that's correct, I'm a mess! Thanks for the reply, do you have a suggestion of a source I can read that talks about the 1-1 relationship? Most articles I have found are pretty advance and gloss it over, and most don't even mention the $t$ restriction. If not I can keep searching, I'm sure I'll find something.
Comment: The books by Tibshirani (and others) himself are my favorites, see [here](http://www-bcf.usc.edu/~gareth/ISL/) and [here](http://statweb.stanford.edu/~tibs/ElemStatLearn/).
Answer: The first equation is the solution of an unconstrained optimisation problem that you get from constructing the Lagrangian of the constrained optimisation problem.  See my answer to this related question.  There isn't usually a simple relationship between $C$ and $t$, but there is a mapping between the two.  It is possible to fir the model using either the unconstrained problem or the constrained one, but usually unconstrained optimisation problems are easier to solve ones with constraints, so the "normal" equations are the way they are normally implemented.
Answer: I THINK its as a result of the Karush-Kuhn-Tucker conditions Karush-Kuhn-Tucker conditions which generalise the lagrange multiplier case. and yes there is no explicit relation between lambda and t.
see in particular the Value function section ( which I have modified hopefully correctly):

Given this definition, the coefficient, $\lambda$, is the rate at which the value function increases as $t$ increases.


Funçao match jQuery, como obter os matches

Question: Como eu posso obter os matches usando a funçao match?
console.log($("COMMANDO database -> run []").match(/COMMAND\S*(.*)\S*->\S*(.*)/g)[0]);

Em teoria eu teria de obter database, run e o que esta dentro do []
Answer: O método Match não é do JQuery, é nativo da linguagem Javascript, modifiquei sua expressão regular para pegar o contéudo dentro dos colchetes.

var regex = /\S*(.*)\S*->\S*(.*)\[(.*?)\]/i;
var input = "COMMANDO database -> run [conteúdo]";
if(regex.test(input)) {
  var matches = input.match(regex);
  for(i = 0; i < matches.length; i++){
        alert(matches[i]);
    }
} else {
  alert("Nenhuma combinação encontrada.");
}
Comment: +1 para testar com `.test` antes! Eu sempre fazia o `.match` e verificava se o resultado não era `null`! Assim é bem mais elegante!
Comment: Para deixar a resposta mais completa eu apenas incluiria o [link para a documentação de `.match` na MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/match)
Answer: Não existe função match no biblioteca jQuery. Talvez queira usar a função String.match nativa do javascript. Ela funciona assim:
"COMMANDO database -> run []".match(/COMMAND\S*(.*)\S*->\S*(.*)/)

Repare que foi preciso remover a flag g da regex para capturar grupos. Note também que a string contém COMMANDO enquanto que a regex procura COMMAND. Nesse caso, não há match.


Custom jQuery sorting on HTML navigation. How to order elements based on title?

Question: I have a custom navigation built that I would like to apply a specific sort order based on their title. How would I go about sorting this menu so that instead of:
Site 1, Site 2, Site 3, Site 4
We get Site 3, Site 2, Site 4, Site 1

        Site 1[+]

Home

Feedback

Offices Maps & Meeting Rooms

System Alerts

        Site 2[+]

Page1

Page2

Page3

        Site 3[+]

Page1

Page2

Page3

        Site 4[+]

Page1

Page2

Page3

fiddle:
http://jsfiddle.net/Colbs/UyDLL/
Comment: Why do it client side? You're using asp.net, why not do it server side?
Answer: Here's one approach that requires an array based on the text. It removes all the elements and appends them in order defined by array
var navOrder=['Site 3','Site 2','Site 4','Site 1'];
var $nav=$('.navSites');
/* detach the list items */
var $items=$nav.children().detach();
/* loop over navOrder array */
$.each(navOrder, function(_, txt){
    $items.filter(function(){
        return $(this).children('a').text() == txt;
    }).appendTo($nav);/* append list item that matches array element value*/
});

DEMO
Comment: Perfect! jQuery is so beautiful


can't connect with mysql on company network

Question: I have built an application in vb.net that needs to connect to a mysql database. This all works fine from my own network and several other home networks.
But if i want to use the application on my company's network, i get the error

Unable to connect to any of the specified MySQL hosts

I thought that this is caused by the firewall of the network.
But I used the "automatic update" option and I publish the application on a online server. This works fine on my company's network.
So the application can download the updates from the network, but can't connect to the mysql server. What could cause this issue?
Comment: You companies network is most likely set up differently than your home network. Talk with your company and get information from them.
Answer: The most common situation that would cause this is selective egress filtering. Specifically, the firewall is most likely only allowing HTTP/HTTPS port connections out.
Try changing mysql to listen on 443, then try again using 443 instead. The firewall may allow the traffic since it is using 443 like web traffic instead of 3306 (mysql default).
Comment: When i use this connectionstring: Dim myConnectionString As String = "Server=(....);Port=443;Database=(...);Uid=(....);Pwd=(...);" I can't connect at home. Isn't this the right connectionstring?
Comment: I've talked to the IT department and it was indeed the TCP port. Thanks!
Answer: If you're testing it locally, its because you need to whitelist the IP that you're CURRENTLY on.
On live sites, the IP of the server doesn't change. So you use that IP with the correct permissions to allow mysql to work.
So basically, figure out where your allowed IP's to talk to the DB are, find your local ip, and modify. Incorrect ports can be a problem also
Comment: I've used a "%" to allow all IP-addresses. This works for all "home"-networks i've been testing on.
Comment: not a good idea! you dont want anyone to be able to modify or view your DB. If the IP is indeed whitelisted, then your firewall can be making the connections timeout
Comment: The users of the application need to fill the database. They need to do this on different locations, so I have to do it this way, right?
Comment: Nope! If your users are viewing it on a website then the IP of it wont change. The DB will talk to the page using the servers IP not your connection IP.


survival analysis unobserved customers

Question: I have got an extensive dataset of customers in a certain industry. I will build a survival model of churn on the customers. Some customers data back to 1990 and are still, as of 2020, customers in the dataset. The dataset was constructed in 2012. I have data on the date customers signed their contract, but I have only the data on those who are still in the dataset after 2012.
Hence my problem: The dataset doesn't contain data on customers who churned before 2012. This means, as I see it, that there is a bias in the data set for customers who stay in for a long time.
Questions:

Am I correct that this is a bias for the long-term customer?
Is this called left-censoring/left-truncation/missing?
Is there a way to deal with this bias? Some papers, for example.
If there isn't an effect, can you covince me there isn't?

My question is similar (i.e. conceptually the same) as Kaplan-Meier estimates with missing data on non-survivors.
Comment: Ah ah. I agree with @StatsPlease. Your edits made your issue clear.
Comment: 1) I don't necessarily think it'd bias your model. They're a part of population. 2) Left - censoring occurs when a subject experiences your event of interest before the observation window starts. For that reason, observations prior to 2012 would be left - censored. 3) Refer to 1).
Comment: @ralph Isn't this a sort of survivorship bias? The dataset will contain only long-term customers who *didn't* churn. You are missing a whole population of customers from 1990 to 2012 who left the population due to censoring or some event?
Comment: Exactly, I miss the whole population of customers between 1990 and 2012 who churned in that time.
Comment: You don't even know how many customers ever signed up or cannot infer it from other records? If you know that, you could see if there would be reasonable ways of imputing data if rough estimates are OK. If you have not such data, I see no solution but removing all costumers that signed up before the dataset was constructed, and only estimate dropouts from then.
Answer: Yes, you are correct that is survivor-ship bias in this data. This data is left truncated data because you only are observing customers who have made it to at least 2012, and hence you need to adjust for this.
Check out this paper
https://www.tandfonline.com/doi/abs/10.1080/10485250500393222
or try to get this paper:
A Note on the Product-Limit Estimator Under Right Censoring and Left Truncation
Wei-Yann Tsai, Nicholas P. Jewell and Mei-Cheng Wang, Biometrika
http://digitool.library.mcgill.ca/webclient/StreamGate?folder_id=0&dvs=1580503242374~565
Good luck!
Comment: This is helpful, but it borders on a link-only answer. Can you post full citations & summaries of these papers?
Comment: Yes, I can do this. I was just trying to answer the question about whether or not it was left truncation, and then also provide links as requested. I need to read these closer to succinctly summarize. Thanks for the feedback!

survival analysis unobserved customers


Função .click sendo executada duas vezes

Question: tenho uma função $(".btn-comprar").click() que, quando clico, ela é executada duas vezes. Não consigo resolver o problema. Já pesquisei o código todo e ela não tem duplicidade. O que pode ser?
Função:

$(".btn-comprar").click(function () {
        var produto = {};
        produto.nome = $(this).parent().find('h3').text();
        produto.valor = $(this).parent().find('.preco').text();
        produto.quantidade = $(this).parent().find('input').val();
        produto.id = $(this).parent().find('input').attr('data-button');
        if (sessionStorage) {
            var cart = JSON.parse(sessionStorage.getItem('cart'));
            cart.produtos.push(produto);
            $(".numCart").text(cart.produtos.length);
            sessionStorage.setItem('cart', JSON.stringify(cart));
            alert('Produto adicionado ao carrinho.');
        }
    });

Comprar
Comment: Tente colocar o e.preventDefault(); antes do var produto = {};
Comment: Verifique se a classe .btn-comprar esta sendo usada em outros elementos.
Comment: Existem outros elementos que utilizam a classe, pois se trata de um botão de compra, comum a todos produtos da página. Mas só é executada quando o usuário dá o click.
Answer: Esse tipo de comportamento geralmente ocorre por duas razões:
1. Evento se aplica a dois elementos na mesma hierarquia
Problema: você adicionou um manipulador de evento que se aplica a mais de um elemento, sendo que um deles é descendente do outro. Ao clicar, o navegador propaga o evento para os dois elementos e assim o manipulador executa duas vezes.
Exemplo:

<button class="botao">Ação</button>

$('.botao').click(...)

Solução:

Use o preventDefault() dentro da função para que o evento não seja propagado para o segundo elemento.
Garante que o manipulador só captura o evento para um dos elementos

2. O código que adiciona o evento executa duas vezes
Problema: um código adiciona uma função para manipular um evento, mas por alguma razão esse código executa duas vezes. Isso pode ocorrer por vários motivos.
Um deles ocorre quando se adiciona um manipulador de eventos genérico após criar um elemento dinamicamente. Exemplo:
$('<button class="botao">').appendTo(body);
$('.botao').click(...)

Na primeira vez que o código executa, o manipulador do evento clique é corretamente adicionado. Mas, da segunda vez, os botões já existentes vão receber um manipulador adicional.
Solução:

Adicione um manipulador específico, apenas para o novo elemento criado.
Adicione uma única vez um manipulador geral usando on(). Exemplo:
$('.local-com-botoes').on('click', '.botao', ...);

No exemplo acima, todos os botões com a classe botao adicionados dinamicamente a um elemento com a classe local-com-botoes irão disparar o manipulador de eventos.
Outras razões para um script executar duas vezes são mais óbvias:

Incluir o script duas vezes na página
Chamar a função que cria o evento mais de uma vez de lugares diferentes

Dica: coloque um log na função que adiciona o manipulador de eventos e verifique se ele executa apenas uma vez.


Boolean algebra simplification (DNF)

Question: I am trying to simplify the following expression:
$(p \wedge r) \vee (\neg p \wedge q) \vee (\neg p \wedge \neg q \wedge r)$
I know that I should get $r \vee (\neg p \wedge q)$ but I am not sure how to explain.
Could you please help ?
Thanks a lot !
Comment: [Here's a MathJax tutorial](https://math.meta.stackexchange.com/q/5020/104041) :)
Comment: Have you tried making a diagram (Caroll, Venn, Karnaugh ...) ? or a truth table ?
Comment: I would like to use the different law to simplify.
Comment: Hint: expand the part: $(¬p∧q)$ as $(¬p∧q ∧ \top) \equiv (¬p∧q)∧ (r \lor ¬r) \equiv (¬p∧q∧r) \lor (¬p∧q∧¬r)$ by Distributivity.
Answer: The ideal way is to use methods such as Karnaugh map to minimize your Boolean function. It can get problematic as the number of variables get larger if you decide to use algebra techniques.
I can propose a method which is very intuitive. We will use the 'Resolution method' (an alternative to Quine–McCluskey algorithm), then we will use Boolean algebra to minimize the expression.
For DNF, we will use this rule:
$$(x \wedge a) \vee (\neg x \wedge b) \iff (x \wedge a) \vee (\neg x \wedge b) \vee (a \wedge b)$$
where $(a \wedge b)$ is your resolvent.

We shall apply the layer algorithm, and find our resolvents.
$$
\begin{align}
(p \wedge r) \vee (\neg p \wedge q) \vee (\neg p \wedge \neg q \wedge r) & \space \space \space \text{(Layer 0)} \\
\vee (q \wedge r) \vee (\neg q \wedge r) \vee (\neg p \wedge r) & \space \space \space \text{(Layer 1)}  \\
\end{align}
$$

We shall minimize the expression using Boolean algebra.
$$
\begin{align}
& (p \wedge r) \vee (\neg p \wedge q) \vee (\neg p \wedge \neg q \wedge r) \vee (q \wedge r) \vee (\neg q \wedge r) \vee (\neg p \wedge r) & \space \space \space \text{} \\
\iff \space & (p \wedge r) \vee (\neg p \wedge q)  \vee (q \wedge r) \vee (\neg q \wedge r) \vee (\neg p \wedge r) \space \space \space \text{[Absorption]} \\
\iff \space & r \vee (\neg p \wedge q) \vee r \space \space \space \text{[Distributivity, Complement]} \\
\iff \space & r \vee (\neg p \wedge q) \\
\end{align}
$$

Hope it helps.
Comment: Thanks a lot Eddy ! However, I didn't get how you were applying absorbtion law between first and second line.
Comment: Hi Martin. I shall zoom into the terms on the first and second line:
$$ (p \wedge r) \vee ... \vee (\neg p \wedge \neg q \wedge r) \vee ... \vee (\neg q \wedge r)$$
$$ \iff  ... \vee (\neg q \wedge r) \vee ...$$

So by rule of absorption (or by factorizing the terms):
$$ (\neg p \wedge \neg q \wedge r) \vee (\neg q \wedge r) = (\neg p \vee t) \wedge (\neg q \wedge r) = (t) \wedge (\neg q \wedge r) = (\neg q \wedge r)$$
Take note, $t$ means true.

Hope it clarifies. Thank you.
(PS: Please do upvote my original post if it solves your problem.)
Comment: Much clearer now Eddy. Thank you !

I have 2 more questions for tomorrow.
Comment: Now working on CNF, and I am having the following:

$ \lnot(p \to q) \lor (r \to p) \equiv \lnot ( \lnot p \lor q) \lor (\lnot r \lor p)
\equiv (p \land \lnot q) \lor (\lnot r \lor p) \equiv (p \lor \lnot r)$

I didn't get how to go from $(p \land \lnot q) \lor (\lnot r \lor p) \equiv (p \lor \lnot r) $

Lastly, using conditional statement, how to go from $ (\lnot p \to \lnot q) \equiv (p \lor \lnot q) $
Comment: It's the same thing. You might just need to rearrange and/or factorize your terms to get your answer.

Hint for $(1):$
$$
\begin{align}
 & (p \wedge \neg q) \vee  (\neg r \vee p) \\
\iff & (p \wedge \neg q) \vee  \neg r \vee p \\
\iff & (p \wedge \neg q) \vee p \vee \neg r  \\
\iff & ...  \\
\end{align}
$$

I'm sure you know how to carry on from here.

Hint for $(2):$ Just apply the conditional rule directly.

Boolean algebra simplification (DNF)


Area of triangle formed by a pair of tangents to a circle, from an external point, with the chord of contact

Question:
If the length of tangent drawn from an external point P to the circle of radius $r$ is $l$ , then prove that area of triangle form by pair of tangent and its chord of contact is $\displaystyle\frac{rl^3}{r^2+l^2}$

I have the solution of this which states: External point P, centre C and one point of contact is A. Let $\theta$ is the angle formed at P and $\angle APC$.
It is given that area =$\frac{1}{2} 2r\cos\theta \cdot l \cos\theta$
My question how come it is $r\cos\theta$ as the point of intersection of chord and line PC is not equal to $r$ (radius).
Answer: We have Area =$2\frac{1}{2} l \sin(\theta)l \cos(\theta)$. However by considering triangle $APC$, we know $\tan(\theta)=\frac{r}{l}$. Hence Area =$2\frac{1}{2} \frac{r}{\tan(\theta)} \sin(\theta)l \cos(\theta)=rl\cos^2(\theta)$  Hence you get the answer in solution.
Answer: Let $A'$ be the other point of contact.
The triangle $APC$ is right. $A'A$ and $PC$ are perpendicular. Let $H$ be the intersection of $A'A$ and $PC$. Then the triangles $ACH$, $AHP$ and $APC$ are similar. Thus, the angle $\angle APC$ is equal to $\angle CAH$. Then, the chord $A'A$ is $2r\cos\theta$. Now, use the similarity:
$$\frac{PH}{AH}=\frac{AP}{AC}$$
that is,
$$\frac{PH}{r\cos\theta}=\frac lr$$
and then
$$PH=l\cos\theta$$
Now we can compute the area:
$$[AA'P]=\frac{AA'\cdot HP}2=rl\cos^2\theta$$
but
$$\cos\theta=\frac {AP}{CP}=\frac l{\sqrt{l^2+r^2}}$$


Is google's definition of polynomial correct?

Question: Definition of polynomial from google's search engine dictionary:

an expression of more than two algebraic terms, especially the sum of several terms that contain different powers of the same variable(s).

I searched on what poly means, and have got this from etymology dictionary:

word-forming element meaning "many, much, multi-, one or more,"....

And from wikipedia, monomial is

a polynomial which has only one term.

If google is right, how can monomial (having one term) be a polynomial (having greater than two terms - from the above definition)? Or is google wrong? Or is Etymology dictionary wrong?
Comment: A simple def is : ["a *polynomial* is an expression ..."](http://mathworld.wolfram.com/Polynomial.html) A formal def is "Let $R$ he a ring and let $R[x]$ denote the set of all sequences of elements
of $R$ : $(a_0,a_1,\ldots)$ such that $a_i = 0$ for all but a finite number of indices $i$."
Comment: polynomial is a general definition , like "tree". Monomial is specific like "oak tree". an oak tree is still a tree, just like a monomial is still a polynomial
Comment: I've always seen that $P_n(x) = \displaystyle \sum_{i=0}^n a_ix^i$ for $n\in\Bbb Z$ where $\bigcup_{i=0}^n\{a_i\}\subset\Bbb R$ or $\subset\Bbb C$, and if $n=0$ then so be it, though I can't substantiate this.
Answer: Don't rely on a dictionary for colloquial (or natural) language to be an accurate source of mathematical terminology. There are plenty of times that a mathematical term has a technical meaning which is not what you might expect based on the "usual" interpretation of the word or its parts. In the case of "polynomial" this is a simple instance of weakening, where "poly"is interpreted as "possibly many" rather than "many" (similarly to the use of "or" to mean inclusive "or" in logic); here are many more drastic examples of this, where the connection between term and meaning is tenuous or even nonexistent, my personal favorite being the use of the word "weasel" in set theory.
Wikipedia's definition of polynomial is in fact correct. (That's not to say that wikipedia is infallible, but it's pretty good generally for mathematics; one should really confirm wikipedia's definition by looking at an appropriate text.)

Incidentally, just to drive the point home: weasels are so called because they are like mice, but larger. Why are mice called that? To quote a famous philosopher, "I'll tell you ... I don't know."
(There are two competing stories that I've heard. One is that the mathematician in question, Jensen, made a typo and "we call such sets nice" turned into "we call such sets mice," and he liked it so much he kept it; the other is that Jensen simply wanted a word that had no prior meaning in mathematics and picked it mostly at random. My understanding is that Jensen himself has told both stories at different times.)
Answer: The definition I learned for polynomials definitely included monomials.  It also included constants and $0$.  It would be very inconvenient to exclude them because the set of polynomials would not be closed under addition.  The etymology is correct, but we don't have to follow etymology exactly when we define terms.  I would see the poly- prefix as reflecting the fact that there may be many terms, but not requiring them.


Proof that $f(x)=x^{1/n}$ is continuous.

Question: Here's what I've done:
According to the definition, a function is continuous at $c$ if, for any $\epsilon>0$, there exists a $\delta>0$ so that, if $|x-c| < \delta$, then $|f(x)-f(c)| < \epsilon$.
$$\begin{split}
|f(x)-f(c)| < \epsilon
  & \Leftrightarrow \left|x^{1/n}-c^{1/n}\right| < \epsilon \\
  & \Leftrightarrow c^{1/n}-\epsilon < x^{1/n} < c^{1/n}+\epsilon \\
  & \Leftrightarrow \left(c^{1/n}-\epsilon\right)^n < x < \left(c^{1/n}+\epsilon\right)^n,
\end{split}
$$
(which we can call $a < x < b$).
Thus, if we make $\delta = \min\{c-a,b-c\}$, then
$$|x-c| < \delta \Rightarrow |f(x)-f(c)| < \epsilon$$
Which proves its continuity. Have I done anything wrong?
Answer: I think you want to take $\delta = \min\{(c^{1/n}+\epsilon)^n-c, c-(c^{1/n}-\epsilon)^n\}$ for $c\ne0$. Otherwise just take $\delta=\epsilon^n$.
EDIT: Looks like you made the correction as I was posting.


Angular queryParams Subscription does not fire (checkbox for check all)

Question: So I have an application where you can select between several regions that you want to display data from. Above the checkboxes of those regions I added a main checkbox "AllRegions" which obv. selects/unselects all other checkboxes.
This works fine, the parameters are posted to the url and all that.
The only problem I have is when I check/uncheck the "AllRegions" checkbox my component does not react to the subscription of parameter change. It works when unchecking single regions, but not with this "AllRegions" even though I call the same function.
Component:
        ngOnInit() {
            this.route.queryParams.subscribe(params => {
            this.loadRegionData();
            })
        }

This code is called when I click the checkbox.
this.router.navigateByUrl(this.router.createUrlTree([url], { queryParams: { regions: regionParameters } }));

Why is the subscription in ngOnInit not fired when I navigateByUrl?
Answer: If the getSelectedRegions returns an Observable, it will not be triggered because you arent subscribing to it (internal observable). I would recommend you to refactor into the following (asuming route is of type ActivatedRoute):
ngOnInit() {
        this.route.queryParams
        .switchMap(params => this.regionsService.getSelectedRegions())
        .subscribe(
         //handle *data* and *error*
        );
    }

Comment: I tried similar code too, but it's not what I'm looking for.
I updated my code. It's not about the "getSelectedRegions" Function.
I subscribed to the route.queryParams and as soon as the Parameters in the URL change I want to do some code. Added the new Function "this.loadRegionData()" so maybe this makes more sense.

Whenever the parameters change I want to load my RegionData again.
This worked perfectly for my single checkboxes but for some reason the subscription does not fire if all checkboxes are unchecked at the same time.


client and server time sync with new Date()

Question: I am trying to sync time between client and the server as accurate as possible.
I've read through lots of articles and most of them recommend us to use NTP time sync, or stream-based protocols such as TCP.
Both of them requires client first to ask the server time, and sync the time using the round trip time.
But I also came to know that, browser(client) and node(server) outputs the same thing when we use new Date with the same timezone(UTC).
so why do we need to sync the time between client and the server?
wouldn't it be better to use UTC time zone respectively?
what is the advantage of using NTP based time sync over using new Date() with the same timezone(UTC) on different environments?
Comment: Different computers may have differing clocks, user's computers may have vastly differing clocks, bad actor users may change their clocks on purpose to introduce bugs or cheat etc. Using a common trusted source fixes this, though people can still work around it sometimes, you should always assume every client can't be trusted!
Comment: @koo I think you're missing the point: you can never trust remote clients (and timezones are irrelevant: always use only UTC)
Comment: I can change my phone's clock to be 9:00 am Nov 1st 1940 right now :)
Comment: How would the device know though? There is no way for a device to pluck out the correct time out of thin air. It has to be told the time. Normally this happens at the factory, but it doesn't necessarily stay accurate forever. Even digital watches break. (And the point about people intentionally changing the device clock time is well made, too. If a licence lasts till 2021, and a user sets theri computer to be permanently in 2020 to avoid the licence, you'd want to know.)
Answer: Unless a computer uses NTP, it cannot be assumed that it knows the exact time.  Just like analog clocks, especially with older computers, the clock could tick faster or slower, getting progressively more inaccurate. Or a battery might fail, resulting in the computer losing the time information, and resetting to a default; and NTP is the mechanism by which the computer can ask an authoritative source to make sure its clock is correct. People used church bells to make sure their grandfather clocks were running on time, then they'd use the TV news; now NTP serves that purpose.
On a server, you can make sure an NTP client is running, which ensures the server clock is correct (or rather, synchronised with the upstream NTP server, which would hopefully be synced with the trusted stratum-0 devices, such as atomic clocks or GPS systems).
Since you have no control over a client computer, it could be in January 1970, for all you know, and asking the server you trust is the safest course.
Comment: My computers all use NTP and they sometimes get the wrong time because the hardware clock in one of my domain-controllers will be off somewhat. So using NTP does not imply anything about accuracy.
Comment: Fair. But it does guarantee it is the same as the NTP server. If you're using your own NTP server instead of the ones trusted worldwide, that's on you :)


Set conditional if statements based on field names in views-view-fields.html.twig

Question: Is there a variable in views-view-fields.html.twig that contains the field machine name, or some other unique indicator? I am attempting something like this:
{% if field.[field_machine_name] == "my_field_machine_name" %}
   // Do stuff
{% endif %}

A massive workaround would be to create individual views.view.field--[my_view]--[my_field].html.twig templates for every field in the view, but it really seems like that shouldn't be necessary.
Answer: I ended up accomplishing this through the views UI by setting all of my fields, except for the last one, to "hidden" and then rewriting the output of the last field to include the hidden fields, and including the markup that I want.
Answer: How to Render Individual Fields in Views Templates: views-view-fields.html.twig
I've created template for views-view-fields.html.twig.
For this I used some fields values as condition to set css classes and conditionally display div elements ect.
so I have set conditions via if statements
almost the same as stated in createdbycocoon
{% if fields.field_custom.content|striptags|trim is not empty  %} and it worked nicely
but when i need get value of field and check its value (in my case it list text field type and i need the key of the list item) it won't work if you'll try to do it. like this sample
{% if (fields.uid.content|striptags) == 'John' %}

so I had my research and figure out how to do it
I did it like this:
{% set bg_type = row._entity.field_background_type.value|striptags|trim %}
{% if bg_type == 'KEY_VALUE' %}
...
{% endif %}

Basically  row._entity.field_background_type.value|striptags|trim helped to get value and check it...
I hope it will help to some one ...
Comment: OP was asking for field named, not field values. I think your answer is probably right, but it's actually an answer to a different question.


Hot deck imputation: validity of double imputation and selection of deck variables for a regression

Question: Background:
I had a data set containing 212 observations with a lots of missing values. Most of the IVs and DVs are categorical (DVs are ordinal) in nature. There are 3 DVs and about 30 IVs. My intention was to run an ordinal logistic regression. A list-wise deletion keeps only 42 observations, so I decided to use hot deck imputation to fill in the missing values. I chose similar variables as the deck variables during the hot deck imputation (the deck variables should always be categorical and as far I know there should be a maximum of 5 deck variables).
Here are my queries:
1) When I imputed via hot deck once, 169 of the observations were filled in completely. If I use these imputed values for another hot deck imputation, then all 212 observations will fill in completely. But I am not sure if it is valid to use the imputed values for a further imputation. Can anyone suggest?
2) Someone suggested me (from his experience) to use the 3 DVs as the background or deck variables for imputing all the DVs and all the IVs, because that will probably facilitate my regression results. May I know your comment about it?
3) If I see almost all of the values (except from a very few) of a continuous IV are 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90 etc. then isn't it better to impute them via hot deck rather than via EM (as the hot deck will impute a variable with it's existing values only)?
Comment: How many missings does a single variable have in your data? If more than, say, 20% of cases are missing in a variable, any imputation is a bad and helpless idea.
Comment: The four variables with highest number of missing values have 62, 58, 41 and 41 missing respectively (out of 212). After imputation has been done once 20, 7, 8 and 3 values of the corresponding variables still remain missing. I have seen that the analysis cannot be done with these many missing values. What should I do now? :(
Comment: Hmm 29% initial missing rate is indeed large. Did you use my macros for hot-deck found on my web page? By default they allow a donor to act only once, but you could permit repeated using of a donor. Another way to preclude failing imputations is to make matching on backgroud vars more liberal (by merging some categories or just allowing partial match).
Comment: Regarding your point 3. EM imputation (as implemented, for example, in SPSS) acts recurrently, so it is superior to hot-deck. The only situation when hot-deck is possible whereas EM is not is when the variable-to-impute is categorical. Also, EM makes assumptions about shapes of distributions while hot-deck is assumption-free (which makes it more general but in no way "better")
Comment: @Blain, frankly, it looks like you are using a poor software implementation and dubious advice. I don't see any reason why a properly coded hot deck procedure should leave any missing values unfilled. I am not sure I am even getting your point 2 on using three DVs (which I assume are dependent variables), and what the best relation of the procedure to regression analysis would be. Generally, I would advise to move on to multiple imputation, and listen to Stef van Burren's advice on it (who wrote a book or two on this).
Comment: @StasK thank you. Actually I don't know myself if there is any advantage in using the dependent variables as deck variables. And I am sorry that I actually don't know much about multiple imputation. I use SPSS 16.0 which does not have the option of multiple imputation I guess! I have found this website which may help me to know about this: http://www.unt.edu/rss/class/Jon/SPSS_SC/Module6/SPSS_M6_2.htm
Comment: @ttnphns Thank you for the advice. I have downloaded your macro. Still I have some values missing, I think I should make matching on backgroud vars more liberal as you suggested. Anyway, could you please explain for me what you meant by- "By default they allow a donor to act only once, but you could permit repeated using of a donor." Do that mean to use the same donor for imputing different variables I'll need to run the macro over and over again? Thank you all for your kind attention and advice.
Comment: @Blain. Donor serves "only once" or "potentially repeatedly" in imputing the variable you're processing. The macro processes (imputes) only one variable at a time. I've explained in the document why it generally different variables should be processed separately, over and over.
Answer: Hot deck is often a good idea to obtain sensible imputations as it produces imputations that are draws from the observed data. However, filling in a single value for the missing data produces standard errors and P values that are too low. For correct statistical inference could use multiple imputation. It is easy to apply hot deck imputation in combination with multiple imputation. The most popular technique for doing this is known as predictive mean matching, and has been implemented on a variety of platforms.
Comment: `filling in a single value for the missing` can you explain this, - i.e. the way hot-deck works to you?
Comment: Replacing each missing entry by one data value is seductive, but current complete-data software that reads the imputed data does not distinguish between the real and the artificial data points. Instead it treats everything as real. Consequently, the software "thinks" that there is more information than there is in reality, and produces too small standard errors and uncorrect statistical tests. These problems of single imputation have been well documented in the book of Little and Rubin (2002).
Comment: In hot deck the missing values are not imputed by one data value, but with different values of the variable that is intended to impute. The values used for imputation are from within the real values of the variable that have missing values. The deck variables help find the match for the missing values. I am still not clear with solution of the three points I mentioned. If someone gives his answers point-wise, that will be really a kind help.
Comment: @Stef, your point that any single imputation is inherently limited because it doesn't recognize the difference between the real gathered data and the guess imputed values is absolutely right. Still, single imputation with either noise or random selection is not so bad. In many cases (e.g. in exploratory rather than inferential alalysis) to use multiple imputation is cumbersome and hot-deck or EM remain nice alternatives.


Web Site Hosting Issue - Windows AD Domain Externally Resolvable

Question: Up until recently we hosted our company web site on an internal Win 2008 IIS server. To ensure that it stayed online in case something happened to the office, we moved the site to some cheap shared hosting with a popular provider. For the most part things are fine but I have run into one problem...
Unfortunately when the Windows domain was set up the admin (not me, I swear to god) used an externally resolvable host name (eg 'example.net' rather than the best practice 'example.local'). This was never a problem as we always hosted our web site on an internal IIS server. Users inside the AD domain are now complaining that they cannot reach the web site from inside the network. I get why this is the case but I am cautious about what sort of DNS changes to make since I am well aware how DNS dependent an active directory domain can be. As a temporary measure I put in a 'www' A record pointing to the IP of the external web server so they can at least reach the site for now.
My question is this: Can I set up a wildcard dns entry on our internal AD DNS server for 'example.net' redirecting to our external web server? I am afraid that putting a wildcard entry for a server that sits outside the AD domain might cause serious problems.
Has anyone ever tried this?
Comment: What's wrong with the solution you've already implemented? If having an A record for www that resolves to the external ip address of the web server does the trick why go any further?
Comment: In the end I wanted the cleanest solution possible that made it transparent for the internal users, so they would hit the web site regardless of whether or not they used www.example.net or simply example.com in the URL bar of their browser
Answer: Cliff,
Yea I know what you mean, been there and done that.  The safest thing you can do is what you have already done by adding a www record.
You really can't add a wildcard record because any request for Domain.net will then redirect externally.  This is especially true if you rely on DNS for all computer name based lookups and have disabled NetBIOS on the network.
Short term what you have done seems about right.  Long term you may want to investigate changing your domain name, I'm not sure how many clients you have internally but this is at times no easy task, but in the longrun will save you so much time and effort.
I think MDMarra has posted before that he doesn't mind using the public DNS records for your internal domain but instead of a local domain extension (i.e. Domain.local) he uses a subdomain (corp.domain.net) or something like that.  Just don't use the root, as you have found out.
Comment: Thanks! This was one of those cases where I saw that simply trying it out and seeing what happened was a little too risky :) One thing is certain, I am going to figure out how to safely change the AD domain name to avoid issues like this in the future.
Comment: Yea, its a tricky process, depending on your environment. If you've got less than 20 PCs you can simply spin up a new DC and physically touch each machine, any more than that and you may want to look at automated tools and possibly consultant help. Although MSFT does provide some good information regarding this subject.


ReadAllText retorna caracteres chineses

Question: Tenho um arquivo .sql de 55GB e precisava executar linha a linha, mas como não consigo carregar um arquivo desse tamanho, dividi em 543 arquivos de 100MB nomeados como Imagens<NumeroSequencial>.sql.
Então fiz um código que le os arquivos 1 a 1 e extrai as linhas em uma lista, após isso executa os comandos linha a linha.
O programa de terceiro que divide os arquivos extrai os arquivos com codificação UTF-16 BE que no c# é Unicode. Quando leio arquivos com o número par no fim do nome e debugo o seguinte código, eu recebo caracteres chineses, mas quando são arquivos com o número ímpar vem tudo normal, o problema é que os de número impar tem a mesma codificação que os de número par, eles vieram do msm software da mesma divisão.
string s_unicode = File.ReadAllText(path,Encoding.Unicode);
//retorno > 猀漀挀挀攀爀

O que pode ser que está acontecendo? ja tentei usar UTF-8 mas ai me retorna um monte de \0\0\0\0\0\0
Segue o arquivo para teste nesse link
Answer: Eu não sei como você extraiu o texto nem em que formato usou para parsear o arquivo original, mas pode tentar resolver o problema lendo esses arquivos "estragados" como arquivos binários de leitura, remover todos os bytes 0x00 e parsear como string.
O trecho com ideogramas chineses traduz para os seguintes bytes Unicode: 0x7300 0x6F00 0x6300 0x6300 0x6500 0x7200.
Se retirar os 0x00 e parsear como string Unicode, o resultado é soccer.
EDIT: tente remover o primeiro 0x00 do arquivo, use o seguinte código:
using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Writing Imagens1.sql now.");
            File.WriteAllBytes("Imagens1.sql", new byte[] { 0x00, 0x73, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x63, 0x00, 0x65, 0x00, 0x72, 0x00 });

            Console.WriteLine("Reading Imagens1.sql and dumping it into Imagens1.new.sql");
            using (BinaryReader br = new BinaryReader(File.OpenRead("Imagens1.sql")))
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("Imagens1.new.sql")))
            {
                byte[] buffer;

                br.ReadByte(); // This should be the heading 0x00 that we want to get rid of.

                while ((buffer = br.ReadBytes(1024)).Length > 0)
                {
                    bw.Write(buffer);
                }

                bw.Close();
                br.Close();
            }

            Console.WriteLine("Finished!");
            Console.Read();
        }
    }
}

Comment: Marcelo, tenho uma experiencia legal com programação, mas não consegui entender como aplicar isso na prática, é muito complexo para você me dar um exemplo?
Comment: Deve ter um caracter \0 bem no começo do arquivo. É só retirar ele.
Answer: Se já sabe efetivamente a codificação utilizada no ficheiro, porque não utilizá-la na leitura do ficheiro?
string s_unicode = File.ReadAllText(path, Encoding.GetEncoding("UTF-16BE"));

Pode também passar os resultados para um array, pode dar jeito:
string[] s_unicode = File.ReadAllLines(path, Encoding.GetEncoding("UTF-16BE"));

Código testado e a funcionar a 100%!

ReadAllText retorna caracteres chineses


Number of edges in a graph

Question: I was wondering, is it possible to find the number of edges in a graph when given the number of vertices and the degree of each vertex?
Comment: sum up the degrees of all the vertices and divide the result by two.
Answer: Of course. To avoid double-counting, the closed form is this, for a graph $G = (V,E)$:
$$|E| = \frac 12 \cdot \sum_{v \in V} \mathrm{deg}(v)$$
This is a very important result, known as the Handshake Lemma.
Answer: If your graph has no buckles, then half of sum of all vertices degrees will give you the edge number. You have to take half of it due to every edge increases degree of $2$ vertices by $1$.
Answer: Imagine taking some scissors and snipping each edge.  Now you have twice as many half-edges.  Each vertex is now the center of a star with as many half-edges as its degree in the original graph.  This allows you to relate the number of edges to the total of all the degrees.  This result is sometimes called the Handshaking Lemma.
If you impose some sort of regularity (say, all vertices are of degree $d$), then you can work out the number of vertices.

Number of edges in a graph


How to call disclaimer page on all media files in Drupal?

Question: I want to display a terms n condition page on every media of website. I collect all media from file managed table of database. I also convert fid to url. Now for each media url I need a disclaimer page.
My issue is something related to this link.
For example:
When I click on each report of news table shown below, on clicking of (say) linux-minimal.pdf , it first redirect to some node which is my disclaimer url, and then pdf open.
How can I achieve this?
I have tried some code which is actually not working. It is:
function hook_init(){
    $get_current_path_media = $GLOBALS['base_url'].'/'.current_path();
    if($get_current_path_media == 'http://my-website/sites/default/files/569338.pdf'){
        drupal_goto('disclaimer');
    }
}

Comment: If I were you, I would use jQuery, instead of php, to display a popup disclaimer and after the user closes or accepts the disclaimer, they are then taken to the pdf file.
Comment: any drupal way of doing it?
Answer: Here is an example
bitcoin.pdf

SEE A DEMO HERE
In Drupal to use jQuery you need to wrap it in
(function ($) {

    //code goes here

})(jQuery);

so your code should look like this
(function ($) {
  $( document ).ready(function() {
    $('.test').click(function() {
        alert('your disclamer goes here');
    });
  });
})(jQuery);

PS: If your div class is outside the

bitcoin.pdf

then use it like this

Comment: edited my answer, fixed errors.


Como coletar e inserir propriedades de gradient de uma div para outra div

Question: Existe este site gerador de gradiente CSS.
E lá, como podem ver, quando clicamos nos pequenos quadradinhos de escolha com gradient ele carrega todas as propriedades gradient para outra div maior.
Pesquisei aqui: https://www.w3schools.com/jquery/jquery_css.asp
html_toggleclass.asp

$(function() {
  $("button").click(function() {
    console.log($("div").css("background"));
  });
});

<div style="width:100px;height:100px;background: rgba(248,80,50,1);
  background: -moz-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(248,80,50,1)), color-stop(50%, rgba(241,111,92,1)), color-stop(51%, rgba(246,41,12,1)), color-stop(71%, rgba(240,47,23,1)), color-stop(100%, rgba(231,56,39,1)));
  background: -webkit-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -o-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -ms-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: linear-gradient(to bottom, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f85032', endColorstr='#e73827', GradientType=0 );">

<button>Botão</button>

Mas não está mostrando as propriedades gradient no console.
Como o site faz pra inserir um gradient de uma div para outra div coletando e inserindo?
Comment: Recomendo que você use uma classe pra tanto css, considere que você ja esta fazendo errado por conta disso. Acho que `element.computedStyle `ou `element.style` é o mais proximo que você consegue na situação atual.
Answer: O porquê de o jQuery não estar buscando corretamente a informação, não sei dizer. Dei uma pesquisada rápida e não encontrei um material adequado. Parece que ele não considera o inline style do elemento como parte do CSS e, por isso, sempre retorna vazio.
Mas, uma forma prática de se contornar isso é acessar diretamente a propriedade style e buscar o atributo background do mesmo, como abaixo:
$("div").prop('style').background

Ficando:

$(function() {
  $("button").click(function() {
    console.log($("div").prop('style').background);
  });
});

<div style="width:100px;height:100px;background: rgba(248,80,50,1);
  background: -moz-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(248,80,50,1)), color-stop(50%, rgba(241,111,92,1)), color-stop(51%, rgba(246,41,12,1)), color-stop(71%, rgba(240,47,23,1)), color-stop(100%, rgba(231,56,39,1)));
  background: -webkit-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -o-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: -ms-linear-gradient(top, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  background: linear-gradient(to bottom, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f85032', endColorstr='#e73827', GradientType=0 );">

<button>Botão</button>

Perceba que, ao pressionar o botão, é devidamente exibido a configuração do gradiente no console.


Dovecot submission service: authentication failes

Question: I have trouble setting up submissions with Dovecot + Postfix.
doveadm auth login user pass gives the right output.
When I try to send a mail with submission(s) it gives authentication failed error.
doveconf -n output:
auth_mechanisms = plain login
disable_plaintext_auth = no
mail_location = maildir:/home/vmail/%d/%n
mail_privileged_group = vmail
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix =
}
passdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
protocols = " imap lmtp submission"
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0666
    user = postfix
  }
}
service lmtp {
  unix_listener /var/spool/postfix/private/lmtp {
    group = postfix
    mode = 0600
    user = postfix
  }
}
ssl_cert = < some_crt
ssl_client_ca_dir = /etc/ssl/certs
ssl_dh = # hidden, use -P to show it
ssl_key = # hidden, use -P to show it
userdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}

Comment: How could we know if you don't share the configuration & the logs / errors you have got?
Comment: I edit the question. Please see the configuration. Thank you for an answer.
Answer: Since version 2.3.0, Dovecot has provided the Submission Server feature, which is an authenticating proxy between MUA and MTA. Its main advantage is the BURL (RFC 4468) extension, which allows saving the message to the Sent folder at the same time it is delivered to SMTP.
On the other hand, it was implemented in 2017, just before the RFC 8314 made the STARTTLS submission obsolete. Personally I would recommend using the traditional way, where Postfix handles both SMTP for incoming mail and submissions (implicit TLS on port 465) for outboud, authenticated mail. There, Dovecot provides the SASL authentication as explained in the two documentations:

Postfix and Dovecot SASL (Dovecot)
Postfix SASL Howto (Postfix)

Your configuration with the current approach is missing configuration for the Relay MTA. In other words, your Dovevot does not understand where the mail should be relayed.

submission_relay_host
Host name for the relay server (required).

If you want to keep this course, please edit your 20-submission.conf with at least, e.g.,
submission_relay_host = localhost

Also, setting disable_plaintext_auth to no is a huge security risk, and you should stick with the default yes:

If yes, disables the LOGIN command and all other plaintext authentication unless SSL/TLS is used (LOGINDISABLED capability) or the connection is "secured":

Client IP is in login_trusted_networks.
Client IP is from localhost, and it's not coming from HAProxy listener.
Comment: Adding the `submission_relay_host = localhost` solved this issue.
Comment: RFC 8314 didn't make the Submission protocol obsolete; it made the accessing of Submission service _via the StartTLS port 587_ obsolete. The protocol remains, on port 465 (which is no longer SMTPS – it has been SubmissionS for quite a while now.)
Comment: @user1686: Thanks for the correction; updated in the answer.


Laravel 5.1 custom method in controller

Question: In a controller name tagController where I define a custom method
public function addTag($id)
{
    $book = $id;
    return view('tag.create', compact('book'));
}

In the route I define the custom route method
Route::get('tag/addTag/{$id}', 'tagController@addTag');
Route::resource('tag', 'tagController');

From my view I'm calling the controller method
id)}}">Add Tag

I'm getting the error every time
NotFoundHttpException in RouteCollection.php line 143:

This is routing problem but I don't understand to how to define a custom method in route and in resourceful controller. Please help to get rid of the error?
Thanks.
Answer: Remove the $ from the path
Route::get('tag/addTag/{id}', 'tagController@addTag');

Comment: @JasonMcCreary markdwhite's answer simply adds a name to a route. It doesn't fix the `NotFoundHttpException` problem.
Comment: + I see now. This answers stands alone :)
Comment: @BenSwinburne - indeed. My answer has been taken out and shot.

Laravel 5.1 custom method in controller


JTable not updating when model updates

Question: Ok, I have read up on this, but I'm still very confused. I have a JTable with a custom Table Model that stores data in an ArrayList. It displays just fine. However, when I want to add a row, I add an object to the ArrayList, then call fireTableRowsInserted(...). However, the table does not refresh.
public Main() {
        initComponents();
        current_map = new Map();
        current_map.authors.add(new Author("New Author"));
        author_model = new AuthorModel(current_map.authors);
        jTable1.setModel(new AuthorModel(current_map.authors)); <---This is the mistake
    }
...

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        author_model.authors.add(new Author("New Author"));
        author_model.fireTableRowsInserted(author_model.authors.size(), author_model.authors.size());
    }

The above code is from my main JFrame. Not sure where to go from here.
I'm lost right now.
Comment: Don't invoke the fireXXX methods of the TableModel directly. These method should only be invoked by the TableModel class itself.
Comment: Ah, so the update will occur automatically then? I'll try it.
Answer: The table is initialized with:
jTable1.setModel(new AuthorModel(current_map.authors));

But when the button is clicked, you modify the variable author_model:
author_model.authors.add(new Author("New Author"));

The initialization of the table should be
jTable1.setModel(author_model);

You should also respect the Java naming conventions, and choose better names for your variables.
Comment: author_model should be authorModel. Same for current_map. Variables are camelCased in Java.
Comment: Oh, duh, how did I miss that one. I know the names are not good, they are temporary.
Comment: In addition, with regards to "temporary names": you should *always* put thought into even the simplest of projects. Underestimation has time and time again proven to be a problem (e.g., creating the internet? who would EVER need more than 4 billion IP addresses?). If you ever end up expanding this project - or even just copying some of the code to use in another project - issues like these will befuddle you and others. And if this somehow gets into a public API... \*shudder\*
Comment: I would echo this, also that effort put into naming things is always worth it.  Get into the habit of telling your readers the truth about everything you name: variables, classes, methods, packages.  The chances that those names live on after a "temporary" period is too great.  Besides, the greatest need for them is at the beginning, while you're trying to debug things like this...

JTable not updating when model updates


Expansion of Laplace operator

Question: Let $\nabla$ be the gradient operator and $\nabla ^2 = \Delta$ be the Laplace operator. Now I know that $$\| \nabla u \|^2 + \| \nabla v \|^2 = (u_x^2 + u_y^2 + v_x^2 + v_y^2).$$
My question is, what is
$$\| \Delta u \|^2 + \| \Delta v \|^2?$$
Answer: Note that $\Delta u=u_{xx}+u_{yy}$, so $\Delta u$ is a real number, not a vector. Compare this to $\nabla u=(u_x,u_y)^T$. Hence, $||\Delta u||^2=|u_{xx}+u_{yy}|^2$ (just absolute values). Therefore, $||\Delta u||^2+||\Delta v||^2=|u_{xx}+u_{yy}|^2+|v_{xx}+v_{yy}|^2$.

Expansion of Laplace operator


Internet Explorer does not show links styled as they are in Visual Studio designer

Question: I use a master page and a theme. After finding that the style does not correctly work in the browser, I took the rendered html and created an html page in visual studio in order to see everything in the designer. I foun the style is showing correctly in visual studio disigner. When I tried to see the page in IE, the styl again didn't work.
Here is the style:
#menu div.menu a
{
    display: block;
    color: #FFFF00;
    font-weight:bold;
}

and here is the HTML code:

<form name="aspnetForm" method="post" action="Welcome.aspx" id="aspnetForm">

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA5MTQxNjgzNWRkziD2ncxUdFPJZHawenZNb39FJFc=" />

Site name

            Login

</form>

Answer: That rule should be for
#menu div.menu a

You're missing the leading #


Error while executing cross-compiled program for openwrt

Question: I'm trying to export a software to openwrt and i'm able to generate the ipk but the compiled file always gives me this error

-ash: scanReportProbe: not found

I've tried everything but i'm not able to make it work.
To be complete this is what i have done to prepare the environment:
git clone git://github.com/openwrt/openwrt.git
cd openwrt
./scripts/feeds update -a
./scripts/feeds install -a
make defconfig
make prereq
make menuconfig
    [here i selected the package with the M and saved the configuration]
make tools/install
make toolchain/install
make package/scanReport_probe/compile

I have no idea of to fix this error so i need some hint of solution.
I don't think that the error is in the code but in casse is needed this is my program:
file structure
scanReport_probe
├── LICENSE
├── Makefile
├── README.md
└── src
    ├── data
    │   └── THIS IS FOR DATA FILES.txt
    ├── runScript
    │   └── scanReportProbe
    ├── scanReport_probe
    │   ├── a.c
    │   └── makefile
    └── scanReport_probe.conf

makefile for openwrt
include $(TOPDIR)/rules.mk

# name of package
# version number of the sources you're using
# how many times you've released a package based on the above version number
PKG_NAME:=scanReport_probe
PKG_VERSION:=1.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT

# sources will be unpacked into this directory (you shouldn't need to change this)
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)

#needed
include $(INCLUDE_DIR)/package.mk

# Metadata; information about what the package is for the ipkg listings
# to keep things simple, a number of fields have been left at their defaults
# and are not shown here.
define Package/scanReport_probe
    SECTION:=utils
    CATEGORY:=Utilities
    TITLE:=scanReport_probe
    URL:=https://github.com/luigiDB/scan-report_probe
    TITLE:=Scan in monitor mode probe over wifi channel with periodic report to a server through http post.
    MAINTAINER:=Please refer to github repository page
endef

define Package/scanReport_probe/description
    This is the best tool ever.
    Scan probe over wifi and at regualar interval send results via http post.
endef

define Build/Prepare
    mkdir -p $(PKG_BUILD_DIR)
    $(CP) ./src/* $(PKG_BUILD_DIR)/
endef

CONFIGURE_VARS+= \
    CC="$(TOOLCHAIN_DIR)/bin/$(TARGET_CC)"

define Build/Compile
    $(MAKE) -C $(PKG_BUILD_DIR)/scanReport_probe $(TARGET_CONFIGURE_OPTS)
endef

# We'll use the OpenWrt defaults to configure and compile the package. Otherwise we'd need to define
# Build/Configure - commands to invoke a configure (or similar) script
# Build/Compile - commands used to run make or otherwise build the source

define Package/scanReport_probe/install
    # Now that we have the source compiled (magic huh?) we need to copy files out of the source
    # directory and into our ipkg file. These are shell commands, so make sure you start the lines
    # with a TAB. $(1) here represents the root filesystem on the router.
    # INSTALL_DIR, INSTALL_BIN, INSTALL_DATA are used for creating a directory, copying an executable,
    # or a data file. +x is set on the target file for INSTALL_BIN, independent of it's mode on the host.

    # make a directory for the config
    $(INSTALL_DIR) $(1)/etc/scanReport_probe/

    # copy the config
    $(INSTALL_CONF) $(PKG_BUILD_DIR)/scanReport_probe.conf $(1)/etc/scanReport_probe

    # make a directory for some random data files required by scanReport_probe
    $(INSTALL_DIR) $(1)/usr/share/scanReport_probe

    # copy the data files
    $(INSTALL_DATA) $(PKG_BUILD_DIR)/data/* $(1)/usr/share/scanReport_probe

    #make directory bin
    $(INSTALL_DIR) $(1)/bin

    # copy the binary
    $(INSTALL_BIN) $(PKG_BUILD_DIR)/scanReport_probe/scanReportProbe $(1)/bin

    #make the directory init.d in case isn't present
    $(INSTALL_DIR) $(1)/etc/init.d

    #copy script to init.d
    $(INSTALL_BIN) $(PKG_BUILD_DIR)/runScript/scanReportProbe $(1)/etc/init.d
endef

#runned post installation call the enable on the service
define Package/scanReport_probe/postinst
    #!/bin/sh
    # check if we are on real system
    if [ -z "$${IPKG_INSTROOT}" ]; then
        echo "Enabling rc.d symlink for scanReportProbe"
        /etc/init.d/scanReportProbe enable
    fi
    exit 0
endef

#runned pre uninstallation call the disable on the service
define Package/scanReport_probe/prerm
    #!/bin/sh
    # check if we are on real system
    if [ -z "$${IPKG_INSTROOT}" ]; then
        echo "Removing rc.d symlink for scanReportProbe"
        /etc/init.d/scanReportProbe disable
    fi
    exit 0
endef

$(eval $(call BuildPackage,scanReport_probe))

a.c
#include <stdio.h>
int main(void)
{
        printf("Hello World\n");
        return 0;
}

makefile for c program
PROFILE = -O2 -s
CFLAGS = $(PROFILE)
LDFLAGS =

all: main

# build it
main: a.o
    $(CC) $(LDFLAGS) a.o -o scanReportProbe

a.o: a.c
    $(CC) $(CFLAGS) -c a.c

# clean it
clean:
    rm *.o a

Comment: Are you sure you have selected correct architecture in menuconfig? What does `file build_dir/target-*/scanReport_probe*/scanReportProbe` say? Compare it to a binary from your openwrt device (e.g. copy `/bin/busybox` to your host machine and run `file` on it).
Comment: Also, try removing `define Build/Compile` clause and `CONFIGURE_VARS` assignment - the defaults should work well for you.
Comment: Everything is configured correctly. I don't know why but compiling this repository git://git.openwrt.org/15.05/openwrt.git instead of the trunk solved the problem.
Answer: For -ash, IIRC, ash is a [boot] shell. It is saying that it can't find a particular command.
So, it may be one of:
(1) In your rc script section, you're doing /etc/init.d/scanReportProbe enable but the package you're building uses scanReport_probe. So, you may need to add or remove an _ here or there and/or some other renames so things match up.
(2) If the file structure you gave is the final one, I'm not sure the script is in the right directory.
(3) Are the permissions for the script correct (i.e. has execute)?
Comment: After the installation every file is in the correct directory and i' ve also tested without the init.d script just to be sure. The executable under the bin folder has execute permission `-rwxr-xr-x    1 root     root          1527 Aug 17 17:15 scanReportProbe` but also with `/bin/scanReportProbe` i receive the same error. I test also other repository that i found online and everyone gives me the same error.


Why my starting Activity is not working?

Question: First I want to say is that I am new to Android. I want to start my Activity from an AsyncTask, but I don't know why I am getting an error.
@Override
protected void onPostExecute(String string) {
    // Now we have your JSONObject, play around with it.

    //MainActivity.t.setText(string);

    MainActivity.mainActivity.startPlataform();
}

This is my onPostExecute() when everything works and I am accessing from a static MainActivity variable, but I don't know another way to do it.
public class MainActivity extends Activity {

    public static MainActivity mainActivity;
    public Intent detailIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainActivity = new MainActivity();
        detailIntent = new Intent(this, Main_Plataform.class);
    }

    ...

    public void startPlataform() {
        try {
            startActivity(detailIntent);
        } catch (Exception e) {
            Log.e("Fehler!", "Error why ???" + e.toString());
        }
    }
}

When I call the startPlataform() method with a Button in my MainActivity it works fine
but it does not in `the onPostExecute(). I think something about the static variable is wrong.
Here is my logcat:
05-03 20:41:37.403: E/AndroidRuntime(1562): FATAL EXCEPTION: main
05-03 20:41:37.403: E/AndroidRuntime(1562): Process: com.example.patronusgps, PID: 1562
05-03 20:41:37.403: E/AndroidRuntime(1562): java.lang.NullPointerException
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.app.Activity.startActivityForResult(Activity.java:3424)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.app.Activity.startActivityForResult(Activity.java:3385)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.app.Activity.startActivity(Activity.java:3627)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.app.Activity.startActivity(Activity.java:3595)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
com.example.patronusgps.MainActivity.startPlataform(MainActivity.java:72)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
com.example.patronusgps.JSONParser.onPostExecute(JSONParser.java:106)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
com.example.patronusgps.JSONParser.onPostExecute(JSONParser.java:1)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.os.AsyncTask.finish(AsyncTask.java:632)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.os.AsyncTask.access$600(AsyncTask.java:177)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.os.Handler.dispatchMessage(Handler.java:102)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.os.Looper.loop(Looper.java:136)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
android.app.ActivityThread.main(ActivityThread.java:5017)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
java.lang.reflect.Method.invokeNative(Native Method)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
java.lang.reflect.Method.invoke(Method.java:515)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-03 20:41:37.403: E/AndroidRuntime(1562):     at
dalvik.system.NativeStart.main(Native Method)

Comment: just a side thing, please format your code better with better intents to make it more readable,
Comment: What do you want to do here: `MainActivity.mainActivity.startPlataform();` or here: `mainActivity = new MainActivity();`? Instantiating an `Activity` like this is something you should NEVER do. Use an `Intent` to start a new `Activity`.
Comment: Ok, i was just traying to get the context from there, but know i feel stupid xD
Answer: First remove everything like this:
public static MainActivity mainActivity;

or this:
mainActivity = new MainActivity();

Both of those things are completely wrong. You should never insatiate an Activity like this and never hold a reference to an Activity in a static variable. This will only cause problems and mess up your app.
You can also remove the definition of detailIntent from your MainActivity:
public Intent detailIntent;

And remove its declartion from the onCreate() method:
detailIntent = new Intent(this, Main_Plataform.class);

You don't need all of that. If you want to start an Activity create a new Intent everytime.
Everytime you want to start any Activity regardless of where in your code you want to do it, you can do it basically like this:
Intent intent = new Intent(context, <Activity you want to start>.class);
startActivity(intent);

You need to pass the Context of your Activity to your AsyncTask to start the Activity from there, in this example I start the MainActivity:
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);

Comment: Ok uderstood, but how do i Pass the context. Like this ?           MainActivity.this.context or , MainActivity.this.getApplicationContext()
Comment: Doesn't matter which `Context` you use. But beware of memory leaks. Use `WeakReferences`.
Comment: Thanks everything went better, hopefully i will be clever as you someday


Trocar imagem com mouse sobre campo de mapa de bits

Question: Em página HTML com imagem tipo mapa com um menu de opções, quero mudar parte da imagem para outra do tamanho do campo definido para essa opção, ao passar o mouse, algo como onfocus ou onmouseover. Como faço, neste exemplo, para substituir (sobrepor) cada parte da imagem delimitada pelas coordenadas por outra como opcao1foco.jpg, opcao2foco.jpg? Obrigado desde já pelo apoio.
Exemplo:

  <map name="FPMap0">
    <area href="opcao1.htm" shape="rect" coords="238, 89, 333, 194">
    <area href="opcao2.htm" shape="rect" coords="348, 89, 542, 198">
  </map>

Answer: Existem alguns plug-ins JQuery que poderão lhe ajudar neste aspecto:
MapHilight
Fonte: http://davidlynch.org/projects/maphilight/docs/
Exemplo de uso: http://davidlynch.org/projects/maphilight/docs/demo_usa.html
ImageMapster
Fonte: http://www.outsharked.com/imagemapster/
Exemplos: http://www.outsharked.com/imagemapster/default.aspx?demos.html


Include HTML tags in custom fields

Question: I have a "currently reading" custom field in my WordPress blog post, and I want to output it wrapped in an HTML tag.
What I tried was this hack:
echo "
" . $mycustomfieldcontent . "
";

What the client prefers to do is to be able to set the HTML in the actual custom field.
What would be the proper way to do that?
Answer: You're close.  Pretty much the same as your previous question, see the screenshots:
Add your Custom Field with HTML in it.

Then display it with this:
<?php echo get_post_meta($post->ID, 'Your Meta Key', true); ?>

And the output should be:
Comment: Or do you mean you want to put HTML in an editor and then output that HTML?
Comment: Yeah, I mean, let the client put `` or whatever other HTML in the actual field in the editor.
Comment: Updated the answer.  Its the same as your previous question basically.
Comment: Almost perfect, except it does something really weird now: wraps the REST of the content in the html tag I used in the custom field! [As can be seen here:](http://dimwp.securedev.co/) (At the bottom the name of the writer and the "Proudly powered with WordPress".
Comment: Good deal.  I upvoted your question to put you over the 15 points so you can upvote.  You should answer your own question if you figured it out so other people can see what worked.
Answer: This also works, in case you're not using 'get_post_meta()'
<?php echo html_entity_decode($custom_field_content); ?>

Include HTML tags in custom fields


What is the right way to clear select2 dropdown when using Ajax?

Question: I am having an issue with select2 where after I enter an item and I want to use the same dropdown again, i can't seem to remove the previously selected item
For example, lets say my id is "#StreamName", I thought this would clear it:
 $("#StreamName").val(null).trigger("change");

but it still seems to show the previous selected item.  From looking at the html it appears that I have brute force it by doing this:
$("#select2-StreamName-container").html("");

but that seems like i am not using the API properly so I wanted to see if there is another suggestion or if I am missing something.
Answer: Working Fiddle - Local Data Source
It looks like the proper way to clear Select2 is what you first suggested as this answer suggests.
Javascript
$(document).ready(function() {
  $("#StreamName").select2();
  $("#StreamName").val(null).trigger("change");
});

HTML
<select id="StreamName">
  <option value="AL">Alabama</option>
  <option value="CA">California</option>
  <option value="WY">Wyoming</option>
</select>

Update - Remote Data Source
JSFiddle Using Remote Data
This should still work to clear a Select2 input even when using a remote data source:
$("#StreamName").val(null).trigger("change");

Full Javascript
$(document).ready(function() {
  $("#StreamName").select2({
    ajax: {
      url: "https://api.github.com/search/repositories",
      dataType: 'json',
      delay: 250,
      data: function(params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function(data, params) {
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data.items,
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },
      cache: true
    },
    escapeMarkup: function(markup) {
      return markup;
    }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo, // omitted for brevity, see the source of this page
    templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
  });

  $("#StreamName").val(null).trigger("change");

  // For testing...
  $('#set-null').click(function() {
    $("#StreamName").val(null).trigger("change");
  });

});

function formatRepo(repo) {
  if (repo.loading) return repo.text;

  var markup = "
" +
    "

" +
    "
" +
    "
" + repo.full_name + "
";

  if (repo.description) {
    markup += "
" + repo.description + "
";
  }

  markup += "
" +
    "
 " + repo.forks_count + " Forks
" +
    "
 " + repo.stargazers_count + " Stars
" +
    "
 " + repo.watchers_count + " Watchers
" +
    "
" +
    "

";

  return markup;
}

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}

HTML
<select id="StreamName">
  <option value="3620194" selected="selected">select2/select2</option>
</select>

Comment: in my case, I am not predefining the list of options upfront.  I am populating from remote data source as per the example on this page: https://select2.github.io/examples.html For some reason, in this usecase, it doesn't seem to clear when doing $("#StreamName").val(null).trigger("change");
Comment: I updated the answer to include a remote data source. Maybe there is something else in your source code that is causing it to fail? Let me know if I can help.
Comment: It's interesting that this method of resetting does not work for me either. Had to sed html('') to make it work
Answer: I also had the issue with
$("#StreamName").val(null).trigger("change");

Setting the select2 option to blank HTML worked for me.
$("#StreamName").html("").trigger("change");

Answer: After change ajax url use
$('#StreamName').select2({
  ajax: {
    url: newUri
  }
})

You should use
$('#StreamName').html('').trigger('change');

to instead of
$('#StreamName').val(null).trigger('change');

to avoid displaying previous text with the same id.


SP list item - disable "Edit" for all users except for the item creator but still leave a single column editable for all users

Question: Is it possible to use Item-level Permissions in SP 2013 to disable other users modifying items not created by them but still allow them to modify a single field (column) from that item?
I want everyone to be able to input information in that column after clicking "Edit" item button but yet not able to modify any other field if the item is not created by him.
Only the item creator should be able to modify all the fields.
Any ideas how to achieve that are more than welcome :)
Answer: You could use client object model for the same as follows:
<code>$(document).ready(function () {
if(CheckCreatedBy() != GetCurrentUser())
{
      $("input[Title='EditableByAllUsers']").prop("disabled", true);
}

});

function CheckCreatedBy()
{
var clientContext = new SP.ClientContext.get_current();
var siteColl = clientContext.get_site();
var oList = siteColl.get_rootWeb().get_lists().getByTitle('ChangeEditForm');
var itemId = _spGetQueryParam('id') ;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' +
    '<Value Type=\'Number\'>'+ itemId +'</Value></Eq></Where></Query></View>');
 this.collListItem= oList.getItems(camlQuery);
 clientContext.load(collListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this,this.onCheckCreatedBySuccessMethod), Function.createDelegate(this, this.onCheckCreatedByFailureMethod));
return this.value;
    }
function onCheckCreatedBySuccessMethod(sender, args)
{
var CreatedBy = '';

var listItemEnumerator = collListItem.getEnumerator();

while (listItemEnumerator.moveNext()) {
    var oListItem = listItemEnumerator.get_current();
    CreatedBy =  oListItem.get_item('Author').get_lookupValue();
      alert(CreatedBy);
      return CreatedBy ;
}
}
function onCheckCreatedByFailureMethod(sender, args)
{
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

function GetCurrentUser()
{
var ClientContext = new  SP.ClientContext.get_current();
this.CurrentWeb = ClientContext.get_web();
ClientContext.load(this.CurrentWeb.get_currentUser());
ClientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
  return this.value;
  }
   function onSuccessMethod(sender, args)
{
   var userObject =this.CurrentWeb.get_currentUser().get_title();
    return userObject;
}
function onFailureMethod(sender, args) {
    alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</code>
It can also be done using XSL. This will help you with the same.
I hope this helps.


Problem with knit Markdown file and pandoc

Question: I am trying to knit my R Markdown file.

Error running filter C:\Users\Админ\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua:
cannot open C:\Users\Админ\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua: No such file or directory
Error: pandoc document conversion failed with error 83
Execution halted

RStudio and rmarkdown are installed and updated to lastest versions.
The file rmarkdown\rmarkdown\lua\pagebreak.lua exists, I checked.
No idea why it happens.
Answer: I have similar issue and solved by setup coding saving encoding to UTF8.

The issue is related to your folder with non-english name.

if your operation system is setup to using utf-8. you can change your project level encoding to utf8 by following steps.

menu --> Tools--> project---> code editing --> Text encoding--> utf8

if you has not solve you need check you current Rstuiod encoding
by > sessionInfo()  to the your R session encoding .

if may list.files('target_file_with_fullpath') to see if the file is exists or not. If you can it the target_file_with_fullpaht in your operation system, but not found in your R project session, pls double check sessionInfo() and change it to make sure both are same.

regarding how to change R sessionInfo() environment variable
, it is another topic.
Comment: Thank you very much. Unfortunately, coding saving encoding to UTF8 did not help in solving my problem. However, I changed the username and user in the path to the file 'pagebreak.lua' (English encoding), and it works
Comment: glad to know you solve it. Recently, I have found another way to solve it as well similar to vscode.
1. open file, and reopen it in another encoding   in menu file ---> reopen with encoding...
2. save the opened file in another encoding. in menu file ---> save with encoding

in this way, you can convert the file encoding.


BAPI_SALESORDER_CHANGE throws type exception

Question: I'm having trouble using the FM BAPI_SALESORDER_CHANGE.
As soon as I execute my report, an exception is thrown by the FM. Following is the dump of the exception.
An exception occurred that is explained in detail below.
The exception, which is assigned to class 'CX_SY_DYN_CALL_ILLEGAL_TYPE', was
 not caught and
therefore caused a runtime error.
The reason for the exception is:
The call to the function module "BAPI_SALESORDER_CHANGE" is incorrect:

In the function module interface, you can specify only
fields of a specific type and length under "ORDER_HEADER_IN".
Although the currently specified field
"LS_ORDER_HEADER_IN" is the correct type, its length is incorrect.

Now, I got that LS_ORDER_HEADER_IN's length is incorrect. But what I don't understand is why it is incorrect.
Following is my report's code:
REPORT ztesting.

DATA:
      lv_sales_document   TYPE bapivbeln-vbeln,

      ls_order_header_in  TYPE bapisdhd1,
      lt_order_header_in  TYPE TABLE OF bapisdhd1,

      ls_order_header_inx TYPE bapisdhd1x,
      lt_order_header_inx TYPE TABLE OF bapisdh1x,

      lt_return           TYPE TABLE OF bapiret2,

      ls_order_item_in    TYPE bapisditm,
      lt_order_item_in    TYPE bapisditm OCCURS 0 WITH HEADER LINE,

      ls_order_item_inx   TYPE bapisditmx,
      lt_order_item_inx   TYPE bapisditmx OCCURS 0 WITH HEADER LINE,

      ls_schedule_lines   TYPE bapischdl,
      lt_schedule_lines   TYPE STANDARD TABLE OF bapischdl WITH HEADER LINE,

      ls_schedule_linesx  TYPE bapischdlx,
      lt_schedule_linesx  TYPE STANDARD TABLE OF bapischdlx WITH HEADER LINE,

      ls_return           TYPE bapiret2.

lv_sales_document               = '5999999'.

ls_order_header_inx-updateflag  = 'U'.

ls_order_item_in-itm_number     = '10'.
ls_order_item_inx-itm_number    = 'X'.

ls_order_item_in-material       = '16'.
ls_order_item_inx-material      = 'X'.

ls_order_item_inx-updateflag    = 'U'.

ls_schedule_lines-itm_number    = '10'.
ls_schedule_linesx-itm_number   = 'X'.

ls_schedule_lines-req_qty       = '1000'.
ls_schedule_linesx-req_qty       = 'X'.

ls_schedule_linesx-req_qty    = 'X'.

APPEND:
  ls_order_header_inx TO lt_order_header_inx,
  ls_order_header_in TO lt_order_header_in,
  ls_order_item_in TO lt_order_item_in,
  ls_order_item_inx TO lt_order_item_inx,
  ls_schedule_lines TO lt_schedule_lines,
  ls_schedule_linesx TO lt_schedule_linesx.

CALL FUNCTION 'BAPI_SALESORDER_CHANGE'
  EXPORTING
    salesdocument    = lv_sales_document
    order_header_in  = ls_order_header_in
    order_header_inx = ls_order_header_inx
  TABLES
    return           = lt_return
    order_item_in    = lt_order_item_in
    order_item_inx   = lt_order_item_inx
    schedule_lines   = lt_schedule_lines
    schedule_linesx  = lt_schedule_linesx.

DATA: lt_return2 TYPE TABLE OF bapiret2.
CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'
  EXPORTING
    wait = 'X'.

LOOP AT lt_return INTO ls_return.
  WRITE: / sy-subrc, ls_return-type, ls_return-number, ls_return-id, ls_return-message.
ENDLOOP.

Also, can you spot any other mistakes I've made? It's the first time I'm using this function.
Note: I copied the code from the SAP Forum. I just modified values and variable names.
Thanks in advance.
Regards, Diego.
Comment: It's just a typo in your code. Don't type the names manually, especially when the compiler tells you the type is incorrect, copy and paste them.
Answer: Your types for header are wrong, you need:
  ls_order_header_in TYPE bapisdh1

instead of bapisdhd1, and
  ls_order_header_inx TYPE bapisdh1x

instead of bapisdhd1x. The table types must also match this.
They looks almost similar, but they are not the same, the ones you used are structures for  generic SD document, not SO.


Rewrite query string for exposed taxonomy filter

Question: I have this page: https://www.meubelentheo.be/catalogus
On the top of this page, just below the title you will see links such as Babykamer, Bureau, Decoratie etc.
These are taxonomy terms in an exposed filter. I use the Views module together with Better exposed filter.
If you click on the first term Babykamer, you will see the URL changes to https://www.meubelentheo.be/catalogus?field_portfolio_tags_tid=34
What I want to achieve: rewrite the part after the ? to something like ?term=babykamer or even better, rewrite the whole querystring to catalogus/babykamer
I tried the Query paramters to URL module and this indeed rewrites the URL to but this is not what I want. I want the taxonomy term name to be shown in the URL.
Any ideas?
Comment: Are you using pathauto, maybe? See [this](http://drupal.stackexchange.com/questions/125764/accessing-all-taxonomy-terms-from-one-specific-vocabulary-through-url).
Answer: You can accomplish this look by using Contextual Filters instead of an exposed filter in Views. But this approach will involve several changes. In a nutshell you would need to:

The list of tags on top would need to be a different (taxonomy) Views, embedded in the Header area of your catalogus View using Global: View area. In the taxonomy view, you will need to rewrite the output of the Taxonomy field (use "Rewrite results" in the taxonomy field) to a link that points to /catalogus/[field_portfolio_tags]
Add a Contextual Filter to your catalogus View. Be sure to add the taxonomy field Portfolio tags to the list of fields in this View (you can hide it if you don't want it to display for every single product). Choose the taxonomy Content: Portfolio tags. Choose Display all results in When filter value is not in URL. In WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED  choose Specify validation criteria. Validator: taxonomy term. Filter value type: term name converted to Term Id.

When you click on a taxonomy term in the embedded header View you will be redirected to /catalogus/name_of_tag. The Contextual Filter will assure that only products with that tag will be shown.
This should be it!
Answer: The use case "Filter my view results with the Term Name in my url" we are discussing here can easily be achieved with "Contextual filter by term ID" + the very old, stable and light "URL alias" feature. Easier and faster.
Please do note also on Drupal 8  this is even more complicated (follow on Druapl.org)
Url alias will make you work easier on both D8 and D7


Presentation of simple group of order 168

Question: I am working on finding the automorphism groups of all small groups. So far I am up to the automorphism group of Z(2)^3. I know that it is the simple group of order 168, but I can't find a presentation of it anywhere. Can anyone help?
Comment: It's generated by an element $x$ of order 2 and and an element $y$ of order $3$ whose product $z$ has order 7, but there are more relations necessary. The elements $x$ and $y$ are as unique as they could be (you can only conjugate them (simultaneously) by elements of $\langle z \rangle$). The group you are looking at is of course the group of invertible $ 3 \times 3$ matrices over the field of $2$ elements.
Answer: Geoff Robinson is on the money, and you only need one more relation:
$$ \langle x,y\ |\ x^2=y^3=(xy)^7=[x,y]^4=1 \rangle.$$


Debugger warning from IPython: frozen modules

Question: I created a new environment using conda and wanted to add it to jupyter-lab. I got a warning about frozen modules? (shown below)
$ ipython kernel install --user --name=testi2
0.00s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
Installed kernelspec testi2 in /home/michael/.local/share/jupyter/kernels/testi2

All I had installed were ipykernel, ipython, ipywidgets, jupyterlab_widgets, ipympl
Python Version 3.11.0, Conda version 22.11.0
And I used conda install nodejs -c conda-forge --repodata-fn=repodata.json to get the latest version of nodejs
I also tried re-installing ipykernel to a previous version (6.20.1 -> 6.19.2)
Answer: This is just a warning that the debugger cannot debug frozen modules.

In Python 3.11, the core modules essential for Python startup are "frozen". ... This reduces the steps in module execution process ... Interpreter startup is now 10-15% faster in Python 3.11. This has a big impact for short-running programs using Python.

— What's New In Python 3.11 § Faster Startup

it's not possible for the debugger to debug frozen modules as the filename is definitely required to hit breakpoints

— https://github.com/fabioz/PyDev.Debugger/issues/213#issuecomment-1058247166
E.g. os.path.realpath.__code__.co_filename is now '<frozen posixpath>' in Python 3.11.

The possible resolutions are mentioned with the warning.

If you need to debug those modules, pass -Xfrozen_modules=off to python:
# ipython kernel install --user --name=testi2
python -Xfrozen_modules=off -m ipykernel install --user --name=testi2

# jupyter-lab
python -Xfrozen_modules=off -m jupyterlab

If you just want to suppress the warning, set PYDEVD_DISABLE_FILE_VALIDATION=1:
PYDEVD_DISABLE_FILE_VALIDATION=1 ipython kernel install --user --name=testi2

PYDEVD_DISABLE_FILE_VALIDATION=1 jupyter-lab

Comment: why would there need to be any debugging of modules when adding a conda virtual environment to jupyter lab?
Comment: Related to this: a follow-up question [here](https://stackoverflow.com/q/76149677/8508004) about where to put `PYDEVD_DISABLE_FILE_VALIDATION=1 jupyter-lab`. I'm just tagging this with a temporary comment in the hopes those knowledgeable may see the new post. New poster cannot comment yet.
Comment: There is no need to. The validation is run at import time: ipkernel.py `from .debugger import ...` → `from debugpy.server import ...` → `import debugpy._vendored.force_pydevd` → `preimport('pydevd', [..., 'pydevd',])` → `import pydevd_file_utils` → filename validation.
Answer: The main problem i noticed with this is that when you try to run python on visual studio without without a py extension you're most likely to run into an issue like this
and Finally make sure python path is added to Environment Variable . I have done this and its working fine . I am Using Visual studio.
Path is always found here on Windows
C:\Users\NEW\AppData\Local\Programs\Python\Python311


Validation of checkboxes with the same name

Question: I need to show an error if none of the below checkboxes are checked using using JavaScript.

  Status

    <input type="checkbox" name="chk_stat[]" value="single" id="chk_stat">single

    <input type="checkbox" name="chk_stat[]" value="married" id="chk_stat">Married

    <input type="checkbox" name="chk_stat[]" value="divorcee" id="chk_stat">Divorcee

    <input type="checkbox" name="chk_stat[]" value="student" id="chk_stat">Student

Comment: `var anychecked = $('input[name="chk_stat[]"]').is(':checked')`
Comment: Anyway this should be re-opened because the other Q&A isn't using vanilla JS...
Comment: @ArunPJohny what should be the next line?
Comment: @DewDrop sorry, missed that there is no jQuery tag
Comment: @ArunPJohny : how can check and where should i write error msg after var anychecked = $('input[name="chk_stat[]"]').is(':checked')
Answer: You can implement it using selecting all elements with some given name using document.querySelectorAll and an attribute selector using the pseudoclass :checked:

var checkedCheckboxes = document.querySelectorAll("[name='chk_stat[]']:checked");

if (checkedCheckboxes.length == 0) {
  console.log("No checkbox is checked...");
}

  Status

    <input type="checkbox" name="chk_stat[]" value="single" id="chk_stat">single

    <input type="checkbox" name="chk_stat[]" value="married" id="chk_stat">Married

    <input type="checkbox" name="chk_stat[]" value="divorcee" id="chk_stat">Divorcee

    <input type="checkbox" name="chk_stat[]" value="student" id="chk_stat">Student

Comment: Thank you so much for your help