Why two symbols for the same purpose? Summation and integral symbol.

Question: I was reading this question. Im not mathematician but I like a lot and in spare time I try to learn something.
My question is: reading the previous question of the link I understand (if Im not wrong) that summation and integral are the same thing but in different type or measure, countable measure and uncountable measure or so.
So the mechanic is the same the only that changes is measure. So, why use different notation or simbology for the same generalized thing? Thank you.
Comment: Historically, they were not considered the same (though the symbol for integral is initially an $S$ for sum), the link has become much clearer with Lebesgue integral (the sum is the integral wrt a discrete measure). Apart from that, I agree with 5xum, no need to introduce at lower levels a notation that is explained by much higher mathematics.
Comment: The integral is quite a specific sort of summation, so instead of writing out a long summation (including limits too actually) to describe an integral, why not just use a shorter notation? Especially since integrals are all over the place in mathematics.
Comment: @SheheryarZaidi Actually, if you introduce the correct measure, integrating wrt that measure is exactly the same as summing. No limits involved. I believe that is what OP is asking.
Comment: $$\int_a^bf(x)~dx~ = ~\lim_{n\to\infty}~\frac1n\cdot\sum_{k=0}^{(b-a)n}f\bigg(a+\frac kn\bigg)~ = ~f^{(-1)}(b)-f^{(-1)}(a).$$
Answer: Shortest answer: Because mathematics is useful.

Short answer: I see no reason to use a unified notation just because there exists some highly theoretical framework in which two things are identical.

Longer answer:
The purpose of mathematical notation is an optimal way of conveying information from the author to the reader. Since people generally start to learn sums and integrals long before they learn measure theory, it is (at that point) completely natural that two notations are introduced.
Later, when the two things are shown to be two sides of one coin, you can simply weight the pros and cons of changing notation:
Pros:

The notation is now more in tune with measure theory

Cons:

The notation is harder to learn
The new notation requires mathematitians to "unlearn" the old notation from their subconsciousness (or else it will cause them to "think" more slowly since they will have to translate)
The new notation confuses engineers and other professions which use mathematics without going to the deep theoretical stuff. It also reinforces the view by these people that mathematics is mental masturbation for its own purpose.

Another point:
Do you really think using only integral notation will be any better? Let us say I have a sequence $a_n$ and a function $f(x)$. If I want to integrate the function and sum the sequence, I write

Let $a_n$ be a sequence and $f$ a real function. Then we calculate $$\int_a^b f(x)dx + \sum_k^l a_n$$

And it is immediatelly clear what is happening. In your case, I would have to say

Let $a$ be a function from $\mathbb N$ to $\mathbb R$ and $f$ be a function from $\mathbb R$ to $\mathbb R$ and let $\mu$ be the Lebesgue measure on $\mathbb R$ and $\lambda$ the counting measure on $\mathbb R$. Then we calculate
  $$\int fd\mu + \int ad\lambda$$

