How to make flexbox items move when growing a div (on hover)

Question: So I expected the icons to move to keep the gap the same when an icon grows on hover, but as it appears transform does not work with flexbox. What should i do to implement this feature? I can code in React if its needed.
Expected flexbox items to move to keep spacing the same.
Items did not change position

:root {
  --bg-color: rgb(20, 20, 20);
}

body {
  align-items: center;
  background-color: var(--bg-color);
  display: flex;
  height: 100vh;
  justify-content: center;
  margin: 0px;
  padding: 0px;
}

#icons {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% -20px);
  gap: 70px;
  max-width: 1500px;
  white-space: nowrap
}

.icon {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  cursor: pointer;
  height: 150px;
  width: 150px;
  transition: transform 400ms cubic-bezier(.05, .43, .25, .95);
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 20px;
}

#icons .icon:hover {
  transform: scale(1.5);
}

#icons .icon:not(:hover) {
  flex-grow: 1;
}

Comment: Transform does not alter the space taken up by the element, it just alters it visually.
Answer: I am not sure if I completely understood your question but from what I read I think you want to grow the image but keep the gap between the icons the same. It does not matter if you are using the flexboxes or not. You can add overflow: hidden on the image wrapper and instead of scaling the wrapper scale up the image inside the wrapper. Hope this helps.

:root {
  --bg-color: rgb(20, 20, 20);
}

body {
  align-items: center;
  background-color: var(--bg-color);
  display: flex;
  height: 100vh;
  justify-content: center;
  margin: 0px;
  padding: 0px;
}

#icons {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% -20px);
  gap: 70px;
  max-width: 1500px;
  white-space: nowrap
}

.icon {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  cursor: pointer;
  height: 150px;
  width: 150px;
  transition: transform 400ms cubic-bezier(.05, .43, .25, .95);
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 20px;
  transition: all 0.5s;
}

#icons .icon:hover img {
  transform: scale(1.3);
}

#icons .icon:not(:hover) {
  flex-grow: 1;
}

Answer: Instead of using the transform property, I think you'll need to declare specific dimensions with width and height.
#icons .icon:hover {
  /* transform: scale(1.5); */
  width: 225px;
  height: 225px;
}

You'll also likely want to declare align-items: center for the Flexbox container.
Additionally, your width calculation is invalid (and therefore ignored) because there is not a space after the minus - character. Instead of "100 percent minus 20 pixels", you have "100 percent negative 20 pixels". However, "100% - 20px" will introduce other issues, so I won't use it in my answer.
#icons {
  align-items: center;
  width: calc(100% - 20px);
}

:root {
  --bg-color: rgb(20, 20, 20);
}

body {
  align-items: center;
  background-color: var(--bg-color);
  display: flex;
  height: 100vh;
  justify-content: center;
  margin: 0px;
  padding: 0px;
}

#icons {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: calc(100% -20px); /* invalid */
  gap: 70px;
  max-width: 1500px;
  white-space: nowrap
}

.icon {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  cursor: pointer;
  height: 150px;
  width: 150px;
  transition: transform 400ms cubic-bezier(.05, .43, .25, .95);
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 20px;
}

#icons .icon:hover {
  /* transform: scale(1.5); */
  width: 225px;
  height: 225px;
}

#icons .icon:not(:hover) {
  flex-grow: 1;
}

Answer: The problem is that transform only changes things visually, not size wise.
So this snippet alters the actual width and height on hover and transitions them.
It also translates the image upwards by half the difference in height but you will have to decide whether that is the effect you want if there are multiple lines of images as it won't move the rows above and below.

:root {
  --bg-color: rgb(20, 20, 20);
}

body {
  align-items: center;
  background-color: var(--bg-color);
  display: flex;
  height: 100vh;
  justify-content: center;
  margin: 0px;
  padding: 0px;
}

#icons {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% -20px);
  gap: 70px;
  max-width: 1500px;
  white-space: nowrap
}

.icon {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  cursor: pointer;
  height: 150px;
  width: 150px;
  transition: all 400ms cubic-bezier(.05, .43, .25, .95);
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 20px;
}

#icons .icon:hover {
  Rtransform: scale(1.5);
  width: 225px;
  height: 225px;
  transform: translateY(-37.5px);
}

#icons .icon:not(:hover) {
  flex-grow: 1;
}


ZeroConf -- should I include dot(.) in the end of the address?

Question: I'm trying to access my machine through ZeroConf. Which address is correct?
machine.local or machine.local. ?
Answer: machine.local. is the recommended and "correct" way.
The final dot makes it an absolute fully qualified host name [just like in Unix when the leading slash (/) makes a path an absolute path].
Without that final dot the host name will become relative to the DNS search domain(s).
Example:

Your DNS search domains contains apple.com as well as microsoft.com.
You look for a host name machine.local.
The resulting list of found names could be machine.local. as well as machine.local.apple.com. and machine.local.microsoft.com. (assuming that within Apple's and Microsoft's domains there are sub-domains local with hostnames machine, which may be not-so likely. Maybe I should think of better examples...)

See also here: Trailing Dots in Domain Names.


Translate an english sentence to first order logic

Question: Here's an English statement -

Politicians can't fool all of the people all of the time.
(x for all things, P(x) x is a person, Q(x) x is a politician, T(x) x is a time and F(x, y, z) x can fool y at t).

I believe this statement seems ambiguous as it is not clear whether
Politicians can't fool all the people all the time
or
Politicians can't fool all of the people all of the time.
Am I correct? BTW, the original question had two more statements similar to the above one and a note at the end reading "One of the above may be ambiguous").
Comment: The context is a quote from [A.Lincoln](http://www.brainyquote.com/quotes/quotes/a/abrahamlin110340.html) : "You can fool all the people some of the time, and some of the people all the time, but you cannot fool all the people all the time." Thus, I do not see any ambiguity...
Comment: The amobiguous sentence is likely another one, about fooling some people all the time. At least I'm unsure what your italicazation is supposed to differentiate. Cf. the joke "This newspaper says that every twenty minutes a man gets run over by a car" - "What a poor fellow that guy is"
Comment: @MauroALLEGRANZA Doesn't that mean "Every politician CAN fool all people all of the time."?
Comment: I meant to say both the sentences are the same, I'm unsure about the scope of "can't fool", as to whether he "can't fool all people" or that he "can't fool all the people all the time"?
Comment: On the other hand, there is a difference between "I can fool A and I can fool B" vs. "I can fool A and B". Cf., if I you replace "fool" with "visit tomorrow" and A,B with Helsinki and Melbourne. I may be able to visit any of the two cities, but not both on the same day.
Answer: It seems to me that we have to translate :

Politicians can't fool all of the people all of the time

as follows :
$\forall x[Q(x) \rightarrow \lnot \forall y \forall z ((P(y) \land T(z)) \rightarrow F(x,y,z))]$
i.e.
$\forall x[Q(x) \rightarrow \exists y \exists z \lnot ((P(y) \land T(z)) \rightarrow F(x,y,z))]$.
Using the equivalence between : $\lnot (p \rightarrow q)$ and $(p \land \lnot q)$, we can rewrite it as :

$\forall x[Q(x) \rightarrow \exists y \exists z (P(y) \land T(z) \land \lnot F(x,y,z))]$

or in prenex form :

$\forall x \exists y \exists z[Q(x) \rightarrow  (P(y) \land T(z) \land \lnot F(x,y,z))]$.


How to get real time frames per second from video file using MPMoviePlayerController without viewing video?

Question: I want to show frames per second of videos which will be played on iPhone. I have stored all videos locally, and accessing them using MPMoviePlayerController.
Is there any simple function or any custom class available for MPMoviePlayerController, which can give me fps.
Thanks in advance.
Answer: No, there is no function within MPMoviePlayerController that reports the preferred FramePerSecond of the content.
You will have to go a little deeper and use AVFoundation.
See AVAssetTrack's property nominalFrameRate.

From the AVAssetTrack Class Reference:
nominalFrameRate

The frame rate of the track, in frames per second. (read-only)
@property(nonatomic, readonly) float nominalFrameRate

Comment: MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];    UIImage *image1 = [movie thumbnailImageAtTime:0 timeOption:MPMovieTimeOptionExact];
    UIImage *image2 = [movie thumbnailImageAtTime:2 timeOption:MPMovieTimeOptionExact]; You can also put float values to get frames in less than a second
Comment: @user731077 How is that connected to getting the **framerate** of a video?
Comment: @user91282 i am not talking about the frame rates this time. i just want to know that how can i get the common part in two different images.


React table with django namedtuple returns .map is not a function

Question: I want to make a table of with django namedtuple but getting an error. Headers(which is list) works fine though.
views.py:
info = [Info(id=5, location_id=861, f=None),Info(id=3, location_id=650, f=None)]
return render('index.html', {'info': info})

index.html
var headers = ['id', 'location', 'f']

var Table = React.createClass({
    render: function() {
        return (

                {this.props.headers.map(function(name, index) {
                    return {name}	;
                })};
                {this.props.tableContent.map(function(row, index) {

                        return(
                            {row.map(function(col, i) {
                                {col}
                            })}
                        );

                })};

        )
    }
});

ReactDOM.render(

,
    document.getElementById('content')
);

I can't see any output and the console says: Uncaught TypeError: this.props.tableContent.map is not a function.
Answer: I forgot to put safe when receiving the data. To someone who might encounter this problem too. Please refer to this question too


The third covariant of a tensor in Riemannian manifolds

Question: I'm reading Petersen's book "Riemannian Geometry 3rd", No.171 in GTM. On page 82, there's a formula reads:
$$\nabla^3_{X,Y,Z}W=\nabla^2_{X,Y}(\nabla_ZW)-\nabla_{\nabla^2_{XY}Z}W$$
I'm quite puzzled with this formula. On the right hand site, it doesn't seem to be tensorial in the "Z" position. Is this formula false?
Comment: Doesn't look hopeless to me. You should check $C^{\infty}$ linearity explicitly; it looks highly likely that the ugly terms you get by expanding this whole thing would cancel each other out because if you multiply $Z$ by a function $f$ you'll have double covariant derivative acting on $f$ on both terms (one is positive, the other is negative); hence it's very likely they cancel out. My suggestion is that you do the calculation explicitly and see where you get.
Comment: Have you tried checking the tensoriality of the corresponding formula for the second covariant tensor of a connection?
Answer: Yeah I don't think that formula works as written; there are some missing terms.
The good news is that the omitted terms don't matter in context. The purpose of the formula in the context of the book was to compute the difference $\nabla^3_{X,Y,Z} W - \nabla^3_{Y,X,Z} W$. The omitted terms are symmetric in $X$ and $Y$, so they cancel out.

The rest of this answer is just the details. My claim is that:
$$
  \nabla^2_{X,Y}(\nabla_Z W)
  = \nabla^3_{X,Y,Z} W
    + \nabla_{\nabla^2_{X,Y} Z} W
    + \nabla^2_{X,\nabla_Y Z} W
    + \nabla^2_{Y,\nabla_X Z} W
