How does CSV cache behave under memory load?

Question: We're looking at using Microsoft's CSV cache feature in our new Hyper-V 2012 R2 clusters:

It's enabled by default, with 512MB allocated to each CSV.
The maximum memory that can be assigned is 80%.
The recommendation is a maximum allocation of 64GB.

Our nodes will have plenty of free memory (in case of node failure, etc.) so for the majority of the time our hosts will have plenty of free memory.
What I would like to find out is what would happen if we allocated, for example, the full 64GB, and a node failure occurred such that the remaining nodes would need to reclaim memory. Would the host be able to reclaim the memory from cache? Is it possible to detect the cache by inspecting the system processes?
Answer: You asked a very specific question -- what does the CSV cache do under memory load?
The answer is that memory is allocated to the CSV cache statically, and never released.  So if you experience a failover, that memory is not available for anything else, like picking up VMs that might need to run.
I suspect that, after a relatively small allocation (the default 1/2 GB) the marginal value of more memory in the CSV cache is low for you.
Comment: I believe you, but it would be nice to have some documentation or empirical evidence :) Does it not exist, or is my google-fu weak?
Answer: What kind of storage do you use as shared storage where your CSV's are hosted?
If it's a software solution (software-defined storage), I would recommend turning native CSV caching off and use solution's cache instead. Software-defined storage like Starwind for example has it's own DRAM caching which can work in write-back mode (CSV has read-only cache) and is unlimited in size (CSV is limited to 64GB) and optionally can be deduplicated (CSV can not)  https://www.starwindsoftware.com/starwind-virtual-san
Answer: The changes you have highlighted were introduced in Windows 2012-R2, specifically for SoFS.
SoFS is very read-intesive and would greatly benifit from higher cache settings (max-80% / recommended-max-64GB)
For Hyper-V the recommendation is to be more conservative, in regards to memory allocation, for exactly the reason you highlight. the CSV cache will be competing for memory as a resource with the Virtual Machines on the node, especially in failure situations where Machines are moved from node to node due to node failure.
Saying that; you simple can take CSV cache as a requirement for your hardware design. You say you have "plenty". So within this "plenty" of memory you need to calculate what the maximum cache is you can use, without limiting the on-lining of Virtual Machines.
HTH.
Comment: Hi Edwin. Thanks for your answer, I understand the differences and recommendations but I want to know the exact behaviour during this scenario. I'm not currently in a position to test it myself so am looking for documentation or experience.
Comment: What I believe is happening that the CSV cache is not freed up for use by Virtual Machines. Unfortunately I do not have documentation or other resources to back that up. Other then experiences and observations. I do realize this answer is not scientific, but it is the best I can give you.


Excluir registro usando NGRX e effects

Question: Estou estudando gerenciamento de estados e ao tentar excluir um registro ao bater no meu endpoint, o valor do id esta indo "undefined".
Component
this.store.dispatch(DELETE_COMANDA(comandaId));

Actions:
export const DELETE_COMANDA = createAction('[Comandas] Delete Comandas', props <{ payload:number }>());
export const DELETE_COMANDA_SUCESS = createAction('[Comandas] Delete comandas SUCESS', props <{ payload }>());
export const DELETE_COMANDA_FAIL = createAction('[Comandas] Delete comandas FAIL', props<Error>());

reducers
  on(comandasActions.DELETE_COMANDA_SUCESS, (state,  { payload } ) => {
    return {
      ...state,
      payload
    };
  }),

  on(comandasActions.DELETE_COMANDA_FAIL, (state, error) => ({ ...state, error})),

effect
  deleteComanda$: Observable<any> = createEffect(() =>
  this.actions$.pipe(
    ofType(comandasActions.DELETE_COMANDA),
    map((action) => action.payload),
    mergeMap((id) =>
      this.comandaService.deleteComanda(id).pipe(
        map((payload) => comandasActions.DELETE_COMANDA_SUCESS({payload})),
        catchError((error) => of(comandasActions.DELETE_COMANDA_FAIL(error)))
        ))
    )
  );

Answer: O problema é que seu efeito esta esperando um objeto com a propiedade payload e vc ta mandando uma chamada comandaId
Tenta assim:
this.store.dispatch(DELETE_COMANDA({payload: comandaId}));

Excluir registro usando NGRX e effects


Irreducibilty of polynomial $x^9-6x^6+282x^3-8$ over $\mathbb {Q} $

Question: While trying to deal with the final parts of this answer I found that one needs to establish $$a=\sqrt[3]{1+\sqrt{11}}\notin\mathbb{Q} (\sqrt{11},\sqrt[3]{10})=F$$ Since both $a, F$ are of degree $6$ over $\mathbb {Q} $  the tower theorem does not help much.
Then I reasoned via contradiction. If $a\in F$ then $b=\sqrt[3]{1-\sqrt{11}}=-\sqrt[3]{10}/a\in F$ and hence $c=a+b\in F$.
One can check that $$c^3=a^3+b^3+3abc=2-3\sqrt[3]{10}c$$ or $$(c^3-2)^3=-270c^3$$ or $c$ is a root of $$f(x) =x^9-6x^6+282x^3-8$$ I checked using pari/gp that the polynomial $f(x) $ is irreducible over $\mathbb {Q} $. Further it can be observed that $f(289)$ is prime (also checked via pari/gp) so that the polynomial $f(x) $ is irreducible by Murty's criterion.
This shows that $c$ is of degree $9$ over $ \mathbb {Q} $ and hence $c\notin F$.
It can be observed that $f(x) $ can not be handled by Eisenstein as $2$ is the only prime which divides all non-leading coefficients and $4\mid 8$. I also checked the reducibility mod $3$ and the polynomial is reducible mod 3. So even that approach does not work. I don't know if using reducibility modulo other primes would help.
Is there is any other simpler way to prove the irreducibilty of $f(x) $ using hand computation?
Update: We have $$f(2x)=8(64x^9-48x^6+282x^3-1)=8g(x)$$ and it is somewhat easier to apply Murty's criterion on $g(x) $ with $g(8)=8577496063$ being prime. But I still find this unsuitable for hand calculation.
Comment: The Galois group of the polynomials is $S_3\times S_3$ which does not contain elements of order 9. Thus the polynomial will be reducible modulo every prime.
Comment: @ahulpke: is there general theorem like that which allows one to conclude that a polynomial will be reducible mod every prime?
Comment: I don't get the reason for downvotes. I am seeing a trend that most of my field theory questions are being downvoted. It would be a lot better if any feedback regarding improvement of the question is given.
Comment: (+1) I didn't know about Murty's criterion until now but it appears to be quite concealed in literature.
Comment: @TheSimpliFire: I came to know about it from mathse. It is a generalization of Cohen's criterion.
Comment: ParamanandSingh Initially I suspected that this can be quickly settled with tools from algebraic number theory. That may still be the case, but I could not see it right away. In the ring $\Bbb{Z}[\sqrt{11}]$ the principal ideal $I=(1+\sqrt{11})$ is the product $\mathfrak{p}_2\mathfrak{p}_5$ where $\mathfrak{p}_2=(2,1+\sqrt{11})$ is the sole prime above $2$, and $\mathfrak{p}_5=(4-\sqrt{11})$ is one of the ideals above the rational prime $5$. However, both $\mathfrak{p}_2$ and $\mathfrak{p}_5$ are totally ramified in the extension $\Bbb{Q}(\sqrt{11},\root3\of{10})/\Bbb{Q}(\sqrt{11})$.
Comment: (cont'd) Meaning that in the ring of integers of the bigger field the ideal $(1+\sqrt{11})$ actually is a third power. This does not imply that the cube root would exist, but it does make the question more delicate. I have the impression that you would prefer a solution that does not need the machinery of ANT, but I suspect that it may be necessary. Therefore I added the tag. Of course, it is your call to remove it should you prefer it that way. My goal was to attract the people with the required expertise here. Hopefully they can rewrite an eventual answer in a more elementary language.
Comment: Hmm. Now I suspect that as $\mathfrak{p}_2$ is not principal, $(1+\sqrt{11})$ cannot be the cube of a *principal* ideal either. That would settle the question, but I need to sort out  a number of things in my head :-)
Comment: @JyrkiLahtonen: although I don't know much of ANT, I would prefer the tag to stay.
Comment: @JyrkiLahtonen : It appears you have figured out that the more interesting question here is about $a\notin F$ rather than the irreducibilty thing. Even I don't like my approach which requires a verification of irreducibilty of a ninth degree polynomial. There should be a more natural approach which is similar to proving $\sqrt[3]{3}\notin\mathbb {Q} (\sqrt[3]{2}) $ which is [handled here](https://math.stackexchange.com/q/2431221/72031).
Comment: @ParamanandSingh Yes, the general theory is a theorem by Frobenius whose more general form is Chebotarev's density theorem: https://en.wikipedia.org/wiki/Chebotarev%27s_density_theorem
Comment: It's unlikely that you can prove this by hand, since it's degree 9 - much harder than proving a 9 digit number is prime.
Comment: Using Dedekind's theorem it is possible to prove that the splitting field of the minimal polynomial of $a$ has degree at least $36$, hence exactly $36$, settling the original question. I posted the argument there. But it is also computer aided, and does not advance the cause much at all.
Answer: The $2$-adic Newton polygon for $f(x) = x^9-6x^6+282x^3-8$ immediately tells us that if $f(x)$ is reducible, its factorization must look like
$$f(x) = (x^6 + \ldots \pm 2)(x^3 + \ldots \mp4).$$
In particular, $f(x)$ must have three roots whose product is $\pm4$. Using any root estimation technique (see below), we find that $f(x)$ has six roots satisfying $2 < |x| < 3$ and three roots satisfying $1/4 < |x| < 1/3$. But no combination of three values from those ranges has product with absolute value $4$, so $f(x)$ is irreducible.