Is the second way really better than the first?
Comment: My argument has nothing to do with tradition. It has to do with practicality. You cannot teach measure theory to 15 year olds, so you must introduce two notations. It is then impractical to unify the two theories as it brings more harm than good.
Comment: @Masacroso From time to time, there are people who try to teach crazy things to young pupils. There have been "mathématiques modernes" in France, following more or less the [same in the USA](https://en.wikipedia.org/wiki/New_Math). It was a **huge** mistake, with dramatic consequences on math education. But that won't prevent (some) people to think that a given subject from higher mathematics should be taught early. It's simply that mathematicians are not necessarily good teachers (I mean, they are usually good at their level, not for the young)
Comment: @Masacroso See my last edit to my answer. Would you say the first or the second way is easier to understand?
Comment: @Masacroso Sure, I agree there may be some case where using integral notation for summing is useful. But in most real world cases, using two notations is much more practical.
Comment: Ok, I understand the practical issues with tradition, but tradition isnt exactly science, more the opposite to science. Comes to my mind the thing that happen with roman numbers. I know is a difference but I dont think that defend a tradition maybe good in any way.
Comment: @5xum You seem to say that these symbols are the same. But in my point of view they are similar but not the same. A simple example :$$\int_0^1x \text{ and} \sum_0^1x$$
Same formula inside $x$ same boundries $0$ and $1$ but you have :
$$\int_0^1x=\frac{1}{2}\ne1=\sum_0^1x$$
Did I miss something?
Comment: @Deuteu Where did I say that the symbols are the same?
Comment: @Deuteu I agree, the symbols are different. I am saying that it is not practical to use one notation for something that most mathematics using people consider two different things.
Comment: I dont think so.I think anyone can understand easily measure theory... more if it is as young as a child. And you dont need to teach measure if you change notation, just using countable measure, no need to explain this thing if you dont want. Or maybe if not needed to declare a different measure the standard must be supposed as the countable. Just some thoughts. (I cant make paragraphs in this text editor... enter key just close the edit :S)
Comment: @Masacroso It is completely useless for an engineer to know measure theory. It is useful for him to know integrals and sums. Therefore, in order to introduce your notation, you would need to teach an engineer something that will be completely useless to him.
Comment: @5xum The fact that your answer wasn't "they are different" let me think that we can consider them the same. And for me as I said there are totally different so I wanted not to be convinced that they are the same but to try to understand how some people assimilate them, as your sentence "there exists some highly theoretical framework in which two things are identical" let me presume it.
Comment: @denteu Summing a sequence is the same as integrating the sequence wrt a counting measure on $\mathbb N$. In *that* framework, summing is integration.
Comment: @5xum I understand the point. I think my idea just maybe interesting if there is some framework where are a lot of summations and integrals or where they are linked strongly in the matter, in other cases isnt so justified.
Comment: @5xum Ok, thanks for the precision. I was stuck in integral on continuous.
Answer: If you need to, you can think of the sum notation as a convenient notation for some common cases in which the full machinery of integration and measure theory is unnecessary, and where a more elementary approach is possible.
The fact that these elementary ideas are also encompassed within the framework of integration, and that the ideas of measure can unify the treatment, for example, of discrete, continuous and mixed distributions is an illustration of the power of the more general point of view. But this does not invalidate the elementary approach for those cases in which it works.


Most general definition of Borel and parabolic Lie algebras?

Question: Let $\mathbb{K}$ be an arbitrary field, and $G$ an algebraic group (=group variety?) over this field. A Borel subgroup of $G$ is a connected solvable subgroup variety $B$ of $G$ such that $G/B$ is complete. A parabolic subgroup of $G$ is a subgroup variety $P$ such that $G/P$ is complete.
Given a group $G$ with lie algebra $\mathfrak{g}$, I would expect that a parabolic Lie subalgebra $\mathfrak{p} \leq \mathfrak{g}$ should be a Lie subalgebra which is the Lie algebra of a parabolic subgroup, and likewise for Borel subalgebras $\mathfrak{b} \leq \mathfrak{g}$.
Since distinct groups can obviously have isomorphic Lie algebras, I would expect that there should be a characterization of Borel and parabolic subalgebras in terms of Lie algebra properties alone, without reference to groups.
However, it seems that in every source I've found that discusses Borel and parabolic subalgebras, that they are defined only for finite-dimensional semisimple and complex lie algebras $\mathfrak{g}$. A Borel subalgebra of a complex finite-dimensional semisimple Lie algebra $\mathfrak{g}$ is usually defined to be a maximal solvable subalgebra $\mathfrak{b} \leq \mathfrak{g}$, and a parabolic subalgebra $\mathfrak{p} \leq \mathfrak{g}$ is any subalgebra containing a Borel subalgebra.
Is there a reason for restricting to complex semisimple Lie algebras? Does the definition not work for general Lie algebras?
More generally, what is the relationship between parabolic subgroups and subalgebras? Does the relationship depend at all on the field $\mathbb{K}$ we are working with (characteristic, whether or not it if it is algebraically closed etc.)? Does it depend on the properties of the group (to connected, simply connected, etc.)?
Unfortunately my algebraic geometry knowledge is very minimal. I'm working on stuff in parabolic differential geometry, so I'm hoping to get a better understanding of parabolic subgroups and algebras, especially in the real case.
Comment: One reason for not usually considering these for non-semisimple Lie algebras is that they correspond to ones for the semisimple quotient anyway (as any Borel will contain the radical).
Comment: Crossposted at [MO](http://mathoverflow.net/questions/245708/relationship-between-parabolic-subgroups-and-parabolic-subalgebras-over-non-alge).
Answer: There are certainly sources defining Borel subalgebras and parabolic subalgebras in general, e.g., in the book "Lie Algebras and Algebraic Groups" by Patrice Tavel and Rupert W. T. Yu. "We generalise the definitions of Borel subalgebras and parabolic subalgebras to arbitrary Lie algebras and establish the relations between the group objects and the Lie algebra objects".
This contains the details we want (Chapter $29$).
Comment: Some results are no longer true in characteristic $p$ here, e.g., the results concerning Levi subgroups in connection with parabolic subgroups are problematic.
Comment: Thanks! This is exactly the sort of text I was looking for. Just one question: the authors state that they restrict to algebraically closed fields of characteristic zero. Do you happen to know how their results in chapter 29 concerning the link between parabolic subgroups and subalgebras changes in the non-algebraically closed case? Or for fields of different characteristic?
Answer: At least for $\mathfrak{g}$ real semisimple there is a nice definition without using maximal solvable Lie subalgebras. A subalgebra $\mathfrak{p}\leq\mathfrak{g}$ is parabolic if $\mathfrak{p}^\perp\leq\mathfrak{p}$ is nilpotent, where $\mathfrak{p}^\perp$ is the polar with respect to the Killing form. I think this definition could be extended to other cases as well.
Answer: Bourbaki, Lie Groups and Algebras, ch. VIII §3 nos. 3--5, uses the following definition. The setting is: $\mathfrak g$ is a reductive Lie algebra over a field $k$ of characteristic $\mathbf{0}$.
A subalgebra $\mathfrak a \subseteq g$ is called Borel / parabolic if, for an algebraic closure $\bar k \vert k$, the subalgebra $\mathfrak a \otimes_k \bar k \subseteq \mathfrak g \otimes_k \bar k$ is Borel / parabolic.
(Where it is used that over an algebraically closed field $\bar k$, Borels and parabolics are defined in one of the well-known ways, equivalently w.r.t. some choice of Cartan subalgebra and appropriate subsets of the corresponding root system.)
So basically a Borel or parabolic is something which after scalar extension to an algebraic closure becomes a Borel or parabolic. A nice side effect of this is that for any scalar extension $K \vert k$, one gets that $\mathfrak a \subseteq \mathfrak g$ is Borel / parabolic if and only if the scalar extension $\mathfrak a_K$ is Borel / parabolic in the scalar extension $\mathfrak g_K$.
Of course what happens now is that many $\mathfrak g$ contain no Borel subalgebras at all ($\mathfrak g$ itself is always a parabolic, but in some cases it's the only parabolic). But that actually becomes part of classifications: Semisimple Lie algebras without proper parabolics are anisotropic (over the reals, "compact"); semisimple Lie algebras which contain some Borel are quasi-split.
While excluding the notoriously troublesome case of positive characteristic, the generality of this definition notably applies to semisimple Lie algebras over the reals, $p$-adics and numbers fields, and should be compared to other definitions for real semisimple ones in other answers. I used it freely in my thesis about semisimple Lie algebras over characteristic $0$ fields, focussing more on the $p$-adic case.


Prove Simple 1-Skeleton is Locally Path-Connected

Question: In solving a different problem, I need to show that the simplest CW complex, i.e. one with just two 0-cells and one 1-cell, must be locally path connected.
In doing so, how do we show that the 1-cell does not exhibit a pattern somewhat like the infinite comb or topologist's sine curve in some localized area, which would preclude local path-connectedness?
I suspect that those structures violate the requirement that 1-cells be homeomorphic to an open line segment, but haven't been able to turn that onto a proof.
Any help would be appreciated.
Answer: A CW complex consisting of two $0$-cells and one $1$-cell is (up to homeomorphism) either the interval $[0,1]$ or the disjoint union of sphere and a point $S^1\sqcup \{*\}$. You can check that by hand.
But that doesn't matter since every CW complex is locally path connected. This follows from the following four facts:

disjoint union of locally path connected spaces is locally path connected
quotient of locally path connected space is locally path connected
the closed disk $D^n$ is locally path connected
weak topology preserves local path connectedness

In fact every CW complex is even locally contractible, which is a stronger property. This can be found in Hatcher's "Algebraic Topology".
Comment: @PossumP no, infinite cw complex is locally path connected as well. Not sure where you get that from.
Comment: Perhaps my question should have been under Topology instead of Algebraic Topology. For me, it come down to a proof that any X homeomorphic to (0,1) is locally path connected. (Or, of course, a proof that locally path connected is a topological property.)
Comment: I'm not sure I understand your construction. Symbolically please. You mean $\big([0,1]\times\{0\}\big)\cup\big(\bigcup_{n=1}^\infty [0,1]\times\{1/n\}\big)$? Indeed, this space is not locally path connected. But what makes you think it is a CW complex? It is not.
Comment: If your intention is that the picture in your post be a depiction of a subset of $\mathbb R^2$ homeomorphic to a CW complex, then I should point out that it fails, because in a CW complex, the $0$-skeleton is discrete.
Comment: @PossumP that is not a CW complex. Verticals are irrelevant.
Comment: @Lee, according to Wikipedia (maybe not the best source), the 0-cells have the discrete topology.  Thus each 0-cell is in an open set that does not intersect the open sets of other 0-cells.  Wouldn't that mean they are discrete??
Comment: Keep in mind, "discrete" is a property of a **topology**. In your question "Wouldn't that mean **they** are discrete??", I do not know what "**they**" stands for, so it's not really an answerable question. My statement "the $0$-skeleton is discrete" means "the subspace topology on the set of $0$-cells is the discrete topology" which is equivalent to "each $0$-cell is contained in an open subset of $X$ that does not intersect any other $0$-cell".
Answer: In the comment to the other answer you say that your question comes "down to a proof that any $X$ homeomorphic to $(0,1)$ is locally path connected".
To prove that, for any $x \in (0,1)$ there is a neighborhood basis consisting of open intervals, namely $(0,1) \cap (x-\epsilon,x+\epsilon)$, $\epsilon > 0$. Every open interval is path connected. Hence $(0,1)$ is path connected.
Comment: Lee, My question comes when a line (homeomorphic to the interval) is placed in the plane, and then in a fashion some-what like the topologist's sine curve whips around on itself in such a way that it is not locally path-connected.  Intuitively and with examples I can see this is impossible, but I can't prove it.
Comment: If you meant what you said in what I put in quotes, then your question has been answered. If instead you meant to say what you just wrote in the comment above, the trouble is that your phrase "in a fashion somewhat like..." is too vague for us to address. We can only point out to you answers to your direct mathematical questions, as my answer has done, and has the answer of @freakish has done.
Comment: My direct math request is for a proof that locally path connectedness is a topological property.  Everything else has been unproductive digressions.
Comment: That not being what you asked in your post, perhaps you want to update your post?
Comment: My post implied that question, but only for 1 dimensional shapes.


Is it possible to add two irrational numbers in finit time to infinite precision?

Question: This question is related to Laplace's demon and the solar system as a chaotic system, as well as the paradox with the hare and the turtle (I think).
Imagine you want to calculate the future of the solar system. Imagine also that the distance between two planets is $\sqrt{2} + \sqrt{3}$. Since the solar system is a chaotic system, you'd need infinite precision. Even if you're an all-powerful demon, would it be possible to do the calculation?
Comment: Most definitely. Irrational bases are weird. But, if this demon is truly all-powerful, it might not be that big of a deal to it.
Comment: In base $\sqrt{2}+\sqrt{3}$, this is just 1.
Comment: @InterstellarProbe But other numbers would be irrational in that base, I assume?
Answer: This boils down to: what do you mean by "add"?  Given two finite expressions representing real numbers, such as $\sqrt{2}$ and $\sqrt{3}$, you can add them in finite time by simply putting a $+$ between them: $\sqrt{2} + \sqrt{3}$.
If you mean you want a numerical representation with infinitely many decimal places, of course you can't do that in finite time unless you can write down an infinite output in finite time.  I'm not familiar enough with  "all-powerful demons" to know whether they can do that.
Comment: Thank you for your answer! Maybe you have some other comment related to the Wikipedia entry about Laplace's demon and chaos theory? https://en.wikipedia.org/wiki/Laplace's_demon#Chaos_theory


"strcpy()" se comportando estranhamente dependendo de como se coloca no "if"

Question: O que está ocorrendo aqui?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

void escolha_simb(char *jog1, char *jog2)   //** escolhe quem vai ser x ou o
{
        char esc;

        while (1) {
                printf("\njogador 1, escolha X ou O \n");
                fflush(stdin);
                scanf("%c",&esc);
                if (esc == 'x')
                {
                        strcpy(jog2,"O");
                        strcpy(jog1,"X");

                        break;
                }
                else if (esc == 'o')
                {
                        strcpy(jog2,"X");
                        strcpy(jog1,"O");

                        break;
                }
        }
}

int main(int argc, char const *argv[]) {
        char jog1=0,jog2=0;
        printf("jog1: %c jog2: %c",jog1,jog2 );
        escolha_simb(&jog1,&jog2);
        printf("depois\njog1: %c jog2: %c",jog1,jog2 );
        return 0;
}

Saida, caso escolha X:

jog1:   jog2:
jogador 1, escolha X ou O
x
depois
jog1: X jog2: O

porém se inverter os strcpy():
 if (esc == 'x')
                {
                        strcpy(jog1,"X");
                        strcpy(jog2,"O");

                        break;
                }
                else if (esc == 'o')
                {
                        strcpy(jog1,"O");
                        strcpy(jog2,"X");

                        break;
                }

saída, caso escolha X :

jog1:   jog2:
jogador 1, escolha X ou O
x
depois
jog1:   jog2: O

por que jog1 fica nulo?
Answer: Está misturando char com string, são coisas diferentes. Quando usa char não deve nem usar strcpy(), nem atribuir usando aspas duplas que se referem à strings. Não dará problema sempre, mas a forma codificada não é correta, assim é mais correto:
#include <stdio.h>

void escolha_simb(char *jog1, char *jog2) {
    while (1) {
        printf("\njogador 1, escolha X ou O \n");
        char esc;
        scanf("%c", &esc);
        if (esc == 'x') {
            *jog2 = 'X';
            *jog1 = 'O';
            break;
        }
        else if (esc == 'o') {
            *jog2 = 'O';
            *jog1 = 'X';
            break;
        }
    }
}

int main() {
    char jog1 = 0, jog2 = 0;
    printf("jog1: %c jog2: %c", jog1, jog2);
    escolha_simb(&jog1, &jog2);
    printf("depois\njog1: %c jog2: %c", jog1, jog2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Provavelmente tem maneiras mais performáticas de realizar isto, mas precisaria testar.
Comment: entendi, vou usar seu metodo. mas mesmo assim, é aleatorio ele dar nulo? porque apenas fazendo uma inversão deles dá o resultado correto?
Comment: Não diria aleatório, mas é difícil saber quando acontece. Em C você precisa entender tudo o que se passa na memória, cada byte que é colocando em cada lugar, entender cada detalhes do funcionamento a linguagem. Ela é uma linguagem flexível e poderosa, e pode dar uma boa noção do funcionamento real de códigos, mas não é simples para uso na maioria das aplicações ou quem naõ quer se aprofundar.


Let $p,q$ are distinct primes and $G$ be a group of order $pq$ then which of the following is true?

Question: Let $p,q$ are distinct primes and $G$ be a group of order $pq$ then which of the following is true?
$1.G$ has exactly $4$ subgroups upto isomorphism.
$2.G$ is abelian.
$3.G$ is isomorphiq to a subgroup of $S_{pq}$.
My attempt: First option is true.
Second option is false $S_3$ is a counterexample.
My problem:I think third option is correct.Is it correct or not?
Comment: you heard of group actions??
Comment: @PraphullaKoushik Yes but not so much just may be definition.
Comment: Nice... That must be enough... You heard regular action??? Supposing $G$ has $ n$ elements we consider $G\times \{g_1,g_2,\cdots , g_n\}\rightarrow \{g_1,g_2,\cdots , g_n\}$ with $(g,g_i)\rightarrow g\cdot g_i =g_j$?? have you seen such action?
Comment: @PraphullaKoushik Sorry but not ok I will check on google you just tell me your answer.
Comment: @PraphullaKoushik I want to solve
Comment: Good... You check that what i have said is actually an action.... each element in $g$ gives you a permutation.... $g$ takes $g_1$ to $gg_1$ and $g_2$ to $gg_2$ and so on... do you understand this???
Comment: @PraphullaKoushik $g,g_1,g_2$ are all from $G$ and what is the permutation?$g$ is the permutation?
Answer: The Cayley's Theorem solves your question: every finite group of order $n$ is isomorphic to a subgroup of the permutations group $S_n$.
Comment: How does this help?
Comment: Saying every finite group is isomorphic to a subgroup of **the** permutations group does not mean much unless you say what that  permutation group is...
Comment: Yes I know the cayley's theorem but how we are sure that $G$ is isomorphic to exactly to a SUBGROUP OF $S_{pq}$?
Comment: @Flip Cayley's theorem implies if $G$ has order $n$ it must be isomorphic to a subgroup of $S_n$. Apply here with $n=pq$. Are you *sure* you know Cayley's theorem?
Answer: Suppose $G$ has $n$ elements $\{g_1,g_2,\ldots,g_n\}$...
Consider the action $\eta : G\times \{g_1,g_2,\ldots,g_n\}\rightarrow \{g_1,g_2,\ldots,g_n\}$
By this we mean, given $g\in G$  we have $\eta _g : \{g_1,g_2,\ldots,g_n\}\rightarrow \{g_1,g_2,\ldots,g_n\}$ with $g\cdot g_i\mapsto gg_i$
This $\eta_g$ is a permutation...
This $\eta_g$ is a permutation on set of $n$ elements so is an element of $S_n$
So, you have map $\eta: G\rightarrow S_n$  with $g\rightarrow \eta_g$
If you can prove that this is an injective homomorphism then you have $G\leq S_n$
So, any group of order $n$ is a subgroup of symmetric group on $n$ elements...
Can you fill the gaps??
Can you see how this is related to your third question??


Characterising almost uniform convergence for step functions

Question: Exercise 3 of these notes describes modes of convergence by showing their relationship with step functions converging to zero.
Let $(X, \mathcal{M}, \mu)$ be a measure space. Consider the sequence of functions $f_n = A_n 1_{E_n}$ where $A_n > 0$, $E_n \in \mathcal{M}$, and $\mu(E_n) > 0$ for all $n$. Define the $N$-th tail support of the sequence by $E_N^* = \bigcup_{n \geq N} E_n$.
Can anyone provide a proof that $f_n$ converges almost uniformly to $0$ if and only if $A_n \to 0$ as $n \to \infty$ or $\mu(E_N^*) \to 0$ as $N \to \infty$.
Comment: Is $A_n$ a function or a set? Also, what does $A_n>0$ mean? What notion of convergence is used for $A_n\to 0$?
Comment: @MichaelGreinecker $A_n$ is a real number, which also pins down the notion of convergence. The definition of almost uniform convergence is as follows. For all $\varepsilon > 0$, there is a measurable set $F$ with $\mu(F) \leq \varepsilon$ such that $f_n \to f$ uniformly on $F^c$.
Answer: I don't think the statement is quite right. Let $E_n$ be a decreasing sequence of measurable sets with $\mu(E_n)\downarrow 0$. Then the sequence
$$1_X,\quad  1_{E_1}, \quad {1\over 2}1_X,\quad 1_{E_2}, \quad{1\over 3}1_X, \quad 1_{E_3},\quad {1\over 4}1_X,\,\dots$$ converges almost uniformly to zero, but $A_n$ doesn't converge and $E^*_N=X$ for all $N$.
Answer: In the original exercise, there is an additional assumption (that cannot be dispensed with, as Byron Schmuland has shown):

We also assume the $A_n$ exhibit one of two modes of behaviour: either
  the $A_n$ converge to zero, or else they are bounded away from zero
  (i.e. there exists $c>0$ such that $A_n\geq c$ for every $n$. It is
  easy to see that if a sequence  does not converge to zero, then it has
  a subsequence that is bounded away from zero, so it does not cause too
  much loss of generality to restrict to one of these two cases.

The proof now becomes rather simple. It is very easy to see that $A_n\to 0$ or $\mu(E_N^*)\to 0$ are sufficient for  almost uniform convergence to zero.
For the other direction, assume that $A_n$ does not converge to $0$, but $f_n$ converges almost uniformly to $0$. Let $\epsilon>0$. There is a $F$ with $\mu F<\epsilon$ such that $f_n$ converges uniformly to zero outside $F$.
In particular there exists $N$, such that outside $F$, we have $f_n< c$ for $n\geq N$. But $$c 1_{E_n}(x)\leq A_n 1_{E_n}(x)< c$$ implies $1_{E_n}(x)=0$, hence $E_n\subseteq F$ for all $n\geq N$. This implies that $\bigcup_{n\geq N} E_n=E_N^*\subseteq F$, and hence $\mu(E_N^*)\leq\mu(F)<\epsilon$. Since  the $E_N^*$ are a decreasing sequence, this shows that $\mu(E_N^*)\to 0$.


Why is a custom field I programmatically created shown as disabled?

Question: I created a Drupal 8 module for creating a custom field. I wrote the code basing on the documentation given in Create a custom field widget, Create a custom field formatter, and Create a custom field type.
I created the .info.yml file, three directories src/Plugin/Field (FieldFormatter, FieldType, and FieldWidget) where I put the files described in those documentation guides.
I could see the custom field in the field list, but it is shown as disabled.
Why does this happen?
Comment: Add a screenshot, it might also be useful to share your code. I'm not sure what you mean exactly.
Comment: I have exactly the same problem. I've created a custom field type and when I create a field in the UI I can't place it anywhere under "Manage form display". The field is always in the 'disabled' section. The widget selection drop down says 'hidden' and doesn't have any other options.
Comment: There are so many tiny things that can make a custom field not work. I don't like it.
Answer: After the field is created and the field instance is added, you need to enable the field in the display settings for the form, for example with the following code.
entity_get_form_display('node', $bundle, 'default')
  ->setComponent('field_custom', array(
    'type' => 'string'
  ))
  ->save();

Answer: I had the same problem and the issue in my case was that I was using default_widget = "options_select" in my FieldType plugin but the options_select widget does not allow my custom field type.
The solution was to create a custom FieldWidget plugin which extends the OptionsSelectWidget and in the field_types declare my custom field type.
This allowed my field to be placed in the form correctly and the options widget to be used.


Can $\sqrt3,\sqrt5,\sqrt7$ all be elements (not necessarily consecutive) of the same arithmetic sequence?

Question: Can $\sqrt3,\sqrt5,\sqrt7$ all be elements (not necessarily consecutive) of the same arithmetic sequence?
An arithmetic sequence is a sequence such that the difference of any two consecutive elements is constant. In other words, we keep adding the same value infinitely.
I've tried making a sort of system equations between these numbers and their differences and trying to find any other connections, but I've not had any success. Can someone, perhaps with experience with these problems, help me? Thanks!
Answer: Hint: If $a,b,c$ are not necessarily consecutive terms in an arithmetic sequence, then, writing the inter-term difference as $d\in\mathbb{R}$, we have $b=a+nd$ and $c=b+md$, where $n,m$ are nonnegative integers. Hence, you may aim to prove whether there is such a difference $d=\frac{\sqrt{5}-\sqrt{3}}{n}=\frac{\sqrt{7}-\sqrt{5}}{m}$. But this would rely on the integers $n,m$ satisfying $m\left(\sqrt{5}-\sqrt{3}\right)=n\left(\sqrt{7}-\sqrt{5}\right)$, which would rely on $\displaystyle \frac{\sqrt{5}-\sqrt{3}}{\sqrt{7}-\sqrt{5}}$ being rational.
Answer: Assume WLOG that $\sqrt{3}$ is the first term of the sequence. Let $a_r=\sqrt 5$ and $a_s=\sqrt 7$ for some integers $s>r>1$. Therefore,
$$\frac{\sqrt 5-\sqrt 3}{\sqrt 7-\sqrt 5}=\frac{r-1}{s-r}$$
This is not possible because LHS is irrational and RHS is rational.
You may need to check the irrationality of LHS.
Proof that $\dfrac{\sqrt 5-\sqrt 3}{\sqrt 7-\sqrt 5}$ is irrational
Assume that $\dfrac{\sqrt 5-\sqrt 3}{\sqrt 7-\sqrt 5}$ is rational. Then
$$\dfrac{\sqrt 5-\sqrt 3}{\sqrt 7-\sqrt 5}\cdot\dfrac{\sqrt 7+\sqrt 5}{\sqrt 7+\sqrt 5}=\dfrac{5+\sqrt{35}-\sqrt{21}-\sqrt{15}}2$$
is rational. Then
$$r=\sqrt{21}+\sqrt{15}-\sqrt{35}$$
is a rational number.
But
$$r^2+2r\sqrt{35}+35=36+6\sqrt{35}$$
If $r=3$ then $9=1$, so $r\neq 3$. Then,
$$\sqrt{35}=\frac{r^2-1}{6-2r}$$
and LHS is irrational and RHS is rational. This is a contradiction, so $\dfrac{\sqrt 5-\sqrt 3}{\sqrt 7-\sqrt 5}$ is not rational.
Answer: Suppose such a sequence exists and has common difference $d \ge 0$.  Then this implies $$\sqrt{5} - \sqrt{3} = kd$$ for some positive integer $k$, and similarly, $$\sqrt{7} - \sqrt{5} = md$$ for some positive integer $m$.  Note that $d$ need not be an integer.  Hence $$\frac{k}{m} = \frac{kd}{md} = \frac{\sqrt{5} - \sqrt{3}}{\sqrt{7} - \sqrt{5}}.$$  The left-hand side, $k/m$, being the ratio of two positive integers, is a rational number.  Is the right-hand side a rational number?  If yes, then we can find such a $k$ and $m$ and in turn, an arithmetic sequence satisfying your criteria; if no, then no such sequence exists.
The answer to this question is left as an exercise for the reader.
Comment: I like to add that one way to solve the last step (which could be a bit of an over kill) is to use that "square root of different primes are $\mathbb{Q}$- linearly independent"


Let $f(x,y) = y^2-x^2, C=D=[-1,1]$

Question: Part a)
Find $v^{+}=\min_{y \in D} \max_{x \in C}$ $f(x,y)$ and
$v^{-}=\max_{x \in C}\min_{y \in D} $ $f(x,y)$
I'm sure I got this: $v^{+} = (-1)^2 - 1^2 = 0$ and
$v^{-} = 1^2-(-1)^2 = 0$
Part b wants a pure saddle point which I find by fixing $y=0$ $ \forall x$ and then fixing $x=0$ $\forall y$?
That would be $f(0,0)$, since $f(x,0) <f(0,0) < f(0,y)$
If my reasoning is off, please give me a hand.
Thanks!
Answer: You are correct, but let's make it clear. A saddle point $(x_0,y_0)$ of a function $f(x,y)$ of two variables is a critical point of $f$ such that $$D=f_{xx}(x_0,y_0)f_{yy}(x_0,y_0)-[f_{xy}(x_0,y_0)]^2\le 0$$
Here $f_{xx}\equiv -2$, $f_{yy}\equiv2$ and $f_{xy}\equiv0$, so any critical point is a saddle point. A critical point is given by $$f_x(x_0,y_0)=-2x_0\overset{!}=0\\f_y(x_0,y_0)=2y_0\overset{!}=0$$ so, indeed $(x_0,y_0)=(0,0)$ is the only saddle point.
But when you have an exercise with parts a) and b) it is 101% sure that in part b) you should part a). So, you should use that if $$\max\min f(x,y)=f(x_0,y_0)=\min\max f(x,y)$$ then $(x_0,y_0)$ is a saddle point of $f$. The reason you missed it, is that you calculated correctly $v^+$ and $v^-$ but you did not observe that $v^+$ and $v^-$ are simultaneously obtained at point $(0,0)$ and not only on the boundaries as you have it.

Let $f(x,y) = y^2-x^2, C=D=[-1,1]$


Windows SBS 2003 file transfers hang on write

Question: CPU usage is ideal... as is everything else.
It will start copying a file, say 700MB, then about 100MB in it will hang, and stop copying.
It hangs for everyone else trying to access files on the server too.
After about a minute it will come back to live and start copying the file again.
Image of when it hangs: https://img.skitch.com/20120417-fwyju56xegtj78yc7je6nf7eqk.png
I have had a look at the HDD, and it seems to be quite fragmented. I was defragmenting it over the weekend, but it only got about 15% in, so had to cancel it.
https://img.skitch.com/20120417-pbuuxgc5tmg7bxassprbuq29id.png
This partition is running on a RAID 1 HDD.
We (about 20) are all connected with gigabit ethernet. But at the time of this test I was the only one copying a large file.
It's been driving me nuts.
Any thoughts?
Edit 1:
About a month ago I swapped both HDDs with slightly bigger ones.
Both "Write caching" and "Advanced performance" are disabled with the 2 new HDDs. I think this may have been enabled before.
I recall reading somewhere that these settings could cause issues when enabled with our tape backups.
Does this really make a difference?
Answer: Take a good look at your drive(s).  It almost sounds like maybe one of the drives in a RAID array has died and the controller is running in degraded mode.  The fact the drive activity hangs for a bit and resumes sounds a bit like an old server that had a grumpy controller.
Comment: I suspect that is probably your answer.  There might be some issue with the older controller and the newer drives.  You might try slowing the ports down if possible on the RAID controller.  This might help even things out.  Sometimes going slower helps smooth out the bumps. You didn't mention the server make and model (or the RAID controller).  But I'd start there.  Of course, just make sure you have a good backup before you go fiddling with the controller setup in case it barfs..
Comment: The server is about 4-5 years old. We are using Windows software RAID... As the hardware RAID controller was never setup due to some issues (this was before I was here). We are upgrading our server in a few months, but I have to keep this one running until then.
Comment: About a month ago I replaced the current HDDs in the server with these 2 new ones as the old ones kept reporting bad blocks. We also needed more space. The issue seems to have arisen since then. But we have also been using the server more and more. So im not sure if it's  the NEW HDDs or something else I done wrong.
Comment: Cheers, that fixed it. Along with defragging all the drives.
Comment: WOOT, glad that fixed it...
Answer: First, update your NIC drivers to the latest version.
Second, open the properties of your network card within device manager and disable all features that use the word "offload."
Reboot as necessary.
Comment: Never thought about updating the NIC drivers. With give that a go tomorrow, let you know how it goes. Thanks


Strange Behavior on 'extends' keyword over unions

Question: Questions:

Why types M0 and M1 below are not the same ?
Why type M0 is not exactly equal to type A ?
What specifically is causing the lack of referential transparency of type Ext?

Please explain in terms of the below example:
// Given
type A = '(T extends U) and (U extends T)'
type B = '(T extends U) and (U NOT extends T)'
type C = '(T NOT extends U) and (U extends T)'
type D = '(T NOT extends U) and (U NOT extends T)'
type Ext<T,U,X,Y> = T extends U ? X : Y

//1
type ExtendsCheck<T,U> = T extends U ? (U extends T ?  A : B) : (U extends T ? C : D)
//2
type ExtendsCheck_<T,U> = Ext<T,U,Ext,Ext>

// Why
type T = 'foo' | 'bar'
type U = T
type M0 = ExtendsCheck<T,U> // M0: "(T extends U) and (U extends T)" | "(T extends U) and (U NOT extends T)"
type M1 = ExtendsCheck_<T,U> // M1: "(T extends U) and (U extends T)"

Playground
Note: If this has to do with Conditional types distributivity mechanism, please show exactly how this is applied in the above context.
Thanks!
Answer: As you correctly intuit this has to do with the distributivity of conditional types.
TL;DR: It all boils down to when distribution is applied. In the first case ExtendsCheck first distributes over T, then over U. In the second case Ext and Ext are first resolved, so distribution over U happens first, then the outer Ext is resolved, and distribution over T happens.
Let's consider the order of evaluation for the two types:
ExtendsCheck<T = 'foo' | 'bar',U ='foo' | 'bar'> =
=> T extends U ?  (U extends T ?  A : B) : (U extends T ? C : D)
// Distribute over T (since T extends U is a condition over a naked type parameter)
=> ('foo' extends U ?  (U extends 'foo' ?  A : B) : (U extends 'foo' ? C : D)) |
   ('bar' extends U ?  (U extends 'bar' ?  A : B) : (U extends 'bar' ? C : D))
// Resolve the first conditional in each distribution result, both are true
=> (U extends 'foo' ?  A : B) |
   (U extends 'bar' ?  A : B)
// Distribute over U (since U extends T is a condition over a naked type parameter)
=> ('foo' extends 'foo' ? A : B) | ('bar' extends 'foo' ? A : B) |
   ('foo' extends 'bar' ? A : B) | ('bar' extends 'bar' ? A : B)
// Resolve the conditional types
=> A | B | A | B
// Union reduction
=> A | B
=> '(T extends U) and (U extends T)' | '(T extends U) and (U NOT extends T)'

For the second type, things go a bit different
type ExtendsCheck_<T= 'foo' | 'bar',U ='foo' | 'bar'>
=> Ext<T,U, Ext, Ext>
// Resolve Ext for U = T = 'foo' | 'bar'
   Ext
   => U extends T ? A : B
   // Distribute over U
   => ('foo' extends 'foo' | 'bar' ? A : B) | ('bar' extends 'foo' | 'bar' ? A : B)
   // Both are true
   => A | A
   // Union reduction
   => A
// Resolve Ext for U = T = 'foo' | 'bar'
   Ext
   => U extends T ? C : D
   // Distribute over U
   => ('foo' extends 'foo' | 'bar' ? C : D) | ('bar' extends 'foo' | 'bar' ? C : D)
   // Both are true
   => C | C
   // Union reduction
   => C
// So we get Ext<T, U, A, C> for U = T = 'foo' | 'bar'
=> Ext<T = 'foo' | 'bar', U = 'foo' | 'bar', A, C>
=> T extends U ? A : C
// Distribute over T
=> ('foo' extends 'foo' | 'bar' ? A : C) | ( 'bar' extends 'foo' | 'bar'? A : C)
// Resolve the conditionals, they are both true
=> A | A
// Union reduction
=> A
=> '(T extends U) and (U extends T)'

And yes, distribution in conditional types does break referential transparency, because it can change the order of operations as we see above. To resolve a type alias, all type parameters must be resolved. To resolve a conditional type, distribution must first happen. So it matters if you put a type alias over a conditional type.


Change reading interval of sensor using php

Question: So, I have arduino code like this :
#include <Ethernet.h>
#include <SPI.h> m
#include "kSeries.h"

kSeries K_30(8,9);

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 229 };
byte gateway[] = { 192, 168, 1, 1 };
byte server[] = { 192, 168, 1, 138 }; // alamat host Server
String location = "GET http://192.168.1.138/SIMON/datasetiapdetik.php?";
//String location = "POST /alvin/datasetiapdetik.php?";
String host = "Host:  192.168.1.138";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  Serial.println("connecting...");
}