$$
Note the last two terms, which didn't appear in the original formula.
I'll do the computation in index notation, but I'm sure you can do it at home in whatever notation you prefer. We can translate $\nabla^2_{X,Y}(\nabla_Z W)$ to index notation and expand using the product rule twice:
\begin{align}
  & X^i Y^j \nabla_i \nabla_j (Z^k \nabla_k W^\ell) \\
  &= X^i Y^j \nabla_i (
    \nabla_j Z^k \nabla_k W^\ell
    + Z^k \nabla_j \nabla_k W^\ell
    ) \\
  &= X^i Y^j (
    \nabla_i \nabla_j Z^k \nabla_k W^\ell
    + \nabla_j Z^k \nabla_i \nabla_k W^\ell
    + \nabla_i Z^k \nabla_j \nabla_k W^\ell
    + Z^k \nabla_i \nabla_j \nabla_k W^\ell
    )
  \end{align}
In this, the first term is $\nabla_{\nabla^2_{X,Y} Z} W$, the second term is $\nabla^2_{X,\nabla_Y Z} W$, the third term is $\nabla^2_{Y,\nabla_X Z} W$, and the last term is $\nabla^3_{X,Y,Z} W$.


How to calculate the general formula for nth term of this recursion?

Question: I'm trying to solve the general formula for nth term:
$a_n = a_{n-1} + 2^{-a_{n-1}}, a_0 = 0$.
And want to if there exists $f(n)$, s.t. $lim_{n\rightarrow \infty}a_n = f(n)$.

First, I've tried to see what do first terms look like:
$a_0 = 0$
$a_1 = 1$
$a_2 = 1.50000000000000$
$a_3 = 1.85355339059327$
$a_4 = 2.13026337562636$
$a_5 = 2.35867953516332$
But I can't find any clue.

Then I tried to directly write down the general formula
$a_1 = 2^{-a_0}$
$a_2 = 2^{-a_0} + (2)^{2^{-a_0}}$
$a_3 = 2^{-a_0} + (2)^{2^{-a_0}} + (2)^{(2)^{2^{-a_0}}}$
In this way, I can definitely write down the general formula in a very silly way. However, I can't see what $f(n)$ would $a_n$ goes to as $n\rightarrow \infty$.

Apparently, it's not arithmetic or geometric sequence. And I don't think the method of characteristic functions would help.
Any hint or detailed steps would be appreciated!
Comment: It doesn't change much, but it should be $a_3 = 2^{-a_0} + (2)^{-2^{-a_0}} + (2)^{-(2^{-a_0} + (2)^{-2^{-a_0}})}$
Answer: (I think I recently answered a similar question.
Oh well,
here I go again.)
If
$a_n = a_{n-1} + c^{-a_{n-1}}, a_0 = 0
$
where $c > 1$,
my conjecture is that
$a_n
\sim \dfrac{\ln(u)}{u}+\dfrac{\ln(n)}{u}
$
where
$u = \ln(c)
$.
I will first show that the
$a_n$ are unbounded.
If the $a_n$ are bounded,
say $a_n < M$,
then
$a_n
= a_{n-1} + 2^{-a_{n-1}}
\gt a_{n-1} + 2^{-M}
$
or
$a_n - a_{n-1}
\gt 2^{-M}
$.
Summing this,
$a_m-a_0
=\sum_{n=1}^m(a_n - a_{n-1})
\gt m2^{-M}
$
which is a contradiction
for large enough $m$.
If $a_n \sim f(n)$,
then
$f'(n)
\sim c^{-f(n)}
= u^{-uf(n)}
$
where $u = \ln c$.
Then
$f''(n)
=(-uf'(n))e^{-uf(n)}
=(-uf'(n))f'(n)
=-uf'^2(n)
$.
Letting $g = f'$,
then
$g' = -ug^2$
so
$\dfrac{-g'}{g^2}
=u
$
or
$(1/g)' = u
$
or
$1/g = dn+r$
or
$g = \dfrac1{dn+r}$.
Therefore
$f'(n) = \dfrac1{un+r}$
so
$\begin{array}\\
f(n)
&= \int \dfrac{dn}{un+r}\\
&=\frac1{u}\ln(un+r)\\
&=\frac1{u}(\ln(u)+\ln(n+r/u))\\
&=\frac{\ln(u)}{u}+\frac1{u}\ln(n+r/u)\\
\end{array}
$
For simplicity's sake
I will assume that $r = 0$.
Then
$\begin{array}\\
f(n)
&=\frac{\ln(u)}{u}+\frac1{u}\ln(n)\\
\text{so}\\
f(n+1)
&=\frac{\ln(u)}{u}+\frac1{u}\ln(n+1)\\
&=\frac{\ln(u)}{u}+\frac1{u}(\ln(n)+\ln(1+1/n))\\
&\sim\frac{\ln(u)}{u}+\frac1{u}(\ln(n)+\frac1{n}+O(\frac1{n^2}))\\
&=f(n)+\frac1{u}(\frac1{n}+O(\frac1{n^2}))\\
&=f(n)+\frac1{un}+O(\frac1{n^2})\\
\end{array}
$
So we want
$\begin{array}\\
\frac1{un}
&\sim c^{-(\ln(u)/u+\ln(n)/u)}\\
&\sim e^{\ln(c)(-\ln(u)/u-\ln(n)/u)}\\
&\sim e^{u(-\ln(u)/u-\ln(n)/u)}\\
&\sim e^{-\ln(u)-\ln(n))}\\
&\sim e^{-\ln(un)}\\
&=\frac1{un}\\
\end{array}
$
So it works.
Comment: I think there is a typo on 6th line. Should be $f'(n) \sim c^{-f(n)} = e^{-uf(n)}$
Comment: It works very well !
Comment: Thanks! This perfectly solved my problem!
Comment: Fortunately, that typo didn't affect anything following.
Answer: It will not converge.  If it converged to a limit $L$, it would solve $$L=L+2^{-L}$$
which has no solution.
Comment: Thanks! I see why it's not convergent. However, I still want to see how big is $a_n$, i.e. to find it's upper bound or lower bound if they exist. It seems $log_2(n)$ is an upper bound. Do you have any advice on finding a good upper/lower bound?
Comment: It is monotonically increasing, so there can't be an upper bound.  If there were it would converge.  It goes off to infinity
Answer: $$a_n=a_{n-1}+\frac{1}{2^{a_{n-1}}}$$
Note that the difference between $a_n$ and $a_{n-1}$ is given in terms of $a_{n-1}$...
$$a_n-a_{n-1}=\frac{1}{2^{a_{n-1}}}$$
Shift the indices by $1$, and you have a difference equation...
$$\Delta a(n)=\frac{1}{2^{a(n)}}$$
...with initial condition $a(0)=0$.
I know nothing about solving difference equations, but from what you have written and the result I got when I put this into Wolfram Alpha, it has no closed-form solution. (If it does have a closed form solution, it will probably be in terms of the natural logarithm, but again, this is not my area of expertise)


Show that no two of the spaces $(0,1), \ (0, 1], \ [0,1]$ are homeomorphic.

Question: I want to show that no two of the spaces $(0,1), \ (0, 1], \ [0,1]$ are homeomorphic, with the hint: what happens if you remove a point from each one of these spaces.
No idea where to begin, except that it concludes a chapter on connectedness.
All these spaces are all in the subspace topology of the usual topology on $\mathbb{R}$.
Edit
(Thanks @Chris Culter)
So far what I've got is:
Let $A = (0,1] - \{1\}$.  If $f:(0,1] \rightarrow (0,1)$ is a homeomorphism, then $f$ restricted to $A$ is a homeorphism onto a subset of $(0,1)$ with one and only one point removed.  But any removal of a point in $(0,1)$ results in a disconnected space, while at the same time $f_A$ ensures that the space is connected, it being a continuous image of a connected space $A$.  Therefore there is no continuous bijective map between the two spaces let alone a homeomorphism.  A similar agument shows that $[0,1]$ and $(0,1)$ are not homeomorphic.
I can't seem to show that $(0,1]$ and $[0,1]$ are not homeomorphic using this method though.
Comment: No, there wasn't. The answer that you accepted is all about cut-points; it just didn't use that term.
Comment: Yes, but I have an answer below checked that doesn't mention cut-points, so obviously there was some stuff left unsaid.
Comment: They have non-isomorphic orders. The topology is the order topology.
Answer: All of them have a different number of non-cut-points, i.e. points that you can remove without disconnecting the set.
Answer: Well, following the hint: if you remove a point from $(0,1)$, is the remaining space connected?
Comment: Okay so if I remove a point from $(0,1]$, namely $1$ then the remaining space is connected but no point can be removed from $(0,1)$ and make the remaining space connected.  But how do I prove that that's a necessary homeomorphism-invariant property?
Comment: Connectedness is defined in terms of the topology of a space, so you could just say that it's "manifestly homeomorphism-invariant". Or, go ahead and prove that any space homeomorphic to a connected space is also connected.
Comment: Please see my edit above.  Thanks for your help!


Show that the smallest sigma field of the subsets of $A$ containing the sets open in $A$.

Question:
If $A$ be a Borel subset of $\mathbb{R}$,show that the smallest sigma field of the subsets of $A$ containing the sets open in $A$ is $\{B \in B_{\mathbb{R}}: B \subset A\}$ .

I was taking $C = \{\text{all open sets in }A\}$.
We need to show $\sigma(C)= \{B \in B_{\mathbb{R}}: B \subset A\}$ .
I think we might need the principle of good sets here.
Any leads?
Answer: Let $\mathcal A$ be the sigma algebra generated by open sets in $A$ and $\mathcal C$ be the class $\{B\in B_{\mathbb R}: B \subset A\}$. We have to show that $\mathcal A=\mathcal C$. First verify that $\mathcal C$ is  a sigma algebra of subsets of $A$. This is straightforward. Next observe that any open set in $A$ is of the form $A \cap U$ where $U$ is open in $\mathbb R$. Celarly. $A\cap U$ is a Borel set in $\mathbb R$ contained in $A$, so it belongs to $\mathcal C$. This proves that $\mathcal A \subset \mathcal C$.
For the reverse inclusion consider $\{E\in B_{\mathbb R}: E \cap A \in \mathcal A\}$. Verify that this is  a sigma algebra containing all open sets in $\mathbb R$. Hence it contains all Borel sets. In partcicular we have proved that any Borel set in $\mathbb R$ already contained in $A$ belongs to $\mathcal A$.
Comment: @LegendKiller If $B_n \in \mathcal C$ for all $n$ then $\cup B_n$ is a Borel set in $\mathbb R$ contained in $A$ so it belongs to$\mathcal C$. If $B \in \mathcal C$  then the complement of $B$ **in** A is $A\setminus B=A\cap B^{c}$ which is a Borel set  in $\mathbb R$ contained in $A$ .Remember to take the complement in $A$, not in $\mathbb R$.
Comment: Yes I could not prove $\mathcal{C}$ to be a sigma field. How can I prove that?
Comment: Ok I think you have written $\mathcal{C}=${$E \in B_{\mathbb{R}}:E \cap A \in \mathcal{A}$}.How can you write this?
Comment: I did not assume that $\mathcal C$ is equal to this class. I just said consider this class , verify that it is  a sigma algebra containing open sets. Then conclude that it contains all Borel sets. Finally we conclude that if $B$ is  a Borel set in $\mathbb R$ then $B \cap A$ belongs to $\mathcal A$. @LegendKiller


Mudar dado dentro de atributo data

Question: Tenho uma página, onde possui um timer.
Ou seja, quando a página é aberta, após 40 segundos, uma section do site é carregada. Isso acontece devido a um serviço de terceiros, não consigo manipular esse tipo de informação.
Mas gostaria de manipular isso no meu navegador.
Por exemplo, ao carregar a página, o atributo recebe o valor 800.
data-delay-duration="800"

Eu gostaria de mudar isso. Não consigo fazer isso diretamente no site, pois como comentei, isso é um serviço de terceiro.
Eu instalei o Tampermonkey para Google Chrome, acho que pode haver essa possibilidade. Mas, gostaria de saber como fazer isso.
Seria algo com o attr do JQuery?
Answer: Se o navegador não tiver suporte ao .dataset então pode usar .setAttribute para trocar o valor e .getAttribute para obter ele, assim:

var teste = document.getElementById('teste');
teste.setAttribute("data-delay-duration", "100");

console.log("data-delay-duration:", teste.getAttribute("data-delay-duration"));
console.log("source:", document.body.innerHTML);

Só pra constar, apesar do caniuse afirmar que IE8, 9 e 10 tem suporte parcial ao dataset e data- em https://caniuse.com/#feat=dataset, na verdade eles se referem ao uso de getAttribute mesmo, ou seja .dataset não esta disponível, conforme a mensagem deles:

Partial support refers to being able to use data-* attributes and access them using getAttribute.

Então se necessitar de um destes navegadores terá que usar o.setAttribute.
Se for para aplicar para multiplos elementos, como um NodeList, pode usar qualquer método para isto (dependendo dos elementos), como alguns exemplos:

document.getElementsByTagName
document.getElementsByName
document.querySelectorAll

Creio que o querySelectorAll é o mais simples de usar, assim:

var els = document.querySelectorAll('.foo, .baz');

for (var i = 0, j = els.length; i < j; ++i) {
    els[i].setAttribute("data-delay-duration", "100");
}

console.log("source:", document.body.innerHTML);

Veja que nesse exemplo somente elementos com class=foo e class=baz tem o valor trocado
Nota: para checar se o DOM já carregou você pode executar o script assim:
(function () { //Isola o escopo para evitar conflito com outras funções e vars

    function trigger() {
        var els = document.querySelectorAll('.foo, .baz');

        for (var i = 0, j = els.length; i < j; ++i) {
            els[i].setAttribute("data-delay-duration", "100");
        }
    }

    if (document.readyState !== "loading") {
        trigger();
    } else {
        document.addEventListener("DOMContentLoaded", trigger);
    }
})();

Comment: Verdade Guilherme, tem que ter suporte do navegador, acabei não colocando na minha resposta.
Comment: Muito obrigado. Na verdade, esse *data-delay-duration* aparece mais de uma vez no site. Não da para usar ID por isso. Além de ser um serviço de terceiro onde eu não consigo manipular isso.
Comment: @FelipeGoulart o ID é apenas exemplo, vou formular um com NodeList, um instante
Comment: @GuilhermeNascimento um exemplo de quantas vezes esse atributo aparece no site https://jsfiddle.net/ujhpawoe/1/
Comment: @FelipeGoulart veja a edição da resposta.
Comment: @GuilhermeNascimento Entendi o seu código. O engraçado é que ele não executa o Tampermonkey
Comment: @FelipeGoulart qual erro aparece no console?
Comment: @GuilhermeNascimento não aparece nenhuma erro referente ao atributo. O estranho é que o Tampermonkey está ativado. O *data-delay-replace* continua igual. O código está assim https://jsfiddle.net/a0k32fmj/ O link seria esse https://lp.luzdaserra.com.br/Iniciados-mensal
Comment: @FelipeGoulart veja a edição da resposta.
Comment: @GuilhermeNascimento infelizmente não funcionou. Mas, deve ser algum problema no Tampermonkey.
Answer: Se for com Vanilla dá para fazer assim:

var teste = document.getElementById('teste');
teste.dataset.delayDuration = 100;

console.log(teste.dataset.delayDuration);

Comment: Algo importante a ser comentado: ao fazer `delayduration = 100` você criou outro atributo. O JavaScript diferencia maiúsculas de minúsculas e, no `dataset`, o atributo `data-delay-duration` será `dataset.delayDuration`, com o d em *Duration* maiúsculo.
Comment: Verdade Anderson, foi eu que escrevi errado mesmo.
Answer: Crie este script no tampermonkey e troque #teste pelo id que você for usar e o respectivo valor na linha $('#teste').attr("data-delay-duration","400");.
// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://stackoverflow.com/questions/10166478/how-to-change-the-value-of-a-custom-attribute
// @grant        none
// ==/UserScript==

// @require http://code.jquery.com/jquery-2.2.4.min.js

var $ = window.jQuery;

(function() {
    'use strict';
    console.log($('#teste').attr("data-delay-duration"));
    $('#teste').attr("data-delay-duration","400");
    console.log($('#teste').attr("data-delay-duration"));
    // Your code here...
})();

Comment: Poderia adicionar uma explicação do que o seu código está fazendo? Sim, fui eu que negativei. Estou dando o feedback, para você não ficar sem saber o que houve.
Comment: Errado, jovem. Não é qualquer programador [em qualquer nível] que entendo o código só de olhar. Sempre é bom ter uma explicação. Pessoas que estão aprendendo a programar também acessam o site.
Comment: Bom... Usando o tampermonkey e jQuery, a resposta é basicamente a linha `$('#teste').attr("data-delay-duration","400");`, que seta o atributo `data-delay-duration` com o valor `400`. O resto é para poder rodar o exemplo.
Comment: Você precisa adicionar isso à resposta. A ideia do site é que a pergunta e a resposta ajudem, não só quem está com o problema atual, mas outros usuários que vierem aqui no futuro. Sugiro que clique em "editar" e adicione os detalhes à sua resposta. **me comprometo** em remover meu negativo, caso algo melhore na sua resposta.
Comment: Bom... eu editei... mas não concordo com os downvotes, qualquer programador entende o que rolava no post original ;). Segue o baile.
Comment: Como prometi, meu downvote foi removido.
Comment: Agora observe a resposta com 0 votes.... Grande diferença, uma com e outra sem jQuery.... Fui o alvo. hahaha
Comment: Particularmente, eu achei que usar `dataset` foi melhor que usar `attr`, visto que o 'jQuery` também possui um recurso melhor que usar `attr`, que é a função `data`.  Eu comentei o meu voto, e acho isso o mais correto pra saber onde errou e melhorar. É uma pena que outros usuários não façam (o medo de retaliação conta, pois já aconteceu muitas vezes).
Comment: **Cross-browser consistency**: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The `.attr()` method reduces such inconsistencies.

Mas não vou entrar nessa discussão. Você tá certo.
Comment: Caro thxmxx o que tampermonkey (add-on) tem haver com a pergunta? Sua resposta inicial mesmo que sem explicações estava bem melhor que a atual https://pt.stackoverflow.com/revisions/322354/1 -- recomendo que volte a primeira e apenas explique o código da outra.

Mudar dado dentro de atributo data


Using a pipe character as a delimiter, but getting an invalid escape sequence error on it?

Question: I'm not certain why I'm getting an "invalid escape sequence" error for using "\|", since it's supposed to make it just a | character? I'm attempting to read in a file, where values are separated by a | character, and for some reason it's giving me a very odd output. I have a text file:
Star Trek|Sci-fi|Sy-fy|48|is
Word Girl|Children's|PBS Kids|21|is
Firefly|Sci-fi|FOX|50|is
America's Next Top Model|Drama|CNN|51|is not
Being Human|Sci-fi|Sy-fy|48|is not
Black Mirror|Anthology|Channel 4|55|is
Grandma's House|Comedy|BBC Two|26|is
Sherlock|Crime drama|BBC One|55|is
Psych|Comedy-Drama|ION|51|is not
The Big Bang Theory|Sitcom|CBS|23|is not

I would like to go through this text file line by line, and then pass it through a TV shows class, which is as follows:
public class TVShows {

    private String showName;
    private String genre;
    private String network;
    private String favourite;
    private String runningTime;

    public TVShows(String showName, String genre, String network, String favourite, String runningTime){
        this.genre = genre;
        this.showName = showName;
        this.network = network;
        this.runningTime = runningTime;
        this.favourite = favourite;
    }

    public String toString(){
        return showName + ", on " + network + ", a " + genre + " show with a running time of " + runningTime + " minutes. This "
                + favourite + " a favourite.";
    }

}

It's all very simple, but for some reason, when I implement it in the driver, which is here:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Driver {

    public static void main(String[] args) throws FileNotFoundException {

        File myFile = new File("./src/TVShows.txt");

        Scanner fileScanner = new Scanner(myFile);

        while(fileScanner.hasNextLine())
        {
            TVShows myShows = new TVShows("test","test","test","test","test");
            String line = fileScanner.nextLine();
            System.out.println(fileScanner.nextLine());
            Scanner lineScanner = new Scanner(line);
            lineScanner.useDelimiter("\|");
            while(lineScanner.hasNext())
            {
                System.out.println(lineScanner.next());
                String showName = lineScanner.next();
                String genre = lineScanner.next();
                String network = lineScanner.next();
                String runningTime = lineScanner.next();
                String favourite = lineScanner.next();
                TVShows myShows1 = new TVShows(showName, genre, network, favourite, runningTime);

                System.out.println(myShows1);

            }

        }
    }
}