To estimate the roots of $f(x)$, we can use an (unfortunately) obscure technique which is essentially a version of Newton polygons for $\mathbb{C}$ instead of $\mathbb{C_p}$:
For this problem, the upper convex hull of the points $(i, \log|a_i|)$ has vertices at $(0, \log 8)$, $(3, \log 282)$, and $(9, 0)$. As with $p$-adic Newton polygons, an estimation for the logarithm of the absolute value of the roots, $\log|x_i|$, is given by the negative slopes of the convex hull. In this case we have six roots with $\log|x_i| \approx -\dfrac{0-\log 282}{9-3} = \log \sqrt[6]{282}$ and three roots with $\log|x_i| \approx -\dfrac{\log 282 - \log 8}{3-0} = \log\sqrt[3]{\dfrac{8}{282}}$, which gives us the estimates above, noting that $2 < \sqrt[6]{282} < 3$ and $\dfrac{1}{4} < \sqrt[3]{\dfrac{8}{282}} < \dfrac{1}{3}$.
To formalize this into a proof, we would use Rouché's Theorem in the two annuli $2 < |x| < 3$ and $1/4 < |x| < 1/3$.
This method is essentially what is used in some implementations of the Aberth root-finding algorithm as a first approximation of the roots; see the paper Numerical computation of polynomial zeros by means of Aberth's method by Bini (1996). One word of caution: this technique is very accurate when the polynomial has roots that are well-separated, but gives inaccurate results when there are several roots that are close together on a log scale.
Comment: This is a very enlightening proof!
Comment: Seconding orangeskid's sentiment :-)
Comment: Nice approach. I will have to read some more details on Newton polygons, but the key idea of using the location of roots is really cool. +1 already given.
Answer: The polynomial $P(x)$ factors $\!\!\!\mod \!\!13$ as $(x^3+6) ( x^6+ x^3 + 3) $  (link).
Assume that $P(x)$  is reducible. We conclude that $P(x)$ is a product of two  polynomials $P_1(x)$, $P_2(x)\in \mathbb{Z}[x]$.  with $P_1(x)\equiv x^3 + 6 \!\!\!\mod \!\!13$, $P_2(x)\equiv x^6 + x^3 + 3 \!\!\!\mod\!\! 13$.
Now, $P(1) =269$, a prime number. We conclude $P_1(1)=\pm 1$, or $P_2(1)=\pm 1$.  But $P_1(1)\equiv  7 \!\!\!\mod \!\!13$, while $P_2(1)\equiv 5 \!\!\!\mod \!\!13$, contradiction.
..........................................................
$\bf{Added:}$ About the factorization $\mod 13$. Our polynomial is $P(x) = Q(x^3)$, with $Q(x)= x^3 - 6 x^2 + 282 x - 8$. Now $Q(x)$ has root $7$ $\mod 13$, so we have
$Q(x) = (x-7)(x^2 + x + 3)$, and so
$P(x) = (x^3 - 7)(x^6+x^3 + 3)$. Now $x^3-7$ has no root $\mod 13$, because $7^{\frac{12}{3}}= 7^4 \not \equiv 1 \mod 13$.  Also, $x^2 + x + 3 = x^2 + 2 \cdot 7 x + 7^2 + 3 - 7^2= (x+7)^2 - 7$, and $7$ is not a quadratic residue $\mod 13$, so $x^2 + x + 3$ is irreducible.
Based on Jyrki's idea: Note that since $13\equiv 1 \mod 3$, there exists $\omega \in \mathbb{F}_{13}$, such that $\omega^3 = 1$, and $\omega\ne 1$ ( a primitive root of $1).  \mod 13$). Now, consider the action of the group of roots of $1$ on monic polynomials $f(x) \mapsto \frac{1}{\omega^{\deg f}} f(\omega x)$. The polynomials in $x^3$ are invariated by the action ( the fixed points are $x^m \cdot $ pol in $x^3$). Therefore, the a polynomial in $x^3$, its irreducible factors will be either polynomials in $x^3$, or group in orbits of size $3$ under this action. Now, if the polynomial $x^6 + x^3 + 3$ were reducible, it would equal $R(x) R(\omega x) R(\omega^2 x)$, where $R$ is a polynomial of degree $2$. But that would imply that the free term $3$ is a cube. However, we have $3^{\frac{12}{3}} = 3^4 =3 \mod 13$. Therefore, $x^6 + x^3 + 3$ is irreducible $\mod 13$.
Comment: That is [Dedekind and Frobenius/Chebotarev](https://math.stackexchange.com/a/160855/11619) in action. The Galois group has no elements of order nine, so the polynomial will factor modulo each and every prime. It does not have irreducible factors of degree three modulo 17 (for example): 3 linear $\times$ 3 quadratics. All in line of the Galois group having elements of order two. All the elements of the Galois group have orders $6,3,2$ or $1$, but I haven't even tried to identify it. The group has order $36$, and its Sylow $3$-subgroup must be elementary abelian, but the rest is unclear to me.
Comment: Oh! User ahulpke had figured out that the Galois group is $S_3\times S_3$. That has elements of all observed orders, and fits the observed facts. I vaguely recall having satisfied myself of that fact at some point, too. But the I got stuck into the "program" of using the third roots of unity. I really should rethink my answer, and rewrite it in a clean way. May be later :-)
Comment: @JyrkiLahtonen: in case you intend to update your answer, please keep original approach also and may be add something more. Your approach can be used in many cases when we have a polynomial in $x^3$.
Comment: Very well spotted! It never ceases to amaze me in how many ways we can skin these cats.
Comment: @Jyrki Lahtonen: Thank you!   Still puzzled why $P$ seems to have a factor of degree $3$  mod every $p$ I tried.
Comment: +1 and this is very smart. It does need a bit of work (or CAS) to factor modulo primes, but overall the argument is easy to understand.
Comment: @Jyrki Lahtonen: Thank you, very useful info, will have to chew on it. About the Galois group being $S_3 \times S_3$, I can think of one transitive action on $9$ objects, more thinking required.
Comment: @Paramanand Singh: Thank you! About your original problem, there is a fairly simple way to show that radicals are linearly independent,  using traces ( in general, the trace of any radical is $0$, so we can play with that).
Comment: @orangeskid: I have seen a few answers related to algebraic number theory which use trace in a simple and elegant manner. It would be nice if you can post an answer (to the original linked question) based on traces.
Comment: I found your answer based on traces: https://math.stackexchange.com/a/2431293/72031 I think that should work fine for the original problem.
Comment: @Paramanand Singh: The basic field should be $\mathbb{Q}(\sqrt{11})$ ( in general, a subfield of $\mathbb{R}$). Then real radicals that are incomparable are also linearly independent over the field. ... there is another answer here https://math.stackexchange.com/questions/158722/linear-independence-of-nth-roots-over-mathbbq/2432555#2432555       turns out it's a result of Siegel... short paper in German
Answer: The following is the most elementary solution that I have.
Let us first consider the problem of factoring $f(x)$ modulo $7$. In the field $\Bbb{F}_7$ we have $11=4$, so $\sqrt{11}=2$. This gives us the counterparts
$\tilde{a}=\root3\of{1+\sqrt{11}}=\root3\of{3}$,
$\tilde{b}=-\root3\of{10}/a=-\root3\of{3}/a=-1$ and hence $\tilde{c}=\tilde{a}+\tilde{b}=\root3\of3-1$. It is easy to check that $3$ is not a cubic residue modulo $7$, so the minimal polynomial of $\tilde{c}$ over $\Bbb{F}_7$ is thus
$$h(x)=(x+1)^3-3=x^3+3x^2+3x-2\in\Bbb{F}_7[x].$$
Paramanand Singh's calculations survive to the extent that we can conclude that $h(x)$ must be a factor of $f(x)$ modulo $7$.
Another ingredient is that $f(x)=x^9-6x^3+282x^3-8$ has the property $f(\omega x)=f(x)$ for any cubic root of unity $\omega$. This follows from the fact that all the terms of $f(x)$ have degrees divisible by three. In $\Bbb{F}_7$ we have the primitive third roots of unity: $\mu_3=\{1,2,4\}$. Therefore $h(2x)=x^3+5x^2+6x-2$ and $h(4x)=x^3+6x^2+5x-2$ must also be factors of $f(x)$ in $\Bbb{F}_7[x]$. Indeed, it is easy to verify that over $\Bbb{F}_7$ the factorization of $f(x)$ into irreducibles is
$$f(x)=h(x)h(2x)h(4x).$$
This implies that any factorization of $f(x)$ over $\Bbb{Q}$ can only have factors of degrees $3$ or $6$, so it suffices to exclude the possibility of a cubic factor. We make the observation that the same applies over the field $\Bbb{Q}(\omega)$, $\omega=(-1+i\sqrt3)/2$. This is because the ring $E=\Bbb{Z}[\omega]$ of Eisensteinian integers is known to be a Euclidean domain (w.r.t. the complex norm) and also because the prime ideal $\mathfrak{p}=\langle 2+i\sqrt3\rangle$ has index seven in $E$. The argument is familiar. By Gauss's lemma a polynomial is irreducible over $\Bbb{Q}(\omega)$ iff it is irreducible over $E$, and then reduction modulo $\mathfrak{p}$ works the same way as reduction modulo $7$ does over $\Bbb{Z}$. This is because $E/\mathfrak{p}\simeq\Bbb{F}_7$.
Assume that $g(x)=x^3+Ax^2+Bx+C\in\Bbb{Z}[x]$ is a cubic factor of $f(x)$. By the above observations then $g(\omega x)$ and $g(\omega^2x)$ are also factors of $f(x)$, but possibly they reside in $E[x]$. Should we have $g(x)=g(\omega x)$ (when also $g(x)=g(\omega^2x)$ by complex conjugation), then $g(x)=x^3+C$. But this is impossible because $f(x)=F(x^3)$ with $F(x)=x^3-6x^2+282x-8$. The rational root test then shows that $F(x)$ is has no rational zeros, so $F(-C)\neq0$.
So we can conclude that $g(x)$, $g(\omega x)$ and $g(\omega^2x)$ are all distinct and irreducible over $E$. We are left with the possibility that
$$f(x)=g(x)g(\omega x)g(\omega^2x).$$
Expanding everything gives
$$g(x)g(\omega x)g(\omega^2x)=x^9+(A^3-3AB+3C)x^6+(B^3-3ABC+3C^2)x^3+C^3.$$
A comparison of the constant terms immediately reveals $C=-2$. Plugging that into the $x^6$-term gives the equation $A^3-3AB=0$. So either $A=0$ or $A^2=3B$.

If $A=0$ a comparison of $x^3$ terms yields $B^3=270$ which is
impossible given that $B$ is an integer.
If $A^2=3B$ and $B^3+3AB=270$, then
$$A^6+27A^3=27(B^3+3AB)=7290.$$ But it is easy to check that this has no integer solutions.