void loop()
{
   double co2 = K_30.getCO2('p');
  // Print the value on Serial
  Serial.print(co2);
  Serial.println("ppm \t");

String data;
  data+="";
  data+="device=arduino";
  data+="&A0=";data+=co2;
  data+="&submit=Submit";
  Serial.print(data);
while (client.connect(server, 80)) {
    Serial.println("Sending data..");

    //lokasi halaman atau form
    client.print(location);
    client.print(data);
    client.println("HTTP/1.1");
    client.println(host);
    //client.println("Connection: close");
    //char web=client.read();
    Serial.print(location);
    Serial.print(data);

    client.stop();
  }
  /*
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  delay(50);
  }*/
  delay(2000);
}

and the php code like this :
<?php
include "config/koneksi.php";
error_reporting(0);
date_default_timezone_set('Asia/Jakarta');
// EDIT: Your mysql database account information
$tablename = "input";
$localhost = "localhost";
$date = date('y-m-d');
$waktu = date('H:i');
$tanggal = date('y-m-d');
$menit = date('i');

    //Create tabel everyday
    $sql = "\n"
    . " CREATE TABLE IF NOT EXISTS `input` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT ,\n"
    . " `date` date NOT NULL ,\n"
    . " `time` time NOT NULL,\n"
    . " `device` text NOT NULL ,\n"
    . " `A0` int( 11 ) NOT NULL ,\n"
    . " PRIMARY KEY ( `ID` ) ) ENGINE = InnoDB DEFAULT CHARSET = latin1;";
    $create = mysql_query($sql);