I get an invalid escape sequence error on "\|". Why is this? Do I just need to put another backslash in? Like "\|"? When I do this, and run the program, I get the output:
ÿþS t a r  T r e k
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at Program3.Driver.main(Driver.java:30)

This is line 30:
String favourite = lineScanner.next();

Thanks for any help.
Comment: Yes, I ran it with two backslashes - it doesn't show up in "Do I just need to put another backslash in? Like "\|"?" For some reason, but I meant like " \ \ | ", and when I run it like that, it gives me the error that I outlined above.
Answer: you should use two backslash in java
lineScanner.useDelimiter("\\|");

Answer: You need two backslashes:
lineScanner.useDelimiter("\\|");

First one is to escape the second one from parsing in the compiler. They together make a single backslash in the string constant that is used to escape the pipe symbol in the regex engine.
Comment: Thank you very much. Do you have any idea why I would still get an error after running it with two backslashes?
Comment: @Sarah, I'm not totally sure as I'm on a mobile device right now and cannot run your code. It is likely an issue where there are no more elements to get when you call next().
Comment: @Sarah, I'm also on a mobile device but @hexafraction would have right. You used `nextLine()` and `next()` into the both of out print.
Comment: @Sarah Your issue is that when you call `println(next())` you are pulling an additional element from the scanner. See my answer.
Answer: This section of code
while(lineScanner.hasNext())
        {
            System.out.println(lineScanner.next());
            String showName = lineScanner.next();
            String genre = lineScanner.next();
            String network = lineScanner.next();
            String runningTime = lineScanner.next();
            String favourite = lineScanner.next();
        }

involves checking hasNext() once, then running next() six times. Therefore, if you have a number of elements not divisible by six, you will inevitably have some n<6 number of elements left, get n elements, then get an error on trying to get the n+1th element.
From your data, I assume you are supposed to have 5 elements, not 6. I'm guessing that your println is disrupting the flow by requesting an extra element. Delete it and add System.out.println(showName); somewhere after you define showName; this should fix your problem.


Ansible: use group_vars directly without with_items

Question: I have defined group_vars to mount nfs shares on numerous hosts based on their environment:
---
mounts:
- path: /home/user1
  src: 10.0.0.1:/home/user1
  fstype: nfs
  state: present
- path: /home/user2
  src: 10.0.0.1:/home/user2
  fstype: nfs
  state: present