The irreducibility of $f(x)$ over $\Bbb{Q}$ follows from this.
Comment: +1. I was  hoping that somehow in this particular case one could deduce the irreducibilty of $f(x) $ using the irreducibilty of the cubic $f(x^{1/3})$. While this is not always guaranteed, for this case your analysis shows that this works. I will need some time to assimilate all the details though.
Comment: Will this argument work? If $p(x) $ is a factor of $f(x) $ then $p(x), p(wx), p(w^2x)$ will be factors of $f(x) $ over $E[x] $. If $p(x) $ is of degree 1, we get a factor. $p(x) p(wx) p(w^2x)\in\mathbb {Q} [x] $ of degree $3$. If $p(x)$ is of degree $2$ then $f(x) /(p(x) p(wx) p(w^2x)$ is a factor of degree $3$. And we can't have degree of $p(x) $ greater than $3$. It follows that if the polynomial is reducible over $\mathbb {Q} [x] $ it must have a cubic polynomial as a factor. This avoids dealing with factorization modulo primes.
Comment: The case $p(x) =p(\omega x) $ will not arise if the degree of $p(x) $ is not divisible by $3$ because the leading coefficients will differ. So I think the argument should work fine.
Comment: The basic idea is similar to the one I used [here](https://math.stackexchange.com/a/3722289/11619) and [here](https://math.stackexchange.com/a/3921481/11619). On the earlier occasions only even degree terms were present, and I used the second primitive root of unity. This time I had to use the third roots of unity. That has the unfortunate consequence of needing to mention the Eisensteinians along the way. I guess further simplification may be possible. Also the presentation can be polished. I need to work on those.
Comment: It was anything but obvious to look at this modulo seven. I guess I might as well confess that I first found the factorization with Mathematica. But I did spot the $g(x)$, $g(\omega x)$, $g(\omega^2x)$ pattern among the factors because I was looking for it!
Comment: Based on my previous comment, I think we can use this technique whenever we need to deal with polynomials in $x^3$ with rational coefficients.
Comment: Something like that should work @ParamanandSingh. We have a cyclic group of order three acting on the factors. There is always the possibility that $p(x)=p(\omega x)$, that is, a fixed point of the action. That possibility leads to a factorization of $f(x^{1/3})$. I was worried about the possibility of those factors not remaining irreducible over $\Bbb{Q}(\omega)$. Particularly because I wanted to call upon the uniqueness of factorization. That is actually not necessary, but I need to think about this a bit more.


How do I change the default theme?

Question: I've installed a premium theme in a Drupal 8.1.0. Each time I log in, the site crashes with the the following message.

An unknown error has occurred.

I then tried to change the default theme using drush vset bartik to change the theme for non administrative pages back to the Bartik theme.
I got this error.

Command variable-set requires Drupal core version 6 or 7 to run.
The drush command 'vset bartik' could not be executed.

How should I change the default theme with Drush?
Answer: The correct command should be drush config-set system.theme default bartik.
You might need to clear or rebuild your CSS/JS and theme caches with drush cr. If the problem still persists, verify the theme hasn't been set in the settings.php file. A theme set in the settings.php file cannot be changed from the user interface.
Reference

Unusable Theme: How to Reset Your Theme

How do I change the default theme?


Open string call out does not match requested music note

Question: I am learning guitar and recently came across a sheet requesting what I understand to be an open B string (red arrow), however the music sheet shows a C (blue arrow) note being played. What is the correct way to interpret the vertically stacked numbers in the attached image? Do they not refer to left hand fingers?
Answer: Note that the music shows a C and also a B.
The first finger (1) of the left hand frets the second fret of the fourth string on the second eighth note of the first beat to make the E. Then the fourth finger of the left hand (4) frets the third string at the fifth fret to make the C in the chord. The first and second strings are left open (0 and 0) to make the B and high E in the chord.
On the third beat, the first finger slides up one fret (--1) on the fourth string to make the F. The fourth finger stays the same and the first and second strings stay open.
You may see a lot of notes in classical guitar made by fretting a lower sounding string with a fret higher than four or five instead of using a higher sounding string. This is idiomatic for the guitar as it is one way to play wider or narrower intervals without having to stretch the left hand as much.
Comment: @MusicHappy nice question.  As a non-guitarist, I found this notation a bit odd at first, but after a second I realized that of course the fingerings are given in string order, which means that the notes, which are necessarily in pitch order, aren't in the same order as the fingering.  Any system that allowed them to be in the same order would be even more confusing.
Comment: @phoog  yep,  that's how us bowed-string players notate as well,  the vertical order matches the notes, not the strings.


Text rendered with incorrect color on IE and Edge

Question: I have this test page that I am trying on several browsers. All them except those from Microsoft, render the page correctly regarding to the text color.
This is how this should be...

this is how IE and Edge render it

I did everything, cleaned the cache, but nothing makes this be rendered correctly on IE/Edge.
Any ideas?
Comment: Page renders "incorrectly" for me in Chrome as well. Not surprising as the body text color is set to `#333`.
Comment: in which line of the css are you seeing that?
Comment: Line 930 of http://triplov.com/revistaTriplov/wp-content/cache/wpfc-minified/6cd6b53d964b7bb3d8ad096fce0365b0/1506099144index.css
Comment: what? I am seeing this line on the server and it says `color:#aaa;" (??) I just opened the css file for edition now using terminal...
Comment: Whatever file you're viewing or editing, is not the one you're serving it seems.
Comment: damn, a wordpress cache plugin was serving a cached version. THANKS for pointing me on the right direction. Please convert your comments to that so I can accept it. thanks
Answer: The page renders "incorrectly" for me in Chrome as well because the text-color for the body element is set to #333 on line 930 of
http://triplov.com/revistaTriplov/wp-content/cache/wpfc-minified/6cd6b53d964b7bb3d8ad096fce0365b0/1506099144index.css
Probably you're not serving the file you think you're serving.
Comment: thanks. Wordpress cache plugin was serving the wrong file and I forgot about that.


How to texture the irregular Planes of a Sphere?

Question: I want to give each face of a THREE.js sphere it's own texture. So I let a SphereGeometry calculate the vertices and convert each face to a PlaneGeometry using the vertices of the faces.
THREE.SpherePlaneGeometry = function ( v1, v2, v3, v4 ) {

  THREE.Geometry.call( this );

  var normal = new THREE.Vector3( 0, 1, 0 );

  this.vertices.push( v1.clone() );
  this.vertices.push( v2.clone() );
  this.vertices.push( v3.clone() );
  this.vertices.push( v4.clone() );

  var face = new THREE.Face4( 0, 1, 2, 3 );

  face.normal.copy( normal );
  face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );

  this.faces.push( face );

  var uvs = [
    new THREE.UV( 1.0, 0.0 ),
    new THREE.UV( 0.0, 0.0 ),
    new THREE.UV( 0.0, 1.0 ),
    new THREE.UV( 1.0, 1.0 ),
  ];
  this.faceVertexUvs[ 0 ].push( uvs );

};

to be sure all of this runs later with the returned geometry:
geometry.computeCentroids();
geometry.computeFaceNormals();
geometry.verticesNeedUpdate = true;
geometry.uvsNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.tangentsNeedUpdate = true;
geometry.elementsNeedUpdate = true;
geometry.dynamic = true;

By applying this texture:

I got this result:

What can be done to remove the distortion between the red and green points? For the poles one vertice is used twice, but it could be better, any idea?
Comment: It looks like this is a similar question: http://stackoverflow.com/questions/6046929/problem-gltexgen-in-open-gl-es-2-0 and the more general is: How to texture a projected Quad? However, is there a solution using THREE.js?
Comment: as noiv said ,it seems that the top quads are triangulated wrong and, I would suggest making a middle point for each quad and make 4 triangles and try then using the texture... maybe even use u,v of the phi and delta to cover the entire sphere and use somekind of repeat factor...
Comment: @EliSherer, overtesselation would solve it, but poly count should remain same. Another approach called projective interpolation is ruled out as it moves the problem to the edge of the quads: http://www.reedbeta.com/blog/2012/05/26/quadrilateral-interpolation-part-1/
Answer: This is a tricky problem. Our texture mapping is still affine.

At some point we'll need to experiment with perspective correct texture mapping. I have read somewhere something about interpolating a w... but I'm not really sure that this would solve your problem.
To simplify the problem... look at the affine mapped quad in texture mapping image. Imagine that you move the top left vertex into the top right. By doing that you're basically turning the left triangle into a simple line that goes from bottom left to top right. This basically mean that you it won't be visible. Because the vertices of the right triangle have not been moved, the triangle is still there, visible, with the UVs asigned to each vertex.
So the only solutions I can think would be:

Add one level of tessellation to those polygons.
Having a special pre-corrected texture (either using canvas or photoshop) for these possible cases.
Comment: I'm not sure whether it's same problem. Maybe it results in same solution or I need a solution to both. But I do not have a rectangle distorted while projected, it's a trapezoid. I found this description useful: http://www.xyzw.us/~cass/qcoord/. However, I have no clue where to start to implement this receipt: "This is good, because instead of specifying the texture coordinates for the upper vertices as (s,t) coordinates of (0, 1) and (1, 1), we can specify them as (s,t,r,q) coordinates of (0, width, 0, width) and (width, width, 0, width)!" It really sounds so simple.
Answer: There are several issues here.
First, you do not need to convert each face of your geometry to plane geometry -- unless for some reason you want to. You can see how this can be handled in the Fiddles below.
Second, your problem is your UV settings.
Here is a Fiddle ( http://jsfiddle.net/PBjEE/ ) showing a problem similar to yours. I have used a simpler geometry, but like yours, the quad faces are trapezoids. In the Fiddle, I followed your approach of setting the UVs for each face to be the corners of the texture, (0,1), (0,0), (1,0), and (1,1). The result is a distorted circle.
Here is another Fiddle ( http://jsfiddle.net/PBjEE/1/ ) where the distortion is removed by changing the UV coordinates.
The UV coordinates must define a trapezoid having the same proportions as the face.
Comment: Ah. Now I see what he was referring to with trapezoid. My eyes totally ignored that distortion and focused on the top triangles :P
Comment: The circles are fine, but the texture is cropped: http://jsfiddle.net/noiv/3Spe3/ . Can't do this with e.g. Google Map tiles. https://mts1.google.com/vt/lyrs=m@183042665&x=129&y=95&z=8
Comment: To be fair, your question was "What can be done to remove the distortion?" This is a solution to that problem. It seems you are adding new requirements now. Perhaps you can make a new post?
Comment: Keeping texture intact was not exactly a hidden requirement. But I'll prep a better fiddle and repost. Btw: your fiddle revealed already next question: How to set up lights?


How to implement navigation "selected" item

Question: I need to implement a navigation menu on a web page, possibly with several levels of tabs. I've used the CSS way whenever the CSS is under my control, but now I'm facing problems when using an exising CSS library (Twitter's Bootstrap in this case).
First, this is the CSS way I've used. Example HTML:

    <title>Example page</title>

Frontpage

Articles

Blah blah.

... and the CSS:
body.frontpage div.navigation li.frontpage,
body.articles div.navigation li.articles {
    background-color:red;
    color:white;
}

Simple enough. Only the body's class needed to be changed when appriopriate.
Now, Bootstrap seems to use the class based style to select navigation items (topbar, tabs, pills). Example:
...

Frontpage

Articles

...

I initially thought of doing something like
navigation = ('frontpage',)
# or
navigation = ('articles', 'categories', 'foo',)

in the controller and then passing this tuple to the templates, but somehow it has this vibe of "doing it wrong".
So the question is: Since I actually have to print the class selection in the templates, how do I keep track of the current location (as in, where in the navigation tree is this page), given that the page may have multiple levels of tabs or other navigation items? Is there a preferred way to do this?
I'm using Pyramid in route style with Mako templates, but generic answers appreciated too.
Answer: I do something similar (Pyramid & Bootstrap as well), but only for one level of navigation.
First thing I did was create a "view" object that passes parameters to every render such as title, header, get_data, etc. Ex.
class View_Controller(object):
    def __init__(self, request, **kwargs):
        self.request = request
        self.nav = kwargs.get('nav', None)

    @property
    def page(self):
        return request.GET.get('page', 1)

@view_config(route_name='home', renderer='templates/homepage.mako')
def Homepage_View(request):
    view = View_Controller(request, nav='homepage')
    stuff = DBSession.query(Stuff).all()
    return {'view': view, 'stuff': stuff}

I set the attribute nav in every page rendering, but have nav = None when no navigation element is activated. I then created a template for navigation elements in Mako:
<%def name="navelements(things)">
% for a in things:

a[0]

% endfor
</%def>

Where "things" is a tuple of all the elements in the navigation. [0] is the display name, and [1] is the internal name. The "| n " is needed to escape the html characters. Ex:
<%! things = [['Frontpage', 'homepage'], ['Articles', 'arts'], ['Categories', 'cats'], ['Foo', 'foo']] %>

% if things:

    ${navelements(things)}

% else:

% endif

Now, you can set things either in the template or in the controller via view. I have the "if things" clause in case you want a generic tab template that is called on every page; you can disable tabs just by setting things = None in the controller.
This is only one level of tabs, but you can do the same by making things a more complicated list. I would make things a more complicated so that compared to how it looks currently, it'll look like:
things = [['displayname1', 'elementname1', things1], ['displayname2', 'elementname2', things2], ...]

I would then make navelements recursive (which Mako doesn't support, so I would just make two copies of the navelements function and have them call each other) and implement support for multiple levels of nav:
<%def name="navelements1(things, level=0)">
% for a in things:

a[0]

   % if a[2]:

       ${navelements2(a[2], level+=1)}

   % endif
% endfor
</%def>

Where nav looks something like:
nav = ['frontpage', 'best', None, ...]

Hope that answers your question. Just make sure your lists are of correct length so you don't get out of bound errors.
Comment: just noticed that you wanted each list item to have its own class. That's just passing another element to each item in things. `<li class="${a[x]}${' active' if nav[y] == a[z] else ''}...</li>`
Comment: This is pretty close to what I eventually did. It's kinda clunky but it works, so I'll accept this answer.
Comment: cool. i actually changed my setup to something even nicer... every nav item is a class object with a title, href, and active attribute and i just loop through them to display the nav. i found it much nicer.
Answer: You can use system values used during rendering to obtain view name in template by accessing variable view.__name__.
Then change active link by (example is in jinja2 but it should be similar)

  Link

More information at
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/templates.html#system-values-used-during-rendering


Global 'Last updated' timestamp

Question: Is there a way to create and display a global 'Last updated' timestamp that would be displayed on every page? 'Last updated' would include adding and changing any piece of content on the website. I know how to display a similar timestamp for each node but I'd like to be able to display just one per page. Maybe looping through all created nodes and finding the latest date? How would I achieve that? Or is there a better solution - looping through all nodes might be memory-intensive, right?
Thanks
Answer: If by "Last Updated" you are only talking about nodes, then yes, you can.
Create a new view for content (using views module), add a block display, do not filter by any content type, but I think that you can keep the "Published" status. Sort by updated time, descendant, set the pager to show only 1 node. And set the display to only show the updated time. That's all.
Comment: I ended up doing a similar thing but with the page preprocessor function

Global 'Last updated' timestamp


Countifs with specified row and column value

Question: Using the data below,
                       HR   SC  HR
Banks                  1    2   2
Insurance              1    5   2
Banks                  2    3   9
Diversified Finance   10    6   7
Banks                  2    4   3
Insurance              8    2   2

I am trying to find the number of times a certain digit shows up for the banks in HR. Have tried to use, countifs and if(and(row="Banks",column="HR"),countif(A1:D8,"1")) but these didn't work.
My goal is to have:
         HR
Banks 1  1
Banks 2  3
Banks 3  1

Any help would be greatly appreciated.
Answer: A SUMPRODUCT formula will work:
=SUMPRODUCT(($A$2:$A$7="Banks")*($B$1:$D$1="HR")*($B$2:$D$7=1))

...or equivalent dynamic formula (as used below)
=SUMPRODUCT(($A$2:$A$7=$A12)*($B$1:$D$1=C$11)*($B$2:$D$7=$B12))

Comment: Thanks so much! I had also tried sumproduct but never realized to remove the cell with no value!


Generate nonnegative variates with mean 1 and specified variance-covariance

Question: Problem
In several applications in surveys, it would be helpful to be able to generate a set of $R$ $n$-dimensional variates with the following properties:

Has mean vector $1$
Has a specified variance-covariance matrix ($\Sigma$, a positive semi-definite matrix, with rank $\leq R$)
Is nonnegative

Some First Thoughts about Solutions
The first two requirements are easy to satisfy. We can just draw from a multivariate Normal distribution, as discussed here: Generating data with a given sample covariance matrix
But if we add the additional requirement that all of the variates are nonnegative, then a multivariate Normal distribution won't work. In the applications I have in mind (described below), typically the diagonal of $\Sigma$ has a few entries which are $1$ or even as large as $1.5$, so a multivariate Normal will easily generate negative values.
In this application, it doesn't matter at all what the skew or kurtosis are, and it doesn't matter whether the random variates come from a particular distribution. All that matters is that they're nonnegative, have mean vector $1$, and have the specified covariance matrix (ideally, it would have the exact specified sample covariance matrix, but it would be OK if it just had the specified covariance matrix in expectation).
The multivariate lognormal and Gamma distributions are nonnegative and seem like fairly natural options, except that there are constraints on their precise shape (due to their density functions) which mean that they will often not be able to attain the desired variance-covariance. So these parametric distributions, at least, seem unnecessarily limiting.
In low dimensions, one can generate random variates and then "fix them up" to satisfy constraints, at least approximately. This StackExchange gets at this kind of approach, but it doesn't really cover the constraint of nonnegativity and is really focused on a univariate case.
How to simulate data that satisfy specific constraints such as having specific mean and standard deviation?
Motivating Application
In survey statistics, resampling methods such as the jackknife or bootstrap are typically implemented by generating replicate weights, which are random variates with a specific mean vector and covariance matrix. To be concrete, if one has a dataset of size $n$, then one generates $R$ sets of replicate weights, which can be represented as a matrix of dimension $R \times n$. In general, we want these replicate weights to be nonnegative, since the weights will frequently be used in statistical procedures that require nonnegative weights and usually even for many procedures that allow negative weights, the software implementations won't allow negative weights because they're just unexpected.
This R package vignette describes the generation of replicate weights for the "generalized survey bootstrap", and describes how multivariate normal distributions are used to generate replicate weights that have mean vector $1$ and a specified variance-covariance matrix, but which can sometimes be negative.
https://cran.r-project.org/web/packages/svrep/vignettes/bootstrap-replicates.html#forming-adjustment-factors
It also describes a rescaling adjustments that makes the random variates nonnegative and with mean vector $1$, but unfortunately that rescaling adjustment increases the variance-covariance by a constant (which is a problem).
Comment: Copulae could be a real pain (after having to use them for multivariate Gamma), however here's one good beginners' tutorial: https://twiecki.io/blog/2018/05/03/copulas/
Comment: Another option you should check out is the folded normal distribution, more specifically the multivariate folded normal: https://www.jstor.org/stable/42003783
Comment: What were typical/interesting sizes for $R$ and $n$? I ask because attempts at direct computational solutions may not work well for those being large.
Comment: Thanks- I added that tag to the question.
Comment: What I meant is that you should investigate *copulas* as a direct manner of imposing a given covariance matrix on rv's with given margins.
Comment: Yes, that seems promising, although I'm not sure it will 100% work
Comment: A copula with gamma marginals seems promising for example, but is limited by the fact that Gamma variables with different scales are restricted in the possible covariances they can have.
Comment: That's a good point. A typical value of $n$ would be something like $1,000$ and $R$ could be anywhere between $50$ and $1,000$. The value of $n$ is determined by the sample size of the survey, and the value of $R$ is chosen to balance data storage / computation costs (lower values of $R$ better) against the desire for more precise variance estimation (higher values of $R$ better).
Comment: I doubt that copulas will work well. Covariance is not a property of the copula alone, but of both copula and margins. It seems this is also the root cause for the problem having no solution in general. Certain margins are just incompatible with certain covariance matrices.
Comment: Maybe it would be helpful if you could give some examples of Σ you are interested in. Wouldn't those matrices not fulfill additional properties from the specific use case? For example [exchangeability](https://en.wikipedia.org/wiki/Exchangeable_random_variables#Covariance_and_correlation)?
Answer: First notice that the requirements of non-negativity and mean equals 1 cannot be simultaneously satisfied for an arbitrary covariance matrix: if $x_i$ is the $i$-th variate ($i=1...n$) with $E[x_i]=1$, then
$$Cov(x_i,x_j)=E[(x_i-1)(x_j-1)]=E[x_ix_j]-1 \ge -1$$
since all the $x_i$'s are nonnegative and therefore $E[x_ix_j] \ge 0$. This implies that all the entries of the covariance matrix $\Sigma_{ij}$ has to be larger than -1, which is a non-trivial constraint. (Note that the same argument applies to the sample covariance. Also note that it does not imply that if $\Sigma_{ij} \ge -1$ then necessarily a solution exists; there might be other constraints).
If you are not interested in the generating distribution but just want to find some matrix $X$ which has the specified properties (assuming it exists), a straightforward approach might be to try to minimize a sum of squared errors using a gradient descent algorithm. To ensure nonnegativity the elements of $X$ can be parametrized e.g. with $X_{in} = e^{W_{in}}$, and you can take advantage of auto-differentiation libraries to calculate the gradients for you.
Here is for example an implementation in PyTorch, which finds a (approximate) solution for $R=20, n=3$ in about 2 seconds:
import torch

R, n = 20, 3

#generate n-by-n random covariance matrix with entries larger than -1
S=torch.Tensor([-2])
while S.min() < -1:
    A = torch.randn(n,n)/2
    S = A.matmul(A.T)

def loss(W,S):
    [R,n]=W.shape
    X = torch.exp(W)
    sse = (torch.cov(X.T,correction = 0) - S).square().sum() + (X.mean(0)-torch.ones(n)).square().sum()
    return sse

#initialize W with random entries
W = torch.randn(R,n,requires_grad=True)
optimizer = torch.optim.Adam([W],lr=0.05)

for iter in range(1000):
    optimizer.zero_grad()
    L = loss(W,S)
    L.backward()
    optimizer.step()

print(f'sse = {L}')
X=torch.exp(W)
print('specified covariance:')
print(S)
print('sample covariance:')
print(torch.cov(X.T,correction = 0))
print('mean:')
print(X.mean(0))

output:
sse = 0.007093742955476046
specified covariance:
tensor([[ 1.9820, -0.2131, -0.5573],
        [-0.2131,  0.8370, -0.0203],
        [-0.5573, -0.0203,  0.1815]])
sample covariance:
tensor([[ 1.9881, -0.2122, -0.5349],
        [-0.2122,  0.8371, -0.0169],
        [-0.5349, -0.0169,  0.2584]], grad_fn=<SqueezeBackward0>)
mean:
tensor([1.0026, 1.0003, 1.0093], grad_fn=<MeanBackward1>)

Comment: I see that, but you want the resulting covariance matrix to be equal to $\Sigma$ which is pre-specified (and needs to have rank $R$). Where does this $\Sigma$ come from ?
Comment: This sounds like you are not interested in a solution for generic $\Sigma$ but in very specific highly structured examples. Since in general a solution may not exist as @J.Delaney has demonstrated, it might be much smarter to start with one of the special cases and take it from there?
Comment: @bschneidr $\Sigma$ in your example has rank $n-1$. Since you want $R \ll n$, you clearly can't get this sample covariance (or even a reasonable low rank approximation, since all non-zeros eigenvalues of $\Sigma$ are close to 1)
Comment: This solution seems to work as well as anything else I've seen. The parameterization of this problem and the suggestion to use one of the gradient descent algorithms available in PyTorch seems quite promising. Would you be OK if edit the answer to add an R equivalent of the code you provided? Thanks again.
Comment: Of course, feel free to add your own implementation
Comment: Thanks, I appreciate your comment about the constraints the nonnegativity and mean requirements imply for the covariance matrix. For the gradient descent algorithm, I wonder how feasible this would be in real applications, where you might have $n=10,000$ and $50 \leq R \leq 1,000$. That's a lot of parameters to try to directly optimize.
Comment: That number of parameters ($R \times n$) is still quite small compared to typical deep learning models which use the same optimization algorithm. I am curious however, from where do you get a $10,000$-by-$10,000$ matrix with rank $50$ ?
Comment: Let me clarify. The application here is creating $R$ length-$n$ vectors of replicate weights, when you have a dataset with $n$ observations and you create $R$ resamples of your data. This is commonly done to represent replication variance estimators such as the bootstrap, where we can choose a suitably large number of replications $R$. So we're generating a $(R \times n)$ matrix, and the covariance matrix of these $R$ vectors has dimension $n \times n$.
Comment: Ah, ok. The $\Sigma$ is chosen to represent a variance estimator appropriate for a given sampling method (SRS, stratified sampling, cluster sampling, etc.) The [section of this page titled "Generalized Survey Bootstrap"](https://bschneidr.github.io/svrep/articles/bootstrap-replicates.html#generalized-survey-bootstrap) goes into more detail. As a specific example, in the case of simple random sampling without replacement, $\Sigma$ is a matrix with diagonal elements equal to $1$ and all non-diagonal elements equal to $-(n-1)^{-1}$. For this special case, jackknife weights work perfectly.


How can I change Wordpress design for each languages?

Question: Recently I work on a multilangual website.
When the design was ready I made a translation with WPML.
Then I made some changes on the original version but the translated version doesn't change with it.
What could be the problem?
Any help would be highly appriciated.
Answer: i`m not sure, but this topic
might help you.

You can uncheck the option "Synchronize page templates" from wpml -> translation management -> multilingual content setup tab.


Amazon Web Service monitoring

Question: I have deployed a web app on an AWS server. I have following questions:
Monitoring

my websphere app server status capacity monitoring?
uptime thru Amazon CloudWatch metrics?

Load balancing

Autoscaling is for only AWS instances scaling and load balancing or it can handle the individual app server load balancing as well?
Is app servers load balancing handled separately by us?
Answer: I'll answer the Websphere portion for ya.
a.  Without other 3rd party tools (ITCAM, Wiley, etc... $$$$) The way to monitor WAS specific metrics, such as datasource usage is to view it using the Tivoli Performance viewer, available using the admin console..  On the file level, you can also turn on verbose GC on the app server level and monitor the heap usage of your Websphere java process.
b.  Load balancing on Websphere is usually handled by using the HTTP Plug-in, which can load balance requests to your applications across multiple app servers in your Websphere cluster/app server.  That is, of course, it assumes that you're using IHS (Apache with IBM branded on top of it).  What is the current setup of the web server layer?

Amazon Web Service monitoring


Como salvar o título de um post com base em um campo selecionado?

Question: O meu problema é o seguinte, criei um custom post type chamado "Destaques da Home" e dentro dele o usuário vai adicionando o post que deseja, esses posts vem de um select_advanced do Metabox, fiz uma função para passar o post selecionado para o título do post atual, porém ele acaba retornando um número não sei porque.
Segue a minha função e alguns prints para ajudar no entendimento:
add_filter( 'the_title', 'teste', 10, 2 );
function teste( $title, $post_id )
{
    if( $new_title = get_post_meta( get_the_ID(), 'id_do_metabox', true ) )
    {
        return $new_title;
    }
    return $title;
}

Answer: Basicamente o select funciona mostrando um par de chave e valor. O que você está vendo e selecionando no select é apenas um label, o que está sendo salvo no banco é o ID do post e não o título, assim você precisa buscar o título do ID do post. Ficando o código assim:
add_filter( 'the_title', 'teste', 10, 2 );
function teste( $title, $post_id )
{
    if( $new_title_id = get_post_meta( get_the_ID(), 'id_do_metabox', true ) )
    {
        return get_the_title($new_title_id);
    }
    return $title;
}


Permitir uma lista como argumento

Question: Tenho uma API REST em Python que recebe 2 argumentos, uma lista de Url e uma palavra. Sou iniciante em Python e gostaria de saber se é possível fazer um split na string da URl para aceitar mais de uma URL qdo for fazer a requisição pelo body da URL. Por exemplo, atualmente consigo fazer a requisição em http://127.0.0.1/?urls=globo.com&word=google
Só que gostaria de incluir mais de um url no body como http://127.0.0.1/?urls=globo.com&urls=terra.com.br&urls=uol.com.br&word=google
Segue o código:
from flask import Flask
from flask_restful import Resource, Api, reqparse, abort
import requests

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('urls', action='append')
parser.add_argument('word')
parser.add_argument('ignorecase')

# Função que faz um GET para a URL e retorna quantas vezes a palavra word aparece no conteudo

def count_words_in(url, word, ignore_case):
    try:
        r = requests.get(url)
        data = str(r.text)
        if (str(ignore_case).lower() == 'true'):
            return data.lower().count(word.lower())
        else:
            return data.count(word)
    except Exception as e:
        raise e

# Função que inclui 'http://' na url e retorna a URL valida

def validate_url(url):
    if not(url.startswith('http')):
        url = 'http://' + url
    return url

class UrlCrawlerAPI(Resource):
    def get(self):
        try:
            args = parser.parse_args()
            valid_urls = [validate_url(url)  for url in args['urls']]
            lista = []
            for valid_url in valid_urls:
                lista.append({valid_url: {args['word']: count_words_in(valid_url, args['word'], args['ignorecase'])}})
                # return {valid_url: {args['word']: count_words_in(valid_url, args['word'], args['ignorecase'])}}
            return lista
        except AttributeError:
            return {'message': 'Please provide URL and WORD arguments'}
        except Exception as e:
            return {'message': 'Unhandled Exception: ' + str(e)}

api.add_resource(UrlCrawlerAPI, "/")

if __name__ == '__main__':
    app.run(debug=True)

Comment: `for valid_url in valid_urls: return ...`. Aqui você está lendo apenas a primeira URL e saindo da função
Comment: sim, mas se valid_urls é um array o for não deveria percorrer todo o array ? está quase certo, pelo postman a função está correta retornando um json com a ocorrência de palavras encontraadas, entretanto só está retornando a primeira url.
Comment: No momento que você dá um `return` dentro de um for, ele sai da execução do for. Você teria que criar uma lista com o resultado que você quer e, fora do for, retorna esta lista
Comment: amigo muitíssimo obrigado, funcionou!! vc me ajudou demais, segue o código editado funcionando 100% e mostrando todas Urls.
Comment: Que bom que funcionou! Você pode marcar a resposta como correta se te ajudou. :D
Answer: Se o que for retornado pelo parser.parse_args() for um dicionário, é impossível.
De outra maneira, você pode passar as urls todas juntas...
Por exemplo:
urls=globo.com,terra.com,uol.com
E separá-las usando str.split()
urls = args.split(',')

ou algo parecido
Comment: obrigado amigo, mas no caso a atribuição seria depois de args ? pois está dando erro na sintaxe. Segue o código completo editado.
Comment: Você deveria usar urls = args['urls'].split(',') em vez de urls = args.split(',').
Comment: obrigado amigo mas continua dando erro de sintaxe. esta atribuição de urls eu devo inserir em qual função ? editei o código novamente.
Answer: Segundo a documentação do Flask Restful basta configurar o parâmetro da URL corretamente para que o framework faça o append dos parâmetros repetidos, ao invés de sobrescrever os existentes:
parser.add_argument('urls', action='append')

E depois para pegar o valor:
args = parser.parse_args()
args['urls']    # seria uma lista com todas as urls passados por parâmetro.
# aplicando `validate_url` para todas as URLs recebidas
valid_urls = [validate_url(url) for url in args['url']]
# ou
valid_urls = map(validate_url, args['url'])

Comment: obrigado jovem, mas qdo eu insiro action='append' nos argumentos ele entra na última exceção inesperada. No caso eu não deveria fazer um split na string das urls ? Editei meu código atual.
Comment: mas `args['urls']` é uma lista e tu está chamado `validate_urls` direto nela como se fosse uma string, está certo lançar uma exceção mesmo. Acho que tu quer aplicar a função em todas urls recebidas, talvez usando `map(validate_urls, args['urls'])` ou uma list comprehension resolva.

Permitir uma lista como argumento


Obter dados de google analitycs em tempo real

Question: Estou tentando integrar a API do google para obter os user's ativos no site.
Alguém consegue dar 1 ajudinha? não estou a conseguir obter resultados, nem erros.
NOVO CODIGO COM SDK GOOGLE
<code>error_reporting(E_ALL);
ini_set('display_errors', '1');

require 'vendor_2/autoload.php';

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = '333966316';

// [START analyticsdata_initialize]
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.

putenv('GOOGLE_APPLICATION_CREDENTIALS=Teste Final-27c88128db22.json');

$client = new BetaAnalyticsDataClient();
// [END analyticsdata_initialize]

// [START analyticsdata_run_report]
// Make an API call.
$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2020-03-31',
            'end_date' => 'today',
        ]),
    ],
    'dimensions' => [new Dimension(
        [
            'name' => 'city',
        ]
    ),
    ],
    'metrics' => [new Metric(
        [
            'name' => 'activeUsers',
        ]
    )
    ]
]);
// [END analyticsdata_run_report]

// [START analyticsdata_run_report_response]
// Print results of an API call.
print 'Report result: ' . PHP_EOL;

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
    // [END analyticsdata_run_report_response]

    var_dump($row->getDimensionValues()[0]->getValue());
}
</code>
Comment: editei o código da pergunta, com o SDK do google para PHP, mas mesmo assim não estou obter resultados nem erros.
Answer: Você precisa criar as credenciais no Google Cloud Console, em APIs e serviços > Credenciais > Contas de serviço.
Recomendo você utilizar o SDK para PHP pelo composer google/analytics-data, pois irá facilitar tanto na confirguração da autenticação quanto nas chamadas aos serviços.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: editei o código da pergunta, com o SDK do google para PHP, mas mesmo assim não estou obter resultados nem erros.
Comment: Estou utilizando exatamente desta forma, a única diferença é na passagem das credenciais para o client. Tente instanciar o client com `$client = new BetaAnalyticsDataClient(['credentials' => 'Teste Final-27c88128db22.json']);`

Porém como não há erro, acredito que a autenticação esteja correta. A propriedade informada possui dados no período solicitado?


Normalization Function for non-linear data

Question: I have gone through the linear normalization however its not solving my transformation. I need to convert the min and max in order of [0-1]
requirement:
Min Value = 0.0
Max Value = 15.0
However, for 0.1 it should give me a high value than liner transformation, something like 0.05.
The graph will be something like y=log(x) or y=root(x) for which
at x =15, y =1.
Comment: The problem isn't really clear to me. What do you mean by linear normalisation? If you want a non-linear transformation to [0, 1] then perhaps a logistic transform would be suitable? It may help to expand on the properties you want the transformation to have.
Answer: You may get what you want with the empirical CDF.
Let $X\sim F_X(x)$ be a (continuous) random variable. It is then the case that $F_X(X)\sim U(0,1)$. This is called the probability integral transform
In the discrete case, such as with data (an empirical distribution is discrete), the resulting distribution isn't quite uniform (and you can make it seriously nonuniform with many observations tied at the same value), but we still end up with the compression to $[0,1]$.
When we apply the empirical distribution to do the probability integral transform, we say that we are using the empirical CDF.
In R, if your data are saved in x, the transformed data are formed by ecdf(x)(x).
I see two advantages to using the empirical CDF as the transformation:
1) It will always give transformed values in $[0,1]$.
2) It feels natural to me to use the data as a guide.


Informação incorreta ao carregar entidade bigdecimal

Question: Eu tenho uma tabela, que uma de suas colunas é um numeric(25,10) que será mostrado as taxas. Mas existe registros que serão zerados ( 0.0000000000 )
Na minha entidade tem a propriedade dessa taxa, como um BigDecimal. Mas quando o hibernate popula essa propriedade ele atribui o valor "0E-10" inves de 0.0000000000. Eu já tentei colocar precision ou Scale, mas não encontrei a solução.
<code>@DecimalMin("0.0")
@Digits(integer = 25, fraction = 10)
@Field(at = 8, required = true)
@Column(name = TableConstants.Columns.TAXA_OPERACAO)
private BigDecimal taxaOperacao;
</code>
Comment: Eu tentei isso também @BrunoCésar, mas continua retornando o "EO-10"
Comment: Se eu tento pegar essa propriedade BigDecimal, e chamar o seu método toPlainString(), ele retorna o valor corretamente.
Comment: Isso não está incorreto @DaniloFernandes. Está ocorrendo que  o BigDecimal está sendo representado na notação científica. Note que 0E-10 = 0x(10^(-10)) = 0/(10^10) = 0. Na sua pergunta está escrito incorreto, está EO-10, enquanto no seu debug está 0E-10.
Answer: Não existe nada incorreto. Ocorre que o 0.0000000000 está sendo representado pela notação científica quando visualizado pelo debug.

Enfim, isso não vai causar nenhum erro, já que é apenas uma representação. Suas contas serão feitas com 0.
UPDATE - Complementado a resposta:
Fiquei curioso com o fato de que pra alguns casos o toString() do BigDecimal imprime na notação científica, pra outros casos não. Verifiquei no código fonte e, como pode ser observado no trecho de código abaixo, a decisão é feita baseado no número armazenado.
O método abaixo, layoutChars, é chamado pelo toString() passando true para o parametro sci. O parametro sci significa imprimir na notação científica. Se ele for falso, então o número é impresso na notação de engenharia.
Note que depende de algumas condições para que o número seja impresso na notação científica, sendo a variável scale, adjusted e o parametro sci responsáveis por isso.
3051  private String layoutChars(boolean sci) {3052      if (scale == 0)                      // zero scale is trivial3053          return (intCompact != INFLATED) ?3054              Long.toString(intCompact):3055              intVal.toString();3057      // Get the significand as an absolute value3058      char coeff[];3059      if (intCompact != INFLATED)3060          coeff = Long.toString(Math.abs(intCompact)).toCharArray();3061      else3062          coeff = intVal.abs().toString().toCharArray();3064      // Construct a buffer, with sufficient capacity for all cases.3065      // If E-notation is needed, length will be: +1 if negative, +13066      // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.3067      // Otherwise it could have +1 if negative, plus leading "0.00000"3068      StringBuilder buf=new StringBuilder(coeff.length+14);3069      if (signum() < 0)             // prefix '-' if negative3070          buf.append('-');3071      long adjusted = -(long)scale + (coeff.length-1);3072      if ((scale >= 0) && (adjusted >= -6)) { // plain number3073          int pad = scale - coeff.length;  // count of padding zeros3074          if (pad >= 0) {                  // 0.xxx form3075              buf.append('0');3076              buf.append('.');3077              for (; pad>0; pad--) {3078                  buf.append('0');3079              }3080              buf.append(coeff);3081          } else {                         // xx.xx form3082              buf.append(coeff, 0, -pad);3083              buf.append('.');3084              buf.append(coeff, -pad, scale);3085          }3086      } else { // E-notation is needed3087          if (sci) {                       // Scientific notation3088              buf.append(coeff[0]);        // first character3089              if (coeff.length > 1) {      // more to come3090                  buf.append('.');3091                  buf.append(coeff, 1, coeff.length-1);3092              }3093          } else {                         // Engineering notation3094              int sig = (int)(adjusted % 3);3095              if (sig < 0)3096                  sig += 3;                // [adjusted was negative]3097              adjusted -= sig;             // now a multiple of 33098              sig++;3099              if (signum() == 0) {3100                  switch (sig) {3101                  case 1:3102                      buf.append('0'); // exponent is a multiple of three3103                      break;3104                  case 2:3105                      buf.append("0.00");3106                      adjusted += 3;3107                      break;3108                  case 3:3109                      buf.append("0.0");3110                      adjusted += 3;3111                      break;3112                  default:3113                      throw new AssertionError("Unexpected sig value " + sig);3114                  }3115              } else if (sig >= coeff.length) {   // significand all in integer3116                  buf.append(coeff, 0, coeff.length);3117                  // may need some zeros, too3118                  for (int i = sig - coeff.length; i > 0; i--)3119                      buf.append('0');3120              } else {                     // xx.xxE form3121                  buf.append(coeff, 0, sig);3122                  buf.append('.');3123                  buf.append(coeff, sig, coeff.length-sig);3124              }3125          }3126          if (adjusted != 0) {             // [!sci could have made 0]3127              buf.append('E');3128              if (adjusted > 0)            // force sign for positive3129                  buf.append('+');3130              buf.append(adjusted);3131          }3132      }3133      return buf.toString();3134  }
Por fim, o debug do Java, mostrado na imagem da pergunta está chamando o toString() e o número armazenado, 0.0000000000, faz com que a impressão seja na notação científica.
Este trecho de código foi extraído de: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/math/BigDecimal.java#BigDecimal.toString%28%29


Cartesian coordinates of the points on the plane in the same order as the Ulam Spiral

Question:
I'm messing around with doing a visualization that has nothing to do with the primes and in order to execute it correctly I need an ordered list of all point in the order that the Ulam Spiral crosses them. I've tried some of my work but have only run in to abundantly complicated paths to solution. Also is there a name for looking for pattern that generally occur in spiral, whether they are related to primes or not?

E.g.: Starting with this image:

if $1$ is at the origin, then the list would be as follows: $$(0,0),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(2,-1),(2,0),...$$
Comment: Starting with this image https://upload.wikimedia.org/wikipedia/commons/1/1d/Ulam_spiral_howto_all_numbers.svg, if 1 is at the origin, then the list would be as follows: (0,0),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(2,-1),(2,0),...
Comment: please can you give an example of your phrase? " I need an ordered list of all point in the order that the Ulam Spiral crosses them". In my case, I find it difficult to understand. An example would clarify what you mean.
Comment: much better with the example! just in case, I did long time ago a similar question, is not exactly the same, but it might give you ideas. If I can think a solution to your request I will be back! so just in case: https://math.stackexchange.com/questions/1345430/how-can-i-calculate-the-formula-of-this-fractal-like-structure
Answer: You are lucky because it seems that a very similar pair of sequences is already at OEIS.
The $x$-coordinates are sequence A174344 ("List of $x$-coordinates of point moving in clockwise spiral") and $y$-coordinates ("List of $y$-coordinates of point moving in clockwise spiral") are sequence A268038.
List of $x$-coordinates of point moving in clockwise spiral.

$$0, 1, 1, 0, -1, -1, -1, 0, 1, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -3, -3, -3, -3, -2, -1, 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, -1, -2, -3, -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -2, \cdots$$

List of $y$-coordinates of point moving in clockwise spiral.

$$0, 0, -1, -1, -1, 0, 1, 1, 1, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2, 2, 2, 1, 0, -1, -2, -3, -3, -3, -3, -3, -3, -3, -2, -1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, -1, -2, -3, -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -2, -1, 0, 1, 2, 3, 4, 4, 4, \cdots$$

In the referred OEIS pages there are formulas to calculate each sequence of coordinates.
Comment: @AaronQuitta I think this fits your needs... basically OEIS is always a good place to start looking for this kind of sequences. The trick is looking for one of the coordinates only or a description of the sequence. It usually works.
Comment: I guess my only problem now is that the program that I am using for implementation does not work with the type of recursive functions mentioned  in the OEIS pages.
Comment: @AaronQuitta really? they seem very easy to implement... which program are you using? If you are learning for yourself, I would suggest you to learn Python to do your Math tests. Specifically the Anaconda distribution.
Comment: By program I do not mean programming language, what I use is Desoms,  desmos.com/calculator/ .
Answer: A piecewise, explicit function is provided by the accepted answer of a similar question.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/1888558)


Is it possible to view an aggregate diff from multiple separate versions in Subversion?

Question: Similar to How to view changes made to files on a certain revision in Subversion but I'd like to be able to view multiple revisions that are not contiguous.
For example, I know that I can do this:
$ svn diff -r 12345:12350

And I'll get the diff between r12345 and 12350 without any of the intervening stuff cluttering the way. It will all be in there, but if there were 500 changes and then 500 more changes to undo-those, then the aggregate diff will be empty.
What I'd like to be able to do is this, or something like it:
$ svn diff -c 12345 -c 12350 -c 14567 -c 67899

And see all 4 revision diffs merged together into a single diff.
Is that possible?
Subversion does not support the syntax I have shown above, complaining:
svn: E205000: Multiple revision arguments encountered; can't specify -c twice, or both -c and -r

I can do this the long way, of course, by checking-out r12345, then selectively-applying the other revisions and then doing an "svn diff". Is there a more convenient way?
Comment: I see that there is a nearly identical question with some good feedback on it. I didn't notice this question when I originally posted mine, so I'm voting to close my own question.
Answer: No, you can't use more than 2 parameters in diff
But you can try (just dirty idea, I have not SVN for test) to create temp-branch (with svn copy URl->URL style into single location, TBT!!!) from these 4 revisions and svn diff resulting range
Comment: I used `svn checkout && svn merge -c && svn merge -c && svn merge -c ...` just as I suggested in the original question to solve the immediate need. No need for `ssvn copy` or anything that modifies the repository.


Rules condition to check if user is a member of a specific group type?

Question: I'm trying to create a rule where the condition is that the currently logged in user is a member of a specific type of group. Can anyone offer assistance on the proper data selectors to use to build this condition?
For example, we have three types of groups:
Group Type 1
Group Type 2
Group Type 3
The condition, upon login, should be to check if the logged in user is an active member of Group Type 2.
Thanks in advance.
Comment: what action should be taken then? Maybe it's a context where rules are not the optimal tool.
Answer: The is a rule action "Rules has role" this should do it.


ListView header with clickable images

Question: I've created the following header for a ListView in WPF but the MouseUp events from both of the images don't fire and I think it's because the header is handling the mouse. Can I disable the header? Or somehow make the images handle the mouse up?

XAML:
<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Colmun1" VerticalAlignment="Center"/>
                        <Image Source="Edit.png" Width="24" Height="24" MouseUp="Image_MouseUp"/>
                        <Image Source="Cancel.png" Width="24" Height="24" MouseUp="Image_MouseUp"/>
                    </StackPanel>
                </GridViewColumn.Header>
            </GridViewColumn>
        </GridView>
    </ListView.View>
    <ListViewItem Content="Test"/>
    <ListViewItem Content="Test"/>
    <ListViewItem Content="Test"/>
    <ListViewItem Content="Test"/>
    <ListViewItem Content="Test"/>
</ListView>

Comment: Most likely the up event is handled before it gets to the Image.  Try MouseDown and see if it fires.  Understand you may now want to handle the MouseDown - this is just for debugging.
Comment: I can handle the MouseDown event. I can use this of course but if possible I prefer MouseUp...
Answer: Try Mouse.PreviewMouseUp Attached Event
UPDATE
You're right. It only works if you wrap the Image into a Button.
<Button PreviewMouseUp="Image_MouseUp">
    <Image Source="Edit.png" Width="24" Height="24" />
</Button>

Maybe somebody else has a even better solution.
Comment: Changing the image to `` doesn't help...

ListView header with clickable images


can't see the error with a list method in python

Question: I'am working on a exercise and I can't see where I get it wrong. I'm trying to add the indexes of the sum of two numbers to a list, but instead of getting the indexes, I'm actually getting the numbers. Here is my code, and many thanks in advance for your precious help and time.
a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []

counter = 0

for i in range(len(a_list)):
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
          counter += 1

print(target_list)

how can I do it with list comprehension.
Thank you again and again.
Comment: What purpose does the `counter` variable serve? It is also not entirely clear what output you expect since the indeces are equal to the values in your example. Pls chose more general sample data and show the expected output.
Comment: Look up `enumerate()`
Comment: you have no problem in your specific case cuz item IS index, what are you expecting?
Comment: I got it guys. Thank you very much
Answer: You are getting the indexes, here is an example, if you change your list to:
a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

The output would be different:
[(0, 1)]

Answer: what you did doesnt make any sense.. :
a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []
for i in range(len(a_list)):
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
>>> target_list
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]

which is equal to :
a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []
for i in a_list:
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
>>> target_list
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]

the point in python loops is that when you call for <item> in <Iterable>: it inserts the items to item and iterating each one by order, when you call range(len(list_a)) it generates a list from 0 to the length of a_list , that is eaqual to [0,1,2,3,4,5,6,7,8,9] and this is the same thing as you list...
you could also do the following:
target_list = [(i,j) for j in range(10) for i in range(10) if j+i ==10]
Target_list
>>>
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9)]


On stage earplugs - what do I technically need?

Question: I'm rehearsing and playing live with a band who work at very high sound levels that I find uncomfortable, and after some discussions it's obvious that I'm going to have to get used to it (or leave, which I don't want to do).
So I'm looking at musicians' earplugs, and my goodness there's a lot of jargon and claims and marketing flummery. I'm not looking for in-ear monitoring, purely volume reduction and protection.
Obviously individual gear recommendations are out of scope for MSE - but what high-level technically should I be looking at? Is it all about a clean, across the frequency range, reduction of 10-20 Db, or are there certain frequencies that should be particularly reduced? As someone without a degree in acoustic engineering, what are the keywords and/or numbers am I looking for in an effective product?
And will the same product also protect my ears as an audience member at very loud concerts, or are there different requirements / specs for plugs for performers compared to plugs for audience members?
TIA
Comment: I still maintain that the sound pressure *on stage* doesn't need to be excessive! I know some here will agree with me. Imagine Glastonbury, with trying to produce, on stage, the amount of sound to reach everyone! It's never going to happen! So, instead, clever and careful positioning of p.a. speakers and foldback make it all work sensibly. You need to educate your band members about sound distribution, - or leave..! (or go prematurely deaf).
Comment: If you think playing in loud environments may become a long-term situation for you, consider having your hearing tested now, to establish your baseline hearing level.  Without a past point of reference, gradual hearing loss may go undetected.
Comment: Aside: I'd recommend getting a cheap decibel meter and keeping it near you. (Or checking to see if your phone/smartwatch can measure for you.) This way you have a better idea of the actual loudness on stage and can adapt accordingly.
Comment: I'd say it depends on what your task is, but if you intend to listen to music with volume attenuation you should probably look for something designed to be somewhat neutral. It think what is quite important is that you feel comfortable wearing these for a longer period of time. If they make your ears hurt after an hour they are probably not the best choice. Such plugs are not insanely expensive, and any protection is better than no protection. So why not try out a few options?
Comment: It may help to know what you're playing (instrument and music wise). If you're the drummer, you should already be using plugs! For rehearsals, there's really no need for ear-splitting volumes, but on the (odd, very odd) occasions I used ear defenders that look like over ear cans.
Comment: In Glastonbury you need some stage volume just to hear yourself over the audience if you don't have in-ear monitoring
Comment: It would help us to know which instrument you play, for example for me basic earplugs are fine because they tend to attenuate treble and medium, and I play bass. It means I'll hear the drum kick and my instrument well. For a guitarist something more advanced would be better
Comment: Hi sincere apologies for asking a question then going silent, life stuff! I play flute and concertina, the others in the band I'm most concerned about are guitars, bass and violin. I also play in other mixed ensembles which can get loud and involve bagpipes. So I need something with a pretty flat response ...
Comment: @Dom What and why was the recent edit?
Comment: @SteveMansfield all the tags you added were not on the site before and tags should only be added when needed. The tags I put are more inline with the what the site used before.
Answer: Good earplugs for performers and audience have quite similar specs: Relatively flat frequency response, attenuation that is suitable for the listening environment (usually somewhere around 15dB) and good enough fit that the plugs are comfortable enough to wear for the duration of the concert or rehearsal, and that they work as intended and do not leak. The comfort part is more important if you wear them for rehearsals several times per week than if you wear them for concerts every now and then.
Custom molded plugs have usually the best fit, and I would recommend having a pair made if your budget allows. Otherwise the best bet is to try out different "musician's earplugs" until you find a model that works for you.
Comment: To add to this: because musicians earplugs are aimed at a flat attenuation curve, they will often have a lower decibel rating than you might find on regular PPE earplugs. This is because the standard rating scale looks for more high-end attenuation, rather than a flat line. Just something to remember if you notice those plugs regularly having a lower attenuation rating than standard PPE plugs.
Comment: @DukeSilver the normal foam earplugs mute higher frequencies more than the low end. The most important reason for lower attenuation is however that musicians' earplugs are intended to let you hear the music at safe level but not blocking all sound. This is different from plugs intended for operating loud machinery or sleeping, where blocking all sounds is a good idea.


How do you do a join on two tables when you are implementing uows & a generic repository

Question: My unit of work is basically set up as this tutorial, with minor additions:
http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
I want to know how to do a join on two tables. I tried adding this to GenericRepository, but as you may guess my Linq knowledge is dubious.
public virtual IQueryable AsQueryable()
        {
            IQueryable<TEntity> query = dbSet;
            return query;
        }

And then doing
// uow is defined as new UnitOfWork() on class instantiation
var data = from x in uow.MyRepository.AsQueryable()
           join y in uow.MyOtherRepository.AsQueryable()
           on x.prop1 equals y.prop2

But it wont let me access properties within my table. I basically need a way of returning the table as a queriable entity (I think)
Comment: I personally wouldn't bother with UoW and Repo pattern, you want to focus on using the best stuff DbContext makes available to you.
Answer: Ironically I worked it out straight after posting. Result, for those who find the same issue:
var entity1 = uow.repo1.Get();
var entity2 = uow.repo2.Get();
var res = (from x in entity1
          join y in entity2
          on x.propToJoin equals y.propToJoin
          select new
          {
              test = x.propertyToGrab
          }).ToList();

Comment: You can skip storing in var as well


Debugging Ember.js from chrome

Question: When I try debug Ember.js from chrome browser, its breakpoint for application.js only persists and rest are removed on page refresh by pressing f5.
I have enabled "Log XMLHTTP Requests" and "Preserve Log Upon Navigation" in console tab. Still the problem is there ..
Any help ?
Answer: As an alternative you can set the breakpoints in your code.
javascript:
<code>debugger;
</code>
handlebars:
<code>{{debugger}}
</code>

Debugging Ember.js from chrome


Prove for all $ n\in \mathbb{N} $ ,$n ≥ 1, a(n)$ is odd.

Question: Prove for all $n\in\mathbb{N}\backslash \{0\}$, $a(n)$ is odd.
Consider the sequence defined as followed:
$a(1)= 1$
$a(2)= 3$,where $n \in \mathbb{N}$
$$a(n)=a(n-2)+2a(n-1), n ≥3$$
Conjecture:

$a(3) = 1+2(3) = 7$
$a(4)= 3+2(1+2(3))= 17$
$a(5)= 7+2(3+2(1+2(3)))=41$

I am unable to see a pattern in the above sequence to conjecture a formula to prove it by induction. Any assistance would be appreciated.
Comment: @saturatedexpo both notations are used.  In the case that the notation used is well enough understood, it is often best to leave it in the same notation used by the OP if possible.
Comment: @saturatedexpo A sequence can be defined as a function whose domain is a subset of integers, hence the functional notation.
Comment: Recommend a proof via strong induction.  In proving that $a(n)$ is odd, recognize that due to induction hypothesis $a(n-2)$ is odd and so $a(n)$ is the sum of an odd number $a(n-2)$ and an even number $2a(n-1)$ and is therefore odd.  You need two base cases (which are given in the problem statement already).
Comment: i'm not the greatest expert, but shouldn't it be $a_n$ ect? (i left it as it is, cuz unsure)
Comment: The induction assumes a() is odd.  One of n-1 and n-2 is even and the other is odd.  So you have an odd times an even plus an odd times an odd.  That's an odd.
Answer: Hint:-$$a(n)-a(n-1)\equiv 0\pmod{2}$$Can you do the proof from here using Mathematical Induction?
Answer: Easier method: proof via strong induction.
Base cases: $a(1)=1$ and $a(2)=3$ are both odd.
Induction hypothesis: All values of $a(k)$ for $1\leq k\leq n$ are odd for some $n$
We wish to show that this implies that $a(n+1)$ is also odd.
Indeed, since $a(n+1)=2a(n)+a(n-1)$, and $a(n-1)$ is odd by the induction hypothesis, we have $a(n-1)=2m+1$ for some $m\in \Bbb Z$ and therefore $a(n+1)=2(a(n)+m)+1$ is odd.
Thus, $a(n)$ is odd for all $n\geq 1$

Overkill method: actually coming up with a closed form expression for $a(n)$
Given the recurrence $a(n)=2a(n-1)+a(n-2)$, we look at the characteristic polynomial: $x^2-2x-1$
This factors as $(x-1-\sqrt{2})(x-1+\sqrt{2})$, implying that $a(n)=c_1 (1-\sqrt{2})^n+c_2 (1+\sqrt{2})^n$ for some values of $c_1$ and $c_2$.
Using the initial conditions, $a(1)=1$ and $a(2)=3$, we find $c_1=c_2=\frac{1}{2}$
That is to say
$$a(n)=\frac{1}{2}\left((1-\sqrt{2})^n+(1+\sqrt{2})^n\right)$$
Applying the binomial theorem:
$a(n)=\frac{1}{2}\sum\limits_{i=0}^n \binom{n}{i}[(-\sqrt{2})^i+(\sqrt{2})^i]=\frac{1}{2}\sum\limits_{i=0}^{\lfloor\frac{n}{2}\rfloor} \binom{n}{2i}[2\cdot 2^i]$
When $i$ is odd, the terms cancel out.  When $i$ is even and at least $2$, the terms will add and be divisible by $4$ and thus still even after dividing by two.  When $i$ is zero, the entry is $2$, which divided by two is one.
Thus, $a(n)=\frac{1}{2}(2+4(k))=1+2k$ for some $k$ and is therefore odd.
Answer: As a serious hint: you constantly add a odd number to an even one(cough 2a). Now just induct your way through it!
Answer: By computation,
$a(n)$ is odd for
$1 \le n \le 5$.
Suppose there is an $n$
such that
$a(n)$ is even.
Let $m$
be the smallest value of $n$
such that
$a(n)$ is even.
Then
$m \ge 6$.
Then
$a(m-2)
=a(m)-2a(m-1)
$
is also even.
This contradicts the assumption
that $m$ is
the smallest such value.
Therefore
there is no $m$
such that
$a(m)$ is even,
so all $a(n)$ are odd.


Points of $\mathbb{Z}[e^{\frac{2\pi i}{n}}]$ in $\mathbb{C}$

Question: When $n = 2$, the points of $\mathbb{Z}[e^{\frac{2\pi i}{n}}]$  are the vertices of a regular tiling of $\mathbb{C}$ by unit squares. When $n = 4$, the points of $\mathbb{Z}[e^{\frac{2\pi i}{n}}]$ are the vertices of a tiling of $\mathbb{C}$ by right triangles. When $n = 3, 6$, the points of $\mathbb{Z}[e^{\frac{2\pi i}{n}}]$ are the vertices of a tiling of $\mathbb{C}$ by equilateral triangles. (NB: I'm not even sure that these remarks are correct. Someone please correct me if I'm wrong).
What about when $n \neq 2,3,4,6$? My guess would be that when $n = 2^m 3^k$ for some $m,k \in \mathbb{N}$, we still get a discrete set of points (what tiling would the points correspond to?). I would also guess that when $n \neq 2^m 3^k$ for some $m,k \in \mathbb{N}$, $\mathbb{Z}[e^{\frac{2\pi i}{n}}]$ is dense in $\mathbb{C}$. Are these guesses right? If not, what actually happens?
Edit
See the comments below this post. I made some mistakes in the first paragraph.
Comment: $n=2$ gives $\mathbb{Z}[e^{\pi i}]=\mathbb{Z}[-1]=\mathbb{Z}$ itself, not squares.  For $n\neq2,3,4,6$, $\mathbb{Z}[\zeta_n]$ is dense in $\mathbb{C}$, e.g., $1,i,\sqrt{-3},\sqrt{3}\in\mathbb{Z}[\zeta_{12}]$.
Comment: my bad. You're right. I was thinking of $n = 2$ as $\mathbb{Z}[i]$ and $n = 4$ as $\mathbb{Z}[e^{i\pi/4}]$. In that case, it seems like there is at least one more $n$ that produces a regular tiling, namely $n =  8$, which does in fact correspond to $\mathbb{Z}[e^{i\pi/4}]$.
Answer: Claim: For $n\neq 1,2,3,4,6$, the cylotomic integers $\mathbb{Z}[\zeta_n]$ is dense in $\mathbb{C}$ (usual topology), where $\zeta_n=e^{2\pi i/n}$.
Proof: Note that, $2\cos(2\pi/n)-1=\zeta_n+\zeta_n^{n-1}-1\in\mathbb{R}^\times$, with absolute value $<1$ for these $n$.  Combining with the rotation $\zeta_n\notin\mathbb{R}$ then yields the desired result.
Comment: Could you explain this answer further? I'm not sure how this shows density. Even if you get density in $\mathbb{R}^x$ and apply the $n$ distinct rotations furnished by $\zeta_n$, you don't get density in $\mathbb{C}$, you only get density on the union of $n$ lines through the origin in $\mathbb{C}$. Am I missing something?
Comment: An additive subgroup of $\mathbb{R}$ is dense iff it accumulates at $0$.  Since $\mathbb{Z}[\zeta]\cap\mathbb{R}$ is a ring and contains an element of absolute value $\in(0,1)$, taking high enough powers get you arbitrarily close to $0$.  So $\mathbb{Z}[\zeta]\cap\mathbb{R}$ is dense in $\mathbb{R}$.  Now use $\{1,\zeta\}$ is an $\mathbb{R}$-basis of $\mathbb{C}$ and do the components separately.
Comment: I think I see. We can show there is some dense subset $A \subset \mathbb{R}$ contained in $\mathbb{Z}[\zeta_n]$. Then $A \oplus A\zeta_n$, which must also be contained $\mathbb{Z}[\zeta_n]$, is dense in $\mathbb{C}$. Edit: I posted this just as you made your last post. That makes sense. Thank you. I'll mark this as an answer.


Difference between SCM and SEM

Question: I'm currently looking into causal modeling (according to Pearl) and I'm having trouble understanding what exactly sets apart structural causal models (SCM) and structural equation models (SEM).
The only info I found to far is that for SCM [1]

The central idea is to exploit the invariant characteristics of structural equations without committing to a specific functional form.

Is that really, in essence, all that differentiates SCM and SEM?
Does that mean that everything we can do with SCM, we can also apply to SEM?
[1] https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2836213/
Answer: It is the same thing, however SEM is not always interpreted as a causal model. Path model might be another closely related term. From Peters et a;. Elements of causal inference (which is free, if you want to read more about):

The idea of autonomy and invariance is deeply engrained in the concept of structural equation models (SEMs) or SCMs. We prefer the latter term, since the term SEM has been used in a number of contexts where the structural assignments are used as algebraic equations rather than assignments.

I am sure Pearl discuss it as well, but I don't have his book on hand
Answer: I am late but anyways.
This is taken from the book Causality by Judea Pearl(2nd edition),Page 27.

A set of equations in the form of (1.40) and in which each equation represents an autonomous mechanism is called a structural model (a.k.a SEM); if each variable has a distinct equation in which it appears on the left-hand side (called
the dependent variable), then the model is called a structural causal model or a causal model for short.

Equation 1.40,
X= some non-parametric function of (X1,...Xn,Ui), where (X1,..Xn) influence X and Ui represents error term.
If it is not clear let me know will expand on it.

Difference between SCM and SEM


Epidemiology cohort studies question

Question: If we are conducting a cohort study of factors associated with recurrent myocardial infarctions (MI) following the first one, should our study population at baseline include subjects who had previously suffered from one MI, or subjects free from any previous MI?
Answer: If you are truly interested in risk factors for MI among those with one MI, then you should enroll people with one MI already. In this case, you are not interested in people who never have an MI, nor are you interested in people who die at first MI, so enrolling these people would not be the most efficient use of resources.
However, you don't want to just enroll anyone who ever had 1 MI, because then people with only 1 and no more MIs and people who survive longer after their MI will both be over-represented in your sample. You should try to enroll people as close as possible to the time of their first MI - for example upon hospital discharge for 1st MI.

Epidemiology cohort studies question


Unable to redirect python script result to a text file in windows

Question: Here is my python code.I'm trying to do elastic search in python.
from pyes import *
from pyes.mappings import *
conn = ES('http://search.twitter.com/search.json?q=poplio')
conn.indices.create_index("test-index")

I'm trying this tutorial pyes
The issue is when i try to run this python script in windows i get a detailed message on msdos prompt which i don't know if its an error or any thing else.
So i tried to redirect that message to a text file but i don't see any thing in that file.
Here is how i redirect the output of script
python script.py > log.txt

But log.txt is empty.
What is going wrong.
Answer: It might be printing those messages to STDERR.
Try doing the following:

python script.py > log.txt 2>&1

This will redirect the STDERR to STDOUT as well. You should see those messages then.