$sql = "SELECT *
    FROM `$tablename`
    WHERE `date`='$date' and `time`='$waktu'
    ";

    $uji = mysql_num_rows(mysql_query($sql));

if ($menit % 1 == 0 and $uji < 1)   {
$query1 = "INSERT INTO `input` (date,time,device,A0 VALUES ('$date','$waktu','$_GET[device]','$_GET[A0]')";
    $result = mysql_query($query1);
    }
else {

}

    echo 'GET  = ' . htmlspecialchars($_GET["device"]) . '!
';
    echo 'GET  = ' . htmlspecialchars($_GET["A0"]) . '!
';

echo "
Sistem Monitoring Siap!!
";
echo `\n`;

?>

it read the data every minute and its fine. But when I change the $menit % 1 to % 5, it didn't work. How I change the interval so i can read the data every 5 minute ? Thanks
Comment: how is this run perhaps its timing out - have you considered a cronjob?
Comment: I am new for this stuff. How i change the code from above ? Or perhaps you can give me a new one ?
Answer: Maybe feasible:
You want to store only one value per time interval. Let's assume the interval to be 5 minutes. So e.g. every request that comes in between 6:40:00 and 6:44:59 would be in the "time slot" 6:40. And every request between 6:45:00 and 6:49:59 in the 6:45 "slot".
That's easy to achieve. You set the seconds to zero and substract from the minutes (minutes modulo interval), e.g. a request comes in at 6:43 -> minutes = 43 - (43%5) = 43-3 = 40.
A request comes in at 6:44 -> minutes = 44 - (44%5) = 44-4 = 40.
A request comes in at 6:45 -> minutes = 45 - (45%5) = 45-0 = 45.
And so on and on.
Now you add a unique index to your mysql table, like so
CREATE TABLE IF NOT EXISTS `input` (
    `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `date` date NOT NULL,
    `time` time NOT NULL,
    `device` VARCHAR(128) NOT NULL,
    `A0` int( 11 ) NOT NULL,
    PRIMARY KEY ( `ID` ),
    UNIQUE KEY(`date`,`time`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1

The UNIQUE KEY(date,time)* won't allow a second record with the same date+time, so once a record for one "time slot" is in the table any subsequent INSERT for the same "time slot" will fail (or be ignored).
The error code you would get back in such case is 1022 ER_DUP_KEY and you could test for that specific error code if you like. If you don't you could just send an INSERT IGNORE INTO ... query. If there's a unique index conflict, that INSERT is just silently ignored.
The mysql_* extension is deprecated and will be removed with the upcoming release 7 of php. So I won't give you a mysql_* example but one using PDO and prepared statements instead (untested, though).
<?php
define('INTERVAL_MINUTES', 5);

include "config/koneksi.php";
date_default_timezone_set('Asia/Jakarta');

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

$pdo->exec('
    CREATE TABLE IF NOT EXISTS `input` (
        `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        `date` date NOT NULL,
        `time` time NOT NULL,
        `device` VARCHAR(128) NOT NULL,
        `A0` int( 11 ) NOT NULL,
        PRIMARY KEY ( `ID` ),
        UNIQUE KEY(`date`,`time`,`device`)
    ) ENGINE = InnoDB DEFAULT CHARSET = latin1
');

$ts = getdate();
// "adjusting" to the time slot
$ts['minutes'] = $ts['minutes'] - ($ts['minutes']%INTERVAL_MINUTES);