In my playbook I have the following task to add those mounts:
---
- hosts: clients
  tasks:
  - name: mounts
    mount:
      path: "{{ item.path }}"
      src: "{{ item.src }}"
      fstype: "{{ item.fstype }}"
      opts: "{{ item.opts }}"
      state: "{{ item.state }}"
    with_items: "{{ mounts }}"

Now I was wondering if there is a shorthand to achieve the same thing? E.g.
---
- hosts: clients
  tasks:
  - name: mounts
    mount: "{{ mounts }}"

Comment: Sure seems like that should work. Did you try it? Perhaps in `--check` mode if you are worried about breaking something?
Comment: Yes, with my example above the error is `"missing required arguments: state, path"`. Which is the same result if I use `mount` with `with_items: "{{ mounts }}"` or `with_list: "{{ mounts }}"` only.
Comment: which version of ansible are you on?
Answer: The module is not capable of making several mounts in a single call, so you will still have to go through each individual mount definition with a loop. But you can set all parameters in one go from your individual dicts.
Before I write the (easy) solution, you should still be warned that setting tasks arguments like this is discouraged in ansible doc because it can be unsafe in some circumstances. This is why you will get a warning when using the code below:
- hosts: clients
  tasks:
    - name: mounts
      mount: "{{ item }}"
      with_items: "{{ mounts }}"


Why is the noetherian ring property not definable in first-order logic?

Question: I am reading this paper on the connection between model theory and algebraic geometry.
https://math.uchicago.edu/~may/REU2015/REUPapers/Zhang,Victor.pdf
On page 9, I have trouble understanding Example 19: it says:

This shows the property of being a noetherian ring is not expressible
as a set of sentences in first-order logic, otherwise $\text{Th}(\mathbb Z)$ would model
such a set and our example model would be a noetherian ring.

I do not know why "otherwise $\text{Th}(\mathbb Z)$ would model
such a set and our example model would be a noetherian ring". May I please ask for a more expanded explanation? Thank you for any help!
Comment: The answer below is spot on! I think there might be a small typo causing you confusion - with my understanding of the terminology, as well as what's stated in Definition 9, it should say ".. otherwise $\Bbb Z$ would model such a set (ie $\mathrm{Th}(\Bbb Z)$ would *contain* such a set) ..", and the idea is $M$ models the same sentences as $\Bbb Z$ (they're "elementarily equivalent"). This is a standard way to show that some property is not axiomatisable. As an aside this isn't the only way to construct such an $M$.. I discuss this a bit [here](https://math.stackexchange.com/a/4790536/473276).
Comment: Thank you for the reference!
Answer: If being a noetherian ring can be expressed as a set of sentences in first-order logic of ring theory, that means, there is a set of first-order sentences $\mathcal S$ (in the language of ring theory), such that a ring $R$ is noetherian iff $\mathcal S\subset \text{Th}(R)$.
If so, then since $\mathbb Z$ is noetherian, $\mathcal S\subset \text{Th}(\mathbb Z)$. As $\text{Th}(\mathbb Z)\subset \text{Th}(M)$ (where $M$ is the special example given in Example 19, which is shown to be non-noetherian), we have $\mathcal S\subset\text{Th}(M)$, so $M$ is noetherian, a contradiction.


How do you use TypeScript's SVG Library?

Question: I'm new to TypeScript and JavaScript, although not completely new to programming. I wondered if someone could help me with a short piece of TypeScript code showing how you would use TypeScripts SVG library to draw. So, for example, should I use SVGRectangle or SVGRectangleElement and how do I use them?
The only example I can find on the TypeScript site uses D3 but I would like to use the built in SVG library.
Comment: What SVG library? I thought TypeScript was just a language, not any libraries.
Comment: There are several .d.ts files available but not yet for SVG.  Typescript is open source, where there's a need there will be some *somebody* that writes an svg.d.ts.  If not you then keep an eye on the Codeplex project for updates.  Meanwhile use straight JS.
Comment: @HansPassant https://github.com/rbakhshi/svg.js/blob/master/svg.d.ts
Comment: @HansPassant and others: nowadays SVG APIs are covered in `lib.d.ts`.
Answer: Just to clarify, TypeScript doesn't have an SVG library - but you can use native JavaScript SVG or one of the SVG libraries in your TypeScript code.
This opens up the samples and tutorials you will find, as you can search for "JavaScript SVG" rather than "TypeScript" SVG.
I recommend the MDN SVG Reference as a starting point.
Comment: OK thanks Sohnee, just out of interest what are the SVG* functions which appear on Intellisense when writing TypeScript?
Comment: By default, TypeScript has a definition for things like the DOM, built-in functions and so on - so it will come from that. I imagine SVG is part of the DOM as it is essentially elements nested within it.
Comment: if you want you can use more specialized SVG libraries like SVG.JS (http://svgjs.com/). I created TypeScript declaration file for it : (https://github.com/rbakhshi/svg.js). i'm using it and it is good enough :D
Comment: @Sohnee how would you create an SVG element with TypeScript?
Answer: You can use TypeScript definition files of existing JavaScript SVG libraries, like Raphael or svgjs.
Comment: Don't forget about [Snap SVG](http://snapsvg.io/)! See the [Type Search](http://microsoft.github.io/TypeSearch/) for JavaScript library type definitions.


ReferenceError: not defined with activeX

Question: what does it mean to get this error:
<code>ReferenceError: ActiveXObject is not defined
var fso = new ActiveXObject("Scripting.FileSystemObject");
</code>
here is my code:
<code>    var fso = new ActiveXObject("Scripting.FileSystemObject");
    varFileObject = fso.OpenTextFile("C:\\LogFile.txt", 8, true,0); // 8=append, true=create if not exist, 0 = ASCII
    newObject.write(XML.innerHTML);
    newFileObject.close();
</code>
thanks in advance..
Comment: ActiveX only works in IE.  What browser are you using?
Comment: lol i was looking at what is broken with old code written well before by someone else.. was just wondering why it was broken.. :)
Comment: Why are you using ActiveX when HTML5 is so much better? :-)
Answer: The problem is the security setting of your browser is blocking it.
If you try IE6 the code should work.  You have to use a dead browser because the new browsers block it from working as part of a killbit fix that Microsoft did to fix a security issue.
Comment: this code was killed purposefully by microsoft see: http://social.msdn.microsoft.com/Forums/en/iewebdevelopment/thread/27092b49-7d3e-4d86-9ffb-223a26037c3f
Comment: All versions of IE support ActiveX, not just IE6 (which is dead).  You can change the security settings to allow it.


Javascript - graph traversal - return shortest path

Question: I want to traverse a graph. I have two structures:
var Node = function(name) {
    this.edge_list = [];
    this.name = name;
};

and
var Graph = function() {
    this.node_list = [];
};

An edge is added to a Node like so:
Node.prototype.addEdge = function(end, distance) {
    this.edge_list.push({end, distance});
};

A graph might look like this:
start:
[ Object { end: '1', distance: 13 },
  Object { end: '2', distance: 14 } ]
1:
[ Object { end: 'start', distance: 13 },
  Object { end: '3', distance: 2 } ]
2:
[ Object { end: 'start', distance: 14 },
  Object { end: '3', distance: 1 } ]
3:
[ Object { end: '1', distance: 2 },
  Object { end: '2', distance: 1 },
  Object { end: 'end', distance: 10 } ]
end:
[ Object { end: '3', distance: 10 } ]

What I'm looking to do is create a function that will return the shortest distance/path from a source to a target.
I currently have a test up https://repl.it/C6Fh
Comment: Try taking a look at the depth-first search algorithm first. Then look at Dijkstra's algorithm (https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
Answer: If the distances are positive, then dijkstra is the way to go. However, a very simple algorithm is:

mark each node having an infinite distance, with the source node having a distance of 0.
perform a breadth-first traversal on the graph starting from the source:

update a node's distance if the current edge leads to a smaller distance
add that node to the end of the queue

Following is my quick solution that stores the distances and the previous nodes on your Node class.
You will find the minimum distance on the node itself, like dstNode.distance.
For the path, just trace back from dstNode and follow the prev links.
function shortest_path(g, src, dst) {
    var get_node = function(n) {
        for (var i = 0; i < g.node_list.length; i++) {
            if (g.node_list[i].name == n) {
                return g.node_list[i];
            }
        }
        return null;
    }

    var srcNode = get_node(src);
    var dstNode = get_node(dst);
    for(var i = 0; i < g.node_list.length; i++) {
        // think of as infinity (currently assumed to be unreachable)
        g.node_list[i].distance = 2147483647;
        g.node_list[i].prev = null;
    }
    srcNode.distance = 0; // src node is of distance zero from itself

    q = [srcNode]; // we will breadth-first traverse the graph
    while (q.length > 0) {
        var cur = q[0];
        q.shift();
        for (var i = 0; i < cur.edge_list.length; i++) {
            n = get_node(cur.edge_list[i].end);
            // here we are looping through neighbors of cur
            // to see if a smaller distance exists
            if (n.distance > cur.distance + cur.edge_list[i].distance) {
                n.distance = cur.distance + cur.edge_list[i].distance;
                n.prev = cur;
                q.push(n);
            }
        }
    }
}


An AJAX HTTP request abnormally terminated in autocomplete textbox

Question: I have autocomplete textbox which populate the suggestion based on search text.
Steps

User type in search text box
User press enter instead of waiting for AJAX autocomplete to respond

It comes up with the following error.

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: path/allcontent/autocomplete
StatusText: error
ResponseText:  ReadyState: 4

