Time localisation - "@count hour" (ago) instead of "1 hour"?

Question: Short story:
When Drupal 6 display time in format "x ago" (for example "3 hours ago"), there are two strings - for singular and plural. Singular string for hours is "1 hour", plural string is "@count hours". My question is - is this a bug? Shouldn't be there "@count hour"?
Long story:
Today, something strange happened to me. I went back to my site where I posted a comment yesterday around this time. However, in recent comments block, there was my comment marked as "1 hour 15 minutes ago" (in my language, not English - that's important!).
After I checked that time zone, server time and comment time are correct, I started debugging the Drupal. Finally, I found the culprit; it's the method format_interval(). At start of the method, there are strings definitions. For hour it's '1 hour|@count hours' - 1 hour for singular, @count hours for plural.
I found out that my comment was posted 21 hours ago and that locale_get_plural() function returned 0 - which is interpreted as singular.
And that's the problem - in my language we read "21 hour", NOT "21 hourS"! However, the count variable is not used, so for each numeric value read as singular (1, 21, 31, 41, ..., 91, 101, 121, 131, ...) (note: yeah, 11 is not singular in my language), the displayed value will be always 1!
I'm writing about hours, but this is same for all other values - years, weeks, minutes and seconds. Experimentally, I changed translation of "1 hour" to "@count hour" (in my language, not English) and the displayed time become correct. However, this is not clean solution, so my question is: is this a bug? If not, how should I solve this correctly?
Notes

I use Drupal 6
Happening on my machine (Xubuntu 14.04) and server (some Gentoo)
My language is Czech
Answer: The change you have made should work until you download and install an update to the drupal core language file.
The Drupal Localize site would allow you to download an check the latest versions of the  core language files to see if the bug also exists latest versions of 6, 7 and 8.
https://localize.drupal.org/translate/languages/cs
Perhaps you could sign up and posting a message into the Czech language forum on the localize site.  You can also find out more about contributing on the localize website.
https://localize.drupal.org
Comment: Note: I use a module which automatically downloads and installs localization (modified strings are kept) so it should be updated. Anyway, do you think it's ok to translate (officially) "1 hour" as "@count hour"? My point is that I'm not sure whether it's translation bug or bug in Drupal itself...


JSP is not getting the updated String value

Question: I want to display something like "log" on the page, I am using textarea for it. I have timer that runs every seconds and calls Test.getConsole(), but once the jsp page is loaded it is not refreshing. The method Test.getConsole() returns always the same value even if it has new text. When I refresh the page (F5) new content of Test.getConsole() displays. How to make the process of (F5) automatic ? I want real-time update of my text area with the right text that  Test.getConsole() is returning.
JSP:

    <title>MultiMine - Home</title>

    <textarea id="1" name="output" style="width:1194px" rows="40"></textarea>

Java:
public static String console = "Console initializing...";

public static String getConsole() {
    return console;
}

    public static void startConsole() {
   Timer t = new Timer();
    TimerTask tt = new TimerTask() {
        int i = 0;
        public void run() {
            try {
                console = console + "\\r" + i;
                i++;
            } catch (Exception e) {

            }
        }
    };
    t.schedule(tt, 1000, 1000);
}

In the textarea I can see the only "Console initializing..." and I need to refresh (F5) to see "Console initializing... 1 2 3 4 etc.." (the timer output). How to "update" the String ?
Answer: The scriptlet <%=Test.getConsole()%> is being executed before the page is loaded. The JSP receives the initial value of the method as plain text, so the Javascript is actually

Javascript cannot call the Java code so easily. A new request must be made to the page to get the scriptlet re-evaluated. To automate it, you will need to use Ajax.
Comment: Thanks for reply. And could you please show any simple example how to get String from java method using ajax and insert it into a var ?


G2 as a subgroup of SO(7) from extended Dynkin diagrams?

Question: As it is shown in the post
Subgroups of $E_8$ by using extended Dynkin diagrams
it is possible to find subgroups of a group from the extended Dynkin diagram by simply cutting nodes.
However, the relation $G_2 \subset SO(7)$ obviously cannot be obtained, since the Dynkin diagram of the $SO(7)$ doesn't contain a triple edge.
Is there an additional rule besides cutting nodes that allows the derivation of the relation on the level of extended Dynkin diagrams?
Comment: Sometimes this operation is called "folding". Similarly, we can fold $D_4 \rightsquigarrow B_3$, which corresponds to the exceptional inclusion $\operatorname{Spin}(7) \hookrightarrow \operatorname{SO}(8, \Bbb R)$. See, e.g., Section 5.3.1 of https://arxiv.org/abs/math/0510216, but n.b. the notion of folding there by definition begins with a simply laced diagram, which $SO(7)$ does not have.
Comment: Why is it not possible to follow the minimal rule of providing any kind of context? Why not reading first https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question?
Comment: I think you can see this inclusion by considering the root system $B_3$  which comprises the midpoints of the edges and faces of a cube and projecting onto a plane. The key is to ensure that each of the short roots is being matched to a long root (orthogonal to each other). Indeed I think you can choose the plane to go through the other 6 long roots and they will form the long roots in $G_2$.
Comment: Sorry, I hoped that there would be a fast answer that I just didn't find anywhere.
Comment: I would begin by using the 7-dimensional fundamental (irreducible) representation of $\mathfrak{g}_2$ (the short roots and $0$ as the weights). That gives us an embedding $\mathfrak{g}_2\to\mathfrak{gl}_7$. With a bit of luck (and checking several known facts) the images actually lies in...
Answer: As mentioned in comments, one has to think not of sub-root systems, but rather of "quotients" of root systems here. As also mentioned in a comment, there is some activity on this topic under the name of "folding" in recent years, but I think it is not explored in the generality that it could be. Cf. https://math.stackexchange.com/a/3972084/96384, https://math.stackexchange.com/a/3300945/96384 and links from there.
In fact, as Callum suggests: Choose a set of simple roots $\gamma_1, \gamma_2, \gamma_3$ for $B_3$, where $\gamma_3$ is the short root. Now "mod out" the relation $\gamma_1=\gamma_3$, i.e. project the ambient, three-dimensional space down to the plane orthogonal to $\gamma_1-\gamma_3$.
If we call $\alpha$ the image of $\gamma_1$ (and $\gamma_3$) under this projection, and $\beta$ the image of $\gamma_2$, one easily checks that all positive roots of $B_3$ get projected to $\alpha$, $\beta$, $\alpha+\beta$, $2\alpha+\beta$, $3\alpha+\beta$, $3\alpha+2\beta$, i.e. the projection/quotient/folding is a root system of type $G_2$ with $\alpha$ (short) and $\beta$ (long) forming a set of simple roots. (If one chooses Cartesian coordinates for better visualization, say  $\gamma_1 = (0,-1,1), \gamma_2= (-1,1,0), \gamma_3 = (1,0,0)$, then we project down to the plane $z=x+y$ (which already contains $\gamma_2$ but is perpendicular to $(1,1,-1) = \gamma_3-\gamma_1$.)
To bring things back up to the Lie algebra or group level, cf. the near-duplicate Understanding $G_2$ inside Spin(7)? (EDIT: problem solved).

What makes this specific "folding" a bit strange compared to the standard first examples is that it is not induced by any kind of automorphism of the roots; in fact, we identified the long root $\gamma_1$ with the short root $\gamma_3$! Maybe it becomes more plausible if one sees $B_3$ already as a folding of $D_4$ (as mentioned in Travis Willse's comment). This $D_4$, its Dynkin diagram being "three branches from a central node" seems to play the role of kind of a "simply laced covering" for both $B_3$ and $G_2$: For $D_4 \twoheadrightarrow B_3$, one identifies two of the outer nodes of $D_4$ (and similarly one always gets $D_{n+1} \twoheadrightarrow B_n$); whereas for $D_4 \twoheadrightarrow G_2$, one identifies all three of the outer nodes of $D_4$. What we are doing here is factoring the second folding through the first: which explains why we had to identify that remaining one-edged branch of the diagram with the two-edged one on the other side, the central node $\gamma_2$ has to stay long, whatever it takes.


Find values in formula $x * z_1 = y * z_2$

Question: I'm working on a number generator for this little formula
$x * z_1 = y * z_2$
The numbers are within this ranges:
$x \in \{1, ..., 10\}$
$y \in \{1, ..., 10\}$
$z_1 \in \{2, ..., 100\}$
$z_2 \in \{2,...,100\}$
I'm currently just running a brute force algorithmen which chooses $x, z_1$ and $z_2$ randomly out of their ranges and try to find the first number in between 1 and 10. If no matching number is found I just start the algorithmen again.
That works pretty OK but is not a nice solution.
How can I find a better algorithmen? Bonus: How can I find an algorithmen which generates formulas of the pattern:
$x \oplus  z_1 = y \oplus  z_2$ where $\oplus \in \{*, +, -, \div\}$? How do you tackle problems like that?
Answer: If you have no further restrictions, you could just choose $x$ and $y$ randomly and set $z_2=2x$ and $z_1=2y$. Here, the $2$ just grants that $z_1$ and $z_2$ are not equal to $1$. If you want to make it a bit more general, you could choose a random $m\in\{2,\cdots,10\}$ and set $z_2=mx$ and $z_1=my$.
An even more sophisticated way would be to choose $x$ and $y$ randomly, compute $g=gcd(x,y)$ and set $z_2=m\frac xg$ and $z_1=m\frac yg$ with $1<m\leq 10g$.
For addition and substraction it is considerably simpler, since you can choose $x$, $y$ and $z_1$ and will always get a $z_2$. You will only have to worry about the range a bit.
Division is equivalent to multiplication by bringing $z_1$ and $z_2$ on the other side. Again you might want to change the range here (and be possibly careful with the number 0).
Comment: Implemented like you suggested. Worked like a charm :-) Any suggestions how I can learn to tackle such problems?
Comment: Right now I find it harder to understand what you mean by 'such problems' than to actually answer the question. I guess one thing to keep in mind is that any number can be written as the product of prime numbers and the primes on both sides must be in correspondence. So if you pick $x$, say, then $y$ and $z_2$ together have to have all prime factors of $x$ as prime factors. The easiest way, of course, is that one of them is already a multiple of $x$.


How do you store result row count in nested SELECT?

Question: I have a MySQL query where I have a nested SELECT that returns an array to the parent:
SELECT ...
FROM ...
WHERE ... IN (SELECT .... etc)

I would like to store the number of returned results (row count) from the nested SELECT, but doing something like IN (SELECT count(...), columnA) does not work, as the IN expects just one result.
Is there a way to store the returned result count for later use within the parent statement?
Comment: Might be something you can do with JOIN/GROUP BY. But you need to elaborate a bit more.
Comment: The query details are:

SELECT tabA.colA,
 tabA.colB
FROM tabA
WHERE tabA.colA IN (
 SELECT tabA.colA
 FROM tabA
 WHERE tabA.colB = 1
)

I would like to then take the number of resultant rows from the nested SELECT and use that for some division in the main query (not written yet).
Comment: Are you this is your query? you don't need a subquery for this!
Answer: You're probably going to have to select the results of your nested statement into a temporary table. Then you can do an IN and a count on it later. I'm more familiar with MS-SQL, but I think you should be able to do it like this:
CREATE TEMPORARY TABLE tmp_table AS
SELECT something
FROM your_table;

SELECT ...
FROM ...
WHERE ... IN (SELECT * FROM tmp_table);

SELECT count(*) FROM tmp_table;

If that doesn't work, you may have to provide full details to the temporary table creation statement as you would with a normal "CREATE TABLE". See here in the MySQL manual, and here for a similar example.
CREATE TEMPORARY TABLE tmp_table
(
    tableid INT,
    somedata VARCHAR(50)
);

INSERT INTO tmp_table
SELECT ...
FROM ...

SELECT ...
FROM ...
WHERE ... IN (SELECT * FROM tmp_table);

SELECT count(*) FROM tmp_table;

Rich
Answer: You mentioned in your comment that your query look like this:
SELECT
  tabA.colA,
  tabA.colB
FROM tabA
WHERE tabA.colA IN ( SELECT tabA.colA FROM tabA WHERE tabA.colB = 1 )

I might be missing something, but you don't need a subquery for this. Why don't you do it in a regular where condition:
SELECT
  tabA.colA,
  tabA.colB,
FROM tabA
WHERE tabA.colB = 1

Comment: tabA.colB = 1 returns an array. I tried this, but I just get one set of results (i.e. the first item in the array)
Answer: You can use IN predicate for multiple columns like this:
SELECT  *
FROM    table
WHERE   (col1, col2) IN
        (
        SELECT  col3, col4
        FROM    othertable
        )

If you want to select COUNT(*) along with each value, use this:
SELECT  colA, colB, cnt
FROM    (
        SELECT  COUNT(*) AS cnt
        FROM    tabA
        WHERE   colB = 1
        ) q,
        tabA
WHERE   colB = 1


find the area of its image under the map $f(x,y)=(e^{x+y},e^{x-y})$

Question: $D$ be the open unit square in first quadrant, I need to find the area of its image under the map $f(x,y)=(e^{x+y},e^{x-y})$
will it be $e^2$? It is just a guess!
Thank you!
Comment: $D$ is bounded by four line segments. Find out how these line segments transform under $f$. Draw a picture. With your reputation, "just a guess" is not good enough!
Answer: All points @Samarat pointed are true. I am adding additional point which is, when we use transformations of multiple integrals, we need to consider the Jacobian of $x$ and $y$ with respect to $u$ and $v$. See this. In fact we have the following integrals instead:
$$\iint_{D_t}\left|\frac{\partial(x,y)}{\partial(u,v)}\right|dudv$$ in which $$\left|\frac{\partial(x,y)}{\partial(u,v)}\right|=|x_uy_v-x_vy_u|$$
Answer: Let $D$ be the unit square. Note that $$\frac{\partial(f_1,f_2)}{\partial(x,y)}=e^{x-y}e^{x+y}-(-e^{x-y}e^{x+y})=2e^{2x}$$
thus your function has nonvanishing Jacobian. Moreover your function is injective (check this). Of course it is $\mathscr C^1$ so we can use the change of variables formula for integrals. This says that if $D$ is the unit square and $f$ you diffeomorphism, $$\int_{f(D)}1dxdy=\int_{D}1\circ f(x,y)|J_f(x,y)|dxdy$$
But of course $1\circ f(x,y)=1$ so we get that $$\int_{f(D)}1dxdy=\int_{D}|J_f(x,y)|dxdy$$
Thus the area is $$\int\limits_0^1 {\int\limits_0^1 {2{e^{2x}}dx} dy}  = {e^2} - 1$$
Answer: If $$u=e^{x+y}\quad v=e^{x-y}$$ then the transformed area in the $u-v$ plane will be bounded by the curves $$uv=1,\quad uv=e^2, \quad u=v,\quad u=e^2v$$ which I denote by the region $D_t$ Then your integration becomes $$\iint_{D_t}du\ dv$$


Are the two prime ideals containing same idempotents always the same?

Question:
If two prime ideals contain the same non trivial idempotents, what can we say about those ideals? Are they equal?
Comment: Is there any reason you think this is true? Some context would help people answer, and probably help give answers that are better for your purpose
Answer: Consider the ring $\mathbb{Z}\times\mathbb{Z}$ (which is arguably the simplest ring having non-trivial idempotents, so it should be one of the first examples we look at). Its non-trivial idempotents are $(1,0)$ and $(0,1)$, and its prime ideals are those ideals of the form $\mathbb{Z}\times P$ and $P\times\mathbb{Z}$ where $P\subset\mathbb{Z}$ is a prime ideal. Thus $\mathbb{Z}\times (2)$ and $\mathbb{Z}\times (3)$ are both prime ideals containing the same non-trivial idempotents (namely, only $(1,0)$) while not being identical.
Comment: Since the OP didn't actually require the ring to have any nontrivial idempotents, even $\mathbb Z$ would give a counterexample,


How to play notes over one and a half octaves/am I reading this music wrong?

Question: I've been trying to play this piece:

Focusing on the left hand for the highlighted bar, it looks like it doesn't fit in with the 9/8 time (7 beats in that bar I think). But if I try to play them together, it looks impossible since it wants my left hand to reach over one and a half octaves while my right hand is occupied. I'm a casual piano player (never been taught piano specifically but have learnt very basic music theory) but I'm sure even experts wouldn't be expected to span this wide (I could be, and am probably, wrong). Am I reading this wrong or am I missing some special technique? How should I play this bar (and hence the next bar too)?
Comment: Notice that this is two separate voices. (How else could that Db both be a half note and be struck again after an eighth beat, and how else could you play both a half note and an eighth rest?) In such cases pedalling that first chord is probably the way to go, especially in Clair de Lune. Note that your right thumb could theoretically grab the middle Db, leaving a span of 12 keys for your left hand, but there's no reason to do this.
Comment: Good points, the answer was simpler than I thought. I'd happily accept this answer if I could, thanks
Answer: As user LukeSawczak wrote in a comment: The left hand plays separate voices.
The upper voice consists of:

an eighth/quaver rest (= 1/8)
a quarter note/crotchet (= 2/8)
a dotted half note/minim (= (6/8)

which nicely sums up to 9/8.
The lower voice starts with a dotted half note (=6/8) and actually the remaining 3/8 are missing. I would have expected a dotted quarter rest here, but maybe that was skipped on purpose (it's the same in the next bar).

As you've noticed already, it is not possible to reach all notes of both voices at the same time.
Therefore, you can pedal the first cord of the lower voice and then change fingering to play the chord of the upper voice.
Comment: FWIW, I think it's not abnormal for voice 2 to omit any rests after the last note.


Find the last two digits of $9^{{9}^{9}}$

Question: I have to find the last two decimal digits of the number $9^{{9}^{9}}$.
That's what I did:
$$m=100 , \phi(m)=40, a=9$$
$$(100,9)=1, \text{ so from Euler's theorem,we have :} 9^{40} \equiv 1 \pmod{100}$$
$$9^{{9}^{9}} \equiv 9^{9^{2+2+2+2+1}} \equiv 9^{9^2 \cdot 9^2 \cdot 9^2 \cdot 9^2 \cdot 9} \equiv 9^{81 \cdot 81 \cdot 81 \cdot 81 \cdot 9} \equiv 9^{(40+40+1) \cdot (40+40+1) \cdot (40+40+1) \cdot (40+40+1) \cdot 9} \equiv (9^{(40+40+1)})^{(40+40+1) \cdot (40+40+1) \cdot (40+40+1) \cdot 9} \equiv 9^9 \equiv 9^4 \cdot 9^4 \cdot 9 \equiv 6561 \cdot 6561 \cdot 9 \equiv 3721 \cdot 9 \\ \equiv 21 \cdot 9 \equiv 89 \pmod{100}$$
So,the last two digits are $8 \text{ and } 9$.
$$$$But,is there also an other way two calculate the last two digits of $9^{{9}^{9}}$ or is the above the only one?
Comment: The Chinese remainder theorem might help, but this looks efficient enough already. You have a typo, by the way, the last equation should be mod 100 :)
Comment: @Thomas How could I use the Chinese remainder theorem?
Comment: From your calculation you want the exponent $\mod 40$. So you want $9^9 \mod 40$, but as you show $9^2=1 \mod 40$ so $9^9=9 \mod 40$ and then $9^{9^9}=9^9 \mod 100$
Comment: From Euler you get that $a^{\phi(100)}\equiv a^{40} \equiv 1 \pmod{100}$. The Chinese remainder theorem gives the sharper $a^{\text{lcm}(\phi(2^2),\phi(5^2))}\equiv a^{20} \equiv 1 \pmod{100}$. This is also known as Carmichael's theorem.
Comment: Yes, thank you!!! @Did :)
Answer:
Key remark: By the binomial theorem, for every odd $k$, $(10-1)^k=n+10\cdot k-1$ for some integer $n$ which is a multiple of $100$. Since $10\cdot k=10\cdot\ell(k)\bmod{100}$ where $\ell(k)$ denotes the last digit of $k$, this shows that, for every odd $k$, $9^k=10\cdot \ell(k)-1\bmod{100}$.

First application: $\ell(9)=9$, hence the key remark above yields $9^9=10\cdot \ell(9)-1=89\bmod{100}$.
Second application: our first application implies that $\ell(9^9)=9$ hence, using the key remark once again but this time for $k=9^9$, one gets $9^k=10\cdot\ell(k)-1=89\bmod{100}$.
And so on: for every tower of nines, $9^{9^{9^{9^{\cdots}}}}=89\bmod{100}$.
Answer: You could also just do modular exponentiation and take note of the periods.
The powers of $9 \mod 100$ are: 1, 9, 81, 29, 61, 49, 41, 69, 21, 89, 1, 9, 81, 29, 61, 49, ... They have a period of $10$. This means that if $n \equiv 9 \mod 10$, then $9^n \equiv 89 \mod 100$. Since $9^9 = 387,420,489$, this means that $9^{9^9} \equiv 89 \mod 100$.
Answer: Let $k$ be the order of $9$ mod $100$. Then
$$1\equiv 9^k=(10-1)^k \equiv 10\binom{k}{1}\cdot 10(-1)^{k-1}+(-1)^k\pmod{100}$$
It implies that $1=\pm (10k-1)\pmod{100}$. The minimal integer which satisfies this condition is $k=10$. It follows that $$9^{9^9} \equiv 9^9 \equiv 9^{-1}\equiv 89\pmod{100}.$$
Answer: A variant to minimise the computation time of the order of $9\bmod100$: by the Chinese remainder theorem,
$$\mathbf Z/100\mathbf Z\simeq\mathbf Z/4\mathbf Z\times \mathbf Z/25\mathbf Z. $$
Now $\varphi(25)=20$, and $9\equiv 1\mod4$. Hence $9^{20}\equiv 1\mod100$, so the order of $9$ is a divisor of 20.
Fast  exponentiation algorithm shows it has order $10$. Thus
$$9^{9^9}\equiv9^{9^9\bmod 10}\equiv 9^{(-1)^9\bmod 10}\equiv 9^{-1}\mod100. $$
Bézout's identity $\;100_11\cdot 9=1\;$ then shows $\; 9^{-1}\equiv -11\equiv 89\mod100$.


Is it OK to handle 2 languages using session variable?

Question: To handle two languages, I have done the following and I want to know if it is fine.
On all my pages, I have a two links in the menu :
English
Français

On language.php, i set a session variable a go back to the page :
if(isset($_GET['l']))
{
    $_SESSION['language']= GetLanguage($_GET['l']);
    header('Location: ' . $_SERVER['HTTP_REFERER']);
}

Then on each php page, every time I have a word, I don't hardcode the it but instead put a PHP variable that depends on the value of $_SESSION['language'].
Do you see a problem using this mechanism ?
Comment: I would suggest to use explicit language like en or en_US instead of numbers.
Comment: don't use the referer. it's not trustworthy, and not always set. but otherwise there's nothing wrong with the general logic.
Answer: Well - if you are using sessions - this is in essence why you would use sessions. So no problem.


Ir para determinado link dependendo da página

Question: Estou desenvolvendo um quiz com vários temas, mas na hora de colocar para ele ir para determinada página dependendo de qual página a pessoa está. Pensei em usar o if mas ele sempre vai para o ultimo if, vou colocar o código aqui. Alguém sabe onde errei?
var url = window.location.href;

if(url = 'tela03.html'){
  window.location.href = 'tela04.html'
}else if(url = 'tela05.html'){
  window.location.href = 'tela06.html'
} else if(url = 'tela07.html'){
  window.location.href = 'tela08.html'
}
else (url = 'tela09.html'){
  window.location.href = 'tela10.html'
}

Comment: Errou em vários pontos. Vamos lá, quando dá um `if` você deve comprar com 2 ou 3 iguais `==` ou `===`. O comando else não pode ter verificação entre parênteses.
Comment: Não conserte os erros que tinha na pergunta, isto invalida a respostas dadas, se o erro está aí as pessoas responderam baseando-se neles, mudando a pergunta ela até deixa de ser válida.
Comment: Seria ideal você depurar. Você pode usar o navegador pausando linha por linha para acompanhar o que está acontecendo. E também pode escrever alguns console.log() das variáveis e em trechos após os comportamentos para ver o que está sendo alterado. Vai ajudar muito trabalhar desta forma, principalmente utilizando o depurador.
Comment: Relacionado: [Saber se o numero é ímpar ou par](https://pt.stackoverflow.com/a/64059/3774)
Comment: Não acredito que sua abordagem seja boa para fazer estes redirecionamentos, mas se for usar a URL atual para isso, use [`Location.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/Location) ao invés de `Location.href`...
Answer: Tem vários erros aí, não sei se resolve tudo.
Tinha operador de atribuição = usado no lugar de comparação ==. Não tem necessidade de === porque você tem certeza dos tipos que estão sendo comparados.
faltava if depois do else para funcionar. Tem respostas que muda a semântica de execução do algoritmo fazendo algo ser executado por default, que é diferente do código original que só deve executar se tiver uma condição específica.
Falta ponto e vírgula, estava bem desorganizado.
Além disso você não pode comparar só com a página, tem que dar o endereço completo, a string que vem de window.location.href tem um URL completo, com protocolo, domínio, porta (pode ser a default), o arquivo da página e eventualmente complementos, tem que comparar com o que vem. Poderia ser por exemplo http://www.thi100.com/tela03.html.
Eu coloquei um console.log() ali para mostrar o que vem, aqui no SOpt não vai funcionar bem por causa do script de execução, mas executando na sua página vai mostrar qual é o URL que está vindo. Aí você pega a informação que vem em cada cenário e pode adaptar na condição para ser o que deseja (teste em cada página que puder receber para ver cada situação, não tente adivinhar o que vem, programação não é jogo de adivinhação, é algo exato que se trabalha com dados reais coletados de forma mecânica e precisa).

var url = window.location.href;
console.log(url);
if (url == 'tela03.html') {
    window.location.href = 'tela04.html';
} else if (url == 'tela05.html') {
    window.location.href = 'tela06.html';
} else if (url == 'tela07.html') {
    window.location.href = 'tela08.html';
} else if (url == 'tela09.html') {
    window.location.href = 'tela10.html';
}

Coloquei no GitHub para referência futura.
Eu acho que isso está conceitualmente errado, mas não vou entrar nesse mérito.
Answer: A correção do seu código deveria ficar +/- assim:
var url = window.location.href;

if(url === 'tela03.html'){
  window.location.href = 'tela04.html'
}else if(url === 'tela05.html'){
  window.location.href = 'tela06.html'
} else if(url === 'tela07.html'){
  window.location.href = 'tela08.html'
}
else {
  window.location.href = 'tela10.html'
}

ou melhor poderia utilizar switch:
var url = window.location.href;
switch (url) {
    case 'tela03.html':
        window.location.href = 'tela04.html';
        break;
    case 'tela05.html':
        window.location.href = 'tela06.html';
        break;
    case 'tela07.html':
        window.location.href = 'tela08.html';
        break;
    defult:
        window.location.href = 'tela10.html';
}

Answer: as suas condições de if estão incorretas... Você apenas alterou o valor da variável url dentro das condições if, e a variável não retornou nenhum valor booleano, por isso todas as condições if foram ignoradas...
E outra: o código window.location.href retorna a url que você está... E não o arquivo do diretório atual...
Se a sua url for http://localhost/projeto/tela03.html, então var url = window.location.href; irá retornar o valor http://localhost/projeto/tela03.html e não tela03.html.
Logo o seu código if deveria ser mais ou menos assim:
if(url == 'url que você está')

Answer: O location.href retorna a URL toda e não apenas a página atual. Em vez de redirecionar para uma página baseando-se na URL ou no nome da página, ao meu ver seria mais prático inserir em cada página uma variável que a identifique.
Por exemplo, na página tela03.html coloque uma variável no script:

Na página tela04.html coloque:

E assim em cada página.
E crie um .js externo e chame-o no final do body de cada página:

No arquivo redirecionamento.js você faz os if's, verificando a variável tela para saber em qual página está e pra onde vai:
if(tela == 3){
   location = "tela04.html";
}else if(tela == 4){
   location = "tela05.html";
}
etc...

Pode também fazer algo mais dinâmico, sem usar if's, apenas incrementando a variável tela com +1 e redirecionar para a próxima página:
location = "tela"+ ("0" + (tela + 1)).slice(-2) +".html";

Se tiver na página tela03.html, irá para a página tela04.html e assim sucessivamente.
Answer: Na condição do seu if/else você está sempre atribuindo um valor ao invés de fazer uma comparação.
Por exemplo, onde está:
if ( url = 'pagina.html' )

deveria ser:
if ( url == 'página.html' )

Além disso, window.location.href retornará a url atual dessa forma:
https://site.com.br/pagina.html

Para fazer o que você quer, poderia usar window.location.pathname, que retornaria dessa forma:
/pagina.html

Aplicando essas mudanças:
var url = window.location.pathname;

if( url == '/tela03.html' ){
  window.location.href = 'tela04.html'
}else if( url == '/tela05.html' ){
  window.location.href = 'tela06.html'
} else if( url == '/tela07.html' ){
  window.location.href = 'tela08.html'
}
else( url == '/tela09.html '){
  window.location.href = 'tela10.html'
}


Kubernetes Nginx Ingress and cert-manager Waiting for HTTP-01 challenge propagation: wrong status code '401', expected '200'

Question: I'm having issues with my rapberry pi kubernetes implementation
Problem:
I have cert-manager letsencrypt ACME challenge waiting due to a 401 error code on bare metal kubernetes install.
Setup
Platform: Raspberry Pi 4
OS: Ubuntu Server 20.04.3 LTS 64 bit
Ingress: Nginx
Loadbalancer: Metallb
Networking: Calico
I installed metallb and nginx via helm using:
helm install metallb metallb/metallb --namespace kube-system\
    --set configInline.address-pools[0].name=default\
    --set configInline.address-pools[0].protocol=layer2\
    --set configInline.address-pools[0].addresses[0]=<ip-range>

and
helm install ingress-nginx ingress-nginx/ingress-nginx --namespace kube-system

My letsencrypt looks like this:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
  namespace: cert-manager
spec:
  acme:
    email: <email redacted>
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx

My nginx ingress set up looks like this:
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: "nextcloud" # Same namespace as the deployment
  name: "nextcloud-ingress" # Name of the ingress (see kubectl get ingress -A)
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    cert-manager.io/cluster-issuer: "letsencrypt-prod" # Encrypt using the ClusterIssuer deployed while setting up Cert-Manager
    nginx.ingress.kubernetes.io/proxy-body-size:  "125m" # Increase the size of the maximum allowed size of the client request body
spec:
  tls:
  - hosts:
    - "nextcloud.<domain redacted>" # Host to access nextcloud
    secretName: "nextcloud-prod-tls" # Name of the certificate (see kubectl get certificate -A)
  rules:
  - host: "nextcloud.<domain redacted>" # Host to access nextcloud
    http:
      paths:
        - path: /  # We will access NextCloud via the URL https://nextcloud.<domain.com>/
          pathType: Prefix
          backend:
            service:
              name: "nextcloud-server" # Mapping to the service (see kubectl get services -n nextcloud)
              port:
                number: 80 # Mapping to the port (see kubectl get services -n nextcloud)
---

Debugging
When I look at the ingress controller logs (different namespace) I see:
Service "nextcloud/cm-acme-http-solver-9tccf" does not have any active Endpoint.

But the endpoint appears to exist when I do kubectl get endpoints -A
My certificate exists as:
kubectl get certificate -n nextcloud
NAME                 READY   SECRET               AGE
nextcloud-prod-tls   False   nextcloud-prod-tls   3h58m

Following the recommended debug steps from cert manager I tracked the issue to the challenges whereby I get:
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for HTTP-01 challenge propagation: wrong status code '401', expected '200'
  State:       pending
Events:        <none>

I'm kinda stuck I've been googling my heart out but there doesn't seem to be a lot on this. I'm guessing I've stuffed up on the set up but I've mainly been following the documentation on the relevant pages. Any pointers would be greatly appreciated :). If you need any additional info let me know this is currently quite long so I tried to include what I thought were problem points.
Comment: if i read your setup correctly you get a 401 on the folder/file the cert-manager (certbot?) requests. This seems to be because the call from letsencrypt transfers to something you might have password protected
Your nginx logs should show you a request to some folder name .well-known or similar.
After that is a generic name. That one needs to be accessable by an outsider (certbot in this example)

For me it worked best to make an exclusing of that specific directory to be directly served by nginx. Something like a location .well-known block in the nginx config.
Comment: The idea of @DennisNolte is good. Could you try it and know us if it works?
Comment: @DennisNolte Thanks for your reply, I couldn't find any attempts to access the/.well-known/ directory in the Nginx controller log but I could find a reference to it and my domain in the nginx.conf
Are you suggesting that I change the location /.well-known/ to another directory in the nginx.conf?
Comment: Did you see [this topic](https://github.com/jetstack/cert-manager/issues/2517)? Is it similar to your problem?
Comment: @MikołajGłodziak I had a look through it but couldn't find anything that applied. Seems like most people don't get 401s... I have no idea how to debug as there's no permissions issues in the ingress log. Just the certificate challenge gets the 401 error. I'm wondering if I can somehow add cert-manager to an RBAC group or something...
Comment: you will need to try and figure out what the cert challenge is actually accessing your server with, this should be in the ingres logs, The file isusually called something like access.log, possibly with a domain name in front. Inthat file you will find the HTTP call nginx is recieving.
If you dont find any entries there do some manually to confirm its the right logfile.
The same is true for your backend, but this might have to be configured first.
Once you know the correct call you can verify that you allow acces to that directory and determine who should serve that directory
Comment: Hello @LlewynS. Any updates?
Comment: Not yet I couldn't track down any helpful logs.
Comment: OK I set up a minimal example with no cert manager. I found that if I was trying to connect to my FQDN via my home network it was actually taking me to the router login... I am able to connect via the FQDN now via VPN or mobile phone. This doesn't really resolve cert-manager having 401 issues other than if the routing via the home network is also sending it to the router login rather than ingress....
Answer: In my case clusterissuer was pointing to wrong ingress class
kubectl edit clusterissuer XXXX
solvers:
- http01:
    ingress:
      class: nginternal

Make sure class is pointing to same as ingress.
Answer: The solution to this question was that the router I had was not capable of performing NAT loop back.
Getting a router that had this functionality resolved my issue. Hopefully that helps anyone having issues like this.


Manipular elemento de lista com Jquery

Question: Gostaria de uma dica para fazer com que ao clicar na lista, ele acene a pergunta correta e acene a errada, ou só a certa se a pessoa acertou,

Simulado Detran – Prova Teórica com Gabarito e Respostas

Questão

1º Pergunta do Simulado

Resposta 1 da Primeira Pergunta

Resposta 2 da Primeira  Pergunta

Resposta 3 da Primeira Pergunta

Resposta 4 da Primeira Pergunta <input type="hidden" name="resposta" id="resposta" value="4" />

Comment: Olá Luciano! Coloca o teu código na pergunta como texto. Se quisermos dar um exemplo é mais fácil e não temos de escrever o código à mão.
Comment: Editado amigo, estou quebrando a cabeça pra conseguir o resultado desejado
Answer: Esta resposta é um modelo funcional, você pode customizá-la da forma que desejar:
Obs.: criei uma class .list-group-item-error como exemplo apenas para estilizar os itens errados.

var qtdCarrinho = $("#resposta").val();

function recebeResposta(id){
 if(qtdCarrinho == id){
  alert("Resposta Correta!");
  $("#"+id).addClass('list-group-item-success');
 }else{
  alert("Você errou!\nA resposta correta é a "+qtdCarrinho);
  $(".list-group-item:not(.list-group-item[id="+qtdCarrinho+"])").addClass("list-group-item-error");
  $(".list-group-item[id="+qtdCarrinho+"]").addClass("list-group-item-success");
 }
  }
.list-group-item-error{
 color: #ddd;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Simulado Detran – Prova Teórica com Gabarito e Respostas

Questão

1º Pergunta do Simulado

Resposta 1 da Primeira Pergunta

Resposta 2 da Primeira  Pergunta

Resposta 3 da Primeira Pergunta

Resposta 4 da Primeira Pergunta <input type="hidden" name="resposta" id="resposta" value="4" />

Comment: FUNCIONOU, muito obrigado amigo, apenas essa linha nao pegou, mas ja tenho o q preciso graça a vc, o resto eu consigo, Obrigado

Manipular elemento de lista com Jquery


Lilypond: multi-bar melisma with extender line in `\lyricmode` context

Question: For reasons, I'm setting the lyrics of a song with \lyricmode instead of \lyricsto. However, I'm having trouble getting a long melisma to work in this mode. Something like this:

is easy to achieve with \lyricsto by using an __ as detailed in the manual here, but I haven't found any reference describing how it might be done with \lyricmode. Everything I've tried so far produces errors. Here's an example of one of these failures:
\version "2.19.12"
\language english

lyricMelody = \relative c' {
  \time 4/4
  \key c \major
  \tempo 4=120
  c2 d( | %m1
  e2 f | %m2
  g2) a | %m3
}

textOne = \lyricmode {
  A2 long__ | %1
  __1 | %2
  __2 note | %3
}

\score {
  <<
  \new Voice = "vocals" { \autoBeamOff \lyricMelody }
  \new Lyrics \lyricmode { \textOne }
  >>
}

Answer: Note that an extender line is some sort of articulation/accent on the previous syllable.  So you are looking for
textOne = \lyricmode {
  A2 long2*4__ % 2.5
  note2 | %3
}

It's a bit awkward that you cannot split this note into parts with a more natural length.  You could write something like
textOne = \lyricmode {
  A2 long$(make-duration-of-length (ly:music-length #{ 2 | 1 | 2 #})) %3
  note2 | %3
}

and the guts of that could be turned into a some Scheme function, but the | in its argument obviously would just be window dressing.
Now if you try this, you'll find that there just isn't an extender line.  The reason for that is that the extender line gets its extent from corresponding notes and your lyrics no longer are associated with any particular Voice or other context.
So in order to have the extender line appear (and have lyrics arranged to match the actual notes rather than more or less the time), you also need to write
  \new Lyrics \with { associatedVoice = "vocals" } \lyricmode { \textOne }

in your score.  \lyricsto and \addlyrics automatically set associatedVoice (well, with \addlyrics it's sometimes hit&miss) so you don't need to do so yourself.  But when your durations are not picked from the Voice, you still need it for the attachment points.


Useful sufficient conditions for a topological space to be the underlying space of a topological group?

Question: Here is a question that I have had in my head for a little while and was recently reminded of.

Let $X$ be a (nonempty!) topological space.  What are useful (or even nontrivial) sufficient conditions for $X$ to admit a group law compatible with its topology?

There are many necessary conditions: for instance $X$ must be completely regular.  In particular, if it is a Kolmogorov space it must be a Urysohn space.  It must be homogeneous in the sense that the self-homeomorphism group $\operatorname{Aut}(X)$ acts transitively.  In particular $\operatorname{Aut}(X)$ must act transitively on the connected components of $X$.
It is rather clear though that these conditions are nowhere near sufficient even for very nice topological spaces.  A recent question on this site calls attention to this: even for the class of smooth manifolds there are a sequence of successively more intricate necessary conditions but (apparently) no good sufficient conditions.
What about for other classes of spaces?  Here are two examples: it suffices for $X$ to be discrete (i.e., every set is open) or indiscrete (i.e., only $\varnothing$ and $X$ are open).  These are, of course, completely trivial.  Can anyone do any better than this?  For instance:

If $X$ is totally disconnected and compact (for me this implies Hausdorff), must it admit the structure of a topological group?

Added: as some have rightly pointed out, the above necessary condition of homogeneity is not implied by my assumptions.  So let us assume this as well.  Note that assuming second-countability as well forces the space to be (finite and discrete or) homeomorphic to the Cantor set, which is well-known to carry a topological group structure, so I don't want to assume that.
Comment: If you add the conditions *homogeneous* and *second countable* to your last question then the answer becomes *yes*, because it then either is discrete (hence finite) or it is homeomorphic to the Cantor set which is homeomorphic to a countable product $\prod\{0,1\}$ and thus a group.
Comment: If it's a simply connected closed 3-manifold... :)
Comment: The answer to your specific question is no, for stupid reasons: such a space need not be homogeneous. For example, the space formed by adding an extra isolated point to the Cantor set is compact, totally disconnected, and has just the one isolated point.
Comment: A little better: Any simply connected manifold that covers a Lie group admits the structure of one. Still though... these aren't very good
Answer: In this short paper we have a counterexample for an even weaker statement (it admits no left topological group structure). There are also consistent examples (under CH) that are S-spaces etc. Note that any first countable compact zero-dimensional homogeneous space that is not metrisable is a counterexample, as a first countable topological group is metrisable.
Comment: @Pete: indeed, I was assuming all topological groups to be at least $T_0$ and thus completely regular etc. The OP also considered only completely regular spaces, so this is what I did too.
Comment: thanks for the reference.  The statement "a first countable topological group is metrizable" seems to be false for trivial reasons -- consider e.g. an indiscrete space -- but after a little internet searching I gather it is true for Hausdorff topological groups.  Very interesting.


Multiple site/url integration with same header that doesn't reload when clicking to other sites

Question: I can't seem to wrap my head around this one, and if it can be done I'll be overjoyed.  I'm building a website for a friend's film company, and he requested that there be a header on the top of each specific film site that links to each other film site with the film names.  The header is the exact same on each film site with the exact placement.  Each film site also resides on a different URL, and not subdirectories in the same URL.
Now he also requested that the header NOT refresh when clicking to other sites.  I'm wondering if this is possible, and I'm totally open to the possibility of having all sites reside on the same URL in separate directories.  He also wants the URL of each site to be visible, so not just loading content for each site in the same site and not having the URL in the browser change as well.
The company URL is www.breakwaterstudios.com
The first film URL is www.dinnerwithfred.com
The second film URL is www.inkandpapermovie.com
(I haven't yet integrated the new header on the sites).
However, if the only way to go about doing this is to have the URLs be
www.breakwaterstudios.com/dinnerwithfred
www.breakwaterstudios.com/inkandpapermovie
And then have the individual URLs redirect to those subdirectories that's fine.
The only way I can figure that I could go about not having the page reload when clicking on each header button is to
1) Code the entirety of all film sites into each individual film site and have each individual film site load its respective site elements first (hiding the other sites' elements).  HOWEVER, this would need some sort of javascript/Ajax URL change/rewrite code or something to mask the fact that each film site is really coded into the same site and it's just reloading using jquery .show and .hide commands.  And it could take a long time to load all the other sites' content in the same index.html file.
2) Use jquery .load or iframes even to dynamically load each site underneath the header when clicking on the header buttons.  However, the URL would need to be rewritten just like number 1.
3) As the header div will be in the same position on all sites, and if the only way to get this to work is to reload to the page, have the header not flash off when another film site loads on a separate or same URL.  Have the header appear to not reload when in fact it's loading on a separate website.  There's a fraction of a second where the header disappears and reappears when clicking to another site.
The part of this that seems difficult is the whole URL change.
I suppose what I'm getting at is the possibility of retaining the header on each site without reloading the header when going to each site.  I see that Facebook can do this, however it's all within the same URL of facebook.com.  I've done research and found that perhaps it's impossible across multiple URLs due to the potential of security risks/masking/fraud/etc.
The jquery .load function and iframe could work, but the URL would need to be changed, and if the entirely of the URL can't be changed from dinnerwithfred.com to inkandpapermovie.com, then at least the subdirectory change in the browser window.
Any help would be GREATLY appreciated!!!  Thanks!!!

Dillon
Answer: On modern Browsers you could use the HTML5 history API:

http://diveintohtml5.info/history.html
HTML5 history APi

I think there are some hacks for older browsers as well.
But as you said i think it only works on the same domain. So you'll be stuck with subdirectory urls here.
As for loading the pages itself i think iFrames are really your best bet.
You could also grab the page with http://simplehtmldom.sourceforge.net/ for example if you really want to integrate the pages in yours. It's probably not that easy though to extract the content correctly. There may also be legal issues with that (since you don't own the other sites, do you?)
Comment: This is great!!  Thank you!  I'm reading about the HTML5 history API on the divintohtml5 site and it's really informative.  I'll report back on the success of implementing this API into my sites.  Fortunately I do own the other sites as well, so all elements are mine, so won't have to worry about that.  Thanks again!  And thanks for your quick response too - I love this site!
Comment: Unfortunately I'm having some difficulty implementing the code.  If the site is organized like

www.breakwaterstudios.com/index.html
www.breakwaterstudios.com/dinnerwithfred/index.html
www.breakwaterstudios.com/inkandpaper/index.html

is it even possible to use the History API?  It would be calling the index.html on multiple subdirectories - not just index1.html, index2.html, etc.  When loading in the content into the div it is breaking all embedded links as it's looking for /images rather than /dinnerwithfred/images folder (not looking in the subdirectory)...
Comment: Can it work with multiple subdomains?  How would the code reference these subdomains if all the examples of History API are only looking for small snippets of code instead of loading an entire website?  Because all the websites have folders in their root directory - images, css, etc. the History API is breaking the links as it's bringing the site from www.breakwaterstudios.com/dinnerwithfred to www.breakwaterstudios.com.  For example, and image linked at www.breakwaterstudios.com/dinnerwithfred/images/picture.jpg is loading as www.breakwaterstudios.com/images/picture.jpg.  Thanks for any help!


Content Type: Is it possible to have Term reference on Parent Term instead of Vocabulary?

Question: I have many Parent Terms with child terms on a Vocabulary. I wanna use one of the parent terms on a content type as option. Is it possible to have a Term Reference field on a Parent Term instead of a Vocabulary?
Answer: Create a view that show the taxonomy terms that you want to have as options for selection (you will have to manipulate depth).
Then you create an Entity reference field on your content type that references a taxonomy term. When you add the field it will ask for Entity Selection mode. You select Views (the alternative is Simple), and then you select the view that you created above.
Comment: The entity reference field mentioned is "Entity reference" module?
Comment: @h-l yes it is.
Comment: On the Views, I only see the depth for Content Has Taxonomy Term ID with Depth, which i have to create Content View not Taxonomy. Is there a depth option for Taxonomy Terms View?
Comment: I actually added the Taxonomy Term: Parent Term on Filter Criteria section, and it works.


Show that for any $E\subseteq X$ we have $f(\overline{E})$ $\subseteq$ $\overline{f(E)}$.

Question: Let $(X, d_X)$ and $(Y, d_Y)$ be metric spaces and $f : X → Y$
(a) Assume that $f$ is continuous. Show that for any $E\subseteq X$ we have $f(\overline{E})$ $\subseteq$   $\overline{f(E)}$.
(b) Assume that $f$ is continuous. Show that for any $B\subseteq X$ we have
$\overline{f^{−1}(B)}$ $\subseteq$  $f^{−1}( \overline B)$
I am having a difficulty understading the differences between these closures. Can I pleasure get further explanation as to what the following differ from one another?
$f(\overline{E})$ vs   $\overline{f(E)}$
and
$\overline{f^{−1}(B)}$ vs  $f^{−1}( \overline B)$
Comment: There is an inversion of the order you follow: in the first case you consider the closure of E and then apply f to this set, in the second you apply f to E and then consider the closure of the set you obtain; for random functions the results can be very different.
Answer: $f(x)=x$ for $x>0$, $f(0)=-1$, $f(x)=x-2$ for $x<0$, then with $E=(0,1)$, $\overline{E}=[0,1]$, so $f(\overline{E})=\{-1\}\cup(0,1]$. But $f(E)=(0,1)$ and hence $\overline{f(E)}=[0,1]$, so $f(\overline{E})$ is not contained in $\overline{f(E)}$, one sees from graph that $f$ is not continuous.
Answer: When we apply successive operations on mathematical objects, the order that we apply them in is important. It makes a difference : if I multiply a number by $3$ and subtract $2$, I would most likely get a different number from the one obtained if I subtracted by $2$ and then multiplied by $3$, isn't it?
In this case, image and closure are the two operations. $f(\overline E)$ is the image, of the closure of $E$, while $\overline {f(E)}$ is the closure, of the image of $E$. Note the difference in the order of application : this tells you that most likely, these operations are to differ in their results.
Now, given $f(\overline E)$, you want to show that it lies in $\overline {f(E)}$. So let $x \in f(\overline E)$. This means, that $x = f(y)$ for some $y \in \overline E$, therefore there is a sequence $y_n \in E$ which converges to $y$. By continuity, $f(y_n) \in f(E)$ converges to $f(y) = x$, but then this implies that $x \in \overline {f( E)}$, since we found a sequence converging to $x$.
A similar argument applies for the second question : use definitions, these are the key for beginners in topology.
EDIT : Of course, the counterexample is vitally important. We'll do better :  we will try to find the problem in the converse statement.
Let $x \in \overline {f(E)}$. Then, there is a sequence of points $x_n \in f(E)$ such that $x_n$ converge to $x$. But, $x_n$ are in the image of $f_n(E)$, so there exist $y_n \in E$ so that $f(y_n)$ converges to $x$.
We wanted to prove that $x$ is in the image of the closure of $E$. But there is a clear problem here : $y_n$ need not be convergent! That is, we can't really do anything with this sequence $y_n$, it won't help give us the point whose image we would like to be $x$.
A nice example of this is given by taking $\mathbb N$ with the standard topology, and taking the function $f : \mathbb N \to \mathbb R$ given by $f(x) = \frac 1x$. Take $E = \mathbb N$. Clearly, $\overline E = E$, so $f(\overline E) = f(\mathbb N)  = (0,1]$, while $\overline {f(E)}$ is just the closure of $(0,1]$, which is $[0,1]$. The two sets are clearly different.
Aside : If it turns out that for all $E$, we have equality above, if and only if, $f$ is a continuous bijection whose inverse is also continuous i.e. $f$ is a homeomorphism.
Comment: Thank you for the explanation. I am able to follow the proof, but I still don't understand why may the closure of the image be bigger than the image of the closure, is there a numerical example that can illustrate this? or a counterexample that shows the other way around may not always be true?
Comment: I am actually adding that as you comment. I will get get back to you in a few minutes or so.
Comment: You may see the edit.
Comment: This makes a lot of sense, thank you very much!
Comment: @астонвіллаолофмэллбэрг I wonder if there is an example of this with $\overline{E} \neq E$ ?
Comment: @krirkrirk That's more interesting! We  will have to think about that.
Answer: To show that the inclusion could be strict : take $f = Arctan$ and $E = \Bbb R$. Then $f(\overline{E}) = (-\frac \pi2, \frac \pi 2) $ while $\overline{f(E)} = [-\frac \pi2, \frac \pi 2]$.


Too many indices for array error - scipy.intergate.solve_ivp(method = Radau) gives error

Question: I am supposed to solve a ODE as follows:
def dHdt(t, H):
  if H>H_p(t) and data2_sleep(t)>0:
    return -0.323*24
  elif H>H_p(t) and data2_sleep(t)==0:
    return 0.116*24
  elif H<=H_m(t) and data2_sleep(t)>0:
    return -0.278*24
  elif H<=H_m(t) and data2_sleep(t)==0:
    return 0.150*24
  elif H<=H_p(t) and  H>H_m(t) and data2_sleep(t) > 0:
    return -0.274*24
  elif H<=H_p(t) and  H>H_m(t) and data2_sleep(t) == 0:
    return 0.096*24

where H_*p, H_m, data2_*sleep are objects that are results of interpolation using scipy.interp1d .
For the solver, I used solve_ivp but methods as 'RK45' or 'LSODA' were not giving good results (by which I mean , I have a approximate solution at hand and comparing with it , results differ a lot. Moreover, another solver odeint can do much better job except it also is unstable I think) and wanted to use stiff solvers as Radau and BDF but when running below
H_new = solve_ivp(dHdt, t_span = [0, 50], y0 = [H0], method = 'Radau', t_eval = t_span)

I get the following error
IndexError                                Traceback (most recent call last)
<ipython-input-107-6595d5c7194d> in <module>
----> 1 H_new = solve_ivp(dHdt, t_span = [0, 50], y0 = [H0], method = 'Radau', t_eval = t_span)

5 frames
/usr/local/lib/python3.8/dist-packages/scipy/integrate/_ivp/common.py in _dense_num_jac(fun, t, y, f, h, factor, y_scale)
    325     h_vecs = np.diag(h)
    326     f_new = fun(t, y[:, None] + h_vecs)
--> 327     diff = f_new - f[:, None]
    328     max_ind = np.argmax(np.abs(diff), axis=0)
    329     r = np.arange(n)

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed

indeed H0 is a single number but in the dHdt there is no indexing and indexing issue is raised by solver itself. (Also, only those stiff solvers make this error but if you change method to RK45 or etc it works).
What do you think is the reason for this error?
Comment: Full error message please!
Comment: You've dug into the source code more than I have.  `f[...,None]` would run if `f` is indeed 0d, but I don't know what this `f` is - or how it relates to your inputs.
Comment: The solver might call the ODE function outside the integration interval. Are the interpolation functions able to handle this? You might catch this with a default return value in the ODE function. // Or in other words, use a debugger to find the inputs to `dHdt` at the point of error and explore the return value of it. I suspect it is `None`, leading to an zero-dimensional numpy array in the wrapper.
Comment: The return value for `fun`, i.e. first positional arg to `solve_ivp`, supposedly must be `array_like` and not just a float.  From https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html "fun must return array_like with shape (n,)".   Note that `H` should also be array_like, yet you are presumably treating it like a float. Without the full code, or at least a representative look at what the other functions do, it is hard to tell for sure.
Answer: Turns out for Radau and some solvers output must be in brackets,[]. For other solvers it is okay not to.
Comment: Instead of simply providing the answer directly, try writing a detailed comment that explains the solution, as long as the explanation is not too lengthy.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Some burning questions on First-order logic from an amateur

Question: I'm currently taking an introductory course in Mathematical logic(prerequisites is only advanced calculus) and my lecture notes are based on Enderton's book 'Mathematical Introduction to Logic'
Suppose $\varphi$ is deducible from $\Gamma$ and we are seeking a proof of this fact. There are several cases, one of the which is $\varphi=\forall x \psi$. According to the book, if $x$ should occur free in $\Gamma,$ there will be a variable $y$ such that $\Gamma \vdash \forall y \ \psi ^{x}_{y}$ and $\forall y \ \psi^{x}_{y} \vdash \forall x \ \psi.$
May I know how do we prove that there will be a variable $y$ such that $\Gamma \vdash \forall y \ \psi ^{x}_{y}$ and $\forall y \ \psi^{x}_{y} \vdash \forall x \ \psi \ ?$ The author then refers one to Re-replacement lemma but I can't see how are both related. Could anyone instruct me please?
Thank you.
Comment: About Re-replacement lemma on page 130, Ex.9 (b) : Show that if $у$ does not occur at all in $\varphi$, then $x$ is substitutable
for $y$ $\varphi^{x}_{y}$ and $(\varphi^{x}_{y})^{y}_{x}=\varphi$ (hint: use induction on $\varphi$) the proof works by induction according the formation rules for formulae (page 74-on) : (i) if $\varphi$ is *atomic* without $y$ you cannot put $x$ in place of it: so, nothing change and the "double subst" gives you $\varphi$; (ii) with connectives, you use the induction hypo: if it works e.g. for $\alpha$ and $\beta$, it will works also for $\alpha \land \beta$. 1/2
Comment: (iii) the last case take care of quantifiers; consider $\forall$ and let $\varphi := \forall z \psi$. If $y$ does not occur in $\varphi$, for sure $y \ne z$ and there is **no** quantifier $\forall y$ in $\psi$; thus, effecting the subst into $\psi$, there is no danger that $y$ get captured by a quantifier inside $\psi$, altering the meaning of the formula. 2/2
Comment: Can you give us the info for the page of Enderton's book where to locate the proof ? Re-replacement lemma [page 130] says that (roughly speaking) with free vars the "change" of $x$ with $y$ and back, in general, is not correct, because the "reverse" operation do not restore the original formula. Think to $\varphi := x=y$; with $\varphi^{x}_{y}$ we will have $\varphi' := y=y$ and with $\varphi'^{y}_{x}$ we will have $\varphi'' := x=x$, which is not the original one.
Comment: @MauroALLEGRANZA: Thanks for reply. I'm referring to pg120. Also, could you advise me on how to prove Re-replacement lemma on pg130(Qn9b) >
Comment: The matter seem obscure but you must re-read the comments by Enderton. (i) page 117 : "The generalization theorem reflects our informal feeling that if we can prove '- - x - -' without any special assumptions about $x$, we then are entitled to say that 'since $x$ was arbitrary, we have $\forall x$ - - x - -' ". (ii) "the foregoing examples illustrate a sort of interchangeability of constant symbols with free variables. This interchangeability is the basis for the following variation on the generalization
theorem [i.e.Th 24F (Generalization on Constants)]". 1/2
Comment: (iii) page 123 : with Corollary 24G, we use a "generic" constant in place of the variable $x$ in $\varphi$. If this constant $c$ does not occur in the assumption $\Gamma$ of the proof, it "works like" a variable; thus, we may "generalize" on it. 2/2
Comment: Comment about page 120: 2. Suppose that $\varphi$ is $\forall x \psi$. If $x$ does not occur free in $\Gamma$, then it
will suffice to show that $\Gamma \vdash \psi$ (Even if $x$ should occur free in $\Gamma$, the difficulty can be circumvented. There will always be a variable $у$ such that $\Gamma \vdash \forall y \psi[x/y]$ and $\forall y \psi[x/y] \vdash \forall x \psi$). **Comm.** (i) $x$ must not be free in $\Gamma$ because otherwise, with $\Gamma = \{ \alpha(x) \}$ we may have $\alpha(x) \vdash \forall x \alpha(x)$, and this in not sound (are you able to find a counterexample ?). 1/2
Comment: (ii) Even if $x$ should occur free in $\Gamma$, the difficulty can be circumvented: we have at our disposal an infinite supply of ind var $x_i$. A derivation is a finite sequence of formulae; thus, it may use at most a *finite* number of variables, and we are always able to find a "new" one not already used in the proof. 2/2
Comment: @Mauro ALLEGRANZA: Thanks for the detailed response. For  the last case of the induction proof(to the Re-replacement lemma), where $\varphi:=\forall z \  \psi$ does not contain $y,$ so $\psi$ does not contain $y.$ Suppose $x\neq y,$ then $(\forall z \ \psi)^{x}_{y}=\forall z(\ \psi^{x}_{y})$ and so $((\forall z \ \psi)^{x}_{y})^{y}_{x}=\forall z((\psi)^{x}_{y})^{y}_{x} = \forall z \ \psi,$ where the last step follows from induction hypothesis applied on $\psi$.  Is my argument correct?
Comment: Basically, if $\varphi$ does not contain $y$, as you say, also $\psi$ does not. Thus, basically, we have "nothing to calculate" : the double substitution does not act on $\psi$, so does not act on $\varphi$.
Answer: I suppose that you are working with Corollary 24G, page 124, of Herbert Enderton, A Mathematical Introduction to Logic (2nd ed Harcourt - 2001) :

Assume that $\Gamma \vdash \varphi^{x}_{c}$, where the constant symbol $c$ does not occur in $\Gamma$ or in $\varphi$. Then $\Gamma \vdash \forall x \varphi$, and there is a deduction of $\forall x \varphi$ from $\Gamma$ in which $c$ does not occur.

The proof invoks Theorem 24F (Generalization on Constants) [page 123].
The motivation of the Corollary is [page 124] : "We want to apply Theorem 24F in circumstances in which not just any variable will do. In the following version, there is a
variable $x$ selected in advance."
From the hypotheses $\Gamma \vdash \varphi^{x}_{c}$, where the constant symbol $c$ does not occur in $\Gamma$ or in $\varphi$, Theorem 24F gives us a deduction (without $c$) from $\Gamma$ of $\forall y ((\varphi^{x}_{c})^{c}_{y})$ where $y$ does not occur in $\varphi^{x}_{c}$.
But since $c$ does not occur in $\varphi$,

$((\varphi^{x}_{c})^{c}_{y}) = \varphi^{x}_{y}$.

This substitution works, because there are no occurrences of $c$ in the "original" formula $\varphi$; thus, substituting $c$ in place of $x$, and then $y$ in place of $c$, we do not have "unpleasant effects".
Thus, we may conclude that :

$\Gamma \vdash \forall y \varphi^{x}_{y}$ --- (a).

The last step in the proof is to show that :

$\forall y \varphi^{x}_{y} \vdash \forall x \varphi$.

To do this, he invokes Axiom 2 [see page 112] : $\forall y \alpha \rightarrow \alpha^{y}_{t}$.
With $\varphi^{x}_{y}$ in place of $\alpha$ and $x$ in place of $t$, we have as $\alpha^{y}_{t}$ the result $(\varphi^{x}_{y})^{y}_{x}$ , i.e. $\varphi$.

The proof now call for a formal verification through Re-replacement lemma.

Having verified this, we have $\vdash \forall y \varphi^{x}_{y} \rightarrow \varphi$.
Then the following generalization is also an axiom [see page 112] :

$\vdash \forall x (\forall y \varphi^{x}_{y} \rightarrow \varphi )$.

By Axiom 4 ($x$ is not free in $\forall y \varphi^{x}_{y}$), we have :

$\vdash \forall y \varphi^{x}_{y} \rightarrow \forall x \varphi$.

Thus, from (a) above, we may finally conclude :

$\Gamma \vdash \forall x \varphi$.


Alter Fieldable Panels Pane form

Question: Im using Panopoly, and have created a new Fieldable Panels Pane (FPP) bundle for a specific content type.
I notice that all preset Panopoly FPP's have a check box labelled 'Make title a link' inside a fieldset called 'General Options', which is also automatically added to my new bundle, and I can't for the life of me work out how to disable it!
For reference, this field is visible through the Panels IPE as well as the traditional /admin/structure/fieldable-panels-panes/manage/BUNDLE-NAME/add.
Does anyone know how I can isolate and disable this option on a per-bundle level?
Thanks!
Answer: Almost all Drupal forms can be edited using hook_form_alter(), specifying the form using its id:
Hide "Make title a link" for all fieldable panels panes:
/**
 * Implements hook_form_alter().
 *
 * Simplify form for fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    $form['link']['#access'] = FALSE;
  }
}

Hide "Make title a link" for all fieldable panels panes of the type "your_bundle":
/**
 * Implements hook_form_alter().
 *
 * Simplify form for 'your_bundle' fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    if ($form['#bundle'] == 'your_bundle') {
      $form['link']['#access'] = FALSE;
    }
  }
}

Answer: There is a new sandbox Simplify Extra which has integration with Fieldable Panels Panes.

Alter Fieldable Panels Pane form


Ao clicar no botão para chamar função javaScript o botão sume

Question: Estou tentando fazer um código para gerar número aleatório em javaScript, coloquei um botão para poder chamar a função, chama a função corretamente, entretanto tenho que atualizar a página para poder visualizar o botão, gostaria de deixar o botão fixo sem precisar atualizar a tela, mas não está dando certo.
Segue o código

    <title>Numero aleatorio</title>

<button type="button" id="nav-button" onclick="Mudarestado('minhaDiv')">Sortear número</button>

         <title>Joao e Maria</title>

        <button type="button" id="nav-button" onclick="Mudarestado('minhaDiv')">Sortear número</button>

Answer: Você não está atualizando a tela. Esse efeito se dá já que você está utilizando o document.write para escrever na tela.
O funcionamento do document.write é simples: basicamente, enquanto a página está carregando, ele insere o conteúdo normalmente sem alterar o restante da página. No entanto, se o documento já foi 100% carregado, quando o document.write for invocado, todo o conteúdo da página será substituído pelo conteúdo que você passou como argumento para esse método. Você pode saber mais sobre essa API aqui.
Então, para resolver isso, você tem que usar algo além do document.write. Vamos usar a técnica de criar um novo elemento e em seguida inseri-lo ao final da página.
Algo assim:

function sortNum() {
  // Gera um número aleatório no intervalo 0~99:
  const random = Math.floor(Math.random() * 100)

  // Cria um elemento
:
  const div = document.createElement('div')

  // Adiciona o número escolhido como texto da
:
  div.textContent = random

  // Adiciona (append) a
 criada ao final do :
  document.body.appendChild(div)
}
<button id="my-button" onclick="sortNum()">Sortear um Número</button>
Answer: Quando usa document.write() ele sobrescreve o conteúdo da página, por isso seu botão some.
Crie um div para receber o resultado e então modifique a propriedade innerHTML para mudar o conteúdo do div.

     <title>Numero aleatório</title>

    <button type="button" id="nav-button" onclick="Mudarestado('minhaDiv')">Sortear número</button>

       Sorteio


Nexus 5 not being detected on pc

Question: Till yesterday my nexus 5 was connecting,
Now when last it was connected to my brother's computer here's what i did:
I was trying to take a 20 gb file from his comp so didn't have enough space, so what i did was figure all i need is photos backed em at his comp and pressed ctrl + a on my internal memory and deleted everything i mean everything in my phone memory to make space, now took the file came back home to my pc and Zoink my nexus phone is not being detected, i mean i went device manager and there's a mtp sign sitting with exclamation mark, now before you say anything here me out.
To keep it short and sweet have read a lot of posts done a lot of things and none worked, did mtp ptp switch, device manager uninstall and reconnect, turn on usb debug then install drivers downloaded from google, turn off usb debugging, Belive me i done most of it but none of em is working, m betting this has something to  do with my ctrl + a delete on my internal memory and if so wht's the solution.
Comment: You might get better feedback @ http://android.stackexchange.com/
Answer: I had the same problem and here is how I solded it:

On the Device Manager, right-click the device entry, and click Uninstall
On the Confirm Device Removal dialog box, click the Delete the driver software for this device option to delete the driver package that was used for the device.
Unplug/replug your device

This did the work for me. Hope that helps you.

Nexus 5 not being detected on pc


How to learn from new data when a gradient descent optimization method has been used?

Question: Consider any situation in which you ultimately use a gradient descent optimization method. Assume that you've successfully created a hypothesis which fits your training set and works fine.
After some time your algorithm receives more and more new data, which it has to learn from.
Questions:
1) Can this algorithm continue to be considered supervised ?
2) If so, is there a way to learn from the new data without iterating again through all ( new + old ) data ?
Answer: There is no generic answer to your question, as this is a very broad problem/issue in machine learning, you should do research in two topics:

Online learning - this is the family of algorithms/models that can learn from the new data without complete re-learning. The simplest such model is naive bayes, but even SVMs can be trained this way
Concept drift - it is a more advanced topic which arises when not only new data is being added but also old data can get "wrong" (is no longer actual, true)

There are dozens of approaches to both problems (and it does not really matter that you use gradient descent, it is more important what exact model are you fitting), everything depends on the particular dataset and application.
So in general:

If your problem seems to be completely stationary, nothing really changes with time, and you are satisfied with your results, you can ignore new data
If problem seems to be rather stationary (small fluctuations) or you are not satisfied with its accuracy - try online learning (or, if for your particular model it is impossible - retrain the whole model once for a while)
If problem seems to be very dynamic (large fluctuations) - consider concept drift solutions

And yes, it is still supervised learning, although there are also semi- and un- supervised algorithms used for dealing with concept drift.


Node app with different environments in jenkins

Question: I'm working actually on a node web application for my master's degree project. I need to make it like a real project with different environments : Dev, Test and Prod in Jenkins
This is my docker ps :
enter image description here
And this is my Jenkinsfile :
enter image description here
Till now I work only in one environment and I do everything on it. I don't know how to do ?
Remarque : I didn't install Mocha and Katalon yet for test.
Thanks by advance.
Mahmoud
Answer:
Create git branches for each environment.
Define criteria for merging from one branch into the next.
Create Jenkins pipelines to enforce this criteria.
Restrict user access to certain branches.

This process acts as a barrier to stop developers from promoting buggy code straight to production.
Comment: Hey, thanks for your reply but I think more details should be very helpful.


Is Entity Translation module compatible with Internationalization and can they be used to translate menus?

Question: I installed the entity translation module for Drupal 7 and it works fine.
However, I also want to translate menus and I found that Internationalization module can do that.
The question is: are they compatible at all? If I install internationalization module will it not break the entity translation one?
Answer: Yes, they are compatible.
Entity Translation deals with entity translations, and menus in Drupal 7 are not entities, there's no clash between Entity Translation and Internationalization modules.


Definition of Ergodicity in Theodoridis' Machine Learning

Question: This is related, but is not the same as https://stats.stackexchange.com/questions/319190/wide-sense-stationary-but-not-ergodic.
Note that I am not assuming stationarity. Theodoridis, in his Machine Learning (2nd ed., p. 44), states the following:

Definition 2.3 (Ergodicity). A stochastic process is said to be ergodic if the complete statistics can be determined by any one of the realizations.

Theodoridis then goes on to state that ergodicity implies stationarity with a vague explanation that I can't seem to parse through:

In other words, if a process is ergodic, every single realization carries identical statistical information and it can describe the entire random process. Since from a single sequence only one set of PDFs [probability density functions] can be obtained, we conclude that every ergodic process is necessarily stationary.

What does ergodicity mean in this situation? In particular, the "complete statistics" phrase is throwing me off. I get the feeling that Theodoridis isn't referring to the
$$\text{"}\mathbb{E}[g(T) \mid \theta] = 0 \implies \mathbb{P}(g(T) = 0 \mid \theta) = 1$$
for all $\theta$" definition of a complete statistic $T$ for $\theta$.
I recently completed a measure-theoretic probability sequence, so if this requires measure-theoretic probability tools to make precise, please use those tools in answering this question.
Some searching talks about how a "time-average is equal to the ensemble average," but I'm not really understanding this explanation and how it relates to the definition in Theodoridis' text.
Sources that I can use to supplement this with a more detailed coverage of the theory would be appreciated as well. Hamilton's Time Series Analysis  (as well as most of my other texts and most coverage I find online on this topic) only covers ergodicity with the assumption that we have stationarity to begin with. Robert and Casella's Monte Carlo Statistical Methods only discuss ergodicity in the context of Markov chains.
Answer: This is simply a quite careless definition of ergodicity!
Here "complete" is used a loose way to mean that you can determine all that there is to determine about some statistics in question.
Surely, the author is talking about a specific statistics and indeed in the same page we have $\hat \mu_N$ and as written "where the sample mean operation can be significantly simplified".
Why is it quite careless then?
Because this is not how it works: we are not going to get the same value for all integers $N$, as the author implies, but can only approximate by taking $N$ large and we know that the approximation converges to the same value for any realization, that is, any choice of particular values (samples).
In more mathematical terms, this is indeed (a failed) try at simplifying the big picture of ergodic theory in which ergodicity is equivalent to the equality of time and space averages.


Ubuntu desktop 22.04 LTS - ethernet connection not working

Question: I have been installed ubuntu desktop 22.04 LTS with ethernet connetion on my Dell Inc. Latitude E7240 computer, it worked properly,
but today in time of work, the ethernet connection is not working
In windows 10 it works properly, wirless connection it works too!
Only cable network connection is not working in my ubuntu 22.04
Anyone can help? Please!.
 rfkill list all

showed
1: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
2: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
3: dell-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: no
4: nfc0: NFC
    Soft blocked: no
    Hard blocked: no

.
sudo lshw -sanitize -c network

showed
*-network DESABILITADO
       descrição: Ethernet interface
       produto: Ethernet Connection I218-LM
       fabricante: Intel Corporation
       ID físico: 19
       informações do barramento: pci@0000:00:19.0
       nome lógico: eno1
       versão: 04
       serial: [REMOVED]
       capacidade: 1Gbit/s
       largura: 32 bits
       clock: 33MHz
       capacidades: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuração: autonegotiation=on broadcast=yes driver=e1000e driverversion=5.15.0-33-generic firmware=0.7-3 latency=0 link=no multicast=yes port=twisted pair
       recursos: irq:46 memória:f7e00000-f7e1ffff memória:f7e3c000-f7e3cfff porta de E/S:f080(tamanho=32)
  *-network
       descrição: Interface sem fio
       produto: Wireless 7260
       fabricante: Intel Corporation
       ID físico: 0
       informações do barramento: pci@0000:02:00.0
       nome lógico: wlp2s0
       versão: 73
       serial: [REMOVED]
       largura: 64 bits
       clock: 33MHz
       capacidades: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuração: broadcast=yes driver=iwlwifi driverversion=5.15.0-33-generic firmware=17.3216344376.0 7260-17.ucode ip=[REMOVED] latency=0 link=yes multicast=yes wireless=IEEE 802.11
       recursos: irq:50 memória:f7d00000-f7d01fff

Answer: I runned bellow:
 sudo systemctl restart NetworkManager

Comment: Unfortunately your question/answer(?) is totally 'off topic' here because you asked it in the wrong part of the metaverse. It would be much better placed at https://askubuntu.com/
Comment: thanks for show me how I can do if future in this case


Selecionar elemento através de parte de atributo contido nele

Question: Possuo um elemento, por exemplo:

E, para selecioná-lo, poderia fazer da seguinte maneira:
$(".teste[data-info='isflaolatesteum']")...

Porém, eu quero selecionar esse elemento através do atributo (data-info) só que eu possuo apenas parte da string contida no atributo. Como no exemplo acima, gostaria de selecionar todos os elementos que contenham teste no meio do atributo, ou seja, seria como um indexOf no atributo.
Isso é possível?
Comment: No começo é tudo muito lindo, mas a dor de cabeça vem depois, recomendo que leia isso.  http://intuio.at/en/blog/dont-use-data-attributes-to-find-html-elements-with-js/
Answer: Podes usar o seletor contains do jQuery para isso.
*= no seletor de atributo quer dizer "que contêm o texto".
No teu caso seria
$(".teste[data-info*='teste']")

Exemplo: http://jsfiddle.net/t8n66jb1/
Comment: Perfeito! Obrigado!


Can I create sub-folders in android drawbale folder for images

Question: I have a large number of images in diffident folder. Can I place these folder in 'drawable' folder or there is any other pattern to add sub-folders in 'drawables'.
Comment: duplicate question http://stackoverflow.com/questions/1077357/can-the-android-drawable-directory-contain-subdirectories
Comment: You can create sub folders.. but you cannot access them via "R.drawable.subfoldername.drawablename".. You can only access it by "R.drawable.drawablename".
Answer: No, the resources mechanism doesn't support subfolders in the drawable directory, so yes - you need to keep that hierarchy flat.
However you can use the assets folder and have sub directories in there and load images that way.
Sample Code
<code>InputStream is = null;
try {
    is = this.getResources().getAssets().open("test/sample.png");
} catch (IOException e) {
    ;
}

image = BitmapFactory.decodeStream(is);
</code>
Answer: By the structure of Android, we can place the images under drawable folders only.
We have the choice to create subfolder, but unable to access them. Depends upon the density of the images we can place images inside the relevant folder: see below:
The folder names need to be :
<code>/drawable-ldpi For low density screens
/drawable-mdpi For medium density screens
/drawable-hdpi For high resolution screens
/drawable-xhdpi For extra high resolution screens
</code>
/drawable should be reserved for assets that you don't either care which device or for xml drawable assets
Then on top of that you can provide different resources based on configuration by using config qualifiers, you can read all about it here http://developer.android.com/guide/topics/resources/providing-resources.html
for instance, you can have high resolution assets for landscape with a folder
<code>/drawable-land-hdpi
</code>
Hope that helps


How to avoid "StaleElementReferenceException" in Selenium?

Question: I have a StaleElementReferenceException.
I found How to avoid "StaleElementReferenceException" in Selenium?. I tried to understand and fit it to my code.
By ordersBy = (By.id("subtab-AdminParentOrders"));
        WebElement orders = driver.findElement(ordersBy);
        orders.click();
        public boolean retryingFindClick () {
            boolean result = false;
            int attempts = 0;
            while (attempts < 2) {
                try {
                    driver.findElement(By.id("subtab-AdminParentOrders")).click();
                    result = true;
                    break;
                } catch (StaleElementReferenceException e) {
                }
                attempts++;
            }
            return result;
        }

First compilation error. What should I paste as argument? Why is a semicolon expected?

I wrote this method in main. Maybe that is why return is denied. How can I adapt this method to my code (in main)?
Comment: If you really are trying to define a method inside bory of another method, then: you can't do that. Method would be defined somewhere outside. And please don't post images. Post actual code instead.
Answer: The way I see it you have created a method inside another method, it doesn't work like that. Also get retryingFindClick() out into class body and Just replace try code with following, it should work:
try{
         WebElement elem = driver.findElement(By.id("subtab-AdminParentOrders"));
         elem.click();
         result = true;
         break;
   }
   ...

How to avoid “StaleElementReferenceException” in Selenium?


Right-continuity of filtrations

Question: To this day I still ignore the reason why ,to define ,for instance, a filtration that is continuous to the right (based on an existing one),We write:
$D_{t}=D_{t+}^{0}=\bigcap_{\epsilon>0} D_{t+\epsilon}^{0}$ (isn't $\bigcap_{\epsilon \geq \alpha} D_{t+\epsilon}^{0}= D_{\alpha}^{0}?$)
instead of just writing
$D_{t}=lim_{\epsilon \rightarrow 0^+ } D_{t+\epsilon}^{0}$
(there is something similar with unions too)
Thank you in advance for your answers and insights
Comment: How do you define $\lim_{\epsilon \to 0} \mathcal{F}_{\epsilon}$ for some family of $\sigma$-algebras $\mathcal{F}_{\epsilon}$? (That's what you need to define in order to write $\lim_{\epsilon \to 0+} D_{t+\epsilon}^0$.)
Comment: Thanks saz. I see what you mean although I can present it in rigorous terms. What I have found confusing was the use of intersection the while we know that in the case of filtrations for instance we have the inclusion $D_r \subseteq D_s$ for $r \leq s$. besides the definitions found in textbooks of limsup and liminf to define the limits (when they exist) are not natural/intuitive and well explained in books. I bet first mathematicians haven't invented those notions out of nowhere.
Comment: Well, $\bigcap_{\epsilon>0} D_{t+\epsilon}^0$ is the smallest $\sigma$-algebra which contains all $D_{t+\epsilon}^0$, $\epsilon>0$. Obviously, we can introduce a new notation and write $$D_{t+}^0 = \lim_{\epsilon \to 0} D_{t+\epsilon}^0,$$ but what's the advantage of this? (Mind that $\limsup$ and $\liminf$ are defined for sequences of sets and not sequences of $\sigma$-algebras; and both notions *have* a natural meaning.)
Comment: Again thank you for pointing out at me confusing sets and filtrations :).
Could you please give me an example of a trivial filtration that doesn't respect continuity?
Answer: By definition,
$$D_{t+}^0 = \bigcap_{\epsilon>0} D_{t+\epsilon}^0$$
is the smallest $\sigma$-algebra which contains $D_{t+\epsilon}^0$ for all $\epsilon>0$. We can introduce a new notation and write
$$D_{t+}^0 = \lim_{\epsilon \to 0} D_{t+\epsilon}.$$
(Mind that we have to give $\lim_{\epsilon \to 0}$ a meaning; in general, it is not clear how to define the limit of a sequence of $\sigma$-algebras.)
An easy example for a filtration which is not right-continuous is the following: Take
$$D_t := \{\emptyset,\Omega\} \qquad \text{for all} \, \, t \leq 1$$
and
$$D_t := \mathcal{A} \qquad \text{for all} \, \, t>1$$
for some (non-trivial) $\sigma$-algebra $\mathcal{A}$ on $\Omega$. Then
$$D_{1+} = \mathcal{A} \neq D_1 = \{\emptyset,\Omega\}.$$
More sophisticated examples are $\sigma$-algebras generated by stochastic processes, i.e.
$$D_t := \sigma(X_s; s \leq t), \qquad t \geq 0;$$
they are (in general) not right-continuous.
Two remarks:

One may ask: Why do we need right-filtrations? Well, one typical application is the following: Suppose that $X \in L^1$ is a random variable and $(D_t)_{t \geq 0}$ a right-continuous filtration. Then $$\lim_{s \downarrow t} \mathbb{E}(X \mid D_s) = \mathbb{E}(X \mid D_t).$$
Even if a given filtration is not right-continuous, it is often possible to enlarge the filtration in such a way that it becomes right-continuous; therefore many authors assume ("without loss of generality") that the given filtration is right-continuous (the so-called usual conditions).

Right-continuity of filtrations


CakePHP - Call to a member function allow() on a non-object error

Question: I am creating one login authentication app in CakePHP
and getting this Fatal error: Call to a member function allow() on a non-object in /var/www/cakephp1/app/Controller/users_controller.php on line 5
and this is my controller code
users_controller.php
<?php
class UsersController extends AppController {
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }
    public function add() {
        if (!empty($this->data)) {
            $this->User->create();
            if ($this->User->save($this->data)) {
                $this->Session->setFlash('User created!');
                $this->redirect(array('action'=>'login'));
            } else {
                $this->Session->setFlash('Please correct the errors');
            }
        }
        $this->set('groups', $this->User->Group->find('list'));
    }
    public function login() {
    }
    public function logout() {
        $this->redirect($this->Auth->logout());
    }
    public function dashboard() {
        $groupName = $this->User->Group->field('name',
            array('Group.id'=>$this->Auth->user('group_id'))
        );
        $this->redirect(array('action'=>strtolower($groupName)));
    }
    public function user() {
    }
    public function administrator() {
    }
    public function manager() {
    }
}
?>

app_controller.php
<?php
class AppController extends Controller {
    public $components = array(
        'Acl',
        'Auth' => array(
            'authorize' => 'actions',
            'loginRedirect' => array(
                'admin' => false,
                'controller' => 'users',
                'action' => 'dashboard'
            )
        ),
        'Session'
    );
}
?>

View login.ctp
<?php
echo $this->Form->create(array('action'=>'login'));
echo $this->Form->inputs(array(
    'legend' => 'Login',
    'username',
    'password',
    'remember' => array('type' => 'checkbox', 'label' => 'Remember me')
));
echo $this->Form->end('Login');
?>

I am using CakePHP version 1.3
Comment: Is your App Controller in the app/ directory like it should be in Cake1.3 ?
Comment: @Dave yes its in cake1.3
Comment: And your AppController file is in the app/ directory, not the app/controllers directory, yes?
Answer: 1.Solution: All what you need to do is to add this line in your UsersController:
public $components = array('Auth');

Or
2.Soluton: In UsersController:
App::uses('AppController', 'Controller');

class UsersController extends AppController {

}

and then in AppController:
public $components = array('Auth');

Answer: There are two common causes for this type of error:
The App controller file is not being loaded
If the AppController class doesn't exist - Cake will use a fallback for it taken from the core - it's just an empty class. For the error in the question to occur - the Auth component hasn't been loaded, the most likely reason for that is that the file app/app_controller.php either doesn't exist or a different AppController class file was loaded before looking for it.
This can be confirmed using get_included_files, e.g.:
class UsersController extends AppController {

    public function beforeFilter() {
        if (!isset($$this->Auth)) {
            debug(get_included_files());
            die;
        }

Look for which app_controller.php file has been loaded - if it's not the file containing the class in the question, that's the problem.
Overridden constructor, not calling parent
Good children always call their parents :)
If the constructor (or any method) is overridden and does not call the parent function, then e.g. the components property won't get merged/set correctly or component classes won't be initialised.
If the right app_controller.php file is being loaded focus on the methods defined within the controller classes and check they are calling parent::methodname (for the users controller, and the app controller). Specifically verify that the Controller::__construct is being called since that's where most of the class initialization logic is in 1.3.
Answer: The error sounds like the loading of the Auth-component failed. Have you tried removing the settings from the $components array and see if the error persists?
Comment: This kind of guess-answer is usually better as a comment (like mine above).  If it turns out to be correct, the person asking can give you more details of why it was correct, and then you can put it in an answer to be accepted.  This helps questions from filling up, and from people ignoring the question due to already having an answer.
Comment: Fair point, thanks for letting me now. Although I must confess I did look for the comment-link but couldn't find it (I do see 'link' and 'edit'), though I'm convinced I've seen that button before...
Comment: You might not yet have the ability to comment with a rep score of 1. (didn't think of that when I mentioned it to you)
Comment: @Joep how can i load Auth-component
Comment: @AjayPatel: I'd suggest making the $components array look like `array('Acl', Auth', 'Session')` And then check to see if your error persists. (to exclude the config options you're specifying there as the cause of this error (which seems unlikely, but still))
Comment: I assume the error occurs on the call APP/users/<someAction/ ?
Comment: @Dave Indeed, I just found out that commenting on other people's questions/answers is a privilege gained at 50 reputation.


In MDX, the price rank of a given number is 0

Question: I have an OLAP cube containing the type price sum for each of number.
Using MDX, how can I output the rank of a given number?
Result should be as follows:

Heare is the MDX query, but all rank values are 0. What is wrong in query?
WITH MEMBER [Measures].[Rank Sum of price] AS
   RANK([NUM_1].[All Numbers].CURRENTMEMBER
   ,[NUM_1].[All Numbers]
   ,[Measures].[Sum of price])

SELECT
 {
  [Measures].[Sum of price]
, [Measures].[Rank Sum of price]
 }
 ON COLUMNS,

  [NUM_1].[All Numbers]
 ON ROWS
 FROM schema1

Answer: Maybe do your ordering in a custom set before hitting the rank function:
WITH
  SET OrderedNums AS
    Order
    (
      [NUM_1].[All Numbers].[All Numbers].MEMBERS
     ,[Measures].[Sum of price]
     ,BDESC
    )
  MEMBER [Measures].[Rank Sum of price] AS
    Rank
    (
      [NUM_1].[All Numbers].CurrentMember
     ,OrderedNums
    )
SELECT
  {
    [Measures].[Sum of price]
   ,[Measures].[Rank Sum of price]
  } ON 0
 ,[NUM_1].[All Numbers].[All Numbers].MEMBERS ON 1
FROM schema1;


How to report exceptions and UncaughtExcept with detail description to Google Analytics v4?

Question: I know this question has been asked many times with different forms but didn't find any working and updated solution that works with GAv4.
So far I've followed these link1 and link2, for tracking exception reports with some custom changes,
<code>public class MyApplication extends Application {
    /**
     * The Analytics singleton. The field is set in onCreate method override
     * when the application class is initially created.
     */
    private static GoogleAnalytics analytics;

    /**
     * The default app tracker. The field is from onCreate callback when the
     * application is initially created.
     */
    private static Tracker tracker;

    /**
     * Access to the global Analytics singleton. If this method returns null you
     * forgot to either set android:name="<this.class.name>" attribute on
     * your application element in AndroidManifest.xml or you are not setting
     * this.analytics field in onCreate method override.
     */
    public static GoogleAnalytics analytics() {
        return analytics;
    }

    /**
     * The default app tracker. If this method returns null you forgot to either
     * set android:name="<this.class.name>" attribute on your application
     * element in AndroidManifest.xml or you are not setting this.tracker field
     * in onCreate method override.
     */
    public static Tracker tracker() {
        return tracker;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        analytics = GoogleAnalytics.getInstance(this);

        // TODO: Replace the tracker-id with your app one from
        // https://www.google.com/analytics/web/
        tracker = analytics.newTracker("UA-**********");

        // Provide unhandled exceptions reports. Do that first after creating
        // the tracker
        tracker.enableExceptionReporting(true);

        // Enable Remarketing, Demographics & Interests reports
        // https://developers.google.com/analytics/devguides/collection/android/display-features
        tracker.enableAdvertisingIdCollection(true);
    }
}
</code>
In GAv4 "Description" has limit of 100 characters for sending exception, but some how I've successfully manage to extend that limit and send stackTrace as follows,
<code>        try {

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            // Get full error message from prinStrackTrace
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));

            String errorMessage = "em-" + extraMessage + "||pst-"
                    + errors.toString();
            Log.e(TAG, "errorMessage = " + errorMessage);
            MyApplication.tracker().send(
                    new HitBuilders.ExceptionBuilder()
                            .setDescription(errorMessage).setFatal(false)
                            .build());
        }
    }
</code>
This is for catching exception, but now I want to send detail stacktrace crash report for uncaught exception. This link has help to get uncaught exception but doesn't provide much detail in GA. I did find this approach but that is basically for GAv2.
Q1 : So is my above approach for sending stacktrace for caught exception will work with future GA or is there any another way to get detail description for exact cause of error, class name and line number?
Q2 : How to send full stacktrace or any exact helpful description to find reason of uncaught exception?
Q3 : I know about ACRA, but is there any free backend?
Answer: You could use a custom dimension to capture any additional information from the Exception object.
add:
<code>.setCustomDimension(1, e.getMessage())
</code>
to your ExceptionBuilder code. Note you need to first create the custom dimension in web interface.
Answer: Q1: Since no one know what a future version of GA will look like this question is unanswerable.
Q3: There are open source implementations of ACRA backends. Look at https://github.com/ACRA/acra/wiki/Backends. But you will need to organise hosting for them. Alternatively many of the commercial versions offer quite reasonable free quota and reasonable plans after that.