$stmt = $pdo->prepare('
    INSERT IGNORE INTO
        `input`
        (`date`,`time`,`device`,`A0`)
    VALUES
        (:date,:time,:device,:A0)
');

$params = array(
    'date'=>sprintf('%04d-%02d-%02d', $ts['year'], $ts['month'], $ts['mday']),
    'time'=>$time = sprintf('%02d:%02d:00', $ts['hours'], $ts['minutes']),
    'device'=>$_GET['device'],
    'A0'=>$_GET['A0']
);

$stmt->execute($params);

edit: * on second thought you probably want UNIQUE KEY(date,time,device) - so that multiple devices can each insert one record per time slot....
and another edit: For this to be working as intended INTERVAL_MINUTES must be a divisor of 60. We probably have 60 minutes to an hour because 60 has so many divisors (1,2,3,4,5,6,10,12,15,20,30,60), so I hope that's ok....


Issues rendering static files on Pythonanywhere

Question: I am trying to host a Flask application using Pythonanywhere and I am having issues with rendering an image. I am pretty sure I have navigated to it correctly but it still fails to find and display it.
The Code for my webpage is here:
{% extends "base.html" %}

{% block content %}

University Attended:

{% endblock %}

My application looks like this:
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
@app.route('/home')
def homepage():
    return render_template("home.html")

@app.route('/education')
def education():
    return render_template("education.html")

@app.route('/employment')
def employment():
    return render_template("employment.html")

if __name__ == "__main__":
    app.run()

I have done a little bit of research and I think its because I need to serve my static folder but I'm not really sure how to go about that so thats why Im asking on here (if thats even the problem)
Answer: On the Web tab in Pythonanywhere, you can find a Static files section.
Add a URL and directory there.
On my application, I have two defined as shown below:
URL              Directory
/static/         /home/user/project/app/static/
/uploads/        /home/user/project/app/uploads/

More details can be found in the Pythonanywhere help document:
https://help.pythonanywhere.com/pages/StaticFiles


Why does Pydantic evaluate Optional values after or as None?

Question: I have a method which returns an instance of a class depending on a user's successful authentication.
account: Optional[Account] = await Account.authenticate(email, password)
return account or account.dict()

From my understanding, since None type is Falsey any occurance of account after the or keyword should be of type Account.
Any insight into why this is reporting an error would be greatly appreciated.
I have already looked for other instances in Pylance's GitHub issues for values after or being reported as None.
Comment: If `account` is `None`, then `account.dict()` is an error. I think you mean `return account and account.dict()`. (If `account` is `None`, the entire expression is `None`; if `account` is not `None`--and presumably truthy--the expression has `account.dict()` as its value.)
Comment: Only if `account` is None (or other falsy value) is the `account.dict()` part of the expression evaluated - this is the exact opposite of what you want.
Comment: Yep, pylance is just being dumb here
Comment: Are you getting an error at runtime or in your IDE?
Comment: I'm getting this error in my IDE it works as expected at runtime.
Comment: what about `return None if account is None else account.dict()`
Comment: That works @Samathingamajig but I'm asking this question to understand the failure. Based on my assumptions from how typing should work in python the `or` method should work, right?
Answer: Your IDE is correct.
Consider what happens when the authenticate() method returns None. You return:
account or account.dict()

It doesn't return account, as you state, because account is falsy. However, you then call None.dict(), which would be a typing error.
You should change account.dict() to some value that doesn't invoke an instance method of None, but what that value is depends on context that isn't provided in the question.


What is the correct way to design a .NET web application?

Question: Months ago, I was put in charge of a web application, from scratch.  I had never programmed in vb.NET and was only familiar with Classic ASP.  That being the case, I put together a very workable site and yet feel as if I didn't do much better than a beginner.
What is the correct or best format for designing a .net website.
Master Pages?
When to use javascript?
Code Behind javascript or slap it on the .aspx page.
etc, etc.
Comment: That's a very broad question, kind of like going to an architecture forum and asking "How do I design a house".  You may get some good answers, but generally you'll get better answers from more specific questions.
Comment: That being said, I don't vote to close.  It's a question lots of folks ask, and there are pretty good (not subjective/argumentative) answers so far.
Comment: Yes.  I can see it is broad.  Asking the question has given me a lot to work with.  Thank you.
Answer: I would suggest downloading sample web applications like NerdDinner and MVC Music Store...
http://nerddinner.codeplex.com/
http://mvcmusicstore.codeplex.com/
See how they structured their examples and where they put different logic...
Domain Driven Design and MVC is something I've been using a-lot as-of-late...
Answer: The main problem here is that you can choose between two approaches: ASP.NET WebForms and ASP.NET MVC. Unless you choose one the question doesn't make sense because good design is different for each of them.
Comment: Ah, right.  We're using this design in our Flex Applications.
Answer: It's hard to say what the "best" way is because it depends on your specific application. There are many ways to organize and design a .NET web application. The most important aspect is that it works. If you are under a tight deadline, getting it to work is critical even if it's not the most elegant solution.
If you're concerned with optimizing the design or refactoring, then again it will depend on the scale and scope of the project. Don't optimize for the sake of optimizing, but try to make things clear and concise in a way that will make future modifications less painful.
Answer: I can relate to your situation almost exactly (except in C#).
It's a very subjective question as to what is best because it all depends on your exact setup, circumstances, and requirements. I'm still fairly new to the deciding what's best for a project but based on my experiences I can let you know what I did.
We went with an N-Tier set up, so we could keep the UI, Logic, and Data separate. This let's us maintain the code easier with the additional separation of concerns.
We went with Masterpages (with WebForms) so we could work on a consistent look and feel for the application. You can further modify things with themes, plus your standard CSS and Javascript. You want to control the layout easily and not force yourself to copy / update code on every page.
When it comes Javascript, it's usually better to not use it directly on the aspx page itself (unless it's very small) as you will benefit from caching in the browser, plus you can also minify the file to allow for quicker/easier downloads. I personally recommend going with jQuery for a framework since it is easy to work with, has a huge community, and is well documented.
Those are of course, just a few things I've done. Whether it's of help to you or not depends on your circumstances. I still have a long way to go and I personally try to read as many blogs on topics I'm curious about, watch training videos when possible, or simply ask targeted questions here (if you can't already find the answers). There is a ton of good information out there and a lot of sample applications that can help you learn new patterns and design methods. In the end, there is no absolute "correct" or "best" way. :)
Comment: Thanks! I appreciate the empathy and the conclusion.
Comment: Glad I could help a little. I've also been looking into other design patterns aside from WebForms (such as MVC, which I am really liking so far). Unfortunately when I took on this project, WebForms was most familiar to me since it was what I was taught in school. There are just a limitless number of approaches to take in the end though. Each with pros and cons.
Answer: There is no one right way.  There are multiple best practices, some of which may be more or less applicable for your situation.
There are also lots of really bad ways to do.  In between there are some so-so approaches that may be good enough.
Comment: Nice!  You have covered all the bases.  I appreciate your answer.


Encoding email with Zend_Mail_Storage_Pop3

Question: I try get email with Zend_Mail_Storage_Pop3 but the chars come with encoding strange.
Example
Endere=E7o
Paran=C3=A1

shold be
Endereço
Paraná

Answer: You do not give much explanation or code ...
I can propose this:
When you set your email, use utf-8:
$mail = new Zend_Mail('UTF-8');

Comment: OK, but how do you create the mail? You don't use Zend_Mail? Give us your code.


Salvar relatório no Django Excel com filtro

Question: Boa tarde...fiz uma função para exportar relatório em excel que deu certo, porem vem tudo que está no banco de dados, eu queria que fosse filtrado...por gentileza alguém poderia me ajudar....
função que lista meu model
# funcao para listas as alocacoes no template
@login_required
def listAlocacao(request):
    varios = request.GET.get('varios', None)
    context = {}
    if varios:
        alocacoes = Alocar.objects.filter(turma__curso__icontains=varios) | \
                    Alocar.objects.filter(turma__periodo__icontains=varios) | \
                    Alocar.objects.filter(turma__disciplina__icontains=varios) | \
                    Alocar.objects.filter(turma__professor__icontains=varios) | \
                    Alocar.objects.filter(dia__icontains=varios) | \
                    Alocar.objects.filter(horario__horario__icontains=varios) | \
                    Alocar.objects.filter(sala__sala__icontains=varios)
    else:
        alocacoes = Alocar.objects.all()

    context = {'alocacoes': alocacoes}
    return render(request, 'alocar/listalocacao.html', context)

funcao para exportar relatorio excel
def export_users_xls(request):
    MDATA = datetime.now().strftime('%d-%m-%Y')
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="alocacoes.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Alocacoes')

    # Sheet header, first row
    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ['BLOCO','SALA','CURSO','PERIODO','DISCIPLINA','PROFESSOR','DIA','HORARIO']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()

    rows = Alocar.objects.all().values_list('sala__bloco__bloco','sala__sala','turma__curso','turma__periodo','turma__disciplina','turma__professor','dia','horario__horario')

    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response

Answer: Você está pegando todos os registros do model Alocar porque está usando .all() no seu QuerySet em:
rows = Alocar.objects.all().values_list('sala__bloco__bloco','sala__sala','turma__curso','turma__periodo','turma__disciplina','turma__professor','dia','horario__horario')

Caso queira filtrar por algum atributo de Alocar você deve substituir o .all() por .filter(<ATRIBUTO_DE_ALOCAR>=<VALOR_DE_FILTRAGEM>)
Você pode ler mais sobre filter na documentação oficial: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#filter
Comment: @malves1982....bom dia...entendi o que vc esta falando em relaçao ao (all()). minha funcao que filtra esta numa outra view...onde eu tenho o queryset filtrado, porem nao consigo puxar o relatorio filtrado dela...ate editei meu post para te mostrar...se vc puder me ajudar te agradeço, isso é um trabalho de TCC
Comment: Bom dia @ElvisDba, pelo o que entendi você chama a view `listAlocacao`, listando as alocações de alguma forma e depois faz a chamada da view `export_users_xls` para gerar o relatório.

Não vi nada que faça comunicação entre estas views informando quais `Alocar`s você está interessado.

Recomendo 1) passar a lista de IDs da primeira view para a segunda; ou 2) passar este parâmetro `varios` da primeira view para a segunda e repetir o QuerySet na segunda pra obter a filtragem que você tem na primeira.
Comment: ...minha dificuldade reside nesse ponto em questão...fazer essa comunicação..pois eu sou um pouco inexperiente com django...entendeu?


link a calendar to another content type

Question: I have a calendar in Drupal 7, and I want to link this calendar with other nodes.
How do I do this? Which module should I use?
I am using Drupal 7.
Answer: You need to add a "date field" to the test content type.
And with views +date field + calendar you will be able to do it.

link a calendar to another content type


Selenium with Jenkins on MAC

Question: Can someone explain step by step procedure to execute Selenium with Jenkins on MAC? There are many Video for windows but nothing on MAC.
Steps required:

How to set Classpath in terminal?
how to resolve "Permission denied" for jar files?
Run scripts in Jenkin.
Answer: You could try out the following:

How to set CLASSPATH in terminal?
A: Open new terminal you will be in your home directory example /User/pavan
You can edit .bash_profile
export JAVA_HOME=/user/pavan/jdk1.8.0_101
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=$JAVA_HOME/lib

you could add your required jar paths with colon separated.
2 How to resolve "Permission deined" for jar files?
You might tried jar command use the following:
    java -jar yourtarget.jar

Run scripts in Jenkin.

You need to create a job in Jenkin dashboard.In the build section you give shell scripts or commands as shown below image:
Comment: Thanks Pavan.. I will check out.

Selenium with Jenkins on MAC


What is the image of the linear mapping ${P} : \mathbb{V}\rightarrow \mathbb{V}$ where $(Pf)(x)= [f(x) + f(-x)]/2$

Question: Let the linear mapping ${P} : \mathbb{V}\rightarrow \mathbb{V}$ where $\mathbb{V}$ is the space of all functions real valueted of real variable, namely x, we set the image under ${P}$ of a function f(x) to be $$(Pf)(x)= \frac{f(x) + f(-x)}{2},$$ what can i say about the image of $\mathbb{V}$ under ${P}$ ?
My initial hypothesis was that the direct image on the whole domain would be the set of all function but the odd functions, i proved if $\mathbb{V}$ is composed only by either odd function or even functions, but trying to be more general, stating $\mathbb{V}$ to be the set defined on the first paragraph i could not prove. Someone know a way to do this?
Comment: You're not on a bad track. Any real function decomposes uniquely as sum of an odd and an even function.
Comment: i don't understand how the image can contain odd functions. If $g(x) = \frac{f(x)+f(-x)}{2}$ then $g(-x) = g(x)$ so the image contains only even functions.
Comment: @gt6989b i agree that the image can not contain odd function, but this set could also contain a function whose is neither odd nor even.
Comment: @PedroTamaroff there is a name for this statement? i mean where can i find more informations about this?
Comment: @YassinRany no it cannot... see Ashwin's answer
Comment: @gt6989bt i was just explaining my question, anyway thank you for the help :)
Answer: The image would be the set of all even functions.  It's clear the image consists only of even functions because for every function $f(x)$, $\frac{f(x)+f(-x)}{2}$ is an even function. Also, the image consists of all even functions because if $g(x)$ is any even function, then $g(x)$ is in the  preimage of $g(x)$.  So $P$ is a map from the set of all functions onto the set of all even functions.