I read Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors, but it didn't help.
This is the callback code.
Autocomplete Textbox
function search_user($form) {
        $form['text_usersearch'] = array(
            '#type' => 'textfield',
            '#title' => t(''),
            '#autocomplete_path' => 'searchuser/autocomplete',
            '#size' => 30,
            '#attributes' => array('class'=> array('auto_submit'),'style'=> array('float:left')),
        );

$form['submit_user'] = array(
            '#type' => 'submit',
            '#value' => t('Find'),
            '#attributes' => array('class'=> array('submit_user linkbuttonAction'),'style'=> array('float:left;margin-left:10px')),

        );

Autocomplete menu register
$items['searchuser/autocomplete'] = array(
     'title' => 'Autocomplete for User',
     'page callback' => 'user_autocomplete_search',
     'access arguments' => array('access content'),  //or whatever permission makes sense
     'type' => MENU_CALLBACK
      );

Menu callback
function user_autocomplete_search($string) {
        global $user;
        $arrUserMatch = array();

        $matchCode = '%'.db_like($string).'%';
        $arrUserTitle = SelectMatchingUserTitle($matchCode,10);

        foreach ($arrUserTitle as $userId=>$userName)
        {
            $autotext .= check_plain($userName);
            $arrUserMatch[$userName] = $autotext;
        }

        drupal_json_output($arrUserMatch);
    }

Form submission handler
function search_user_submit($form, &$form_state) {

        $searchval= $form['text_usersearch']['#value'];

        if($searchval=='')
            return;
        else
           drupal_goto('user/'.$searchval);
}

JavaScript autocomplete
$(window).load(function(){
                Drupal.jsAC.prototype.select = function (node) {
                        this.input.value = $(node).data('autocompleteValue');

                        if(jQuery(this.input).hasClass('auto_submit')){
                              this.input.form.submit();
                        }};

        });

Comment: Could you show us the highlights of your code? It could be a number of things.
Comment: try to set up `'delivery callback' => 'ajax_deliver'` and return array of matches from your `page callback`.
Comment: I have added 'delivery callback' => 'ajax_deliver' line in $items['searchuser/autocomplete'] function but it didn't work. Is anything extra I need to do?
Answer: i am using the following code to auto complete the name of the partners (store owners) in a search box in a form to edit a store's detail (not all form elements used are shown here):
the auto_complete call back returns the list of all the partners in the database.
(here one partner owns one store)
you could try and workout something similar:
the submit button links to a submit handler that updates the database.
function partner_store_form($form, &$form_state, $sid = 0) {
      $edit = NULL;
      if ($sid != 0) {
      $query = db_select('store', 's')
        ->fields('s', array('partner_pid'));
      $query->leftJoin('partner', 'p', 's.partner_pid = p.pid');
      $query->condition('s.sid', $sid);
      $query->addField('p', 'name', 'p_name');
      $edit = $query->execute()->fetchObject();
      }
      $form['pid'] = array(
        '#type' => 'textfield',
        '#title' => t('Partner Name'),
        '#size' => 30,
        '#required' => TRUE,
        '#default_value' => isset($edit) ? $edit->p_name . "  [Id:" . $edit->partner_pid . "]" : '',
        '#maxlength' => 96,
        '#autocomplete_path' => 'partner/autocomplete'
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($edit) ? t('Edit') : t('Save'),
        '#submit' => array('partner_store_form_submit')
      );
    }

    ----------

    $items['partner/autocomplete'] = array(
        'title' => 'store autocomplete',
        'page callback' => 'partner_store_autocomplete',
        'access arguments' => array(CONST_PERM_LIST_PARTNER),
        'type' => MENU_CALLBACK,
      );

    -----------------

    function partner_store_autocomplete($string) {
      $store = array();
      $query = db_select('partner', 'p');
      $return = $query->fields('p', array('pid', 'name'))
        ->condition('p.name', '%' . db_like($string) . '%', 'LIKE')
        ->condition('p.remove', 0)
        ->execute();
      foreach ($return as $field) {
        $store[$field->name . "  [Id:" . $field->pid . "]"] = check_plain($field->name);
      }
      if (empty($store)) {
        $store[''] = t('No Such User');
      }
      drupal_json_output($store);
    }

Answer: This could be caused by an open problem to correct in Drupal core (Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors). Certain developers claim that it is not a bug but a UX problem. Either way, you can apply the recommended patch until the core team backport a fix when ready for Drupal 8 (autocomplete-1232416-218-7.37.patch):
diff --git a/misc/ajax.js b/misc/ajax.js
index 01b894d..34831e8 100644
--- a/misc/ajax.js
+++ b/misc/ajax.js
@@ -448,7 +448,10 @@
  * Handler for the form redirection error.
  */
 Drupal.ajax.prototype.error = function (response, uri) {
-  alert(Drupal.ajaxError(response, uri));
+  if(response.status != 0) {
+    alert(Drupal.ajaxError(response, uri));
+  }
+
   // Remove the progress element.
   if (this.progress.element) {
     $(this.progress.element).remove();
diff --git a/misc/autocomplete.js b/misc/autocomplete.js
index 5679081..ee4e336 100644
--- a/misc/autocomplete.js
+++ b/misc/autocomplete.js
@@ -307,7 +307,9 @@
         }
       },
       error: function (xmlhttp) {
-        alert(Drupal.ajaxError(xmlhttp, db.uri));
+        if (xmlhttp.status != 0) {
+          alert(Drupal.ajaxError(xmlhttp, db.uri));
+        }
       }
     });
   }, this.delay);

However, to avoid patching core each time Drupal needs updating, another solution, depending on how important keeping abnormal AJAX request termination error reporting alerts is for you, could be what I and a few others did by injecting a redefined Drupal behavio(u)rs AJAX error handling function as so(ish) in forms, etc. that suffer from unnecessary AJAX termination alerts:
(function($){
  Drupal.behaviors.YourThemeNameOrWhatever = (function(){
    return {
      attach:function(context, settings){
        $.ajaxSetup({
          beforeSend: function(jqXHR, settings) {
            settings.error = function(jqXHR, textStatus, errorThrown) {
                if (window.console && console.log)
                {
                  console.log(textStatus);
                }
            };
          }
        });
      }
    }
  })();
})(jQuery);


Need new strategy for single class classifier

Question: I am attempting to create a single class classifier where the classes are fairly close to balanced (+/- 25). My dataset has ~2,800 samples and ~1,100 features. All of the features are binary except for one (length of a document related to each record.) Some of the features are very sparse, ~650 of the features show up in only 5 or less samples. I've tried using a randomized search for random forest parameters, and after much tinkering the best classifier I could produce was:
<code>clf = AdaBoostClassifier(sklearn.ensemble.RandomForestClassifier(n_estimators=1500, max_features = 4, criterion='gini', max_depth=None, bootstrap=True, random_state=42, class_weight='balanced'), algorithm="SAMME", n_estimators=200)
</code>
My cross validation results are:
<code>           precision    recall  f1-score   support

      0       0.64      0.55      0.59       374
      1       0.57      0.66      0.61       344

