Geometrically explained, why do Linear Transformations Take a circle to an ellipse

Question: Short Version:
How can it be geometrically shown that non-singular 2D linear transformations take circles to ellipses?
(Also, its probably important to state I'd prefer an explanation that doesn't use SVD, as I don't really understand it yet...although I see it everywhere)
Long Version:
Let's use the definition of an ellipse as being a circle stretched in two perpendicular directions. The two directions its stretched in will correspond to the two axes of the ellipse.
We begin by defining the circle as the endpoints of all possible 2D unit vectors. The ellipse (or at least I"m TOLD it's an ellipse) is the shape drawn by the endpoints of all these vectors after they have all been transformed in the same way (aka multiplied by the same nonsingular matrix $A$).

For linear transformations represented by diagonal matrices, it's easy to see. We're just stretching the circle in the X and Y directions.
For linear transformations represented by symmetric matrices...its a little harder, but I can see the transformation because the eigenvectors of the symmetric matrix are perpendicular, and if we change to a basis where those eigenvectors are the basis vectors, the transformation can be represented by a diagonal matrix (as for WHY symmetric matrices can be decomposed this way I don't yet really understand - but for the purpose of this question I'm just accepting that they can; I'm accepting that the eigenvectors of symmetric matrices are perpendicular to one another).
So, just like diagonal matrices, symmetric matrices also correspond to stretching a unit circle in perpendicular directions - but unless the symmetric matrix is diagonal, these are perpendicular directions different from the X and Y directions.
Buuut...what about for nonsymmetric matrices?

Thanks!

EDIT:
I've now learned of the polar decomposition of any real matrix, and that provides a beautiful explanation for why any real matrix takes a circle to an ellipse!
$A=QS$, where $Q$ is an orthogonal matrix (rotation) and $S$ is a symmetric matrix (stretching in the direction of the eigenvectors).
The symmetric matrix will definitely correspond to making an ellipse (since it scales in orthogonal directions, although perhaps not our regular $x$ and $y$ directions) and all the orthonormal matrix will do is rotate this ellipse.
However, all the explanations I've seen so far that PROVE that polar decompositions of real matrices are always possible use an algebraic explanation instead of a geometric one...so they aren't really what I'm looking for.
Thanks again!
Comment: A conic's equation has the form $x\cdot Ax+\mathbb{b}\cdot x+ c =0$. If you do a linear change of coordinates $x=By$. the equation becomes $y\cdot B^*ABy+(B^*y)\cdot y + c=0$. The determinant $\det(B^*AB)=\det(A)(\det(B))^2$ has the same sign as $\det(A)>0$.
Comment: Short answer: ... for the same reason that it can transform a square into a rectangle.  It can strech objects with 2 different factors in 2 different directions.
Comment: You might find the answer here helpful: [What shape do we get when we shear an ellipse? And more generally, do affine transformations always map conic sections to conic sections?](https://math.stackexchange.com/questions/1498799/what-shape-do-we-get-when-we-shear-an-ellipse-and-more-generally-do-affine-tra?rq=1).
Answer: The equation of a circle is $x^2 + y^2 = r^2$, or in terms of vectors $(x,y) \pmatrix{x\cr y} = r^2$  An invertible linear transformation $T$ takes $\pmatrix{x\cr y}$ to $\pmatrix{X\cr Y} = T\pmatrix{x\cr y}$.  Thus $\pmatrix{x\cr y\cr} = T^{-1} \pmatrix{X\cr Y}$, and $(x,y) = (X, Y) (T^{-1})^\top$.  The equation becomes
$$(X, Y) (T^{-1})^\top T^{-1} \pmatrix{X\cr Y} = r^2 $$
Note that $(T^{-1})^\top T^{-1}$ is a real symmetric matrix, so it can be diagonalized, and its eigenvalues are positive.
Comment: Thanks! I feel like I'm so close to understanding your explanation, but I'm still a little lost. All I'm getting here is that a symmetric matrix, which can be expressed as the product of two non-symmetric matrices, make an ellipse. But I'm still a little lost as to how to apply it to non-symmetric matrices themselves...I feel like I'm just having a brain-freeze, but if you could give me some pointers, I'd really appreciate it!
Comment: The transformation $T$ maps the circle an ellipse, whose equation is expressed using the symmetric matrix $(T^{-1})^\top T^{-1}$.  The non-symmetric matrix of the transformation is not the same as the symmetric matrix in the equation of the ellipse.
Comment: Got you!! So you're using the symmetric matrix $(T^{-1})^\top T^{-1}$ to show the EQUATION of the ellipse, but $T$ is still the transformation. But, and this is definitely my fault (I'm still learning and really confused about a lot of stuff), why does $(T^{-1})^\top T^{-1}$ being a real symmetric positive definite matrix mean $T$ maps the circle to an ellipse...?
Answer: Every real square matrix has a polar decomposition into the product of an orthogonal matrix $U$ and a positive-semidefinite (symmetric) matrix $P$. If the original matrix is nonsingular, then $P$ is positive-definite. In 2-D, orthogonal matrices represent either rotations or reflections, which are both isometries, so they don't affect the shape of the transformed circle. As you've mentioned, $P$ can be orthogonally diagonalized, so it represents a stretch in some set of perpendicular directions.
The existence of this decomposition is equivalent to the existence of the SVD, but can be shown without relying on the latter. In a similar vein, the SVD decomposes the matrix into the product of a rotation or reflection, a scaling, and another rotation or reflection.
You might also have a look at the Steiner generation of an ellipse. This uses intersecting line segments drawn between points on the sides of a parallelogram to generate ellipses, including circles. Affine transformations preserve incidence relationships (the image of the intersection of a pair of lines is the intersection of the lines' images) and maps paralellograms to parallelograms, so the image of an ellipse under an affine transformation is another ellipse.
Comment: Thanks for your answer! +1 for use of geometry! Okay, I've now learned a bit about the SVD decomposition, and this is literally one step away from it, and I kind of understand it. I see it works, but still a little confused on the geometric reason why every real-valued square matrix has a polar decomposition...most sources talk about tack on the $U$ at the beginning and then go into some algebra I haven't really looked at yet. Any pointers to good geometric explanations? Thanks!
Comment: Instead of the polar decomposition, one could use the $QR$ decomposition...
Answer: The answers on this thread are quite insightful but I am attempting here a rather very geometric answer, as the OP demanded so. For this I am going to use another interesting geometric interpretation of linear transformation (which is easier to imagine)
An alternate geometric interpretation of (dimension-preserving) linear transformation is that it's a transformation such that any line in original space is always transformed into a line and origin is not shifted.
Now imagine a freshly made pizza base/crust. Even more, let's make grids on it.
Our job is now to transform it's shape such that all the grid lines (or any possible line) remain lines. So you see at best what we can do is *stretch it with equal forces on opposite sides. You are free to choose where to stretch and Of course we can simply rotate it also after or before all the stretching.
It's not difficult to imagine that we can only get an ellipse (or bigger circle if we stretched from all sides with equal force).
Other interesting points:
(1): The direction of stretch is eigen vector and extent to which it is stretched is eigen value;
(2): Each rectangle from the gridlines is now parallelogram.
Answer: This answer really demands illustrations, but I'm too lazy to draw them. I encourage you to draw your own illustrations as you read. If you like them enough to share, leave a comment—I'll make the answer community wiki so you can add them!
The outermost points
Take an invertible linear map $A$ from one two-dimensional space to another. This map turns the unit circle $\mathcal{S}$ into some mystery shape $A\mathcal{S}$, which we want to understand. If we take a unit vector $\mathbf{u}$ and spin it all the way around the unit circle, $\|A\mathbf{u}\|^2$ can't increase forever, because $\mathbf{u}$ will eventually come back to where it started. That means there must be places where $A\mathcal{S}$ reaches a maximum distance from the origin. Let's focus on those outermost points.
Suppose $A\mathbf{u}_0$ is one of the outermost points of $A\mathcal{S}$. Choose a moving unit vector $\mathbf{u}_t$ that travels at unit speed along the unit circle, passing through $\mathbf{u}_0$ at time $t = 0$. If we graph $\|A\mathbf{u}_t\|^2$ with respect to $t$, we get a smooth curve. At $t = 0$, the graph has a maximum, so its slope must be zero. That's a clue about what $A\mathcal{S}$ looks like near $A\mathbf{u}_0$. Let's study it more carefully.
Over short distances, moving at unit speed along a circle is very close to moving at unit speed along a straight line [1]. In symbols,
$$\mathbf{u}_t \approx \mathbf{u}_0 + t\mathbf{w},$$
where $\mathbf{w}$ is a unit vector perpendicular to $\mathbf{u}_0$. This means that when $t$ is near zero, the graph of $\|A\mathbf{u}_t\|^2$ is very close to the graph of $\|A(\mathbf{u}_0 + t\mathbf{w})\|^2$. In particular, at $t = 0$, the slope of the graph of $\|A(\mathbf{u}_0 + t\mathbf{w})\|^2$ matches the slope of the graph of $\|A\mathbf{u}_t\|$—which is zero.
The function $\|A(\mathbf{u}_0 + t\mathbf{w})\|^2$ is convenient, because we can break it down using dot product algebra:
$$\begin{align*}
\|A(\mathbf{u}_0 + t\mathbf{w})\|^2 & = \|A\mathbf{u}_0 + tA\mathbf{w}\|^2 \\
& = (A\mathbf{u}_0 + tA\mathbf{w}) \cdot (A\mathbf{u}_0 + tA\mathbf{w}) \\
& = (A\mathbf{u}_0 \cdot A\mathbf{u}_0) + 2(A\mathbf{u}_0 \cdot A\mathbf{w})\,t + (A\mathbf{w} \cdot A\mathbf{w})\,t^2.
\end{align*}$$
Now we see that $\|A(\mathbf{u} + t\mathbf{w})\|^2$ is a quadratic function. Its graph is a parabola. Since know the graph has slope zero at $t = 0$, the coefficient of $t$ must be zero. In other words, $A\mathbf{u}_0 \cdot A\mathbf{w} = 0$, which means $A\mathbf{u}_0$ and $A\mathbf{w}$ are perpendicular.
Let's review. We started by looking at $A\mathbf{u}_0$, one of the outermost points of $A\mathcal{S}$. Then we chose [2] a unit vector $\mathbf{w}$ perpendicular to $\mathbf{u}_0$. By thinking about what a maximum looks like, we concluded that $A\mathbf{w}$ was perpendicular to $A\mathbf{u}_0$. In summary:

If $A\mathbf{u}_0$ is one of the outermost points of $A\mathcal{S}$, then $A$ sends every unit vector perpendicular to $\mathbf{u}_0$ to a unit vector perpendicular to $A\mathbf{u}_0$.

The longest axes
Each unit vector $\mathbf{u}$ has a counterpart $-\mathbf{u}$ on the opposite side of the unit circle. Since $A(-\mathbf{u}) = -A\mathbf{u}$, it follows that every point $A\mathbf{u}$ on $A\mathcal{S}$ has a counterpart $-A\mathbf{u}$ on the opposite side of $A\mathcal{S}$. If $A\mathbf{u}$ is an outermost point, then $-A\mathbf{u}$ is too, because a vector and its opposite always have the same length. We've discovered that the outermost points of $A\mathcal{S}$ come in opposing pairs. Each pair sits on a line through the origin: a longest axis of $A\mathcal{S}$.
This point of view is convenient, because linear maps send lines to lines. If $\mathcal{L}$ is the line along a vector $\mathbf{v}$, then $A\mathcal{L}$ is the line along the vector $A\mathbf{v}$. We can use that idea to make our summary statement even more geometric. For brevity, I'll write $\text{line}^0$ to mean a line through the origin, and I'll write $\mathcal{L}^\perp$ to mean the $\text{line}^0$ perpendicular to $\mathcal{L}$.

If $A\mathcal{L}$ is one of the longest axes of $A\mathcal{S}$, then $\mathcal{L}$ and $\mathcal{L}^\perp$ stay perpendicular when you apply $A$. In other words, $A\mathcal{L}$ and $A\mathcal{L}^\perp$ are perpendicular.

We can use this idea to draw a picture of $A\mathcal{S}$. First, pick a $\text{line}^0$ $A\mathcal{L}$ which is one of the longest axes of $A\mathcal{S}$. Since we're working in two dimensions, we can use $\mathcal{L}$ and $\mathcal{L}^\perp$ as the axes of a coordinate grid. When we apply $A$ to this grid, the axes stay perpendicular; the only kind of distortion we can get is stretching along the axes. If you draw a circle on a coordinate grid and then distort it by stretching along the axes, you get an ellipse! That means $A\mathcal{S}$ is an ellipse.
We now see that in most cases, $A\mathcal{S}$ only has one longest axis: the major axis of the ellipse. The exception is when the stretch factors along both axes happen to be the same, making $A\mathcal{S}$ a circle.
[1] If you've ridden a bike or driven a car, imagine locking the handlebars or steering wheel just a tiny bit off center. If you travel a long distance this way, you'll go in a huge circle, but over short distances it will be hard to tell you're not going straight.
[2] In our original reasoning, $\mathbf{w}$ was determined by the direction $\mathbf{u}_t$ was moving at $t = 0$. However, we're the ones who chose $\mathbf{u}_t$, and we could make it move in any direction.
The next dimension
The same reasoning works in three dimensions, where it shows that applying an invertible linear map $A$ to the unit sphere $\mathcal{S}$ turns it into an ellipsoid. Like before, we see that if $A\mathcal{L}_1$ is one of the longest axes of $A\mathcal{S}$, then $\mathcal{L}_1$ and $\mathcal{L}_1^\perp$ stay perpendicular when you apply $A$. The only complication is that $\mathcal{L}_1^\perp$ is a $\text{plane}^0$ instead of a $\text{line}^0$. The trick is to realize that $A$ is a linear map from $\mathcal{L}_1^\perp$ to $A\mathcal{L}_1^\perp$. In other words, it's a map from one two-dimensional space to another—so our two-dimensional reasoning applies. If $A\mathcal{L}_2$ is one of the longest axes of $A\mathcal{S}$ within $A\mathcal{L}_1^\perp$, and $\mathcal{L}_3$ is the $\text{line}^0$ perpendicular to $\mathcal{L}_2$ within $\mathcal{L}_1^\perp$, then $A$ keeps $\mathcal{L}_2$ and $\mathcal{L}_3$ perpendicular. We end up with three perpendicular $\text{lines}^0$: the longest axis $\mathcal{L}_1$, the second-longest axis $\mathcal{L}_2$, and the third-longest axis $\mathcal{L}_3$. These lines stay perpendicular when we apply $A$.
We can extend this reasoning to any finite number of dimensions. Given an invertible linear map $A$ from one $n$-dimensional space to another, we pick one of the $\text{lines}^0$ that $A$ stretches the most, focus on the $(n-1)\text{-plane}^0$ perpendicular to it, and repeat. We end up with perpendicular $\text{lines}^0$ $\mathcal{L}_1, \mathcal{L}_2, \ldots, \mathcal{L}_n$ which stay perpendicular when we apply $A$, and are ordered from most to least stretched. You asked for an answer that doesn't use singular value decomposition, but the joke's on you: if you try to understand why applying a linear map to a sphere turns it into an ellipsoid, you'll inevitably end up understanding singular value decomposition.


How to solve for dx in the numerator by itself

Question: $$\int \frac{dx}{1+x^2} $$
I'm having a hard time knowing what to do when it's just dx on top
Answer: If this was your confusion: the integral is precisely by definition equal to $$\int \frac{1}{1+x^2} \ \mathrm{d}x$$
which is a very well-known integral.
Answer: $$\int \frac{1}{1+x^2} \space dx = \tan^{-1}(x) + C$$


How can I convert my string to type for enums?

Question: For example I have enumtype like: "SampleEnum"
SampleEnum: {
        Day: 0,
        Week: 1,
        Month: 2
    },

But for one spesific stuff, it comes me as string like "SampleEnum"
I have to convert it ------> type directly it should be SampleEnum so I can use
Enums.SampleEnum. I need this. How can I do ??
Comment: it should not come to your as string, but if you insist to take this path, just consider as you suggested having a map Enums = {SampleEnumKEY:SampleEnum} so you can get your SampleEnum from the map by referring to its key (here would be Enums.SampleEnumKEY)
Comment: I put column type as Enum for mygrid. So it comes as string
Answer: SampleEnum= {
    Day: 0,
    Week: 1,
    Month: 2
}

var str="SampleEnum";

You can access SampleEnum using window object of the browser like
window[str]


Drupal 6 and Varnish Cache

Question: Is Pressflow really required for Varnish? I ask because I've set up Varnish on my server with drupal 6.30 standard, and installed the Varnish module, and it's sped up my website no end. Really amazing speed results here, and I'm getting plenty of cache hits.
So my question, what's different about the Pressflow install, and why is it required for Varnish?
Answer: Varnish and Pressflow are two different things.. Pressflow uses varnish to improve performance.. More details goes below..
Pressflow is "a derivative of Drupal core providing enhanced performance, scalability, and data integrity". Basically, some really smart guys at Four Kitchens and elsewhere back-ported a bunch of Drupal 7 performance enhancements to the Drupal 6 (and even Drupal 5!) code base.
Pressflow adds the following features to Drupal.

Support for database replication
Support for Squid and Varnish reverse proxy caching
Optimization for MySQL
Optimization for PHP 5

What:
Varnish is an HTTP accelerator and caching reverse proxy. Varnish is all about speed. It stores as much content as it can in the fastest place possible – RAM in this case – and bypasses the expensive process of making a request to Apache.
Why:
Pressflow structures the Drupal content to be more cache-friendly, but we still need something to actually cache the content.
How:
Varnish sits in front of Apache, accepts incoming connections from browsers and, if possible, fulfills the requests from its cache. If it can't, it passes the request on to the underlying Apache/PHP stack. It then takes the response from Apache and forwards it on to the requesting browser. If the response from Apache is cacheable, Varnish stores it in RAM for fulfilling future requests.
Comment: I would just clarify the first paragraph to say that Pressflow *can* use Varnish.  You can run Pressflow w/o it, too.
Comment: Thanks for the response, interesting. It says 'Pressflow adds support for varnish cache', but it is working on my server anyway with standard Drupal?
Comment: My understanding is that you can effectively run Varnish on ANY web app. Which is why standard Drupal still works with it, as it's just a reverse proxy (Varnish that is)
Answer: Hmm. According to the Varnish documentation: Varnish and Drupal:

Using Varnish with  Drupal prior to version 7 will require the use of
  Pressflow, which backports Drupal 7's lazy session creation and other
  important performance enhancement. Without this, Drupal will create a
  PHP session cookie for all users, meaning Varnish is reduced to
  caching static files only.

This seems to contradict the statements made in the answers in this thread.

Drupal 6 and Varnish Cache


Which Area of mathematics can explain this?

Question: https://i.stack.imgur.com/rij3X.png
As in the image we can see that ray of light is bouncing off objects. Black ones are opaque objects and white ones are transparent objects. I want to calculate how many times a ray of light bounces to reach a particular point, "without tracing rays". I am looking for the mathematical equation(that takes scene and a point as its input and outputs the number of bounces) that tells how many times ray of light will bounce to reach a particular point.
Is this type of mathematical equation exists? If not, which area of mathematics should I study to find solution to this problem?
Comment: Geometric optics is probably what you want to look up. It's mostly planar geometry (trig at worst) with some minor physics involved.
Comment: It looks like simple geometry.
Comment: I don't think you'll avoid ray tracing - the output is complicated and unlikely to decompose further. Given a fixed scene and variable ray, you might be able to do some productive preprocessing, but really, if you need an efficient solution, you should be looking more at getting your hands dirty with things like [spatial databases](https://en.wikipedia.org/wiki/Spatial_database) than holding out for a clean mathematical solution.
Comment: [This seems relevant](http://mathworld.wolfram.com/Billiards.html)
Answer: I don't see any way other than ray-tracing.
The rays reflect off the
black rectangles
and are refracted
(presumably using Snell's law)
by the white rectangles.
I noticed that
either ray 2 or 3
near the bottom right
seem to have been absorbed
by a white rectangle.
It would be an interesting exercise
to program this
given a set of rectangles
and the index of refraction
of the white rectangles.
I wonder how much precomputation
could be done,
given the location and type
of the rectangles,
to speed up the ray tracing.


Como copiar div do iframe para o pai? (replicar) pode ser usando ajax, jquery, javascript

Question: Tenho um index.php que faz um post em conteudo.php, e pega o resultado e escreve na div #conteudo dentro de index.php.
Post:

no conteudo. php, tenho:

<?php require_once('Connections/Gymo.php');
$aba = $_POST['dados'];

 if ($aba == "nada") {

 echo "

 ";
?>

dentro do iframe inicio.php, tenho:

 Quero replicar esta div para index.php com o mesmo id

Minha questão: Como fazer para que o conteudo desta div contida no iFrame seja passada para a div #conteudo contida no index.php, substituindo os valores dela, seja eles quais forem?
Esta ação teria que acontecer ao ativar a função ajax do iframe: "$(this).on('load',function()..."
Answer: Primeiro você precisa pegar todo o conteúdo que vem dentro do iframe, nesse caso é sua div.
Você pode fazer dessa forma:
var iframeContent = $(data).text(); // aqui vai retornar todo conteúdo dentro do iframe

Após isso, pegue todo o conteúdo que está dentro da sua div do iframe e coloque na div de destino.
var divContent = $(iframeContent).text(); // aqui temos todo o conteúdo da div do iframe

$("#conteudo").empty().html(divContent); // limpando a div de destino e colocando o conteúdo da div do iframe.

Comment: Obrigado. Editei minha pergunta para ficar mais clara. Tentei desta forma acima mas não consegui, talvez com algum exemplo mais passo a passo eu consiga entender, peço desculpas por ser meio newbie.
Comment: É só colocar o conteúdo da resposta dentro do seu success: function(data) {}, talvez eu também não tenha entendido muito bem a pergunta.


Duvida calcular média com Python 3.5

Question: Estou criando um programa, utilizando Python 3.5, para calcular média, mas na minha escola há algumas matérias com dois professores, e cada um da uma prova diferente.
O problema é que o código que criei faz a media de (Prova 1 + Prova 2)/2, que é igual a media1, (Atividade 1 + Atividade 2)/2, que é igual a média 2, e a média final é com o Simulado (media1+media2+simulado)/3, e quando é uma matéria não coloco nada na P2 dá erro. Eu estava pensando, quando o usuário inserir o nome da matéria executar tal código, e outro nome, outro código, como faço isso?
Meu código:
nota1 = float(input("Nota1: "))

nota2 = float(input('Nota 2: '))

simulado = float(input('Nota simulado: '))

ac1 = float(input('Nota AC1: '))

ac2 = float(input('Nota AC2: '))

media1 = (nota1+nota2)/2
mediaAC = (ac1+ac2)/2
mediaf = (media1+simulado+mediaAC)/3

print (mediaf)

if mediaf == 6:
   print("na media")

if mediaf < 6:
   print("abaixo da media")

Comment: Olá @gust4vo, você poderia colocar o código que você já construiu e o que você já tentou na sua pergunta?
Comment: pronto, inseri o codigo.
Comment: Qual erro você está obtendo? Detalhe um pouco mais...
Comment: Não é um erro, eu queria saber como faço para quando, por exemplo, uma variavel for igual a Matematica, um determinado código é executado(se matemática tem 2 provas, o código com média para duas matérias é executado), e caso for uma matéria com uma prova, o código dessa média é executado. Tentei deixar o espaço da P2 em branco, mas o erro foi esse: Traceback (most recent call last):
  File "C:\Users\gusta\AppData\Local\Programs\Python\Python35-32\notateste.py", line 2, in
    nota2 = float(input('Nota 2: '))
ValueError: could not convert string to float:
Comment: @gust4vo, muda o titulo com um resumo da sua duvida, para outros usuarios identificar sua duvida e poder te ajudar também. Abracos!
Answer: from functools import partial

notas = list(map(float,list(iter(partial(input, 'Nota: '), ''))))
ac = list(map(float,list(iter(partial(input, 'AC: '), ''))))
simulado = float(input('Nota simulado: '))

media_notas = sum(notas)/len(notas)
media_ac = sum(ac)/len(ac)
media_final = (media_notas + media_ac + simulado) / 3

print('medias: ', media_notas, media_ac, media_final)

if media_final >= 6:
    print('na media')
else:
    print('abaixo da media')

Dessa maneira tu digitas quantas notas forem necessárias, até o valor da nota ser vazio (digitar 'Enter'). Exemplo:
$ python notas.py
Nota: 5
Nota: 10
Nota:
AC: 5
AC: 5
AC:
Nota simulado: 10
notas:  7.5 5.0 7.5
na media

Comment: @GuilhermeIA Quando eu respondi a pergunta não estava escrito a versão do python. O título, texto e TAG foram adicionados nas edições. Editei a resposta para executar no python 3.5
Comment: Olá, o código deu erro.
Comment: Qual erro? Estás usando qual versão do Python? Testei novamente aqui e funcionou. Uso python2.7
Comment: Antes de mais nada, um dos problemas do seu código é o `print`, pois em Python 3 precisa de parenteses: `print('abaixo da media')`
Answer: Opa! Cara, sou iniciante mas tentei implementar uma solução para você:
qtd_notas = int(input("Digite a quantidade de notas: "))
notas = 0
for i in range(0, qtd_notas):
    notas += input("Digite a nota " + str(i + 1) + ": ")

media = notas / qtd_notas

simulado = input("Nota Simulado: ")

acs = 0

for i in range(0, qtd_notas):
    acs += input("Notas AC" + str(i + 1) + ": ")

media_ac = acs/qtd_notas

media_final = (media + simulado + media_ac) / 3

print (media_final)

if media_final == 6:
    print ("na media")
if media_final < 6:
    print ("abaixo da media")

O que eu fiz foi colocar para, no início, o usuário digitar a quantidade de notas que irão compor as médias. Ignore as variáveis.
Espero ter ajudado.
Comment: Olá, não consegui executar o código, deu erro: Traceback (most recent call last):
  File "C:/Users/gusta/AppData/Local/Programs/Python/Python35-32/teste.py", line 3, in
    for i in range(0, qtd_notas):
TypeError: 'str' object cannot be interpreted as an integer
Comment: Opa! Editei o código, adicionei uma conversão para int em qtd_notas. Espero que agora dê! rsrs
Answer: Outra forma de se resolver a questão é a seguinte:
notas = list(map(float, input('Digite as notas das provas: ').split()))
ac = list(map(float, input('Digite as notas das atividades: ').split()))
simulado = float(input('Digite a nota do simulado: '))

media_provas = (sum(notas) / len(notas))
media_ac = (sum(ac) / len(ac))
media_final = ((media_provas + media_ac + simulado) / 3)

print(f'\033[32mA Média Final é: {media_final:.1f}')

if media_final >= 6:
    print('Na média!')
else:
    print('Abaixo da média')

Quando executamos o algoritmo recebemos a seguinte mensagem: Digite a nota das provas:. Neste momento devemos digitar todas as notas das provas, na mesma linha, separados por um só espaço e pressionar enter. Em seguida, recebemos a seguinte mensagem Digite as notas das atividades:. Neste momento devemos digitar todas as notas das atividades, na mesma linha, separados por um só espaço e pressionar enter. Em seguida recebemos a seguinte mensagem: Digite a nota do simulado:. Neste momento devemos digitar a nota do simulado e pressionar enter.
Depois de ter inserido todas as notas o algoritmo irá realizar o cálculo das médias, exibindo apenas a média final e a situação do aluno.
Answer: from functools import partial

notas = list(map(float,list(iter(partial(input, 'Nota: '), ''))))

media_notas = sum(notas)/len(notas)

print(f'media: {media_notas:.2f}')

if media_notas == 6:

print('na media')
elif media_notas > 6:
print('acima da media')
else:
print('abaixo da media')

Answer: Tá aqui o que eu fiz, ta bem simplezinho mas serve.
     pn=float(input('Digite sua primeira nota: '))

     sn=float(input('Digite sua segunda nota: '))

     m=(pn+sn)/2

     if m<6.00:
         print('Você não passou com {} de média'.format(m))
     if m>=6.00:
         print('Você passou com {} de média'.format(m))

Duvida calcular média com Python 3.5


Must sambaAcctFlags have 11 characters?

Question: Still going through my LDAP database in my search for the wicked, I noticed a lot of accounts have sambaAcctFlags equal to [U], though the Samba docs says it should have 11 characters between [ and ] (and some actually do).
Is that a problem, or is 11 characters just an upper limit?
EDIT
Just to be clear, many entries are like this:
sambaAcctFlags: [U          ]

But some are like this:
sambaAcctFlags: [U]

It is the later I'm concerned about.
Answer: According to the passdb documentation on Samba.org, the account flag field can contain up to 16 characters. Presently, only 11 are in use.
I can confirm that we've been using it in production for many years with accounts having just one flag.
Comment: Not much a question of having one flag, but of the field being filled with spaces to make up 11 characters or not. I hadn't noticed that section (I was looking up the field name), so that's +1. I don't feel, however, confident that there's a definitive answer. Sure, it _works_ here, but that doesn't mean it may not cause subtle problems.

Must sambaAcctFlags have 11 characters?


Enemy movement to only follow player when in range using navmesh

Question: I am very new at C# (around 1 week in), so I have been following a lot of tutorials. I am at the moment trying to edit a piece of code (unity tutorial) to only have the enemy follow the player when in a certain range of the player  (10 foot), but unfortunately without changing the code completely, I cannot find a solution. At the moment the enemy will only follow the player when the player is alive (which i also want).
I've tried googling what I want, but I don't want to change the code from what is it too much. I am very new at c# and and currently learning bit by bit, other methods I have found require me changing the code a lot. As far as I understand, the main focus of the code below is for the enemy to be completely controlled by the Nav Mesh Agent, is it possible for me to keep the same technique?
using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour
{
    Transform player;
    PlayerHealth playerHealth;
    EnemyHealth enemyHealth;
    UnityEngine.AI.NavMeshAgent nav;

    void Awake()
    {
        // references
        player = GameObject.FindGameObjectWithTag("Player").transform;
        playerHealth = player.GetComponent<PlayerHealth>();
        enemyHealth = GetComponent<EnemyHealth>();
        nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
    }

    void Update()
    {
        if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
        {
            nav.SetDestination(player.position);
            transform.LookAt(player);
        }
        else
        {
            nav.enabled = false;
        }
    }
}

If possible, I would like to add 2 if functions. 1 being the check if the player is alive, and the other to check if the player is within distance. I don't know much about raycast at the moment, so will this be the next step for me to learn to get this to work how i want?
Thankyou for your time.
Dean.
Comment: you can calculate distance by doing `float distance = Vector3.Distance(player.transform.position,transform.position);`, do a check if it's no larger than some `amount` with `bool playerIsCloseEnough = distance <= amount;` and you can check if the player is alive with `bool playerIsAlive = playerHealth.currentHealth > 0;`. Then you can do things if they're both true with `if (playerIsAlive && playerIsCloseEnough) {...}`.
Comment: Perfect! Thank you, worked exactly how I wanted it to. I also had to set `nav.enabled=true;` within void awake for it to work with the nav mesh, for some reason it was disabling on startup. I also added `enemyHealth.currentHealth > 0 &&` to `if (playerIsAlive && playerIsCloseEnough) {...}` to stop the enemy from moving after it was dead.
Answer: You can calculate distance by doing:
float distance = Vector3.Distance(player.transform.position,transform.position);

You can do a check if it's no larger than some amount with:
bool playerIsCloseEnough = distance <= amount;

And you can check if the player is alive with:
 bool playerIsAlive = playerHealth.currentHealth > 0;

Then, you can do things if they're both true with:
if (playerIsAlive && playerIsCloseEnough)
{
    // ...
}

And as you mentioned in the comment, you'll need to set nav.enabled=true; in void Awake or void Start to make sure the nav mesh is turned on :)
Comment: You've been a great help Ruzihm, I've got the enemy movement working exactly how i want it for now :)


Split rows in multiple rows based on variable time condition

Question: I have shifts that work like this:
<code>  Shift horaIni     horaFin
0   A   00:00:00    08:00:00
1   B   08:00:00    16:00:00
2   C   16:00:00    23:59:59
</code>
Dataframe below is my input and I need to split a row according to the shifts. So if a row has an INITRA in shift A on day 1 and a FINTRA in shift C on day 3 I need to split that in multiple rows having all shifts and days. All other colum values of that row are repeated.
FOCUS ON ROW 1 (index 0)
<code>   col1 col2       INITRA               FINTRA     col3 col4 col5
0   C2  Y5  2021-02-15 22:07:00 2021-02-17 05:26:42 AA  AL  111871
1   X12 Y1  2021-02-15 22:00:36 2021-02-15 22:02:40 AA  AL  111863
2   S44 S1  2021-02-15 21:30:39 2021-02-15 21:44:51 AA  AL  111863
3   Z1  J7  2021-02-15 21:26:28 2021-02-15 21:28:00 AA  AL  111863
4   O9  H5  2021-02-15 21:14:29 2021-02-15 21:15:40 AA  AL  111863
5   O7  H8  2021-02-15 20:45:31 2021-02-15 20:46:39 AA  AL  111863
6   H8  Y5  2021-02-15 20:37:05 2021-02-15 20:38:10 AA  AL  111863
7   C2  Q1  2021-02-15 20:15:49 2021-02-15 20:27:22 AA  AL  111863
</code>
Expected result below
<code>  col1 col2 col3 col4  col5  dateIni      dateFin   horaIni      horaFin  Shift
0   C2  Y5  AA  AL  111871  2021-02-15  2021-02-15  22:07:00    23:59:59    C
1   C2  Y5  AA  AL  111871  2021-02-16  2021-02-16  00:00:00    08:00:00    A
2   C2  Y5  AA  AL  111871  2021-02-16  2021-02-16  08:00:00    16:00:00    B
3   C2  Y5  AA  AL  111871  2021-02-16  2021-02-16  16:00:00    23:59:59    C
4   C2  Y5  AA  AL  111871  2021-02-17  2021-02-17  00:00:00    05:26:42    A
5   X12 Y1  AA  AL  111863  2021-02-15  2021-02-15  22:00:36    22:02:40    C
6   S44 S1  AA  AL  111863  2021-02-15  2021-02-15  21:30:39    21:44:51    C
7   Z1  J7  AA  AL  111863  2021-02-15  2021-02-15  21:26:28    21:28:00    C
8   O9  H5  AA  AL  111863  2021-02-15  2021-02-15  21:14:29    21:15:40    C
9   O7  H8  AA  AL  111863  2021-02-15  2021-02-15  20:45:31    20:46:39    C
10  H8  Y5  AA  AL  111863  2021-02-15  2021-02-15  20:37:05    20:38:10    C
11  C2  Q1  AA  AL  111863  2021-02-15  2021-02-15  20:15:49    20:27:22    C
</code>
I was able to solve the problem for INITRA and FINTRA happening on consecutive shifts on the same day but when I have a greater difference I cant seem to solve it. My database has hundreds of thousands of rows.
I've been stuck on this for a while now. I appreciate any help. Thank you in advance
Answer: <code>from pprint import pprint
initra = ['2021-02-15 22:07:00','2021-02-15 22:00:36']
fintra = ['2021-02-17 05:26:42','2021-02-15 22:02:40']

dateIni = [t[:-9] for t in initra]
horaIni = [t[11:] for t in initra]
dateFin = [t[:-9] for t in fintra]
horaFin = [t[11:] for t in fintra]

updatedDatabase = [[],[],[],[],[]]

def generate_database(enterdate,exitdate,entertime,exittime,Shift):
    updatedDatabase[0].append(enterdate)
    updatedDatabase[1].append(exitdate)
    updatedDatabase[2].append(entertime)
    updatedDatabase[3].append(exittime)
    updatedDatabase[4].append(Shift)

def generate_shift(dateIni,dateFin,horaIni,horaFin):
    for index,elem in enumerate(dateIni):
        enterdate = dateIni[index]
        exitdate = dateFin[index]
        entertime = horaIni[index]
        exittime = horaFin[index]
        count = abs(int(dateIni[index][8:]) - int(dateFin[index][8:]))
        count = count if count != 0 else 1
        for h in range(3*count):

            if enterdate == exitdate:
                if int(entertime[:-6]) >= 0 and int(entertime[:-6]) < 8:
                    if int(exittime[:-6]) > 8:
                        generate_database(enterdate,enterdate,entertime,'08:00:00','A')
                        entertime = '08:00:00'
                    else:
                        generate_database(enterdate,enterdate,entertime,exittime,'A')
                        break

                elif int(entertime[:-6]) >= 8 and int(entertime[:-6]) < 16:
                    if int(exittime[:-6])> 16:
                        generate_database(enterdate,enterdate,entertime,'16:00:00','B')
                        entertime = '16:00:00'
                    else:
                        generate_database(enterdate,enterdate,entertime,exittime,'B')
                        break
                elif int(entertime[:-6]) >= 16 and int(entertime[:-6]) < 24:
                    if int(exittime[:-6])> 24:
                        generate_database(enterdate,enterdate,entertime,'16:00:00','B')
                        entertime = exittime
                    else:
                        generate_database(enterdate,enterdate,entertime,exittime,'B')
                        break

            else:
                if int(entertime[:-6]) >= 0 and int(entertime[:-6]) < 8:
                    generate_database(enterdate,enterdate,entertime,'08:00:00','A')
                    entertime = '08:00:00'

                elif int(entertime[:-6]) >= 8 and int(entertime[:-6]) < 16:
                    generate_database(enterdate,enterdate,entertime,'16:00:00','B')
                    entertime = '16:00:00'

                elif int(entertime[:-6]) >= 16 and int(entertime[:-6]) < 24:
                    generate_database(enterdate,enterdate,entertime,'23:59:59','C')
                    x = str(int(enterdate.replace('-','')) + 1)
                    enterdate = x[:-4]+'-'+x[4:-2]+'-'+x[6:]
                    entertime = '00:00:00'

generate_shift(dateIni,dateFin,horaIni,horaFin)

for i in range(len(updatedDatabase[0])):
    print(updatedDatabase[0][i],updatedDatabase[1][i],updatedDatabase[2][i],updatedDatabase[3][i],updatedDatabase[4][i])
</code>
Comment: you just assigned the shift considering the the inverval of INITRA and FINTRA. What I need is to split a row in multiple rows when my INITRA and FINTRA go through multiple shifts.
Comment: well this will work :), Now you just have to update database to your end
Comment: that almost worked but I was able to built something with your idea. Thank you so much for your help.

Just an observation: Instead of doing this:

                    x = str(int(enterdate.replace('-','')) + 1)
                    enterdate = x[:-4]+'-'+x[4:-2]+'-'+x[6:]

Its better to use .datetime + timedelta because it fixes the problem when you go over a month.

Thanks again for the help


Question about a corollary of Bessel inequiality

Question: I'm trying to prove:

Let $(X,<,>)$ be a vector space with inner product and $E \subseteq X$ be a orthonormal subset of $X$. Prove that
$\mathcal A$={$x \in E : |<y,x>| \neq0$} it's numerable.

Using the Bessel inequality that says:

Let $(X,<,>)$ be a vector space with inner product.
If {$x_i$}$_{i=1}^n$ are orthonormal then $\sum_{i=1}^n |<x_i,y>|^2 \le \|y\|^2 $ for every $y\in X$.

I have the suggestion to take $\mathcal A_n=${$x \in E : |<y,x>| ⩾1/n$} for every $n \in \mathbb N$ and aplly Bessel inequiality. I understand why it ends with this, but really don't see how make the $\mathcal A_n$ numerable with Bessel inequality.
Thank you.
Answer: Let $x\in A_n$. From Bessel inequality (and the fact that being $A_n\subseteq E$ it's an orthornomal subset of X) we obtain
$||y||^2\ge\sum_{x\in A_n} |\langle x,y \rangle|^2\ge
\sum_{x \in A_n} \frac{1}{n^2}$
Thus, if $A_n$ was infinite, the RHT would diverge, which is absurd since it is bounded by $||y||^2$.
Since $A_n$ is finite, $A=\bigcup_{n\in \mathbb{N}}A_n$ is numerable (being a numerable union of finite sets)
Comment: Thank you!!!!!!


How to join the `field_data_field_*` tables with `node` table using SQL?

Question: I apologize if I ask for something obvious, but I am asking because I could not find a simple answer anywhere.
I know how to work with these tables in the PHP Drupal code, which built-in functions to use, etc., but for some reasons, I have to write a literal SQL query to the Drupal database.
That's why I'm asking what condition I need to use in the SQL query to connect the field_data_field_abc table with the node table?
If the data in the field_data_field_abc table contains the entity_type column with the value "node", can I do something like this:
SELECT *
FROM node n
LEFT JOIN field_data_field_abc abc ON n.nid = abc.entity_id
WHERE abc.entity_type = 'node'

Comment: Take a look at this https://drupal.stackexchange.com/questions/121960/left-join-with-db-select and this https://www.drupal.org/forum/support/module-development-and-code-questions/2012-02-14/db_selectleft-join-vs-db_query
Comment: In fact, I only need to confirm whether I think well or wrong if I'm wrong, I'd like to ask you how to write some example query?
Comment: OK, thank you @berramou for these links. The content of these pages indirectly answers my question.
Answer: Yes, you are right :)
In general, for each table from field_data_field_* family, if its entity_type is equal to  the "node" value, then it can be associated with the n.nid from the node table and if the entity_type is equal to the "user" then the entity_id value is associated with the uid value from the users table.
I hope it will help somebody.


Nginx block for multiple domains to redirect all traffic to https?

Question: I have a web server running nginx 1.6 with one IP address and hosting www.domainname.com as well as dev.domainname.com.
I'm trying to find a smart way to route all http traffic to https and I want to make sure that my default server is the 'www' live version of the time. So the end goal is that unless the user specifies https://dev.domainname.com they will be redirected to https://www.domainname.com.
My nginx.conf setup is configured to include for '/etc/nginx/etc/sites-enabled/*'. So my configuration example is located at 'etc/nginx/sites-enabled/www.domainname.com'.
Also, to clarify. My current configuration has issues loading the dev site when you are visiting the domain without the www.
Edit: I just tried this method locally and http and https are not allowed in the '/etc/nginx/sites-enabled/'. Is there a better solution or should I move this configuration into the nginx.conf?*
So my question is there a better way to handle this type of setup?
http {

# all traffic should be over https
listen 80 default;

# listen for all server names
server_name *.domainname.com;

# redirect to www with https
return 301 $scheme://www.domainname.com$request_uri;

}

https {

# configuration for all https sites
listen 443 default ssl;
ssl on;

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

location ~ /\.ht {
    deny all;
}

# configuration for the non-www redirect
server {

    # non-www server name
    server_name domainname.com;
    # return to www
    return 301 $scheme://www.domainname.com$request_uri;

}

# configuration for the live website
server {

    # www server name
    server_name www.domainname.com;

    # root to public directory
    root /path/to/www.domainname.com/public;

    # ssl certificates
    ssl_certificate /etc/nginx/ssl/www.domainname.com/ssl-bundle.crt;
    ssl_certificate_key /etc/nginx/ssl/www.domainname.com/server.key;

    # error logs for www site
    error_log  /var/log/nginx/www.domainname.com-error.log error;

}

# configuration for the dev site
server {

    # dev server name
    server_name dev.domainname.com;

    # root to public directory
    root /path/to/dev.domainname.com/public;

    # ssl certificates - using multi domain ssl
    ssl_certificate /etc/nginx/ssl/www.domainname.com/ssl-bundle.crt;
    ssl_certificate_key /etc/nginx/ssl/www.domainname.com/server.key;

    # error logs for dev site
    error_log  /var/log/nginx/dev.domainname.com-error.log error;

}

}

Answer: All you need is this:
server {
       listen         80;
       server_name    *.domainname.com;
       return         301 https://$host$request_uri;
}

Comment: Worked a treat!
Answer: If your distribution is Debian-based, you have sites-available/default file installed. That is the file that configures default pages for nginx.
You need to disable this virtual host by running its symlink with rm sites-enabled/default.
Then, you need to make a new default with the following content:
server {
    listen 80 default_server;
    listen 443 default_server ssl;
    server_name _;

    ssl_certificate /path/to/your/certificate;
    ssl_certificate_key /path/to/your/key;

    redirect 301 https://www.domainname.com$request_uri;
}

This block makes sure that all requests to other domains not listed everywhere get redirected to https://www.domainname.com.
Then, make another file, for example dev.domainname.com:
server {
    listen 443 ssl;

    server_name dev.domainname.com;

    ssl_certificate /path/to/your/certificate;
    ssl_certificate_key /path/to/your/key;

    # Other config for dev.domainname.com
}

This block handles the requests for dev.domainname.com.
And finally, www.domainname.com:
server {
    listen 443 ssl;

    server_name www.domainname.com;

    ssl_certificate /path/to/your/certificate;
    ssl_certificate_key /path/to/your/key;

    # Other config for www.domainname.com
}

And this block handles requests for www.domainname.com.


How I can alter reCAPTCHA script tag in html_head

Question: The reCaptcha module adds a Javascript with hook_captcha(). I want to add another attribute "type" to this script tag. I can't find a hook to achieve this.
Here is the code from the recaptcha.module (line 118):
$captcha['form']['recaptcha_widget'] = [
        '#markup' => '

',
        '#suffix' => $noscript,
        '#attached' => [
          'html_head' => [
            [
              [
                '#tag' => 'script',
                '#attributes' => [
                  'src' => Url::fromUri($recaptcha_src, ['query' => ['hl' => \Drupal::service('language_manager')->getCurrentLanguage()->getId()], 'absolute' => TRUE])->toString(),
                  'async' => TRUE,
                  'defer' => TRUE,
                ],
              ],
              'recaptcha_api',
            ],
          ],
        ],
      ];

When I try to access the script tag with e.g. hook_page_attachments_alter() or any other hook_preprocess_xxxx() it is missing. I also tried to increase my module weight.
Comment: The code you tried already, especially the hook_page_attachments_alter() version would be helpful for figuring out what needs to be possibly adjusted to get this to work.
Comment: @StefanosPetrakis I didn't write any code, I just set a breakpoint and tried to find the script tag added by the recaptcha module. But it was not included in the data array (added after execution of this hook).
Answer: I would suggest using a #process callback and avoid code duplication.
This is what such a solution could look like:
/**
 * Implements hook_element_info_alter().
 */
function my_module_element_info_alter(array &$element) {
  if (isset($element['captcha'])) {
    $element['captcha']['#process'][] = '_custom_recaptcha_process';
  }
}

/**
 * Add type attribute to recaptcha form element.
 *
 * @return array
 *   The processed element.
 *
 * @see captcha_element_info()
 * @see image_captcha_element_info_alter()
 */
function _custom_recaptcha_process($element) {
  $recatchaWidgetHtmlHead = &$element['captcha_widgets']['recaptcha_widget']['#attached']['html_head'] ?? [];
  array_walk($recatchaWidgetHtmlHead, function(&$captcha_widget) {
    if ($captcha_widget[1] === 'recaptcha_api') {
      $captcha_widget[0]['#attributes']['type'] = 'value';
    }
  });
  return $element;
}

and this would be the output:

Good luck!
Answer: Since hook_captcha() is  a hook, you can override it by implementing it in your own custom module.
As long as your module has higher weight, it will run after recaptcha_captcha.
So basically copy all the code in recaptcha_captcha and rename the function name to mymodule_captcha and add the type to the #attributes array and you're golden.

In this rare case, the only way appears to be patching the module directly.
Hopefully you're using a composer managed site and all you have to do is create a patch and have composer auto apply it for you.
Comment: I am on D8 and D9. Yes I checked all this. The hook_catcha() function implements a new captcha type. The hook seems only to be invoked, when I select reCAPTCHA (from mymodule) as default captcha in the Captcha config form.
Comment: Sorry, I tried that before, but the hook does not invoke mymodule_captcha(). That's somthing I also don't understand. Something is missing here.
Comment: @JoachimFeltkamp are you on D7 or D8 or D9? and you doubled checked your custom module is enabled?
Comment: and did you rename the `mymodule` part to the actual name of your module? and you checked with the [modules weight](https://www.drupal.org/project/modules_weight) module that your custom module has indeed higher weight?
Comment: @JoachimFeltkamp after trying it out myself. I experienced the same issues. When I put a breakpoint on the custom module, it never breaks. Which means the hook is not ran. However, if add the type directly to the reCaptcha module, it works. Thus, seems the only way is to alter the module directly. Hopefully, you're using a composer manage site, and all you have to do is create a patch and have composer auto apply it for you when you do `composer install` or `composer update`


Java Lambda Expression for if condition - not expected here

Question: Consider the case where an if condition needs to evaluate an array or a List. A simple example: check if all elements are true. But I'm looking for generic way to do it
Normally I'd do it like that:
boolean allTrue = true;
for (Boolean bool : bools){
    if (!bool) {
        allTrue = false;
        break;
     }
}
if (allTrue){
     // do Something
}

But now I'd like to hide it into my if condition. I tried using Lambda Expressions for this, but it's not working:
if (() -> {
    for (Boolean bool : bools)
        if (!bool)
            return false;
    return true;
}){
      // do something
}

If this were working I could do something more complicated like
if (() -> {
   int number = 0;
   for (MyObject myobject : myobjects)
       if (myObject.getNumber() != 0)
           numbers++;
   if (numbers > 2)
       return false;
   return true;
 }{
     //do something
 }

Is there a better way to do it is it just a syntax error?
UPDATE
I'm not talking about the boolean array, rather looking for a generic way to achieve that.
Comment: Well, a `@FunctionalInterface` is not a `boolean` even if some of them return `boolean`s; you'd have to invoke that "interface" to have a boolean result anyway
Comment: Uh, use `.anyMatch()`?
Comment: @fge .allMatch () maybe? He wanta to return true if all are true
Comment: Could conceivably use `anyMatch` instead - just `!` the inputs and `!` the whole expression.
Comment: Thx, not aware of those functions. I'm actually looking for a generic way to do it, probably unclear here.
Comment: Uh, your question edit makes things very unclear -- what do you _need_? A count of elements matching a certain predicate?
Comment: @fge I wanted to use a lambda function in my if condition. But haven't been aware of stream functions, very nice new possibilities here.
Comment: Ok, nice that was the point!
Answer: You can write, given for instance a List<Boolean>:
if (!list.stream().allMatch(x -> x)) {
    // not every member is true
}

Or:
if (list.stream().anyMatch(x -> !x)) {
    // at least one member is false
}

If you have an array of booleans, then use Arrays.stream() to obtain a stream out of it instead.

More generally, for a Stream providing elements of (generic) type X, you have to provide a Predicate<? super X> to .{all,any}Match() (either a "full" predicate, or a lambda, or a method reference -- many things go). The return value of these methods are self explanatory -- I think.

Now, to count elements which obey a certain predicate, you have .count(), which you can combine with .filter() -- which also takes (whatever is) a Predicate as an argument. For instance checking if you have more than 2 elements in a List<String> whose length is greater than 5 you'd do:
if (list.stream().filter(s -> s.length() > 5).count() > 2L) {
    // Yup...
}

Answer: Your problem
Your current problem is that you use directly a lambda expression. Lambdas are instances of functional interfaces. Your lambda does not have the boolean type, that's why your if does not accept it.
This special case's solution
You can use a stream from your collections of booleans here.
if (bools.stream().allMatch((Boolean b)->b)) {
    // do something
}

It is actually much more powerful than this, but this does the trick I believe.
General hint
Basically, since you want an if condition, you want a boolean result.
Since your result depends on a collection, you can use Java 8 streams on collections.
Java 8 streams allow you to do many operations on a collection, and finish with a terminal operation. You can do whatever complicated stuff you want with Stream's non-terminal operations. In the end you need one of 2 things:

use a terminal operation that returns a boolean (such as allMatch, anyMatch...), and you're done
use any terminal operation, but use it in a boolean expression, such as myStream.filter(...).limit(...).count() > 2

You should have a look at your possibilities in this Stream documentation or this one.
Comment: This gives a syntax error for me: Incompatible types: cannot infer functional interface descriptor for Predicate


Consider the experiment of rolling two dice. If X =(second die−first die), then find the probability mass function of X.

Question: What should be the probability mass function for this question??
Comment: Welcome to MSE! Please use the [basic tutorial and quick reference guide](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) and also show the work you have done so far.
Answer: Just write down all possible values of $X$ and find the probabilities for each of those events. First find the range of $X$. In this case the range will be $1-6 = -5$ to $6-1 = 5$. So PMF can be found as follows:
$$P(X<-5) = P(X>-5) = 0$$
$$P(X = -5) = P(die2 = 1)P(die1 = 6) = \frac{1}{6}\frac{1}{6} = \frac{1}{36}$$
$$P(X = -4) = P(die2 = 2)P(die1 = 6)+ P(die2 = 1)P(die1 = 5) = \frac{2}{36}$$
$$P(X = -3) = \frac{3}{36}$$ and so on
Answer: Quick answer: same distribution as sum, but shifted so that it is centered at zero.  $P(X=0)=6/36$, $P(X=\pm 1)=5/36$ each, ..., $P(X=\pm 5)=1/36$ each.
Answer: Let A, B be the rolls of the first and second die, respectively, and $X=A-B$.
$\begin{matrix}
Rolls &A+B &Probability& A-B&Rolls\\
1,\textbf 1&2&\frac 1{36}&\textbf{-5}&1,6\\
1,\textbf2;2,\textbf1&3&\frac 2{36}&\textbf{-4}&1,5;2,6\\
1,\textbf3;2,\textbf2;3,\textbf1&4&\frac 3{36}&\textbf{-3}&1,4;2,5;3,6\\
...&...&...&...&...\\
6,\textbf4;5,\textbf5;4,\textbf6&10&\frac 3 {36}&\textbf{3}&4,1;5,2;6,3\\
6,\textbf5;5,\textbf6&11&\frac 2{36}&\textbf{4}&6,2;5,1\\
6,\textbf6&12&\frac 1{36}&\textbf{5}&6,1
\end{matrix}$
Notice that the pmf of $A-B$ follows a similar pattern as the pmf for $A+B$. In particular, the center is now at 0 (instead of 7), and the second dice now runs in the "opposite direction". The pmf is then, as stated in the quick answer, $P(A-B=\pm5)=\frac 1 {36} \text { each},...,P(A-B=\pm1)=\frac 5 {36} \text{ each},P(X=0)=\frac 6 {36}$.


Diferença entre o /dev/urandom e /dev/random

Question: Recentemente, li um post sobre o driver jdbc da oracle, falando que se fizesse a seguinte configuração na jvm rodando no Linux:
-Djava.security.egd=file:/dev/../dev/urandom

De acordo com a referencia, a geração de números randômicos com o urandom é mais rápida que o default, random. Qual é a diferença entre o urandom e random?
Comment: Sua pergunta não tem relação com Java e muito menos com JDBC. O fato de você ter visto em um tópico sobre JDBC onde alguém falou de um problema que teve porque lá nas profundezas do driver JDBC da Oracle, são usados números aleatórios para alguma coisa, não faz com que conhecimento em Java ou em JDBC seja relevante para catalogar ou para responder a sua pergunta. Assim sendo, estou removendo essas duas tags da sua pergunta.
Comment: Ambos são tipos de geradores de número pseudo-aleatório (conhecido como PRNG). A diferença até onde eu saiba é como cada um gerencia o uso da entropia (que é fonte verdadeiramente aleatória), pode ver mais em https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/.
Comment: Além disso, qual é o motivo de usar `file:/dev/../dev/urandom` ao invés de simplesmente `file:/dev/urandom`?
Comment: Eu retirei a url `file:/dev/../dev/urandom` do post, por isso eu a mantive. Eu relacionei a java e jdbc, porque o driver da oracle sugere essa alteração em seus manuais. Devo editar a pergonta?
Answer: São geradores de ruídos de sistema, ou seja, entropia.Esses ruídos são usados para fins de geração de números aleatórios e criptografia.Os dois são nativos dos sistemas Unix e sistemas Unix-like como o GNU/Linux e outros.O /dev/urandom pode ser usado para tudo menos para fins de segurança. Pois não há um sistema de travamento quando não atinge números entrópicos suficiente e, nesse caso, ele chuta o balde e diz: Que se dane! Vai assim mesmo.Já o /dev/random não tem a cabeça quente. Ele é como um mestre supremo das artes marciais. Tem muita paciência e possui um bloqueio que só libera quando se consegue entropia(ruídos) suficiente para gerar encriptação da ordem de 4096 bits ou mais.No windows o responsável por isso é o arquivo ksecdd.sys.Vale lembrar que nos sistema Unix-Like esse arquivo não é algo físico, ele reside na memória e, atualmente, a despeito dos kerneis mais antigo ele é somente leitura por questão de segurança.Bem é isso!PS: Ele só gera os ruídos, entropia, para que o openssl e o gnupg e outras ferramentas de encriptação possam gerar chaves de encriptação. Quando a gente está a gerar uma chave no GNU/Linux muitas vezes não tem entropia o suficiente e o /dev/random ativa o bloqueio e ai vem aquela mensagem para a gente fazer algo tipo mover o mouse feito louco, teclar no teclado ou assoviar e chupar cana ao mesmo tempo para ver se ajuda a gerar mais ruido no sistema.PS2: Os sistemas Unix-based como o GNU/Linux, usa, por padrão o /dev/random para fins de segurança. Como a maioria dos servidores e supercomputadores do mundo prezam por segurança, estabilidade e um código fonte que possa ser analisado para verificar que não exista nenhuma linha de código spybot seja de desenvolvedores da comunidade ou de organizações privadas ou governamentais, com certeza eles usam sistemas Unix-Like e, portanto, usam /dev/random, pois é o padrão dos sistema para fins de segurança.
Answer:
Fonte
Tanto o /dev/urandom quanto o /dev/random são capazes de gerar bits pseudo-randômicos com a diferença de que um está sempre disponível e o outro não.
Se o nível de entropia (do "Entropy Pool")  estiver abaixo o /dev/random deixará de funcionar, em tese. Enquanto isso na mesma situação o /dev/urandom continuará funcionando normalmente, mesmo em níveis críticos de entropia.

Entropia:
Em resumo a entropia é um repositório de dados verdadeiramente aleatórios. Por exemplo, temperatura dos processadores, uso de disco, consumo energético, uso de rede de internet, uso do teclado, uso do mouse...
Imagine que duas pessoas ligam o computador e entram num mesmo jogo online, uma pessoa pode usar uma sensibilidade diferente, cada jogador estará num ponto diferente do mapa fazendo andar mais e menos, a placa de vídeo renderizará pontos diferentes do mapa e o uso de memoria será diferente, o som produzido pelos passos e tiros serão diferentes.... No final  de uma partida a entropia coletada usando esses dados são completamente diferentes entre os dois jogadores, se então criptografássemos um trecho dessa entropia o resultado seria ainda mais diferente.
A entropia é basicamente os bits coletados a partir das atividades daquele dispositivo. Existem também hardwares/dispositivos específicos para essa atividade, como por exemplo o PQ4000KS e o TrueRNGpro que tendem a produzir bits verdadeiramente aleatório e que podem ser utilizados como entropia pelo próprio sistema, assim criando entropia mais "forte".
Também existe o polemico RdRand utilizado e integrado nos processadores da Intel, porém existem diversas críticas em relação ao seu uso. Ignorando isto o  RdRand seria um pequeno gerador verdadeiramente aleatório, assim abastecendo a entropia.
Pseudo-Randômico ("PRNG"):
Primeiro é preciso resumir o que é o PRNG, ele constitui de duas bases:
"Imprevisível" para "quem ver de fora" (mas previsível por dentro):
Os bits gerados devem ser imprevisíveis para quem observa o resultado de fora do sistema, basicamente imagine gerar vários número de 0 até 9, deve ser impossível saber o próximo número baseado na resposta anterior. Se deu 5, não pode ser possível saber que o próximo é 6, ou que se o próximo for 7 o outro vai ser 2. Além disso se gerar 6,3,4,5,1,7,7,8,4,2 deve ser impossível descobrir qual "seed" está sendo utilizada.
Uniformidade:
Um pseudo-randômico deve gerar resultados com mesmas chances, as mesmas as chances de 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 devem ser igual se gerar um número de 0 até 9. Um pseudo-randômico não pode gerar mais 9 do que 0, por exemplo se gerar 10000 números (de 0 até 9) não pode apenas uma única vez ter resultado em 0 e em 5000 vezes gerar 9.
O PRNG utiliza da entropia (que é verdadeiramente aleatória) para gerar outros bits. A entropia serve para gerar uma "senha", na verdade é gerada pelo CSPRNG, que gera uma hash dos bits da entropia, assim utiliza a hash resultante como uma "chave" (tecnicamente é mais chamado de seed) e por essa razão os algorítimos continuamente ficam "mudando de senha" (tecnicamente isso se chama re-seeding). Isso é feito para que possa garantir que gerará bits com maior segurança (entenda "segurança" como: manter os dois itens acima, "imprevisível" e "uniforme", evitando que a seed pode ter sido "vazada" ou tenha ficado previsível de alguma forma).

PS: Ficando claro que isso é uma tentativa de resumo, enfatizando pontos que acredito que seja importante! Porém existem outros detalhes, como gerar um CSPRNG baseado na entropia para então utilizar no PRNG que são bem importantes. Mas, para não haver confusão, o CSPRNG tem como base a criptografia, portanto não há "uniformidade" e deve ser verdadeiramente "imprevisível", seguindo as bases da criptografia...

/dev/random VS /dev/urandom:
Semelhanças:

Ambos são pseudo-aleatórios.

Diferença:

O random se não há entropia suficiente ele deixará de funcionar.
O random utiliza o "Entropy Pool".
O random mantêm o nível de entropia alto, mesmo que não possa "consumir".
O urandom não irá fazer o re-seed se não houver entropia suficiente, continuando a funcionar.
O urandom funcionará mesmo após o boot do sistema, onde não existe entropia suficiente, isso pode ser grave.
O urandom utiliza diretamente o resultado do CSPRNG não usando o "Entropy Pool".

Qual utilizar?
Pessoalmente urandom, mas primeiro dizer quem também usa o /dev/urandom:

BoringSSL (OpenSSL do Google) utiliza /dev/urandom.
GnuPG utiliza o /dev/urandom (exceto para geração de chaves, pode ser alterado manualmente).
OpenSSL parece utilizar o /dev/urandom, preciso verificar (me baseando em "On systems without /dev/urandom (or similar) device, it may be necessary to install additional support software to obtain a random seed.").

Agora os motivos de diferença entre os dois, que favorecem o /dev/urandom:

Sempre está disponível, exceto com o dispositivo recém ligado em alguns sistemas operacionais, consequentemente o seu software será muito mais estável.
Embora seja importante o re-seed, uma seed é suficiente para gerar muitos bits pseudo-randômicos.
Em qualquer situação (baixa ou alta entropia) o que será utilizado é o resultado do CSPRNG. A CSPRNG é, por ser criptograficamente seguro, tem como base ter uma saída imprevisível, essa é umas das "regras" da criptografia, mesmo em baixa entropia. Somente em raros casos isso seria um problema, se realmente a situação tiver literalmente critica, porque aí nem mesmo o CSPRNG não terá entropia suficiente.

Para todos os propósitos aconselho utilizar o /dev/urandom o seu software será muito mais estável (sem interrupções inesperadas) e terá resultados pseudo-aleatórios. Se quer resultados verdadeiramente aleatório nenhum dos dois irá cumprir esse objetivo.

Quando não usar o urandom?
Isso é delicado, geralmente para gerações de chaves de longa duração tende a acreditar que o uso do random seja melhor. Porém, boa sorte, vou aguardar digitar e mover o mouse ficar copiando arquivos para outro disco...
O uso do random para chaves de longa duração e emitidas com baixa periodicidade pode possível e recomendado, gerar uma chave por ano, ok. Porém se você vai gerar uma (ou mais) chave(s) a cada hora ou minuto isso pode passar a ser um problema, pois pode em diversas situações não haver como gerar as chaves devido ao random bloquear.
Isso piora se o uso do random feito por uma maquina diretamente. Imagine hipoteticamente que use um um crontab (uma tarefa agendada) para gerar uma nova chave por minuto, usando random. Não há como o software bater a cabeça no teclado para digitar alguma coisa, fazendo que fique sem chave por longo tempo, se for depender sempre desta chave já era.
O mesmo ocorre com as identificações de sessões, como os cookies, que precisam ser randômicos e não repetidos. Imagina ficar sem entropia e não há como gerar mais sessões?! Se utilizar o random isso pode ocorrer (isto é o comportamento padrão do PHP até o PHP 7, no PHP 7.1 em diante utiliza urandom, por exemplo).
O caso mais grave do urandom é no boot do sistema, quando com extrema certeza não haverá entropia suficiente e com certeza irá gerar dados extremamente previsíveis (em ambos os aspectos, para o sistema e para quem vê de fora). Algumas distribuições do linux, não sei se todas, guardam um arquivo na hora de desligar o sistema (não se aplica em caso de desligamento inesperado), assim quando liga o dispositivo o urandom utilizará o arquivo salvo como um seed. No caso do FreeBSD o urandom ficará bloqueado enquanto não houver entropia suficiente, apenas nesta situação.


How to extract type from string

Question: I need some way to reliably identify whether a string can be of another type eg. "1" would evaluate to 1 - an int, "2.0" would evaluate to 2.0 - a float and "John has 3 apples" would just evaluate to a string. Is there some package that does this - builtin or otherwise?
It would be great if it also worked on dates and currency
Answer: You can use try/except block for primitive types:
strings = ["1", "2.0", "John has 3 apples"]

def get_value(s):
    types = (int, float, str)
    for type in types:
        try:
            return type(s)
        except ValueError:
            pass

print(get_value(strings[0]))
print(get_value(strings[1]))
print(get_value(strings[2]))

Answer: You can do this with ast.literal_eval
int_type = ast.literal_eval("1")
float_type = ast.literal_eval("2.0")

But will only work on python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis

How to extract type from string


This problem is about Summation of two series

Question: I care about the results of $\large\sum\limits_{n = 1}^\infty  {\frac{1}{{{n^4} + {a^4}}}}$ and $\large \sum\limits_{n = 1}^\infty  {\frac{{{n^2}}}{{{n^4} + {a^4}}}} , (a\geqslant0)$ ,can you give me a help
Comment: Your question is phrased as an isolated problem, without any further information or context. This does not match many users' quality standards [link](https://math.meta.stackexchange.com/questions/9201/proposal-discourage-questions-that-are-nothing-besides-a-problem-statement), so it may attract downvotes, or be closed.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: Thanks for your care,I just made changes of my question,and wish you can have a look .
Comment: You could be interested in the fact that nobody has yet found a closed form for the series $$\sum_{n=1}^{\infty} \frac{1}{n^3}$$ (called Apery's constant). In other words, you can't always solve such series.
Answer: Hint
Write first
$$\frac 1 {n^4+a^4}=\frac{1}{\left(n^2-i a^2\right) \left(n^2+i a^2\right)}$$ Using partial fraction decomposition
$$\frac 1 {n^4+a^4}=\frac i {2a^2}\left(\frac{1}{n^2+i a^2}-\frac{1}{n^2-i a^2} \right)$$ and remember the famous
$$\sum_{n=1}^\infty\frac 1 {n^2+k}=\frac{\pi  \sqrt{k} \coth \left(\pi  \sqrt{k}\right)-1}{2 k}$$
Same approach for the second one.


Fingertip sensitivity/pain related to nail separation

Question: I've been playing for decades.  Every now and then  I do something that causes a fingertip on my fretting hand to be extremely sensitive — to the point where the slightest pressure causes pain.  I think I've finally figured out what's going on.
Every time I've had this pain, there's been a slight separation between the finger and the nail - not the entire nail, just that line where the nail separates from the finger moves back a tiny bit.  I've resisted this conclusion, because that's not where the pain comes from - it comes from the fingertip!  But every time I've had this problem, there has been a little fingernail separation.
So my question is, should I play through this, or wait until the pain goes away?
Comment: Can you describe the pain a bit more?  I occasionally get pain in my fingertips where it feels like I've damaged or "dislocated" the fleshy bit and the string is now pushing into my tendons or ligaments or something.  I wonder if that could be what you're referring to, though I haven't noticed anything going on with my nails.
Comment: I've had that problem too! It feels to me (since it's so sudden and so excruciating) that it's some sort of nerve hypersensitivity. Just like you say, the slightest pressure.. even typing at a keyboard, causes pain. Mine is so severe when it happens, there's no way I'd be able to play guitar… but it usually only lasts… I don't know… half an hour? At the most an hour, I'd say.
Comment: I just did that last night! Jabbed myself with the cat brush. ~24hrs later, pain is gone. Unless it's severe enough to cause you worry (psychosomatic amplification), you can tough it out. In fact, I think playing may help reduce pain faster by the creation of 'pleasant' sensations. FWIW, Apply with caution. :)
Comment: Related quesyion: http://music.stackexchange.com/questions/3567/causes-of-sharp-pain-in-a-fretting-finger-after-playing-guitar-or-bass
Answer: Bear with me.
Fingernail and toenail seperation is extremely painful. But, there is no mandatory function from having them. What I mean is, if you did not have your fingernails, you would still be able to function 100% except maybe scratching your noggin.
In fact, I have had my two big toenails removed for pain reasons. The pain is gone and the toes are fine.
Now, where I'm going with this is, the pain you are experiencing is not doing any real, life-altering damage. If you can play through the pain, there is no reason not to. On the other hand (pun noted), there are things you can do like seeing a doctor about the root cause of the pain.
For me, I use medical-grade moisturizer on my picking hand for a different, but possibly related problem. As long as I don't use it on days I'm playing out, it's a non-issue.
I wish you well!
Answer: I've been playing for a while now and had the same problem and I noticed that every once in a while the calluses fell off. Next time you have this problem, happens see if that's what is happening. Let me now if that works.
Comment: Welcome to Music SE! I've removed your email address per [this section of the FAQ](http://music.stackexchange.com/faq#signatures). You can place whatever you like on your user page, however. Thanks for the input!
Answer: Don't cut your fingernails too short. Only cut down the white part of your nail. In fact, leave a little bit of the white nail. This will stop this recurring problem for good!
Answer: This crops up with me at the strangest times.  I don't feel that I did anything unusual to start the process.  It is painful to play and I am no doctor but I know what works for me. After I do this, it relieves a lot of the discomfort and helps the separation heal faster. The tiny separation of the nail is not causing that much pain.  What is causing the intense pain is the additional skin buildup just below the nail that is basically extra material that, when you press on your finger tip, you push this extra material into the slight separation keeping it from healing quickly and causing the additional pain.  The extras material seems to build up over time.  Not sure why.  So what I do is take an exacto knife and carefully lift and remove the extra layer of skin buildup.  I have to use considerable magnification to see what I am doing.  It is really not painful at all just removing this extra layer.  With the layer gone, there is no extra thickness there to press into the nail separation.  Way less pain and it heels quickly after I do this.  This works for me and is just based on my experience over the years.
partial removal - and after complete
Answer: This is collation of what I felt were the best answers. First, do not attempt any of the auto–surgery approaches listed above. Instead, start with a visit to a manicurist. Explain the details of your problem. An experienced manicurist will definitely have seen more fingernail problems than one could possibly imagine. After your fingernails have been correctly trimmed, use a super-glue based first-aid brush-on liquid on the delineation section between the nail and underlying tissue. Use a nail brush daily to remove dead tissue and stimulate the strengthening of the connective tissue. A weekly trimming and a monthly visit to your new found manicurist will aid in the healing and strengthening process. Restrict practice sessions to no more than 45 minutes, with a 30-minute rest in-between. If you are using steel strings, switch off to classical strings for 6 weeks until the healing process has completed.
Answer: Not a direct answer to your question but a suggestion for the next time this happens.
I get this too. I've even had to cancel gigs due to this problem (don't worry. There were no riots). But I recently discovered something just a few days ago that will allow me to play through it. Just take some contact anesthetic like orajel or similar and press some up under the nail about a half hour before playing. I just used orajel because I saw some in the medicine cabinet the last time I had this problem. It worked quite well. Now I'm going to see if there's anything stronger but the orajel got me though it.
Answer: I have a tip for when this kind of pain happens. I have exactly the same problem, generally on fingers 2 and 3, and it is very painful! It prevents me from playing, especially pull-offs and bends.
MY SOLUTION : While it does not completely remove the pain, I scotch-tape my nail and my finger together, using a normal scotch tape cut in half to make it slimmer. I go around the finger for 2-3 laps, using maybe 2 inch tapes. It makes me able to play by keeping the nailbed and the nail firmly together. On these days, I won't bend and I will play carefully, but I'm able to give my lessons all day. I change the tape often.
Usually, the problems lasts less than a week, but it comes up often!
I really have to be careful not to cut my nail too short, I keep them unconfortably long but it makes the problem come up less often. It really sucks though, I'm thinking about removing the nails completely via surgery.
Answer: I heard Stevie used superglue when that happened. Anyone else hear that? I figured nail glue might be less toxic.
Answer: I don't think there is enough info in your description to evaluate the problem.  Is it really due to nail separation or something else?  The correlation you mention could be completely coincidental and not causal.  I have been playing for decades and can describe a few different fretting hand sensitivities.
(1) If you over practice on the electric (short nail or not) and you are doing a lot of string bending you may pull the finger nail away from the flesh a little.  Once that happens it will be harder to practice without pain for a while but once it heals your finger should be tougher and not likely to experience this again unless you (a) stop for a while then start up again or (b) increase your practice time thus causing more stress on the flesh.  This type of "injury" may become slightly infected and playing without bending can cause pain.
I must admit, when I was younger that kind of pain felt good so I played through it.  I don't think there is any long term damage from that but I couldn't tell you for sure.
(2) One the classical guitar the strings are quite a bit thicker and proper technique has our fretting fingers right up on the tip (about 90 degree angle from the finger board).  It can happen that one unfortunately hits a nerve ending in the tip of the finger causing a very "shocking" type of shooting pain through the finger.  This can get worse over time.  Sometimes a callus develops over the nerve and instead of protecting it the callus stabs the nerve every time your finger touches the string the wrong way.  Since this is an example of a nerve getting pressed I'd back off until it gets better.  Perhaps don't stop practicing but change the angle of attack for the fretting hand.  If you don't find a way to stop this you could cause permanent nerve damage.  Perhaps numbness or constant shooting pain (not sure).
(3) Another possibility is dried cracked skin on a callus.  Here the string can dig into the wound or just put pressure on it causing pain.
(4) Since you claimed that the nail is always separated from the flesh when it happens it could be that the rest of your finger has become sensitive to touch because of the wound.  I can't visualize how as I'm not a doctor, just speculating.
(5) Possible arthritis flare up. I have psoriatic arthritis and when it flares up the fingers become hyper sensitive to any touch. Of course this is usually on the joint and affects bar chords more than playing notes on the tip but I find that there is a sort of non-locality to pain during these flare ups.  Playing through arthritis pain is a double edged sword.  Movement is good for the joints but overdoing it I suspect could cause joint damage.
It is not a good idea for anyone to tell you would can or should "play through it".  That is bad advise without really seeing your hands.  If it's a persistent thing you should see a doctor. I share my personal experiences with you in the above comments.
Numbness and shooting pain = stop for a while, or back off, adjust your playing
Stinging wound pain = watch out that it doesn't get worse, avoid techniques that make it worse.
As for not cutting the nails back?  I cut mine very far back, every day.  I don't want to see a hair thickness of nail beyond the skin.  I will push the skin underneath the nail back a little and either cut or file them back.  And I don't have the problem you are describing on a regular basis.  Only if I cannot manage to practice, the fingers get "soft", then I go back to extreme practice sessions.  My fingers are used to it, and yours will be too in time.
Answer: Here is an image 2 1/2 hours after I removed the extra layer of hardened skin from just under my nail.
See my previous post from today 10/29/19
Answer: I might sound weird but my teacher use to do this.. also i do it.. and it never goes old... Apply a nail polish to the area which is exposed due to the separation.. it feels like hell when u apply it there.. bt after that the pain doesn't cause a problem while playing.. the reason behind this is simple.. the nailpolish, when dried, acts sort of like an adhesive to keep the exposed area cover and hold the nail close to the skin.. Let me know if it helps


Como eliminar colunas sem títulos e dados no dataframe criado a partir do Openpyxl

Question: Transformei o objeto Openpyxl (pasta_quimica), criado a partir de uma planilha, em um Dataframe.
<code># Transforma objeto openpyxl em DataFrame
dados = pasta_quimica.values
cabecalho = next(dados)[0:]
df = pd.DataFrame(dados, columns=cabecalho)
</code>
No dataframe pandas aparecem duas colunas no final, sem dados e sem título. Qual a melhor maneira de eliminar estas colunas, no Openpyxs ou no Pandas?
Resultado da conversão do objeto Openpyxl em dataframe
Comment: Tende o drop. Mais ou menos assim: `novo_df = df2 = df.drop(df.columns[[-2, -1]],axis = 1)`. Nao tenho certeza que indice negativo funciona... Qualquer coisa, pegue o numero de colunas com `len(df.columns)` e depois coloca os indices...
Answer: Abaixo os dados foram obtidos de um arquivo de log, e as colunas vazias foram removidas.
<code>df = pd.read_table('log_file.txt', sep=';')

#Remove empty column
for column in df:
    if 'Unnamed: ' in column:
        df.drop(columns=[column], axis=1, inplace=True)

df.columns = ['Folder','File','Hour','Channel','Command','Art']
df.to_excel('Sheet.xlsx', 'Sheet1', index=False)
print('Finished!')
</code>


How to remove comma from a number being dynamically inserted in the value of a key in the properties file / resource bundle?

Question: I am using Struts 2. I have a JSP. It has this code:

    <s:text name="page.key">
        <s:param value="%{request.id}" />
    </s:text>

request object is a member of my action class, and id is a property of the request object. id is of the type int.
In my properties file I have written the following text:
page.key=The request ID is {0}

My request id is a 6 digit number. Whenever it is displayed on the jsp it is displayed with a comma, eg: 765,239. I want it to be displayed without a comma, like this: 765239. I think the comma is being displayed because the data type of the id is int.
If I convert it to a string by writing the code below then the comma is not displayed.
<s:param value="%{request.id.toString()}" />

I want to know if instead of the above modification in the JSP can I do some modification in the properties file/resource bundle, like inserting a number format, to remove the comma in the number?
Answer: i think you are looking for setting the number format..
here is the documentation from Struts 2 regarding this.
format.number = {0} # i think this should do
Comment: Thank you very much for the answer and the link, modifying the key value in the properties file to the below mentioned value helped me get rid of the comma without modifying the JSP!!
`page.key=The request ID is {0,number,#}`


Is the sum of a number of ordinal variables still ordinal?

Question: I have performed a survey where I have a number of questions which can be answered Strongly Agree, Agree etc. to Strongly Disagree. Some of the questions have been designed to measure the same thing.
I have summed these variables to get a 'score' for this underlying trait, and I wish to predict this score in a regression
My question is then, can I still considered this summed variable an ordinal variable? And therefore should be using an ordinal regression. Or should I consider this now a continuous variable and use a simple regression?
There have been a few questions I have seen that discuss whether agree / disagree variables can be considered ordinal at all, and others which question whether it is ok to sum these kinds of questions, but I have not found one that discusses the properties of the new variable.
Comment: Well, you say they were asked if they strongly agree, agree, some neutral answer, disagree, strongly disagree. I assume you assigned them 5, 4, 3, 2, 1, right? Now think about this: if the respondents weren't told you were using that numerical scale, why aren't you using a different one? 5:1:1 is as good as 500,120,9,4,1, but surely this is not going to give you the same estimates, right?
Comment: If you are convinced by the answers already given to you then you might arrive to a reply to your exect question `can I consider the summed variable an ordinal variable? Or should I consider this now a continuous variable?`: that variable is generally _nominal_, neither ordinal or interval. It may prove to be ordinal occasionally, under some circumstances, - but who can say under which?
Comment: Thankyou all for the excellent response. I was also drawn to this question by the 1+4 = 2+3 = 5 idea, but was confused because I had been assured it was common practice to sum agree/disagree variables to capture an intrinsic trait. I had though that because these questions SHOULD be measureing the same thing, most people should be answering one way or the other. But I fear this is too big of an assumption, because you could never KNOW this. The responses here lead me to another question - how do people measure underlying traits with agree/disagree questions? Because I am sure it is being done
Answer: When you say things like 4+1 = 3+2 = 5, -- which you must do when you sum the components -- you (pretty much unavoidably) assumed they were interval at that time.
[If the components weren't interval, in general 4+1 $\neq$ 3+2 ... so you'd certainly have no business calling both of them "5".]
If the components were interval when you summed them, their sum is certainly interval.
[People may well disagree with me on this, but I can't see any basis for saying things like 4+1 = 3+2 = 5 -- along with all the similar statements that must be made -- unless you have assumed an interval scale. What basis would there be for thinking the summed-category-labels are equivalent outside the assumption that all gaps between adjacent values are equi-distant?]
Don't take this as an assertion that people should not add scale-items; in general I think it's a pretty reasonable thing to do. But in any case, once you do it, you shouldn't be uncomfortable about calling the sum interval-scale; you already went there.
Comment: +1. @SamPassmore: Think of a ordinal scale levels as twisted. So you cannot reliably sum them up. The only thing that you know is that ordinal scale is related to the unobserved "underlying" and "true" interval scale is some _unknown_ and _monotonic_ way.
Comment: @Alexis That we might both do so surprises me not at all. I actually recycled the example (4+1 vs 3+2) from a comment under an answer by Nick Cox that I made earlier today.
Comment: ZOMG we both used the same numeric example codes. :D
Answer: (What a fun question! My answer is a reflection, and others might have interesting opposing viewpoints.)
No. The pairs of ordinal numbers 1 & 4 and 2 & 3 both sum to 5. But suppose such variables were coding, for example, functional mobility in an individual, where 1 indicated no impairment, 2 impairment not requiring assistance, 3 impairment requiring assistance, and 4 immobility. The codes meaningfully represent a progression along a continuum of impairment. But problems obtain:

The idea of summing 'no impairment' and 'immobility' does not necessarily have conceptual validity (beyond two individuals with different experiences).
The substantive meaning of a sum=5 is unclear.
The meaning of an average of these numbers (i.e. a normalized sum), for example 2.5 (the average of 1 and 4, or 2 and 3) means what? Requiring or not requiring assistance in this example?
One of the individuals measured by the 1 and 4 pair will ever complete any kind of race, but both of the 2 and 3 pair will eventually traverse a distance.
Recall also that the many different quantities in ordinal codes will be ordinally identical (i.e. preserve rank), but will be radically different in quantity. For example the same four values above might be coded 0, 1.5, 7 and 92, both the sums and the averages change then, and ordering is not preserved in the resulting sums compared to the 1, 2, 3, 4 codes.
Comment: At the last point I prefer the coding "Jack, Queen, King, As" in order to prevent summation. How to sum them up clearly depends on the rules of the game, i.e. the unknown monotone transformation @ttnphns mentioned. ;)
Answer: In order to add the numbers of the codification of two ordinal variables you have to make two assumptions:
1- The distance between any two adjacent categories is the same in each variable. That is, if you measure the distance between categories as "the effort it takes to change a customer's mind", then you must consider that changing somebody's mind from "strongly disagree" to "disagree" takes the same effort as changing it from "disagree" to "neutral", etc.
2- The impact of scoring minimum and maximum is the same for each variable. One example in which this would not apply would be these two variables: "Do you like the service given by this company?" and "Do you like the candies on the front desk?". Of course, the impact of each variable on the overall evaluation is much different.
All this problems could be avoided if you tune the score that each category adds to the global punctuation, so for these two variables you could use:
"Do you like the service given by this company?" 100, 90, 30, 5, 0 (You consider "Agree" and "Strongly agree" as nearly the same answer, "Neutral" as a bad outcome, and "Disagree" and "Strongly disagree" as VERY BAD)
"Do you like the candies on the front desk?" 5, 4, 3, 2, 1 (In this case you may consider the first assumption as real, but of course this variable contributes much less than the previous one to the global image of your company)
Another BIG problem is how to tune the category scores properly. In this case I can only say... Good luck, and don't forget to tell me how to do it!
Answer: I guess there are enough answers that state that sum of ordinal variables is itself not a well defined concept. But the OP mention Likert scales and indeed there are arguments that it is OK to sum up the Likert items (each answer) which results in what can be considered an interval number! See the discussion on scoring and analysis on the wikipedia page of Likert scales


Unable to find field when running test on Device Farm

Question: I'm trying to write a test using Java/TestNG running on AWS's Device Farm; however I cannot find my "account" field.
HomePage.java
public class HomePage {

    @iOSFindBy(accessibility = "account")
    public IOSElement accountField;

    public HomePage(AppiumDriver driver) {
        PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this);
    }
}

Test Class
@BeforeMethod
public void setup() throws MalformedURLException {
    DesiredCapabilities capabilities = DesiredCapabilities.iphone();
    driver = new IOSDriver<IOSElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}

@Test
public void selectAccount() throws InterruptedException {

    driver.manage().timeouts().implicitlyWait(35, TimeUnit.SECONDS);

    HomePage page = new HomePage(driver);
    new TouchAction(driver).tap(page.accountField).perform();
}

Running this test on device farm gives me this error:
selectAccount failed: Can't locate an element by this strategy: Locator map: - native content: "By.AccessibilityId: account" - html content: "by id or name "account""

Relevant Local Logs
...

[MJSONWP] Responding to client with driver.createSession() result: {"webStorageEnabled":false,"locationContextEnabled":false,"browserName":"","platform":"MAC","javascriptEnabled":true,"databaseEnabled":false,"takesScreenshot":true,"networkConnectionEnabled":false,"app":"/Users/..../Downloads/.....ipa","platformVersion":"11.3.1","automationName":"XCUITest","platformName":"iOS","udid":".....","deviceName":"iPhone SE"}
[JSONWP Proxy] Proxying [POST /elements] to [POST http://localhost:8100/session/1470E279-8FD3-4CFE-944C-051CDF7F2A25/elements] with body: {"using":"accessibility id","value":"account"}
[JSONWP Proxy] Got response with status 200: {"value":[{"ELEMENT":"0C000000-0000-0000-1701-000000000000"}],"sessionId":"1470E279-8FD3-4CFE-944C-051CDF7F2A25","status":0}
[MJSONWP] Responding to client with driver.findElements() result: [{"ELEMENT":"0C000000-0000-0000-1701-000000000000"}]

...

Relevant Device Farm Logs
...

New IosDriver session created successfully, session 1dd93c26-55f6-4fdd-9963-2e3dbbc17386 added to master session list
[BaseDriver] Event 'newSessionStarted' logged at 1528814874003 (14:47:54 GMT+0000 (UTC))
[MJSONWP] Responding to client with driver.createSession() result: {\"webStorageEnabled\":false,\"locationContextEnabled\":false,\"browserName\":\"iPhone\",\"platform\":\"MAC\",\"javascriptEnabled\":true,\"databaseEnabled\":false,\"takesScreenshot\":true,\"networkConnectionEnabled\":false,\"platformName\":\"iOS\",\"version\":\"\",\"platformVersion\":\"9.3\",\"deviceName\":\".....\",\"app\":\"/tmp/scratch4iVs4j.scratch/share-CjbXpc.scratch/app-3ZPujz.ipa\",\"udid\":\".....\",\"desired\":{\"browserName\":\"iPhone\",\"platformName\":\"iOS\",\"version\":\"\",\"platform\":\"MAC\",\"platformVersion\":\"9.3\",\"deviceName\":\".....\",\"app\":\"/tmp/scratch4iVs4j.scratch/share-CjbXpc.scratch/app-3ZPujz.ipa\",\"udid\":\".....\"}}

...

[MJSONWP] Responding to client with driver.getCurrentContext() result: \"NATIVE_APP\"
<-- GET /wd/hub/session/1dd93c26-55f6-4fdd-9963-2e3dbbc17386/context 200 18 ms - 84
--> POST /wd/hub/session/1dd93c26-55f6-4fdd-9963-2e3dbbc17386/elements {\"using\":\"accessibility id\",\"value\":\"account\"}
[MJSONWP] Calling AppiumDriver.findElements() with args: [\"accessibility id\",\"account\",\"1dd93c26-55f6-4fdd-9963-2e3dbbc17386\"]
[iOS] Executing iOS command 'findElements'
[BaseDriver] Valid locator strategies for this request: xpath, id, class name, -ios uiautomation, accessibility id
[BaseDriver] Waiting up to 0 ms for condition
[UIAuto] Sending command to instruments: au.getElementsByAccessibilityId('account')
[UIAuto] Socket data received (25 bytes)
[UIAuto] Got result from instruments: {\"status\":0,\"value\":[]}
[MJSONWP] Responding to client with driver.findElements() result: []
<-- POST /wd/hub/session/1dd93c26-55f6-4fdd-9963-2e3dbbc17386/elements 200 834 ms - 74

...

I have made a screen shot after the 35 second implicit wait and confirmed my field is on the page.
I have also tried this method for selecting the account field without success:
@Test
public void selectAccount() throws InterruptedException {

    driver.manage().timeouts().implicitlyWait(35, TimeUnit.SECONDS);

    WebElement el = driver.findElement(By.name("account"));
    new TouchAction(driver).tap(el).perform();
}

Does anyone have an idea on how to find my "account" field? This works locally using appium.
Comment: Could you please add the appium server logs from the device farm test and your local execution?
Comment: Sure! Let me know if you need more info from them. I've tried messing around with the device capabilities with no luck. I've tried a couple other techniques for waiting on the element to get on the page also: I added `@WithTimeout(time = 5000, unit = TimeUnit.MILLISECONDS)` below the `@iOSFindBy` annotation and added this wait command `WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(page.account));`after `HomePage page = new HomePage(driver);` with no luck. All still passes locally, just not on device farm
Comment: It looks like Device farm is  using uiautomation and I bet your local logs are using xcui. Could you confirm that when you have the chance?
Comment: If that is the case try using an iOS device with OS level of 10 or greater and see if it works then.  Device farm should choose xcui as the automation name then if it's not set in code and it might make a difference.
Comment: Hey sorry for the late response. I can confirm that the local test run is using xcui. It seems that IOS 11 works on device farm but IOS 10 and less does not work even after setting the automationName device capability to XCUITest. Going off of https://github.com/appium/appium/blob/master/docs/en/drivers/ios-xcuitest.md, that's the only capability that I would need to manually set since device farm takes care of the platformName, platformVersion, deviceName, and app capabilities right? Am I missing something to make < iOS11 devices work? It Also it seems like `plus` phones do not work IOS 11
Comment: Try again but don't set the automation name. Device Farm will choose it on our behalf and trying to use that capability may conflict with what device farm does. From my experience it will use XCUI for iOS 10 and above and uiautomation for lower than 10.

I think this difference is the cause of the issue. If you use uiautomation locally does the same issue happen?
Comment: any update on the local execution using uiautomation?
Comment: Hello again, I have decided to test the current devices working on Device Farm for now to get things moving again. Thank you for all the help. I will circle back around to this in the future to see if I can get through it.
Answer: I'm testing an Android app in ADF, and was facing the same issue, but setting up the automationName desired capability works for me.
capabilities.setCapability("automationName", "uiautomator2");