How to solve recurrence relation $a_{k}=7a_{k-1}-10a_{k-2}, \forall k\ge2$ with $a_{0} = a_{1} = 2$

Question: Unfortunately I have no idea where to even start with this.  This is my first math class in almost a decade.  Can anybody tell me how i would go about solving for the following recurrence relation?  All help greatly appreciated.
$a_{k}=7a_{k-1}-10a_{k-2}, \forall k\ge2$ with $a_{0} = a_{1} = 2$
Comment: Do you know linear algebra and matrices?
Comment: I know of linear algebra.  I am more comfortable with Algebra than any other form of math.  Don't know much about matrices.
Comment: This may not be a good first math class to take if you are uncomfortable with mathematics, but if you are willing to study 2x of the other students then you can maybe do it.  A "college algebra" class may be preferred to take to brush up on your skills before what seems to be a combinatorics class.  I recommend having a discussion with your professor.  Be honest about what you do and don't remember.
Answer: Using the classical approach, start with the corresponding characteristic equation. If $$a_{k}=7a_{k-1}-10a_{k-2}$$ then $$r^2=7r-10$$ the roots of which being $2$ and $5$. So, the general form is $$a_k=c_1 2^k+c_2 5^k$$ Now, apply the conditions for $a_0$ and $a_1$; they will give you two linear equations with $c_1,c_2$ as unknwowns.
Comment: What is a root, and how did you get the roots to be 2 and 5?
Comment: Solutions of the equation which is a quadratic polynomial.
Comment: @OmarN Are you comfortable solving quadratic equations?
Comment: @DanielV I am not an expert, but I think I have a decent handle on quadratic equations for a novice.
Answer: $a_k - na_{k-1} = m(a_{k-1} - na_{k-2}) \to m+n=7,mn = 10 \to n = 5, m = 2 \to a_k - 5a_{k-1} = 2(a_{k-1} - 5 a_{k-2})$. Put $b_k = a_k - 5a_{k-1} \to b_k = 2b_{k-1},k \geq 2, b_1 = 2 - 2\cdot 5 = 2 - 10 = -8$. Thus $b_k = b_1\cdot 2^{k-1} = -8\cdot 2^{k-1}$. Can you continue?
Comment: One thing that I think would help me is, what does $a_{0} = a_{1} = 2$ mean?
Comment: @Omar: We are given some partial info about a sequence of numbers. With this partial info as clues we have to solve the puzzle; The info are two kinds: how the $k$ th term of the sequence is related to the previous two terms; and the other info is what the first two terms are ($a_0$ and $a_1$).

Solving means getting a formula for the $k$th term $a_k$ directly in terms of $k$ and not in terms of other members of this sequence.
Answer: If you don't mind using matrices, you can combine:
$$a_{k+1} = 7~a_{k} - 10~a_{k-1}$$
with
$$a_{k} = a_{k}$$
To get:
$$\begin{align}
a_{k+1} &= 7~a_k - 10~a_{k-1} \\
a_{k} &= 1~a_k + 0~a_{k-1}
\end{align}$$
$$\begin{align}
\begin{bmatrix} a_{k+1} \\ a_{k} \end{bmatrix}
%
&= \begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} a_{k} \\ a_{k-1}\end{bmatrix}
%
\\ &=
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} a_{k-1} \\ a_{k-2}\end{bmatrix}
%
\\ &=
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} a_{k-2} \\ a_{k-3}\end{bmatrix}
%
\\ \vdots
%
\\ &=
\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}^k
\begin{bmatrix} a_{1} \\ a_{0}\end{bmatrix}
%
\end{align}$$
The eigenvalues of $\begin{bmatrix} 7 & -10 \\ 1 & 0 \end{bmatrix}$ are $5$ and $2$, so for some matrix $P$:
$$\begin{bmatrix} a_{k+1} \\ a_{k} \end{bmatrix}
%
= P~\begin{bmatrix} 5 & 0 \\ 0 & 2 \end{bmatrix}^k~P^{-1} \begin{bmatrix} a_{1} \\ a_{0}\end{bmatrix}$$
So for some numbers $X$ and $Y$:
$$a_{k+1} = X~5^k + Y~2^k$$
You can use the initial conditions $a_0 = a_1 = 2$ to find $X$ and $Y$:
$$2 = X~5^1 + Y~2^1$$
$$2 = X~5^0 + Y~2^0$$
To get:

 $x = \frac{-2}{3}$ and $y = \frac{8}{3}$

to get the total solution:

 $$a_{k+1} = -\frac{2}{3}~5^k + \frac{8}{3}~2^k$$

If you aren't comfortable with matrices, and just want "how do I do this" rather than "why does this work", then I recommend Claude's answer.
Comment: I think I understand now.  The only part I am confused on is when you got to 2=X 5^1+Y 2^1 and 2=X 5^0+Y 2^0, how did you come up with the answer of -2/3 and 8/3?
Comment: $$X + Y = 2 \implies X = 2 - Y \implies 2 = (2 - Y)~5 + 2Y \implies Y = \frac 83 \implies X + \frac 83 = 2 \implies X = -2/3$$.  Frankly, this is a fairly high school level task, to solve 2 equations and 2 variables.  I really strongly suggest talking to your professor about whether you should be taking a college algebra class instead.  You won't enjoy mathematics if you are taking courses that you aren't prepared for.
Comment: PS, that's college algebra, not abstract algebra.  Make sure not to confuse those.


Has anyone ever thrown a 4-out immaculate inning?

Question: Has any pitcher ever thrown a 4-out immaculate inning, and if so, was it still considered immaculate?
That is 4 strikeouts on 12 pitches, with one batter having reached due to a wild pitch.
Comment: I can't imagine the second part of your question having a useful answer - it's not a technical term.
Comment: Just as it would eliminate a perfect game, I would suggest that an error would also eliminate and immaculate inning. Noted that the feat is possible, but the terminology can never be used.
Comment: For those not too familiar with baseball, can you explain more how there would be 4 strikeouts with 12 pitches in 1 inning (well, actually, I think that would be half an inning)?
Comment: If on strike 3, the ball is not caught and first base is open (except when there's 2 outs, it doesn't matter if first is open), the batter becomes a runner, and can run to first base. If he makes it there before he's either tagged or the ball is thrown to the base, he is safe. But the pitcher is still credited with the strike out. Hence getting 4 strikeouts in an inning. It's been done before, but apparently never on 12 pitches.
Answer: No. There has never been an MLB immaculate inning with four outs.
Every source available on immaculate innings is quick to list those pitchers who had managed the feat more than once at that point, and annotate additional information that is tangential to the feat, but none (especially from MLB themselves) refer to an inning where more than three strikeouts occur.
While impossible to prove a negative, this is very strong evidence that the feat has not occurred.
Answer: (Too long for a comment)
Wikipedia claims

[N]o player has ever struck out four batters on twelve pitches in an inning.

in its List of Major League Baseball pitchers who have thrown an immaculate inning, referencing four sources but I could not find the claim in any of them.


Dois spinners que não podem ter o mesmo valor selecionado

Question: Ola, eu tenho um código que tem dois spinners e que caso selecionamos uma opção num spinner no outro essa opção deixa de existir , o que eu fiz foi o seguinte : Sempre que clica no spinner ele faz clear e adiciona todos e depois remove o que esta selecionado no outro de modo a não se poder seleccionar o mesmo nos dois! Mas quando seleciono alguma coisa num , ele entra num loop infinito , como se estivesse sempre a efetuar o método OnItemSelected alguém sabe porque ? Aqui esta o código:
   disciplinasFirst.add("Biologia e Geologia");
                disciplinasFirst.add("Física e Química A");
                disciplinasFirst.add("Geometria Descritiva A");
                disciplinasFirst.add("Química");

                final ArrayAdapter<String> adapterDitsciplinasFirst = new ArrayAdapter<String>(ChoseDisciplinas2.this, R.layout.spinner_item_beggin, disciplinasFirst);

                adapterDitsciplinasFirst.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                SpinnerFirst.setAdapter(
                        new NothingSelectedSpinnerAdapter(
                                adapterDitsciplinasFirst,
                                R.layout.contact_spinner_row_nothing_selected,
                                // R.layout.contact_spinner_nothing_selected_dropdown, // Optional
                                this));

                disciplinasSecond.add("Biologia e Geologia");
                disciplinasSecond.add("Física e Química A");
                disciplinasSecond.add("Geometria Descritiva A");
                disciplinasSecond.add("Química");

                    final ArrayAdapter<String> adapterDisciplinasSecond = new ArrayAdapter<String>(ChoseDisciplinas2.this, R.layout.spinner_item_beggin, disciplinasSecond);

                adapterDisciplinasSecond.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                SpinnerSecond.setAdapter(
                        new NothingSelectedSpinnerAdapter(
                                adapterDisciplinasSecond,
                                R.layout.contact_spinner_row_nothing_selected,
                                // R.layout.contact_spinner_nothing_selected_dropdown, // Optional
                                this));

                SpinnerSecond.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (SpinnerFirst.getSelectedItem() != null) {
                            disciplinasSecond.clear();
                            disciplinasSecond.add("Biologia e Geologia");
                            disciplinasSecond.add("Física e Química A");
                            disciplinasSecond.add("Geometria Descritiva A");
                            disciplinasSecond.add("Química");
                            disciplinasSecond.remove(SpinnerFirst.getSelectedItem().toString());
                            final ArrayAdapter<String> adapterDisciplinasSecond = new ArrayAdapter<String>(ChoseDisciplinas2.this, R.layout.spinner_item_beggin, disciplinasSecond);
                            SpinnerSecond.setAdapter(adapterDisciplinasSecond);
                            Log.d(Tag,"fui selecionado2");
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }

                });
                SpinnerFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if(SpinnerSecond.getSelectedItem()!=null){
                            disciplinasFirst.clear();
                            disciplinasFirst.add("Biologia e Geologia");
                            disciplinasFirst.add("Física e Química A");
                            disciplinasFirst.add("Geometria Descritiva A");
                            disciplinasFirst.add("Química");
                            disciplinasFirst.remove(SpinnerSecond.getSelectedItem().toString());
                            final ArrayAdapter<String> adapterDitsciplinasFirst = new ArrayAdapter<String>(ChoseDisciplinas2.this, R.layout.spinner_item_beggin, disciplinasFirst);
                            SpinnerFirst.setAdapter(adapterDitsciplinasFirst);

                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }

                });

            }

Disciplinas First e Disciplinas Second são o conteúdo dos Spinners nest caso o Spinner First e Spinner Second respetivamente.
Muito obrigado e uma boa noite ou boa tarde para os brasileiros!
Answer: Penso que o seu algoritmo deveria ser: se eu selecionar algo no primeiro Spinner, altera o conteudo do segundo; e vice-versa. Do jeito que fez, sempre que fizer uma escolha no primeiro, o conteúdo dele será alterado o que equivale a fazer uma nova seleção ativando o onItemSelected recursivamente.
Mas esse algoritmo também pode causar um problema semelhante: quando seleciona um valor, o onItemSelected vai alterar o outro spinner, cujo onItemSelected vai alterar o primeiro, que por sua vez ira novamente alterar o segundo, ... Não tenho android, portanto não testei.
Solução simples: use um boolean como 'guarda' para evitar que o onItemSelected faça alguma alteração se já tiver um outro rodando.
Esquema:
private boolean selecionando = false;

SpinnerFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (!selecionando) {
            selecionando = true;
            try {
                if (SpinnerFirst.getSelectedItem() != null) {
                    disciplinasSecond.clear();
                    disciplinasSecond.add("Biologia e Geologia");
                    ...
                    disciplinasSecond.remove(SpinnerFirst.getSelectedItem().toString());
                    ...
                }
            } finally {
                selecionando = false;
            }
        }
    }
});

SpinnerSecond.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (!selecionando) {
            selecionando = true;
            try {
                if (SpinnerSecond.getSelectedItem() != null) {
                    disciplinasFirst.clear();
                    disciplinasFirst.add("Biologia e Geologia");
                    ...
                    disciplinasFirst.remove(SpinnerSecond.getSelectedItem().toString());
                    ...
                }
            } finally {
                selecionando = false;
            }
        }
    }
});

O try-finally é para garantir, mesmo no caso de uma Exception, que selecionando seja resetada. Syncronização nào deve ser problema pois esses métodos sempre são chamados da mesma Thread.
Obs:
esse esquema é muito instável e complicado, talvez funcione melhor se deixar todas as opções nos spinner e, caso o usuário escolher a mesma opçõa, simplesmente desabilitar o botão que aceita a escolha.


Area of bounded between $y=x-1$ and $(y-1)^2=4 (x+1)$

Question: Find the area enclosed by curves $y=x-1$ and $(y-1)^2=4 (x+1)$.
I found point of intersection as $(0,-1)$ and $(8,7)$ and set up integral as:
$|\int_{-1}^{7} [(y+1)-\frac{(y-1)^2}{4}-1]dy|$. Am I heading in right direction?
Answer: Finding the points of intersection of the two curves: $(y-1)^2 = 4(y+2) \Rightarrow y^2-2y+1 - 4y-8 = 0\Rightarrow y^2-6y-7 = 0\Rightarrow (y+1)(y-7) = 0\Rightarrow y = -1, 7\Rightarrow A = \displaystyle \int_{-1}^7 \left(y+1- \left(\dfrac{(y-1)^2}{4}-1\right)\right)dy$. The difference between your answer and mine is the last $-1$ in your answer. I think it should be $+1$.


Differences in power in regression versus mean of a ratio

Question: I've been futzing around with the following example, and feel that there must be a good explanation or reference that I am blindly missing.
Supposer you have a linear relationship between two variables.  Let's even assume that the intercept goes through 0.  Why would there be more power in analysis by regression of y~x versus y/x ~ 1?  And in particular, if x is biased, the decrease in power is even more dramatic.  I can show this by simulation in the following R code, it strikes me that there is easy explanation here.
<code>simBiasPower <- function(b=-1, ySD = 2, n=100, nsim=100){
  sapply(1:nsim, function(i) {
    unbiasedX <- runif(nsim, 0,10)
    biasedX <- rexp(nsim,0.5)

    unbiasedY <- rnorm(100, b*unbiasedX, ySD)
    biasedY <- rnorm(100, b*biasedX, ySD)

    return(c(unbiasedSlopeP= coef(summary(lm(unbiasedY ~ unbiasedX)))[2,4],
             unbiasedRatioP = coef(summary(lm(unbiasedY/unbiasedX ~ 1)))[1,4],
             biasedSlopeP = coef(summary(lm(biasedY ~ biasedX)))[2,4],
             biasedRatioP = coef(summary(lm(biasedY/biasedX ~ 1)))[1,4]
    ))
  })

}

pMat <- as.data.frame(t(simBiasPower()))

library(plyr)
powerBySim <- colwise(function(acol) sum(acol<=0.05)/100)(pMat)

powerBySim
</code>
This produces the following estimates of power for the four analyses:
<code>  unbiasedSlopeP unbiasedRatioP biasedSlopeP biasedRatioP
1              1           0.66            1         0.16
</code>
Note, I've tried this also forcing the intercept through 0 and thus not estimating an intercept for y~x, and the answer doesn't change. I've also changed the distributional form of the unbiased x, and it doesn't seem to matter very much.  Similar drop in power.
Of of the top of my head, when one divides by x, you reduce the leverage of points at the extreme end of the relationship - along the lines of reducing your variability in x in a regression context.  But it feels like there is something more forehead-smackingly basic going on here.
Comment: You are comparing two distinct models: the error structure in `y ~ x-1` and that in `y/x ~ 1` are very different.
Comment: Yes, I think that is the heart of the matter.  It's not a Cauchy, as y is dependent on x.  I feel like this might be getting at the heart of the matter.  That some property of the distribution of the ration is where I'm headed, but I'm unclear on what distribution is appropriate.
Comment: It's rarely a matter of what distribution is *appropriate*, but rather of what distribution actually pertains in any given problem. In some contexts a symmetrical distribution of errors for `y~x-1` may be appropriate while in others a symmetrical distribution for `y/x~1` may be suitable and in yet others something else is needed.
Comment: Indeed, very true.  Still, struggling to figure out how to connect this back to finding why there is such a drop in power.
Answer: if Y and X are both normally distributed, Y/X follows the Cauchy distribution, (which has several strange properties... for example, the mean is not a measure of central tendency in this distribution... and the properties of the Cauchy distribution might be what is messing up the power in your regressions).
Comment: Correct me if I'm wrong, but, I thought that a Cauchy distribution was due to the ratio of two independent normal variables.  Here, y is dependent on x, so, this wouldn't quite be right.  But this seems like it's on the right track...
Comment: Neither: the Cauchy arises as the ratio of two *zero-mean* normal variates.  See http://en.wikipedia.org/wiki/Ratio_distribution#Gaussian_ratio_distribution.


How can I learn the theory behind chord progressions?

Question: How can I learn about the relationships between chords to build chords progressions?
Every book I read explains how to build chords, but they don't teach how to put the chords in progression. They just teach you some common chords progressions like I-V-IV, but they don't teach the "why" of this progression.
Let's say I have a Bb7/G# chord. How can I know the next chord that would fit in the progression and why this chord?
In particular the chord progression is:
Bb7/G#       Gm6  Ebmmaj7/F#  Bb
These chords are from the song "Aguas de Marzo" by Tom Jobim. They are very weirds chords to me. If I play the chord Bb7/G# alone it sounds very dissonant. But play the fours chords following the rythming of the song and it sounds beatiful.
What is the area of music theory who study the "why" of this, and not only the "how", which is what I have read in every book of "chord theory" for guitar. Any book you would recommend?
Thanks.
Comment: As a point of accuracy, those chords are misnamed (specifically the bass notes). The sharps should be spelled as flats: Bb7/Ab - Gm6 - EbmM7/Gb - Bb
Answer: Look for a book on harmony? Schoenberg builds things up from chord positions to progressions (and rants about The War And Other Things!) in "Theory of Harmony" while Piston uses examples taken from common practice music in "Harmony," to name just two books. Some knowledge of counterpoint may also be helpful, e.g. to better understand voice leading.
Answer: Just studying the basics of music theory and voice leading should give you the tools to notice what's going on. No matter what the chords in the progression, it's pretty easy to figure out what is going on by looking at the notes in the progression, how the move, and what they emphasize.
I quickly sketched out one possible voicing for this progression in Finale to show you how the notes most likely would move:

There are a few things to notice which are:

The Bb and D is common in every chord.
The first chord is in 3rd inversion which is rather unstable.
The bass line is chromatically descending in the first three chords then moves to the note common in all three chords.
The voices other then bass move very little.
The very dissonant interval of Eb to D (M7/m2) resolves to a very consonant F to D (M6/m3).
The ending motion can be viewed as a plagal cadence in first inversion.

As you can see there is a lot to look at in these four chords, but the reason why someone may like it is simple. While the line may start dissonant, the constant descending chromatic motion in the bass and the combination of common tones and small motion in the other voices keeps the chords related and  "spins" until there is an obvious resolution reached on the last chord.
Comment: The E in the second chord (Gm6) should have a natural sign, it's no Eb. With this correction it becomes obvious that we have two chromatic lines moving in parallel. The higher line is F-E-Eb-(D). Also note that the chromatic movement of the bass line can be finalized by moving down to the F when reaching the last chord. This progression is basically a double [line cliche](http://music.stackexchange.com/questions/24285/name-for-descending-semitones-under-a-repeating-musical-phrase/24295#24295).
Comment: Could you recommend a good book on Voice Leading?
Comment: @MattL., a minor sixth from G is E♭, not E♮.
Comment: @Patrx2: That's true but irrelevant. A Gm6 chord has a major sixth: G Bb D E
Comment: Fair enough. Jobim's score shows an F♯ here (the score is up a tone from what OP posted). I'm used to a somewhat different notation: added sixths in Classical _aren't_ always major in this case.
Comment: @Carlitos_30 Any theory book should go over the basics of voice leading. Here's a PDF that goes over most of the basics: http://cnu.edu/music/pdf/theory_exit_review.pdf
Answer: This progression works because of its strong chromatic movement. Note that there are two chromatic lines moving downwards. One of them (in the bass) was already noted in Dom's answer. The first is the bass line: Ab-G-Gb-(F) (the Gb can move down to the F, which is the fifth of the Bb chord). The other chromatic movement is F-E-Eb-D. Apart from the chromatic movements, the other notes (Bb and D) are common to all four chords. What you basically have here is a line cliché.
The movement of Ebm-maj7 to Bb can also be viewed as a iv-I resolution, which is very common in many genres. The iv chord is borrowed from the parallel minor key.
As for recommendations on how to learn about chord progressions: since you seem to be interested in Bossa Nova, have a look at jazz harmony. An excellent book is The Chord Scale Theory & Jazz Harmony by Nettles and Graf. And don't forget to use your ears in addition to trying to "understand" a progression. The progression in your question is a great example of a progression that can be understood quickly by hearing the two chromatic lines, instead of thinking about some functional connection between the chords.
Answer: There are several summaries of common chord syntax based on a given style. Like this one in Kostka & Payne which is meant to model common-practice tonal music syntax. Note that this is based on the circle of fifths which is understandable but can be critiqued in that one can easily argue that not all idiomatic progressions are derived from the circle of fifths progression.