avg / total   0.61      0.60      0.60       718
</code>
In this particular case I only care about classifying the 1's well, the precision and recall for the 0 class doesn't matter to me. I also care a lot more about precision than recall but I would ideally like to have at least 50% recall. I'm out of idea about what I can do to improve my results and would love to hear about some strategies that you may have.
Thank you!
Edit: I should probably mention that I'm fairly positive that the predictive power of my features is pretty low.
Comment: This a nice paper that helped me when I was dealing with single classes: https://www.cs.uic.edu/~liub/publications/ICDM-03.pdf
Comment: Keep in mind that if you keep adjusting your model by hand to optimize your cross-validation results, you run the risk of overfitting the cross-validated estimates. See https://web.archive.org/web/20120708051027/http://www.gregorypark.org/?p=359 for an example of this issue.
Comment: Features that show up in only 5/2800 or less samples are called "features with low variance"  and are typically removed. See, for example, [scikit-learn documentation](http://scikit-learn.org/stable/modules/feature_selection.html)
Answer: Try increasing the weights of class 1 while training... This will ensure to make your algorithm to be extra careful with class 1. Also try different types of algorithms and tune them carefully with your metrics you care about.


Only take contains string and skip remaining string C#

Question: i am searching for searchText in someText. if the searchText found in someText it is returning the whole someText. but i want only searchText if found in someText and skip the remaining text. hope you understand my question!
if foundText is true than it should only searchText
string someText = "i have Samsung Glaxy";
string searchText = "Samsung Glaxy";

bool foundText = someText.Contains(searchText);
if(foundText)
{
    // here i want only searchText;
    // here found text like this in output
    // Output foundText = "Samsung Glaxy" skip remaining text.
}

Comment: `Contains` returns a `bool` (`true` if the searchText was found), not a `string`. What exactly is the problem? Are you looking for `string foundText = someText.Contains(searchText) ? searchText : null;`?
Comment: @RenéVogt `... someText.Contains(searchText) ? someText ...` - _"if the `searchText` found in `someText` it is returning the whole `someText`"_.
Comment: @SᴇM not sure what you mean, my code returns `searchText` if it was found, and that's what OP asked for (_"but I want only `searchText`"_)
Comment: @RenéVogt yeah contains return bool it is my mistake.
Comment: @shahsawar482 Can you give sample inputs and outcomes?
Comment: you have the search text, so if someText contains searchText then you do something with searchText in the if statement. otherwise it doesn't go into the if because that text was not in someText. I think you're overcomplicating it.
Answer: It seems you are just trying to return the string you are searching for, so this would do:
string foundText = someText.Contains(searchText) ? searchText : null;

Or written in full:
string foundText;
if (someText.Contains(searchText))
{
    foundText = searchText;
}
else
{
    foundText = null;
}

Comment: _"but I want only `searchText`"_ ....seems the question is rather unclear
Comment: _"if the `searchText` found in `someText` it is returning the whole `someText`"_, so it will be `string foundText = someText.Contains(searchText) ? someText : null;`
Comment: It seems you are right @SᴇM
Comment: @PatrickHofman please see updated question
Comment: I did. Thanks @shahsawar482


Probability that minimum of two numbers is less than 4

Question: Suppose I have to choose two numbers from set $$S=\{1,2,3,4,5,6 \}$$ without a replacement , then what is the probability that minimum of two is less than $4$?
I made two groups for this problem $A= \{1,2,3 \}$ and $B=\{4,5,6 \}$
.There are two possibilities , either both are from $A$ or one from $A$ and one from $B$ to satisfy our requirement. Hence
$$P(E)=\frac{3}{6}.\frac{2}{5} + \frac{3}{6}.\frac{3}{5}$$
but answer is incorrect. Help?
Answer: The probability $P$(minimum is $ \lt 4)$ is
$1 - P($ minimum is $\geq 4 ) = 1 - P($ both choices are from $A$ $)$.
The probability that both choices are from $A$ is $\frac{3}{6} \cdot \frac{2}{5}=\frac{1}{5}$.
Thus, the probability you're looking for is $\frac{4}{5}$.
Answer: We have $\binom{6}{2}$ possibilities, but $\binom{3}{2}$ of them are not what we want, more precisely, those events that 2 elements are chosen from $\{4,5,6\}$, hence, $P(E)=\frac{\binom{6}{2}-\binom{3}{2}}{\binom{6}{2}}$.
Comment: Would you mind explaining what you did there?
Answer: It is easy as P.I.E.. Use the Principle of Inclusion and Exclusion.
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = \mathsf P(X < 4)+\mathsf P(Y < 4)- \mathsf P(X< 4 \cap Y< 4)
\\ &= \frac 3 6 + \frac 3 6 - \frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$
Or you can use the Law of Complements
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = 1- \mathsf P(X \geq 4 \cap Y\geq 4)
\\ &= 1 - \frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$
Or by your method (the Law of Total Probability), but remembering that there are two ways for one pick to be in A and the other in B.
$$\begin{align}
\mathsf P(\min(X,Y) < 4) & = \mathsf P(X < 4 \cap Y\geq 4)+\mathsf P(X \geq 4 \cap Y< 4) + \mathsf P(X< 4\cap Y< 4)
\\ & = \frac 3 6\cdot\frac 3 5 +\frac 3 6\cdot\frac 3 5 +\frac 3 6\cdot\frac 2 5
\\ & = \frac 4 5
\end{align}$$
Answer: The error with your approach is that "One from $A$ and one from $B$" has two ways of happening: $A$ then $B$, or $B$ then $A$. So you need to multiply your calculation of this case by 2.
$$P(E) = \frac{3}{6} \cdot \frac{2}{5} + 2 \cdot \frac{3}{6} \cdot \frac{3}{5} = \frac{4}{5}$$


Which is the easiest way to simulate keyboard and mouse on Python?

Question: I need to do some macros and I wanna know what is the most recommended way to do it.
So, I need to write somethings and click some places with it and I need to emulate the TAB key to.
Comment: You might want to be more specific about what it is you're testing.  Web pages? Desktop applications?
Comment: web pages, desktop applications, everything =)
Comment: [Here](http://stackoverflow.com/a/35373648/2924421) is a way to simulate keyboard events in OS X.
Answer: I do automated testing stuff in Python.  I tend to use the following:
http://www.tizmoi.net/watsup/intro.html
Edit: Link is dead, archived version: https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html
http://www.mayukhbose.com/python/IEC/index.php
I do not always (almost never) simulate key presses and mouse movement.  I usually use COM to set values of windows objects and call their .click() methods.
You can send keypress signals with this:
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text?  Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever

This is all in Windows.  If you're in another environment, I have no clue.
Comment: To activate the program you want to send the keys to, use `shell.AppActivate("Notepad")` (replace Notepad)
Comment: Good to know: to use win32com you first have to install [Python for Windows extensions](http://sourceforge.net/projects/pywin32/).
Comment: This worked wonderfully - thanks @dagur for the tip on window focus! I also needed mouse event simulation - [this anser](http://stackoverflow.com/a/1181538/957950) was the best for me and worked well with this keyboard solution.
Answer: Maybe you are looking for Sendkeys?

SendKeys is a Python module for
  Windows that can send one or more
  keystrokes or keystroke combinations
  to the active window.

it seems it is windows only
Also you have pywinauto (copied from my SO answer)

pywinauto is a set of open-source
  (LGPL) modules for using Python as a
  GUI automation 'driver' for Windows NT
  based Operating Systems (NT/W2K/XP).

and example from the web page
> from pywinauto import application
> app = application.Application.start("notepad.exe")
> app.notepad.TypeKeys("%FX")
> app.Notepad.MenuSelect("File->SaveAs")
> app.SaveAs.ComboBox5.Select("UTF-8")
> app.SaveAs.edit1.SetText("Example-utf8.txt")
> app.SaveAs.Save.Click()

Comment: SendKeys appear to be for Python 2.x only. Moreover, its website is dead now
Answer: pyautogui is a great package to send keys and automate several keyboard / mouse related tasks.  Check out Controlling the Keyboard and Mouse with GUI Automation and PyAutoGUI's documentation.
Answer: You can use PyAutoGUI library for Python which works on Windows, macOS, and Linux.
Mouse
Here is a simple code to move the mouse to the middle of the screen:
import pyautogui
screenWidth, screenHeight = pyautogui.size()
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)

Docs page: Mouse Control Functions.
Related question: Controlling mouse with Python.
Keyboard
Example:
pyautogui.typewrite('Hello world!')                 # prints out "Hello world!" instantly
pyautogui.typewrite('Hello world!', interval=0.25)  # prints out "Hello world!" with a quarter second delay after each character

Docs page: Keyboard Control Functions.

More reading: Controlling the Keyboard and Mouse with GUI Automation (Chapter 18 of e-book).
Related questions:

Python GUI automation library for simulating user interaction in apps.
Python simulate keydown.
Answer: Two other options are:

pynput - https://pypi.org/project/pynput/ - which is for Windows (tested), Linux and MacOS- docs are at https://pynput.readthedocs.io/en/latest/
PyDirectInput - https://pypi.org/project/PyDirectInput/ - which is for Windows only and can be used with (or without) PyAutoGUI

Warning - if you are wanting to use keyboard control for games, then pynput doesn't always work - e.g. it works for Valheim, but not for the Witcher 3 - which is where PyDirectInput will work instead.  I also tested PyDirectInput and it works for Half life 2 (as a test of an older game).
Tip - You will likely need to reduce (don't remove for games) the delay between character typing - use pydirectinput.PAUSE = 0.05
As an example, here is a function that allows virtual keyboard typing - currently only tested on Windows:
from pynput import keyboard
try:
    import pydirectinput
    pydirectinput.PAUSE = 0.05
except ImportError as err:
    pydirectinput = False
    print("pydirectinput not found:")

def write_char(ch):
    upper = ch.isupper()
    if pydirectinput and pydirectinput.KEYBOARD_MAPPING.get(ch.lower(), False):
        if upper:
            pydirectinput.keyDown('shift')
            print('^')
        pydirectinput.write(ch.lower(), interval=0.0)
        print(ch)
        if upper:
            pydirectinput.keyUp('shift')
    else:
        keyboard.Controller().type(ch)

This allows a string to be sent in, with upper case alphabetic characters handled through pydirectinput.  When characters don't simply map, the function falls back to using pynput.  Note that PyAutoGUI also can't handled some shifted characters - such as the £ symbol, etc.
Answer: ctypes!
An answer that hasn't been mentioned here is ctypes, it's major advantage being it's a native library you can use right off the bat. I've personally had fewer issues with it than other libraries, too.
import ctypes

ctypes.windll.user32.keybd_event(0x73, 0, 0, 0) # F4 Down
ctypes.windll.user32.keybd_event(0x73, 0, 0x0002, 0) # F4 Up

ctypes.windll.user32.mouse_event(2, 0, 0, 0, 0) #Left mouse button down
ctypes.windll.user32.mouse_event(4, 0, 0, 0, 0) #Left mouse button up

ctypes.windll.user32.SetCursorPos(100, 100)

Mouse controls are self-explanatory, and keycodes on Windows are documented here.


Add a field programmatically to taxonomy

Question: We have a field.storage.taxonomy_term.field_name.yml file that adds the storage configuration for our custom field. The field is available to be added from the GUI to each vocabulary.
The issue we are facing is adding the field to every taxonomy automatically.
We have added the field from GUI and exported the configuration in order to change the form and we place the exported configuration in a file named field.field.taxonomy_term.field_name.yml, the problem that we are facing is modifying this config file in order to add them on all taxonomies.
In the configuration exported where we found the vocabulary name we switch it to * and also the bundle property had the vocabulary name, that property can't be removed since it throws an error.
Comment: "...it throws an error." – What error?
Answer: You can use yaml files only if you create new vocabularies. Adding a field to existing vocabularies is the same as doing this for content types, both are bundles, content types for nodes and vocabularies for taxonomy terms. See this question:
8 Add content type field programmatically
Comment: Isn't the question a duplicate then?
Comment: @leymannx, I don't know, both questions a more specific versions of how to add bundle fields programmatically.


How to disable fields in a symfony-form after submitting and validating the data?

Question: I have the following problem: I create a form, which has a select field and different text fields. When the select field has a certain value, than some text fields should be disabled. So I have JavaScript code, which handles the onchange event on my select field, and then disables/enables the text fields. And I have some PHP logic, which disables the text fields initially depending on the value which is retrieved from the database. This all works. The problem is, that when I validate my form, and I have an validation-error, I don't know, how to disable my text fields (without using JavaScript) when I render the validated form again. Because in my validation, I setup an fresh and empty entity, then I create the form based on this entity, and then I handle the request. So in the moment of creating the form, I don't have the values, which I need to determine if the text fields should be disabled or enabled initally.
So the question is, how do I disable some form fields after handling the validation?
Here is some pseudo-code with the problem pointed out in the comments
// create the form object depending on the form entity
private function createForm($formEntity) {
    $attributes = [];
    if ($formEntity->getType() === 'x') {
        // disable fields if type === 'x'
        $attributes = ['disabled' => 'disabled'];
    }

    $form = $this->createFormBuilder($task)
        ->add('type', ChoiceType::class)
        ->add('fieldA', TextType::class, ['attr' => $attributes])
        ->add('fieldB', TextType::class, ['attr' => $attributes])
        ->add('save', SubmitType::class, ['label' => 'Create Task'])
        ->getForm();

    return $form;
}

// action to just view the form
public function detailsAction($id) {
    $databaseEntity = $service->get(id);
    $formEntity = FormEntity::fromDatabaseEntity();

    // in this case, the $formEntity has the values from the database
    // so inside the createForm, the fields can be disabled/enabled
    $form = $this->createForm($formEntity);

    // when I render the form, the fields are disabled initially
    return render('views/details.twig.html', ['form' => $form->createView()]);
}

// action which handles the submit of the form, and render the form with validation constraints, if there are some
public function handleSubmitAction($id) {
    $formEntity = new FormEntity();

    // in this case, the $formEntity is empty
    // so inside the createForm, the fields can not be disabled/enabled
    $form = $this->createForm($formEntity);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        return $this->redirectToRoute('task_success');
    }

    // when I render the form, the fields are not disabled initially
    return render('views/details.twig.html', ['form' => $form->createView()]);
}

Answer: You need to modify your form before submit, based on request data you get. This can be done before the request data gets applied to form during submit by using PRE_SUBMIT method.
private function createForm($formEntity) {
    $attributes = [];
    if ($formEntity->getType() === 'x') {
        // disable fields if type === 'x'
        $attributes = ['disabled' => 'disabled'];
    }

    $form = $this->createFormBuilder($formEntity)
        ->add('type', ChoiceType::class)
        ->add('save', SubmitType::class, ['label' => 'Create Task'])
        ->add('fieldA', TextType::class, ['attr' => $attributes]);
        ->add('fieldB', TextType::class, ['attr' => $attributes]);
        ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
            $attributes = [];
            if ($event->getData()['type'] === 'x') {
              $attributes = ['disabled' => 'disabled'];
            }
            $form = $event->getForm();

            $dataA = $form->get('fieldA')->getData();
            $dataB = $form->get('fieldB')->getData();
            $form->remove('fieldA');
            $form->remove('fieldB');
            $form->add('fieldA', TextType::class, ['attr' => $attributes]);
            $form->add('fieldB', TextType::class, ['attr' => $attributes]);
            $form->get('fieldA')->setData($dataA);
            $form->get('fieldB')->setData($dataB);
        })
        ->getForm();

    return $form;
}

https://symfony.com/doc/current/form/events.html
And you should separate your form creation to separate FormType and Handler classes.
Comment: Seems to work, but if I `remove` and `add` a field, then the value which is bound to this field gets lost and when I render the form again, the input field is empty.
Comment: i updated the example, where it first takes data from the form fields and then sets them back
Comment: Disables fields are not send anymore. Even if the form would send it, Symfony simply ignores all disabled values. You also should store the entity in the user's session and use this entity in form until it's persisted.


Convergence on a metric space with two equivalent metrics

Question:
Let $X$ be a set. Let $d$ and $d'$ be equivalent metrics on $X$. Show that a sequence $x_n \in X$ converges in $(X,d)$ iff $x_n$ converges in $(X,d')$.

$" \Longrightarrow"$ Assume that $x_n \to x$ in $(X,d)$. Since $d$ and $d'$ are equivalent we have that $id : (X,d) \to (X,d')$ is a homeomorphism and thus continuous. From continuity we have that since $x_n \to x$, then $id(x_n) \to id(x)$
$" \Longleftarrow"$ Assume that $x_n \to x$ in $(X,d')$. Since $id : (X,d) \to (X,d')$ is a homeomoprhism it also has a continuous inverse call it $g :(X,d') \to (X,d)$. Now since $x_n \to x$ by the continuity of $g$ we have that $g(x_n) \to g(x)$.
I'm not sure this is correct. I would appreciate if someone could give me some advice on how to improve this?
Comment: You only have to prove on direction. The other follows from the first  by switching the two.
Comment: Your proof is, however, correct. I like using that $id$ is continuous
Answer: $d$ and $d'$ generate the same topology on $X$ so have the same convergent sequences in $X$ by definition. You don't have to mention homeomorphisms.
Note that $x_n \to x$ iff $$\forall O \in \mathcal{T}: (x \in O) \implies (\exists N \in \Bbb N: \forall n \ge N: x_n \in O)$$
so convergence only depends on the open sets in a topology. And $d$ and $d'$ have the same open sets by definition of equivalent topologies.
Comment: Technically, convergence is defined in metric spaces in terms of the metric and balls, not in terms of general open sets. And convergence doesn't make sense in general topology (where you get stuck with things like "nets.") Plus, I liked using the homomorphism. (Technically, OP only needed that $id$ is continuous....)
Comment: @ThomasAndrews convergence *is* defined in all topological spaces (exactly as above) and it's a special case of net convergence. "doesn't make sense" is not true, many topological spaces are even sequential.
Comment: Maybe I'm misremembering, I thought nets were used because convergence is not unique in general topology.
Comment: @ThomasAndrews net convergence need also not be unique in general. It's only that in a general space closed and sequentially closed need not be the same. Likewise with continuity and sequential continuity. To get such an equivalence we need nets.


Can I configure a software synth to use multiple patches on a channel?

Question: I am writing music for organ in LilyPond and listening to it via the LilyPond MIDI output through Qsynth/FluidSynth. I've been using Fluid_R3, but it only has a very generic (and not very convincing) "Church Organ" patch. I recently found JEUX, a soundfont with all sorts of organ stops, and I'd like to export a synthesis that works like a real organ, with multiple patches registered on each channel.
Is there a straightforward way to configure FluidSynth (or a similar software synth) to apply multiple patches on a single MIDI channel? If so, would I have to do something special in LilyPond for its MIDI output to work? (I could do something like multiple exports and add the sound files together, but that's a lot of complication!)
Comment: Given the synth you're using, you're are using gnu/Linux right?
Comment: @Tom Yes, I'm on GNU/Linux. FluidSynth because it's something of a default, but I'm open to alternatives.
Comment: Maybe qmidiroute could help you? That's a midi utility that can route midi signals depending on conditions, for instance to another channel or things like that... I did not understand exactly what you wanted to do but Could be worth a try! You can intercalate it between LP and qsynth.
Comment: @Tom Hmm, checking that out! I am wanting to do this in CLI mode to produce a "recording"; do you know offhand whether it would work sensibly in that context?
Comment: Cli?  Command line? If so, all these tools are compatible for that! That's part of the alsa library suite.
Comment: Can you use jack to route MIDI? Then perhaps you can use it to route MIDI signal to multiple fluidsynth instances? Anyway, unless I miss something, Lilypond doesn't seem to me a tool made to generate high quality audio output.
Answer: Speaking in principle, MIDI specifications allow only one patch per channel. You can change the patch as often as you want, you can set a different patch before every note you play, but a channel can only have a single patch at any time.
Comment: @chrylis-cautiouslyoptimistic-  Program Change is an actual instrument event, just like Note On. "_The Program Change message is used to specify the type of instrument which should be used to play sounds on a given Channel._" https://www.midi.org/midi-articles/about-midi-part-3-midi-messages MIDI channel number is a part of the Program Change message.
Comment: I'm not the downvoter, but while MIDI can send Program Change commands, I can certainly imagine a means to provide a channel mapping that would be used instead. Program Change is a side-channel to the actual instrument events.


From combinatorial entropy to Shannon entropy

Question: This blog, Shannon entropy, by Yurii Lahodiuk shows the link (derivation) of Shannon entropy from basic combinatorics. I would like to know the first person that made this combinatorial interpretation of Shannon entropy.

Who is the first person who gave this interpretation? What is the first appearance of this combinatorial interpretation in the literature?
Comment: This will surely be someone like Boltzmann or Gibbs from the 19th century. The accepted answer links to lecture notes from 2009, which is definitely not the origin of this argument!!
Comment: Yurii Lahodiuk is a member here known as @stemm
Comment: FWIW there's a beta [History of Science and Mathematics](//hsm.stackexchange.com) stack where this question would also be on topic. To be clear, I am not advising that you cross-post. However, if you don't get an answer here you could request migration and take your chances there.
Comment: My understanding is that Shannon himself was aware of this link, which is why he called in Entropy to begin with. The combinatorial approach was well known from Statistical Mechanics of Boltzmann, Gibbs, and others of the 19th century.
Answer: I have written the blog post: http://lagodiuk.github.io/computer_science/2016/10/31/entropy.html.
Frankly speaking, I have learnt about this interpretation from the exam-preparation notes, which I have found here: https://github.com/dmitriykovalev/nsu.videosoft.org/blob/master/assets/content/pdf/entropy.pdf
Which seems to be a part of the course taught by Kovalev Dmitry Sergeyevich "Data presentation and compression": http://nsu.videosoft.org/2009/.
Comment: Thanks Yurii, I have enjoyed reading your nice blog.
Comment: Thank you for your feedback, Mohammad!
Answer: According to Wikipeida, this interpretation (known as the maximum entropy principle) was given by Jaynes (based on a suggestion by Wallis). Here is an excerpt:

The principle was first expounded by E. T. Jaynes in two papers in 1957 where he emphasized a natural correspondence between statistical mechanics and information theory. In particular, Jaynes offered a new and very general rationale why the Gibbsian method of statistical mechanics works. He argued that the entropy of statistical mechanics and the information entropy of information theory are basically the same thing.


Selecionar texto na frente do texto atual usando TextBox

Question: Preciso que quando uma pessoa digite uma palavra, vai preenchendo automaticamente na frente do TextBox.
Esse é o texto PADRÃO Por Exemplo:

sdfdsfasfColocar esse texto no TextBoxsdfdsassdf

Quando eu preencher um pedaço do texto acima no TextBox,

Colo(...)

O resultado final terá que ficar assim no mesmo TextBox que digito:

O azul só poderá desaparecer quando a palavra não for igual ao padrão, ou for maior.
Montei um código para isso, mas na hora de digitar, o texto selecionado não acompanha a sequência de palavras do texto padrão.
  private void TextBox1_TextChanged(object sender, EventArgs e)
  {
        int first = this.textBox1.TextLength;
        string padrao = "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi";
        string textIndex = padrao.Remove(0, padrao.IndexOf(this.textBox1.Text, 0) + this.textBox1.TextLength);
        this.textBox1.Text = this.textBox1.Text.Insert(this.textBox1.Text.Length, textIndex);
        this.textBox1.Select(first, this.textBox1.Text.Length);
  }

O meu objetivo é apenas selecionar o texto padrão enquanto digito e colocar na frente do texto atual.
Answer: A textbox tem um modo de auto complete, o que difere do que prentende é que apenas pega a string do inicio.
public Form1()
{
    InitializeComponent();

    this.textBox1.AutoCompleteMode = AutoCompleteMode.Append;
    this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

    AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection
    {
        "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi"
    };

    textBox1.AutoCompleteCustomSource = stringCollection;
}

Fiz aqui um exemplo para pegar a string pelo meio, usei uma variável string chamada typed no escopo da classe para guardar o que foi digitado, tem algumas falhas, precisa remover caracteres em caso de delete/backspace, saber o sitio onde remover, selecionar vários caracteres e apagar etc....
string typed = "";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    string padrao = "asdfjdkjdfColocar esse texto no TextBoxqewprqewriworuoewi";

    e.Handled = true;

    // TODO:: tratamento de delete, backspace, escape etc

    typed += ((char)e.KeyChar).ToString();

    this.textBox1.Text = typed;

    int indexOf = padrao.IndexOf(typed, StringComparison.OrdinalIgnoreCase);
    if (indexOf >= 0)
    {
        this.textBox1.Text += padrao.Substring(indexOf + typed.Length);
    }

     this.textBox1.SelectionStart = typed.Length;
     this.textBox1.SelectionLength = this.textBox1.Text.Length - typed.Length;

}

Comment: Excelente! estava tentando isso há dias e nada...


Zend_Pdf table?

Question: Is it possible to create a table in Zend_Pdf? If yes, could you give me some code snippet?
I've tried searching documentation and devzone but I couldn't find anything about adding tables to pdf.
Comment: As far as I know, this is not possible. Take a look at fpdf.

http://www.fpdf.org/
Comment: Thanks, after all I "created" tables by drawing lines and rectangles with Zend_Pdf, it was a little more difficult but it worked (fpdf can create tables but there are problems when you need to wrap a text inside a cell).
Answer: Yea you have to manually draw the lines. Something to get you started:

$pdf->pages[0]
->setStyle($h3)
->drawLine(73, 244, 512, 244)   // HEAD Bottom
->drawLine(73, 244, 73, 166)    // MOST Left
->drawLine(512, 244, 512, 166)  // MOST Right
->drawLine(73, 166, 512, 166)       // MOST Bottom
->drawLine(225, 244, 225, 166)      // MOST Left
->setStyle($h2)
->drawText('Analytics Site', 73, 252)   // Table Headers
->setStyle($h3)
->drawText('Page Views', 80, 225)           // Table Headers (402) - 27
->drawText('Bounce Rate', 80, 200)      // Table Headers
->drawText('Avg. Time On Site', 80, 174)    // Table Headers
->drawLine(73, 192, 512, 192)   // Bottom
->drawLine(73, 218, 512, 218)   // Bottom
->drawText($site_metrics[0]->{"ga:pageviews"}, 235, 225)
->drawText(sprintf('%1.02f%%', $site_metrics[0]->{"ga:visitBounceRate"}), 235, 200)
->drawText($avg_time, 235, 174);

that snippet was for a pdf for monthly analytics reports on a site i did.
Comment: just realized im a month or two late =/ hopefully someone finds it useful regardless
Answer: Try Zend_Pdf_Table  (http://sourceforge.net/projects/zendpdftable/)
It's based on ZF1, handles rows, columns, headers, does text wrapping, renders multi-page tables, supports cell padding and left/right/center alignment. It can be quirky at times, but does its job.

Zend_Pdf table?


Problema com ordenação de vetor

Question: Boa tarde, estou tendo um problema com um exercício de ordenação de vetores, já revisei o código, ele compila, mas não estou achando o erro para a ordem não ficar de forma crescente, variando em certos trechos. Segue abaixo o código:
#include <stdio.h> //Declaracao de bibliteca para entradas e saidas de valores

int main (void) //Declaracao do programa principal
{
    int i, j, troca, vetorA[10];
    for (i = 0; i < 10 ; i++)
    {
        printf("Digite o valor do elemento:");
        scanf("%d", &vetorA[i]);
    }
    for(i=0; j<10; i++)
    {
        for (j=i+1; j<10; j++)
        {
            if(vetorA[i]>vetorA[j])
            {
                troca=vetorA[i];
                vetorA[i] = vetorA[j];
                vetorA[j] = troca;
            }
        }
    }
    printf("\nvetor ordenado \n");
    for(i=0; i<10; i++)
    {
        printf("%d - ", vetorA[i]);
    }
    system("pause");
    return 0;
}

Answer: em vez de
for(i=0; j<10; i++)

pqrece-me que querias dizer
for(i=0; i<10; i++)

Answer: Acredito que era um erro de digitação apenas:
#include <stdio.h>

int main (void) {
    int troca, vetorA[10];
        for (int i = 0; i < 10; i++) {
        printf("Digite o valor do elemento:");
        scanf("%d", &vetorA[i]);
    }
    for (int i = 0; i < 10; i++) { // <=========== Aqui tinha um j < 10 que obviamente causa confusão
        for (int j = i + 1; j < 10; j++) {
            if (vetorA[i] > vetorA[j]) {
                troca = vetorA[i];
                vetorA[i] = vetorA[j];
                vetorA[j] = troca;
             }
        }
    }
    printf("\nvetor ordenado\n");
    for (int i = 0; i < 10; i++) {
        printf("%d - ", vetorA[i]);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Problema com ordenação de vetor


Adding local task tabs to node display for specific content type

Question: I'm creating a custom module (it's called cil_meet) which adds two content types (organisation and room).  On an organisation node I want a local task tab (next to 'view' and 'edit') of 'add room', for administrators.  On a room node I want two tabs 'publish' and 'info'.
After some research, I've figured out a way to achieve this, but I want to know if there is a better way of doing this?
cil_meet.routing.yml:
cil_meet.addroom:
  requirements:
    _role: 'administrator'
cil_meet.roompublish:
#  path: '/meet/{organisation}/{room}/publish'
  requirements:
    _role: 'authenticated'
cil_meet.roominfo:
#  path: '/meet/{organisation}/{room}/info'
  requirements:
    _role: 'authenticated'

I've commented out the path for publish & info for now - I'll set up controllers, etc later.
cil_meet.links.task.yml:
cil_meet.addroom:
  route_name: 'node.add'
  title: 'Add Room'
  weight: 100
  route_parameters:
    node_type: 'room'
  base_route: entity.node.canonical
cil_meet.roompublish:
  route_name: 'cil_meet.roompublish'
  title: 'Publish'
  weight: 100
  base_route: entity.node.canonical
cil_meet.roominfo:
  route_name: 'cil_meet.roominfo'
  title: 'Info'
  weight: 101
  base_route: entity.node.canonical

This adds the tabs to all nodes.  So to remove the tabs from anything other than organisation or room nodes, I've got to add some code to the module.
cil_meet.module:
<?php
/**
 * Implements hook_local_tasks_alter().
 */
function cil_meet_menu_local_tasks_alter(&$local_tasks, $route_name) {
    $route_match = \Drupal::routeMatch();

    if ($route_match->getRouteName() == 'entity.node.canonical') {
        $node = $route_match->getParameter('node');
        if($node->bundle()!='organisation') {
            unset($local_tasks['tabs'][0]['cil_meet.addroom']);
        }

        if($node->bundle()!='room') {
            unset($local_tasks['tabs'][0]['cil_meet.roompublish']);
            unset($local_tasks['tabs'][0]['cil_meet.roominfo']);
        }
    }
}

All works as expected, the above may help others needing a similar solution.  Is there a better way of doing this?
Comment: Also, not that I need to do it, but a nice to have would be for the 'Add Room' tab to pre-populate the node add form with the organisation from the organisation node where the user has clicked on the tab.  The Room content type has an entity reference field called 'field_organisation'.
Comment: I did something similar not too long ago. I think this is the right approach, you overwrite Drupal's behavior in your custom module with the recommended method and implement the right hook to only affect the content types you want. Kudos !
Answer: Solution from Matt B only hides the tab on the node view page, but not on the node edit etc. The direct url will also be accessible in that case.
A better solution is to write a custom access handler
See Custom validation of route parameters


Android sqlite - Retornar _id logado ListView apenas um valor selecionado usando condição Where

Question: Boa noite pessoal, sou novato aqui, sou novato em programação Android, porém decidi fazer o meu TCC, um projeto em Android. por estar fazendo sozinho, encontrando material na internet, sem ter aulas de Android, estou indo até que bem (ou não), mas encalhei num determinado ponto.
Tenho uma ListView que me retorna os dados do banco SQLite.
Se eu deixar o SELECT * FROM tbl_usuario; ele me traz todos os usuários cadastrados no banco, mas eu queria apenas deixar aparecendo o usuário que fez o login no sistema.
ou seja, eu queria fazer uma condição dentro do Select, ficando "SELECT * FROM tbl_usuario WHERE _id = id que está logado no sistema.
porém não consigo, já perdi dois dias procurando um jeito de fazer, já mudei a estrutura do código e estou perdido.
Bom, meu código está aí.
public class Area_Usuario extends ActionBarActivity{
private String TABLE;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.area_usuario);
    TABLE = "tbl_usuario";

    DatabaseHandler db = new DatabaseHandler(this);
    Usuario usuario = new Usuario();
    SQLiteDatabase db1 = db.getReadableDatabase();
    String sql = ("SELECT * FROM " + TABLE);
    Cursor cursor= db1.rawQuery(sql,new String[]{String.valueOf(usuario.get_id())});
    String[] from = {"nome", "email", "senha"};
    int[] to = {R.id.Usuario_RowNome, R.id.Usuario_RowEmail, R.id.Usuario_RowSenha};
    ListView ltUsuario = (ListView) findViewById(R.id.listViewDadosUsuario);
    SimpleCursorAdapter ad = new SimpleCursorAdapter(getBaseContext(), R.layout.usuario_row, cursor, from, to, 1);
    ltUsuario.setAdapter(ad);
    db1.close();
   }
}

Answer: Se quer usar a cláusula WHERE terá de indicá-la na Query:
String sql = ("SELECT * FROM " + TABLE + " WHERE _id = ?");
Cursor cursor= db1.rawQuery(sql,new String[]{String.valueOf(usuario.get_id())});

O ? é um 'placeholder' para receber o valor indicado em new String[]{String.valueOf(usuario.get_id())}
Sugiro que, em alternativa a db.rawQuery, use os métodos que SQLiteDatabase disponibiliza para as operações CRUD.
No caso da leitura de dados deve usar uma das variantes de SQLiteDatabase.query
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs,
                    String groupBy, String having, String orderBy)