Or the one on page 37 of this article by Tymocko.
Note that Schoenberg's famous chart of the regions (mentioned above) is more of a map of key relations, but doesn't prescribe a suggested or typical syntax. In fact Schoenberg's HarmonieLehre has surprisingly little advice or commentary about chord syntax.
Answer: It seems to be about how "close" (smaller interval) notes change within a chord progression. EG. a change from A to D involves a strong common note (the A), the E moving to a F#, and the C# moving to a D.
I say "Moving" because that's how the ear percievs it: Even though all but the A note have changed when going from A to D, we hear that there's a change in the E and C# because they've only changed by a tone and semitone respectively.
This theme accounts for a lot of chord progressions-  for example Whiter Shade of Pale uses (something like) C G Am G F Em Dm C .. etc
They might seem a bit random but there's a descending note through the chords whcih follows a major scale in C (notes C B A G). Your ear picks this up (assuming you're attoned to western music chord structures) and you find you 'know' what comes next even before you hear it. That's not because it's a cliche- it's your brain doing some anticipation, and the song author knows this and probably did it quite deliberately. It's a suimilar but different story at the beginning of Stairway to Heaven.
It's not a hard and fast rule - but then nothing is in music. For example the smalles change would be to have a chord drop or raise a semitone in its entirety. That's not so common and doesn't sound great.
Part of working out a chord structure is to work out what you want to achieve in terms of mood, and which chord you want to end up on ready for the next section, and deliver something whcih plays withthe human ear. It;s entirely up to you whether you go by the manifestation I've mentioned above, but that is one reason why chord sequences are arranged as they are.
Answer: One of the things that helped me in understanding how to put chords into progressions came from pure experimentation.  I was practicing various types of harmonized chords around the major scale.  I would practice playing all the harmonized sus4 chords of a scale then the sus2, 6 chords, 7 chords, etc.  I harmonized chords around different types of minor, major, and exotic scales.
I would go up and down the harmonized scale alternating between two different types of chords such as 6 chords and 7 chords. {The first two chords of your example are actually very close to this}  I would try things like alternating two harmonized 6 chords followed by two harmonized 7 chords.
I would take a single chord and listen to how it sounded paired with other chords by moving any single note up or down a variety of half and whole steps.  I would move pairs of notes by half steps and whole steps.  I would move entire chords up and down half and whole steps.
In experimenting and practicing the variety of harmonized chord types, I began to hear which chords complimented each other and which chords could go to other chords.
Answer: Written and played properly, it's also used as a blues turnaround. Often with the notes played as triplets, the first 3 being Ab-F-Ab, etc. Ending with F and D played together.


(compelx analysis) Let $I_m = \int_{-\infty}^\infty \frac{dx}{1+x+x^2+\cdots+x^{2m}}$. Calculate $I_2$ and $I_3$.

Question:
Let
  $$I_m = \int_{-\infty}^\infty \frac{dx}{1+x+x^2+\cdots+x^{2m}}.$$
Calculate $I_2$ and $I_3$.

In studying complex variables, I have come across this question in both Churchill's and Ahlfors' textbooks on complex analysis. Where does one begin for an integral like this? Is it best to use residues and should one attempt to factor the denominator?
Comment: For $k\in\mathbb N>2$, we have $$\int_{-\infty}^\infty\frac{1-x~}{1-x^k}dx=\dfrac\pi k\cdot\cot\dfrac\pi{2k}\cdot\sec\dfrac\pi k,\qquad\text{for odd }k$$ and $$\int_{-\infty}^\infty\frac{1-x~}{1-x^k}dx=2\cdot\dfrac\pi k\cdot\cot\dfrac\pi k,\qquad\qquad\text{for even }k$$
Comment: @Lucian . Thanks. How did you derive those integrals? Are they commonly known identities?
Comment: For the odd case, the whole idea is to subdivide $(-\infty,\infty)$ into three subintervals: $(-\infty,0)$, $(0,1)$, and $(1,\infty)$, then to use substitutions like $t=-x$ and $u=\dfrac1{1+t^k}$ on the former, and $v=\dfrac1x$ on the latter, along with rewriting $x^a-x^b=(1-x^b)-(1-x^a)$. This will yield a linear combination of [beta functions](http://en.wikipedia.org/wiki/Beta_function) and [generalized harmonic numbers](http://en.wikipedia.org/wiki/Harmonic_number#Calculation) $\ldots$
Comment: $\ldots$ at which point [Euler's reflection formula](http://en.wikipedia.org/wiki/Reflection_formula) for the [$\Gamma$ function](http://en.wikipedia.org/wiki/Gamma_function#Properties) will come into play. As for the even case, use the [symmetry](http://en.wikipedia.org/wiki/Even_and_odd_functions) of the integrand.
Answer: If you want a possible starting point, write the denominator as
$$
\frac{1-x^{2m+1}}{1-x}
$$
(There is justification of this, in that that form is an analytic continuation of the sum form.)
You then get the difference of two integrals that will look more like the sort of residue problem you are studying in your complex variables class.  For example, integrals like
$$\int_{-\infty}^{\infty} \frac{x}{1-x^5} dx
$$
Comment: Thanks, Mark. My confusion is that we have been dealing with integrals that have their points of singularity ABOVE the real axis but $\frac{1-z}{1-z^5}$ seems to have its singularity ON the real axis when $z = 1$. What's the best way to deal with that?


Closed set in the product space implies sequential closure

Question: Let $(X, \ge)$ be an ordered topological space. Let $\succsim$ be another order relation on $X \times X$ such that for all $x,y,z,w \in X$ the set $$\{(x,y,z,w) \in X \times X \times X \times X : (x,y) \succcurlyeq (z,w) \}$$ is closed in the product topology.
Suppose $(x_n)$, $(y_n), (w_n)$, $(z_n)$ converge to $x$, $y$, $w$ and $z$ respectively. If for every $n \in \mathbb{N}$ we have $(x_n,y_n) \succsim (w_n,z_n)$ then $(x,y) \succsim (w,z).$
My tentative proof is:
i) Show that component-wise convergence is equivalent to convergence of the quadruple in the product space (known result).
ii) Denote $K = \{(x,y,w,z) \in X \times X \times X \times X : (x,y) \succsim (w,z)\}$ and pick a sequence of points with values in $K$ converging to $(x,y,w,z)$. Since every closed set in the product topology is sequentially closed, the conclusion follows.
Does it sound correct?
Answer: Yes, that argument works as closed sets are always sequentially closed (the reverse need not hold, but that's not an issue here). IN the last step you don't have to pick such a sequence of points, as the $(x_n,y_n)$ and $(w_n, x_n)$ are already given such that $(x_n, y_n, w_n, z_n)$ are in $K$ aren't they ? They converge to $(x,y)$ and $(w,z)$ resp. because of the convergence iff pointwise convergence fact in all product topologies.
Comment: You are right. Here I applied the known result of topologically closed implies sequentially closed and the $\textit{pick}$ term came from a possible proof of that fact. But yes, you are right, I do not pick any sequence, I just use the one I have by assumption.


How to animate the div from bottom to top without stop?

Question: I would like to have this div animated anytime with no stop, How can I animate it from bottom to top without stopping?
div {
  width: 10px;
  height: 100px;
  background: red;
  position: relative;
  animation: animateDiv 5s 2;
  animation-direction: alternate;
}

@keyframes animateDiv {
  0%   {bottom: 0px; top: 10px;}
  25%  {bottom: 200px; top:30px;}
}

Answer: You can use animation infinite in css
div {
  width: 10px;
  height: 100px;
  background: red;
  position: relative;
  animation: animateDiv 5s 2;
  animation-direction: alternate;
  animation-iteration-count: infinite; //You must add this to make it infinite
}

and also you can make this keyframe to 100% to see a smooth animation :D
@keyframes animateDiv {
  0%   {bottom: 0px; top: 50px;}
  100%  {bottom: 50px; top:0px;
}

Answer: You can use infinite for your animation. An example is below:

.container {
  position: relative;
  background-color: #eee;
  height: 100px;
  width: 500px;
}

#box {
  position: absolute;
  top: 0;
  left: calc(50% - 5px);
  animation: move 2s infinite;
  background-color: red;
  height: 10px;
  transform: translateY(0);
  width: 10px;
}

@keyframes move {
  0%, 100% {transform: translateY(0)}
  50% {transform: translateY(90px)}
}

Answer: Use "infinite" instead of "2". This will make the animation repeat forever!


nagios nrpe plugin output not complete

Question: I have written a small script to check the states of PfSense, and using this script to get the output in nagios, through NRPE...
Here is the script

used=`pfctl -s state | wc -l | bc | cut -c1-5 | bc`
echo "States consumed=$used"

Normal output of the script is as follows (as it runs on the client.
States consumed=25519

But the issue is that when the same script is ran through NRPE from the nagios server, I get this command.
States consumed=0

But when I put anything in the variable "used" , for example pass it value of 123, or abc,,it is visible on the nagios server through nrpe...
What can be the issue here? I have tried every possible solution from my side, since last 5 days..
Answer: Is "pfctl" in the PATH for nagios user?  I would use the absolute path in the script.
Comment: You may have to invoke your script using sudo.  You can restrict nagios user to only that command run by adding something like this to the sudoers file: "nagios ALL=(ALL) NOPASSWD: /path/to/script" and then changing your nrpe.cfg so that you're running "sudo /path/to/script".  See if that works.  It's possible pfctl won't run as non-root, even with a user in the right group.  Again, I'm not a BSD user so I'm not sure if that's the case.
Comment: yes, thats why i am getting an output, otherwise script wont run at all
Comment: I don't mean the check script called by nrpe.  I mean the pfctl command itself (I'm not familiar with FreeBSD, so I don't know if that's standard, or if it's in /usr/sbin and /usr/sbin isn't in the default PATH for nagios user).  From what you've pasted, you're calling "pfctl" and assuming that the nagios user can find it in its PATH.
Comment: got it. i am running it with /sbin/pfctl ...now i have added the nrpe user to WHEELS group, but still nrpe is unable to run the command pfctl..
Comment: i was trying not to use sudo, but as it was last resort, that i had left with..so its working now. Thanks
Answer: Is it because of the user that the script runs as?
Comment: the permission of script is 777, which means anyone can execute this command. but with which user nrpe runs the scripts?
Comment: What user is the nrpe daemon running as?  That's the user that will run the script.

nagios nrpe plugin output not complete


Como renderizar corretamente um Array usando React

Question: Eu tenho um componente MotoboyPage, onde nele eu criei um protótipo do que eu quero, pra ficar mais fácil inicialmente. Então creio que ficou fácil de ler, cheguei a um erro, onde minha função getListOfMotoboys, que renderiza o conteudo usando .map, esta renderizando na tela [object Object], não sei porque isso esta acontecendo, o esperado era renderizar o retorno da função renderListOfMotoboys.
MotoboyPage.jsx
import { useState } from 'react'
import { Motoboy } from '../../components/Motoboy'

export const MotoboyPage = () => {
  const [name, setName] = useState('')
  const [age, setAge] = useState(0)

  const [motoboys, setMotoboys] = useState([{name: 'sacoludo', age: 2}])

  const getListOfMotoboys = () => {
    let list = motoboys.map((motoboy, index) => <Motoboy key={index} _name={motoboy.name} _age={motoboy.age} /> )
    return (

motoboys

{list}

    )
  }

  const renderListOfMotoboys = () => {
    const listDiv = document.getElementById('list');
    const content = getListOfMotoboys();
    console.log(content)
    listDiv.innerHTML = content;
  }

  const handleSubmit = (e) => {
    e.preventDefault()

    setMotoboys([{ name: name, age: age }, ...motoboys])
    renderListOfMotoboys();
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          placeholder='name'
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type='number'
          name='age'
          id='age'
          value={age}
          onChange={(e) => setAge(e.target.value)}
        />

        <button type='submit'>criar novo motoboy</button>
      </form>

    </>
  )
}

Comment: Não tenho certeza pq estou vendo do cel, mas talvez seja pq você na hora de criar a lista em setMotoboy, no handle, você está criando um obj ao invés de criar uma array, tenta aí.
Answer: A sua função renderListOfMotoboys está alterando o DOM diretamente, o que a gente deixa pro React cuidar pra gente, você não precisa fazer isso na maioria dos casos.
O conceito do React é ser declarativo, você declara o que você quer que ele faz e ele faz. Por exemplo, você não precisa ter

 pra depois imperativamente colocar as coisas dentro dessa div, você pode simplesmente fazer:

motoboys

  {
    motoboys.map((motoboy, index) => <Motoboy key={index} _name={motoboy.name} _age={motoboy.age} />)
  }

Com essa mudança você não precisa mais de getListOfMotoboys e renderListOfMotoboys.
De uma olhada na documentação oficial aqui