Ficaria assim:
Cursor cursor = db1.query(TABLE, null, "_id = ?",
                           new String[]{String.valueOf(usuario.get_id())},null,null,null);

Comment: ramaral, entendi sim essa forma de utilizar o Cursor, até achei melhor, eu digito usuário e senha, e efetuo o login, mas ainda meu ListView aparece em branco, ou seja, acredito que ele não está carregando os dados da.

    String[] from = {.....};
        int[] to = {.....};
Comment: Você está a instanciar a classe *Usuario* e não lhe atribui nenhum valor, por isso `usuario.get_id()` irá retornar sempre `0`. Se não souber o id do usuário terá de procurar, na tabela, o usuário pelo nome e não pelo id.
Comment: Não entendo por que você quer utilizar um *ListView* quando o resultado da query irá ser apenas um registo.
Comment: Posso retornar os dados do usuário em um TextView simples(no caso um TextView para cada dado retornado)??
Comment: claro que pode. Use os métodos `getInt(int columnIndex)`, `getDouble(int columnIndex)`, [`getString(int columnIndex)`](http://developer.android.com/reference/android/database/Cursor.html#getString%28int%29), etc, para obter os dados referentes a cada coluna.
Comment: Faltou indicar, no meu comentário anterior, que os métodos a que faço referência são da classe *Cursor*
Comment: consegui resolver meu problema, invés de eu trazer os dados do usuário pelo Id, resolvi trazer por e-mail, porém preciso apenas agora, conseguir fazer uma verificação se o e-mail já está cadastrado no banco de dados, para o que o usuário não consiga fazer duas vezes o cadastro do mesmo e-mail.
coloque o email em putExtra na tela 1 e na tela 2 eu recebi o email com o getExtra e fiz a query usando o email recebido da tela 1.
Comment: Essa é a forma usual de verificar se um usuário está cadastrado, quando o *username* é o e-mail. Não esqueça de verificar a *password*. O conjunto *username* e *password* é o que identifica um utilizador.


How can I get the most popular words in a table via mysql?

Question: I've got a table with a BLOB column. What I want to do is get it to be able to pick out words and list them in order.
For example if it contained:

Bob Smith likes cheese but loves reading
Charlie likes chocolate milk
Charl loves manga but also likes cookies

Then I would get

likes
loves

as a result... is this possible and if so how?
I'd like to be able to do it in just mysql alone, but I can use php as well.
Thanks in advance,
kenny
Answer: Don't think there is any built in MySQL function to do this so you are probably best using PHP to do the work for you using either explode(' ', $myString) or str_word_count($myString, 1) to create an array containing each word. Then loop through each word in the array and count them.
Answer: Sphinx Search (http://sphinxsearch.com/) is a application that does a lot around searching full text in mysql as well as other db's and file formats.  In short, it offers search with relavence of mysql tables.
One of it's tools performs word counts, the following is a bash script to get it to output the most popular words in a database:
GET_TOP_X_STOP_WORDS=27
WORD_FREQ_FILE=~/wordfreq.txt
/usr/local/bin/indexer test1 --buildstops $WORD_FREQ_FILE $GET_TOP_X_STOP_WORDS --buildfreqs

Comment: i'm sorry... but I wouldn't be able to run that
Answer: I've re-worked my code so I no longer need to do this... it seems impossible with standart setups


Parallel line with a known point

Question: Line m goes through a point D(2, -4). Line m is parallel to line l: $5x+3y=-17$. Describe line m with an equation of type $ax+by=c$.
The solution should be $c=5*2+3*-4=-2$ so $\text{m: }5x+3y=-2$
The lines are parallel so $a=5$, $x$ and $y$ are known so: $5*2+b(-4)=c$. At this point I lack some information I should know to push that equation further. I suppose I should be able to fill either $b$ or $c$, but which one and why?
Answer: Knowing that they're parallel tells you that they share the same gradient.
Try solving it like this and see if you can follow the method;
Rearranging line l into the standard form y = mx + c should show you that the gradient (m) of both lines (since they're parallel) is -(5/3)
Then you have that the equation of line m is;
y = -(5/3)x + c
Substitute in point D(2 , -4) to get c;
-4 = -(5/3)*2 + c
c = -4 + 10/3
c = -2/3
So putting everything into an equation for m, we have;
y = -(5/3)x -2/3
Just rearrange for the form asked for in the question;
(5/3)x + y = -2/3
Or in a little bit nicer form;
5x + 3y = -2

Parallel line with a known point


FreeRADIUS and Redis Module

Question: I am wanting to use FreeRADIUS with REDIS for authorisation and accounting.  I am running FreeRADIUS 3.0.3.
I note the rlm_rediswho module, which appears to be used for caching recent accounting records for users.
I also note a rlm_redisn module that appears to be the fore bearer of the current rlm_redis module.
The redis module configuration file does not give any guidance on how to configure authorisation queries etc, but the rlm_redisn module does have syntax for this in it's example file (see http://free.oxymium.net/freeradius/rlm_redisn/redisn.example)
If I try and add the redis module to the authorisation section in sites-enabled/default, I get the following error:
Thu Sep  4 02:06:08 2014 : Error: /etc/freeradius/sites-enabled/default[332]: "redis" modules aren't allowed in 'authorize' sections -- they have no such method.
Thu Sep  4 02:06:08 2014 : Error: /etc/freeradius/sites-enabled/default[220]: Errors parsing authorize section.

Answer: The REDIS module is not meant to be used directly, but referenced from other modules like rlm_rediswho.
There is one exception to that, in that it appears to register a string expansion matching the module name.
update control {
    Cleartext-Password := "%{redis:<redis query>}"
    Group := "%{redis:<redis query>}"
}

If you want authorization logic you'll have to write you own module, or retrieve individual attributes using something like the above string expansions.
Comment: Thanks - I have successfully implemented a basic test using this approach.  Can you advise if REDIS returns multiple values from a query, is this returned as string array processable by unlang.   E.g. if "%{redis:[n]}" or something to that affect...
Comment: No, it will return the first value only.
Comment: Thanks for the clarification - so can you use the string expansion in a conditional unlang statement as an example?
Comment: if ("%{redis:}" == &User-Pasword)

FreeRADIUS and Redis Module