Fourier Series of a Constant Function

Question: My question is kinda dumb, but here I go: I'm studying Fourier Series on my own for my next semester. I needed to calculate the Fourier Series of the function $f(x) = 5$ defined in $[-4,4]$.
In this case, using the standard notation, $L = 4$ are the coefficients are
$a_{0} = \dfrac{1}{L} \displaystyle \int_{-L}^{L} f(x) \ dx$; $a_{n} = \dfrac{1}{L} \displaystyle \int_{-L}^{L} f(x) \cdot \cos\bigg(\dfrac{n\pi x}{L}\bigg) \ dx$ and $b_{n} = \dfrac{1}{L} \displaystyle \int_{-L}^{L} f(x) \cdot \sin\bigg(\dfrac{n\pi x}{L}\bigg) \ dx$, correct?
Since the function is constant the sines and cosines must have no contribution to the Fourier series at all, i.e., $a_{n} = b_{n} = 0$, but when I'm doing the calculations I'm getting $a_{n} = \dfrac{10}{\pi n} \sin(\pi n)$. It must be a pretty dumb mistake I'm not seeing, I'm kinda new at this subject.
Thanks for the help :]
Comment: Check the values of  $\sin \pi, \sin 2\pi, \dots $
Comment: $sin(\pi) = 0$, etc, those terms should naturally die out
Comment: You're correct. Notice that the sines are equal to zero, therefore $a_{n} = 0$ for all $n > 0$.
Comment: $\sin (n \pi) = 0 \ \forall \, n \in \mathbb{Z}$
Answer: This complements the previous answers by providing an additional answer to the title: Fourier series approximation of a constant.
The answers before are all correct for the example presented over the domain $x\in[-4,4]$. Now consider the case of the sine Fourier series for $f(x)=1$ in the interval $x\in(0, \pi)$. You need to create the odd extension of $f(x)$, i.e. $f(x)=-1, \;x\in[-\pi,0)$ (I want $f$ to be piecewise continuous in $x\in(-\pi, \pi)$). In such case,
$$a_{n}\equiv0\text {, whereas}$$
$$b_{n} = \dfrac{2}{\pi}\int_{0}^{\pi}\sin{(nx)}dx = \dfrac{2}{\pi}\left[1 - (-1)^{n} \right]$$
With this, the sine Fourier series approximation to the constant function $f(x)=1$ in $x\in(0, \pi)$ is
$$1 = \dfrac{4}{\pi}\sum_{n=0}^{\infty}\dfrac{\sin[(2n+1)x]}{(2n+1)}$$
This approximation has some issues at the end points $x=\{0, \pi\}$ which results from the discontinuity of the odd extension, converging to $f(0)=f(\pi)=0$. Not a problem when considering the open interval $x\in(0, \pi)$. All in all, this presents a well documented example in which the Fourier series is not the average ($a_{0}=1$). Besides, the sine series of a constant arises in the 1D wave equation with constant forcing, with Dirichlet bc on one end and Neumann bc on the other end.
enter image description here
Answer: As a footnote to the other answers/comments showing that $a_n$ and $b_n$ are zero for all $n>0$, it is important to see that this means that the "Fourier series" of a constant function is actually just the constant function itself.
In a normal Fourier series one can shift it up or down with this constant term $a_0$. However, in this case, the constant term is all you need: you just put $f(x)=a_0=5$ and make the coefficient in front of the other terms zero.
Answer: $a_n = $$\frac {1}{L}\int_{-L}^L 5\cos(\frac {n\pi x}{L}) dx\\
\frac {1}{L}(5\sin(\frac {n\pi x}{L})(\frac {L}{n\pi})|_{-L}^L\\
(\frac {5}{n\pi})(\sin( {n\pi})-\sin(-{n\pi})) = 0$
since $\sin( {n\pi}) = 0$
$b_n = $$\frac {1}{L}\int_{-L}^L 5\sin(\frac {n\pi x}{L}) dx\\
\frac {1}{L}(-5\cos(\frac {n\pi x}{L})(\frac {L}{n\pi})|_{-L}^L\\
(\frac {-5}{n\pi})(\cos( {n\pi})-\cos(-{n\pi})) = 0$
since $\cos x$ is an even function.

Fourier Series of a Constant Function


Unicode characters in NSString

Question: Here is my code and the logs, it will be more efficient than a long speech :)
NSString* cat = [categories objectAtIndex:i];
NSLog(@"category : :%@:", cat);
NSString* decodedString = [NSString stringWithUTF8String:[cat cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(@"category decoede : %@", decodedString);

LOG : category : :Boissons fra?ches:
And after, I get this exception : *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString'
I just want to convert strings like "Boissons fra?ches" in "Boissons fraîches". How can I do ?
EDIT
I just want to get content of a CSV file. My complete code is :
// Getting content of CSV file
NSError* error;
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"csv"];
NSString* data = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:&error];
NSArray* categories = [data componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

for (int i = 0; i < categories.count; ++i) {
    NSString* cat = [categories objectAtIndex:i];
    NSLog(@"categorie : :%@:", [categories objectAtIndex:i]);
    NSString* decodedString = [NSString stringWithUTF8String:[cat cStringUsingEncoding:[NSString defaultCStringEncoding]]];
    NSLog(@"categorie : %@", decodedString);
    [self.categories addObject:decodedString];
}

Comment: You have loaded the file using `NSASCIIStringEncoding`. If the file is truly ASCII, then it can't properly represent "Boissons fraîches" and the data was lost. However, I suspect the file is not ASCII. You must find out what encoding was used to create the file. If it comes from a program, hopefully that program documents the encoding it used.
Comment: Look here: http://macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
Comment: What encoding is the actual CSV file? Try `NSUTF8StringEncoding` if you don't know. Or try running the `file` command on the file from the command line. That should show you the file's encoding.
Comment: @rmaddy : I try your command and this is what I get : `categories.csv: Non-ISO extended-ASCII text, with CR line terminators`.

I already tried `NSUTF8StringEncoding` and the NSString called `data` is null :/
Comment: How was the CSV file created? As Ken stated in his comment, look into the tool used to create the file. If you have the option, recreate the CSV file again but specify that you want UTF-8 encoding. This is always best. Otherwise, try all of the different encodings. Start with `NSWindowsCP1252StringEncoding` is you used MS Windows or `NSMacOSRomanStringEncoding` is you used a Mac.
Comment: First use characterAtIndex to extract the problem character and print its decimal value.  Then look up that character in the likely character set maps to see what character set was used.  Then, ideally, work backwards to the creation of the NSString to use the correct encoding, otherwise translate the character individually to what you need.
Comment: As @KenThomases notes, you should not have used NSASCIIStringEncoding. The important thing to note is that when Cocoa says "ASCII" it really means ASCII, not "extended ASCII" or some other "ASCII-like" encoding. The character î cannot be encoded in ASCII.
Comment: @rmaddy : I created a file with Microsoft Excel, it was a XLSX file before the conversion.
Comment: @Seb Hopefully Excel gives you the option to export the spreadsheet using UTF-8 encoding. This would be the best option.
Comment: @rmaddy How can you do this ?
Answer: The C string conversion is failing because you have a character in the original string that cannot be represented in the default C string encoding (which is MacRoman, an older 8-bit encoding similar to ISO Latin-1.)
I'm not entirely sure what you're trying to do, but [NSString defaultCStringEncoding] is almost never the encoding you want to use. If you can elaborate, I might be able to provide another approach to the problem.
Comment: I edited my question in order to precise my aim. Thanks for your help.
Comment: I just want to convert my string with strange characters to a normal and readable string.
Answer: Instead of using NSASCIIStringEncoding in [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:&error], you need to find out the encoding of the text file and use the appropriate enum value.

Unicode characters in NSString


Intuition for geometric product being dot + wedge product

Question: While I feel quite comfortable with the meaning of the dot and exterior products separately (parallelity and perpendicularity), I struggle to find meaning in the geometric product as the combination of the two given that one's a scalar and the other is a bivector:
$ ab = a \cdot b + a \wedge b $
I can't shake the feeling that you can't add apples and oranges and produce something meaningful.
I feel like Lagrange's Identity is saying something similar for dot and cross products, while at the same time relating them to a circle/pythagoras:
$ \vert a \vert^2 \vert b \vert^2 = \vert a \cdot b \vert^2 + \vert a \times b \vert^2 $
but for some reason it's just not clicking. I'd love to hear suggestions for how to think about this and what it means.
Comment: How do you feel about complex numbers? Is `a+ib` apples and oranges?
Comment: perhaps geometric products are not actually as geometric as the name suggests?
Comment: @Rob3c thats a good point but complex numbers seem less like apples and oranges because its easy to think of "4 + 5i" as similar to the vector $ 4 \hat{i} + 5 \hat{j} $ or as a rotation.
Comment: @KevinGoodman see my answer for how the geometric product can similarly be seen as a rotation operator.
Answer: Some authors define the geometric product in terms of the dot and wedge product, which are introduced separately.  I think that accentuates an apples vs oranges view.  Suppose instead you expand a geometric product in terms of coordinates, with $ \mathbf{a} = \sum_{i = 1}^N a_i \mathbf{e}_i, \mathbf{b} = \sum_{i = 1}^N b_i \mathbf{e}_i $, so that the product is
$$\mathbf{a} \mathbf{b}= \sum_{i, j = 1}^N a_i b_j \mathbf{e}_i \mathbf{e}_j= \sum_{i = 1}^N a_i b_i \mathbf{e}_i \mathbf{e}_i+ \sum_{1 \le i \ne j \le N}^N a_i b_j \mathbf{e}_i \mathbf{e}_j.$$
An axiomatic presentation of geometric algebra defines the square of a vector as $ \mathbf{x}^2 = \left\lVert {\mathbf{x}} \right\rVert^2 $ (the contraction axiom.).  An immediate consequence of this axiom is that $ \mathbf{e}_i \mathbf{e}_i = 1$.  Another consequence of the axiom is that any two orthogonal vectors, such as $ \mathbf{e}_i, \mathbf{e}_j $ for $ i \ne j $ anticommute.  That is, for $ i \ne j $
$$\mathbf{e}_i \mathbf{e}_j = - \mathbf{e}_j \mathbf{e}_i.$$
Utilizing these consequences of the contraction axiom, we see that the geometric product splits into two irreducible portions
$$\mathbf{a} \mathbf{b}=\sum_{i = 1}^N a_i b_i+ \sum_{1 \le i < j \le N}^N (a_i b_j - b_i a_j) \mathbf{e}_i \mathbf{e}_j.$$
The first sum (the symmetric sum) is a scalar, which we recognize as the dot product $ \mathbf{a} \cdot \mathbf{b}$, and the second (the antisymmetric sum) is something else.  We call this a bivector, or identify it as the wedge product $\mathbf{a} \wedge \mathbf{b}$.
In this sense, the dot and wedge product sum representation of a geometric product, are just groupings of terms of a larger integrated product.
Another way of reconciling the fact that we appear able to add two unlike entities, is to recast the geometric product in polar form.  To do so, consider a decomposition of a geometric product in terms of constituent unit vectors
$$\mathbf{a} \mathbf{b} = \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert \left( { \hat{\mathbf{a}} \cdot \hat{\mathbf{b}} + \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right),$$
and assume that we are interested in the non-trivial case where $ \mathbf{a} $ and $ \mathbf{b} $ are not colinear (where the product reduces to just $ \mathbf{a} \mathbf{b} = \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert $).  It can be shown that the square of a wedge product is always non-positive, so it is reasonable to define the length of a wedge product like so
$$\left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert = \sqrt{-(\hat{\mathbf{a}} \wedge \hat{\mathbf{b}})^2}.$$
We can use this to massage the dot plus wedge unit vector sum above into
$$\mathbf{a} \mathbf{b} = \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert \left( { \hat{\mathbf{a}} \cdot \hat{\mathbf{b}} +\frac{\hat{\mathbf{a}} \wedge \hat{\mathbf{b}} }{\left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert}\left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert} \right).$$
The sum has two scalar factors of interest, the dot product $ \hat{\mathbf{a}} \cdot \hat{\mathbf{b}} $ and the length of the wedge product $ \left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert $.  Viewed geometrically, these are the respective projections onto two perpendicular axes, as crudely sketched in the figure

That is, we can make the identifications
$$\hat{\mathbf{a}} \cdot \hat{\mathbf{b}} = \cos\theta$$
$$\left\lVert { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right\rVert = \sin\theta.$$
(Aside: Admittedly, I've pulled this sine/wedge identification out of a black hat, but it follows logically from study of projection and rejection in geometric algebra.  The black hat magic trick may at least be verified by computing the length of the "rejection" component of the vector $\hat{\mathbf{a}}$, that is, $\hat{\mathbf{a}} - \hat{\mathbf{b}} \left( {\hat{\mathbf{a}} \cdot \hat{\mathbf{b}}} \right)$, which has squared length $ 1 - \left( {\hat{\mathbf{a}} \cdot \hat{\mathbf{b}}} \right)^2$.  Expanding $ -\left( { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right)^2 = -\left( { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right) \cdot \left( { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right) = -\hat{\mathbf{a}} \cdot \left( { \hat{\mathbf{b}} \cdot \left( { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right) } \right) $ produces the same result.)
Inserting the trigonometric identification of these two scalars into the expansion of the geometric product, we now have
$$\mathbf{a} \mathbf{b} = \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert \left( { \cos\theta +\frac{\hat{\mathbf{a}} \wedge \hat{\mathbf{b}} }{\left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert}\sin\theta} \right).$$
This has a complex structure that can be called out explicitly by making the identification
$$\mathbf{i} \equiv\frac{\hat{\mathbf{a}} \wedge \hat{\mathbf{b}} }{\left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert},$$
where by our definition of the length of a wedge product $ \mathbf{i}^2 = -1 $.
With such an identification, we see that the multivector factor
of a geometric product
has a complex exponential structure
$$\begin{aligned}\mathbf{a} \mathbf{b}= \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert \left( { \cos\theta + \mathbf{i} \sin\theta } \right)= \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert e^{\mathbf{i} \theta }.\end{aligned}$$
In this view of the geometric product, while we initially added two apparently dissimilar objects, this was really no less foreign than adding real and imaginary portions of a complex number, and we see that the geometric product can be viewed as a scaled rotation operator operating in the plane spanned by the two vectors.
In 3D, the wedge and the cross products are related by what is called a duality relationship, relating a bivector that can be interpreted as an oriented plane, and the normal to that plane.  Algebraically, this relationship is
$$\mathbf{a} \wedge \mathbf{b} = I (\mathbf{a} \times \mathbf{b}),$$
where $ I = \mathbf{e}_1 \mathbf{e}_2 \mathbf{e}_3 $ is a unit trivector (often called the 3D pseudoscalar), which also satisfies $ I^2 = -1 $.  With the usual normal notation for the cross product $ \mathbf{a} \times \mathbf{b} = \hat{\mathbf{n}} \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert \sin\theta $ we see our unit bivector $\mathbf{i}$, is related to the cross product normal-direction by $\mathbf{i} = I \hat{\mathbf{n}} $.  A rough characterization of this is that $ \mathbf{i} $ is a unit (oriented) plane that is spanned by $ \mathbf{a}, \mathbf{b} $ normal to $ \hat{\mathbf{n}}$.
The intuition of that the geometric product and the Lagrange identity are related is on the mark.  There is a wedge product generalization of the Lagrange identity in geometric algebra.  The 3D form stated in the question follows from the duality relationship of the wedge and cross products.
Comment: That's an interesting angle to come at this from - thanks! Btw, which author did you find that approaches things that way? Incidentally, I think showing ab as the product of the norms times the inner and outer product of the unit vectors is a neat way to quickly see that the vector product produces an area scaled according to the relative orientation of the vectors. Same for when you relate it to Euler's e^i. A question though: at one point you wrote the norm of the dot product is sin, did you mean wedge product instead?
Comment: @KevinGoodman, Yes, I meant the wedge.  That's fixed.  The axiomatic approach can be found in many sources (one is "Geometric Algebra for Physicists").  The angle interpretation of the product can also be found in many places (I think that Alan MacDonald's "Linear and Geometric Algebra" may have been one of them.)
Comment: Can you clarify how you recognized that the opposite side of the triangle you drew would be: $ \left\lVert {\hat{\mathbf{a}} \wedge \hat{\mathbf{b}}} \right\rVert $? (Unless the hypotenuse was intended to be:  $ \left\lVert {\mathbf{a}} \right\rVert \left\lVert {\mathbf{b}} \right\rVert $ ?) It's not obvious to be how the previous equation led to that.
Comment: I didn't show that, but it's not too hard to do.  The rejection component of that vector is $\hat{\mathbf{a}} - \hat{\mathbf{b}} \left( {\hat{\mathbf{a}} \cdot \hat{\mathbf{b}}} \right)$ which has squared length $ 1 - \left( {\hat{\mathbf{a}} \cdot \hat{\mathbf{b}}} \right)^2$.  If you expand $ -\left( { \hat{\mathbf{a}} \wedge \hat{\mathbf{b}} } \right)^2 $ you'll get the same result.
Comment: I've edited the answer to at least describe where this magic trick comes from.
Comment: Why does the contraction axiom imply that orthogonal vectors anticommute?
Comment: For orthogonal vectors $\mathbf{a}, \mathbf{b}$, we have

$(\mathbf{a} + \mathbf{b})^2 = (\mathbf{a} + \mathbf{b}) \cdot (\mathbf{a} + \mathbf{b}) = \mathbf{a}^2 + \mathbf{b}^2$

but also:

$(\mathbf{a} + \mathbf{b})^2 = \mathbf{a}^2 +  \mathbf{a} \mathbf{b} + \mathbf{b} \mathbf{a} + \mathbf{b}^2$.  By comparison, we see that:

$\mathbf{a} \mathbf{b} + \mathbf{b} \mathbf{a} = 0$.
Answer: Yes, you are adding apples and oranges. But there is a sense in which one can add apples and oranges: put them together in a bag. The apples and oranges retain their separate identities, but there are "apples + oranges" are in the bag.
The situation with the inner and outer products of vectors is analogous: the bag is $ab$ and $a \cdot b$ and $a \wedge b$ are "in" it.
Adapted from my text Linear and Geometric Algebra.
Comment: For what it is worth,  $(\mathbf{a}\mathbf{b})^2 = (\mathbf{a} \cdot \mathbf{b})^2 - (\mathbf{a} \wedge \mathbf{b})^2$ with $(\mathbf{a} \wedge \mathbf{b})^2 < 0$ is more basic. (Lagrange's identity).
Comment: @KevinGoodman Ah, good point. Yes, length/norm is extended to all sums of "apples and oranges" in a natural way, and we have $|\mathbf a\mathbf b|^2=|\mathbf a\cdot\mathbf b|^2+|\mathbf a\wedge\mathbf b|^2$ when $\mathbf a$ and $\mathbf b$ are vectors, just like the pythagorean theorem.
Comment: @MarkS. I meant orthogonal in the same sense that a right triangle has opposite and adjacent sides that are orthogonal because Lagrange's Identity seems to be ~= a restating of Pythagorus applied to the vector product equation. It's in that sense that I *think* the inner and outer products are orthogonal components of the vector product...?
Comment: In the comments for OP above, robc pointed out that components of complex numbers also have the property of seeming like apples and oranges. So a complex number might also be thought of as a bag like you describe. Is Lagrange's Identity saying that the inner and outer products are orthogonal components of the vector product, just as the real and imaginary components of a complex number are orthogonal? Is that a reasonable way to think of them?
Comment: @KevinGoodman It depends what you mean by "orthogonal". If you just mean "add component-wise", then definitely yes. If you meant something more, I don't think it's very natural to think that way. You'd sort of give up the geometry of geometric algebra to claim that there was a sense in which nonzero scalars are orthogonal to nonzero bivectors (or individual 2-blades/2-wedges).
Answer: As I alluded to in my original comment, the isomorphism to complex numbers (that other answers also mention) is a good path to thinking about it...assuming complex numbers are ok intuitively, that is! :-) The symmetric dot product part corresponds to the real part of a complex number, and the antisymmetric wedge part corresponds to the imaginary part.
However, i prefer the following intuition for both in terms of how the math works out (without actually doing the math, of course lol):
The geometric product between two vectors produces a geometric operator that can perform a scaled rotation of another vector (or other GA objects via linearity) according to the properties of the relationship it captures between the two vectors: their relative angle and magnitudes. However you label it, the main intuition for visualizing it is that it is an operator with the potential to rotate something, rather than being a rotation itself (or 'directed arc' a la Hestenes, which creates more confusion than clarity IMHO).
To see it easily without cranking through the details, note that the geometric product results in a value with scalar and bivector parts. When multiplying a third vector by the product (now an operator), the operator's scalar part will just create a weighted version of the vector along its same direction, and the operator's bivector part will created a weighted vector in its orthogonal direction, since wedging a vector with a bivector 'cancels' any part in the shared direction. The sum of those two vector 'components' results in the third vector being essentially rotated/scaled, depending on all of the relative magnitudes and angles.
Answer: The most intuitive interpretation of a Geometric Product I have found is from Hestenes who notes that it can be visualized as a directed arc just as a vector can be viewed as a directed line.

For more depth, see page 11 of the following:
Hestenes - Oersted Medal Lecture.
Comment: That's really cool, but not at all obvious. Lol I'll definitely take a look at that link!
Answer: I'll try to explain why there are no apples and oranges, there are only reflections. The apples and oranges appear because in order to actually compute the geometric story I'm about to tell you, we use an orthogonal basis.
Vectors can be thought of as representing (hyper)planes. For example, in 3D space a vector can be used to represent a plane through the origin. Now, a plane $u$ can be reflected in a plane $v$ using
$$ v[u] = -vuv^{-1}, $$
where the minus sign is needed such that when you reflect $v$ in itself, the front and back of the mirror flip ($v[v] = -v$). If we now also perform a reflection in a second plane $w$, we get the rotation
$$ w[v[u]] = (wv)u v^{-1} w^{-1} = (wv) u (wv)^{-1} $$
The composition of two reflections $wv$ is called a bireflection, and could in fact be either a rotation, translation, or a boost. The picture below shows how two intersecting reflections form a rotation, while parallel reflections form a translation.

So the product of two vectors is a bireflection.
The apples and oranges only appear because in order to actually compute it, we would have to somehow choose a basis. Staying with the 3D example, we could choose an orthogonal basis $e_1, e_2, e_3$ such that $e_i e_j = \delta_{ij} + e_{ij}$ and represent any plane as $x = \sum_i x^i e_i$.
Now, when we compute the bireflection $wv$ we will get a scalar and bivector part:
$$ w v = \sum_{ij}(w^i e_i) (v^j e_j) = \sum_i w^i v^i + \sum_{i \neq j} w^iv^j e_{ij}. $$
So just remember the truth: there are no apples and oranges. For more detail on this approach I would refer to this video, or to the Graded Symmetry Groups paper. Full disclaimer: I'm one of the authors.


Multiple types of media held in playlist in Java

Question: I'm currently trying to write a playlist in Java.
The idea is that it can support many different types of media...
Music: mp3, flac, wav, etc
Video: avi mp4 etc
Music/Video from weblinks
I'm planning to maintain all these in one list. I'm trying to figure out a best approach. Should I implement a common interface for MediaItem which agrees a contract needed for each media item type (represented by different classes) or should I deal with all types in one class?
Any help is much appreciated.
Comment: IMO 'a) the interface'  Please don't add sigs. to the text of questions.
Answer: I discovered the javaFx libraries offer a Class called Media which represents different types of media.


find a function in cakephp

Question: I am learning cakephp. can someone explain me what this is for
<code>$this->RunFunction->bindModel(array('belongsTo'=>array('Audio','Image','Video')));
</code>
where would I find the RunFunction. Its in a plugin folder of cakephp
Answer: Is it a model in the plugin?  The models would be found in app/plugins/pluginname/models...
So app/plugins/name/models/run_function.php I guess.
Comment: Cake has its conventional methods of naming things... file names containing underscores turn into camel-cased class objects.  Takes a bit of getting used to, but I think it's pretty consistent...
Comment: I see it there but why is it run_function instead of RunFunction.php
Comment: @Autolycus if your question is answered, indicate so with a tick ;)

find a function in cakephp


Add Special Symbols to the end of a line in Notepad++

Question: I have a huge file and I know how to add some then at the end or start of line. I've following scenario
aaaaa
bbbbb
ccccc
And I need to add ") by the end of the line but add only " and missed ).
Is there someone who could help me to figure it out?
Comment: It was resolved, by using alt+shift+keyDown or keyUp combination at the end of the line and then paste what was required.
Answer: You need to escape the parenthesis in the replacement part:
Find what: $
Replace with: "\)
At the bottom of pop up box for replacing, change Search Mode to Regular expression(no need match newline)


Does $(\alpha=\int_{-\infty}^{\infty} f(x)\, \mathrm{d}x)$ follow from $(\lim_{k\to \infty} \int_{a_k}^{b_k} f(x)\,\mathrm{d}x=\alpha)$?

Question: Today I learned a bit about integrals and I'd like to know if that is true, or if there is a counterexample that disproves the following:
When an $(\alpha\in \mathbb{R})$ exists, so that for all sequences $((a_k)_{k\in \mathbb{N}}, (b_k)_{k\in \mathbb{N}} \subset\mathbb{R})$ with $(a_k\to -\infty, b_k\to \infty)$ for $(k\to \infty)$ already $(\lim_{k\to \infty} \int_{a_k}^{b_k} f(x)\,\mathrm{d}x=\alpha)$ applies, then the following $(\alpha=\int_{-\infty}^{\infty} f(x)\, \mathrm{d}x)$ applies too.
My thoughts are that when $(a_k\to -\infty, b_k\to \infty)$ for $(k\to \infty)$ applies, then at some time (meaning for $(k\geq k_0)$ with a $(k_0\in \mathbb{N}))$ the following: $(a_k<0)$ and $(b_k>0)$ hold.
So the integral can be split like that: $(\int_{a_k}^{b_k} f(x)\mathrm{d}x=\int_{a_k}^{0} f(x)\mathrm{d}x+\int_{0}^{b_k} f(x)\mathrm{d}x)$ which leads us to the definition of improper integrals.
Is my argumentation correct or wrong? Because from $(\lim_{n\to \infty} (c_n+d_n))$ the existence of $(\lim_{n\to \infty}c_n)$ or $(\lim_{n\to \infty}d_n))$ do not follow...
Answer: The claim is correct: Using the assumption show that
$$\lim_{k\rightarrow\infty}\int_{c_k}^{d_k}f=0$$
for any two sequences $c_k,d_k\rightarrow\infty$, or equivalently
$$\lim_{x,y\rightarrow\infty}\int_x^yf=0$$
Hence By Cauchy $\lim_{x\rightarrow\infty}\int_0^xf$ converges. Similarly $\lim_{x\rightarrow-\infty}\int_x^0f$ converges so overall $f$ is integrable over $\mathbb{R}$. Choosing $a_k=-k,\ b_k=k$ gives you the integral is $\alpha$.
Your argument is wrong for the reason you have mentioned.


AppCompat and ViewPagerIndicator fragments submenu not showing

Question: I have a pretty simple use case which does not work with the AppCompat library on Android 8.
I have one Activity that includes two fragments that can be swipped between using a TabPagerIndicator. The first of the fragments shows an SubMenu on the ActionBar, the second does not.
When starting the activity the first fragment is shown. Clicking the SubMenu correctly shows the SubMenu items for selection. However, if swiping to fragment two and back again, clicking the SubMenu does nothing.
Instead of supplying large blocks of code here, I have created a sample project that shows the problem. It is on github: https://github.com/foens/appcompatsubmenu/
Shortcuts:

Activity code
Fragment with menu
Fragment without menu
Menu xml
Activity layout

What am I doing wrong?
Comment: I've the same problem. Even in some device the submenu can never show. I've made sure that the menu uses `myapp:` prefix instead of `android:` in the `res/menu`.
Answer: Code has been removed, so I presume your problem has been resolved (and this question should be as well).
A shot in the dark though - the issue may be that you're missing setHasOptionsMenu.  Without it, the onCreateOptionsMenu is not reliably called when switching tabs, and your menu isn't populated.
<code>@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setHasOptionsMenu(true);
}
</code>


Atlassian Confluence with Active Directory Authentication

Question: I have one question about the Confluence and Active Directory Integration. We have successful intergration and users are now authenticated against the AD. But the problem is when user enters wrond windows credentials, instead of give message like "Invalid Username/Password" it is throwing an exception. Does anyone had seen this issue? We also contact the support on Confluence but I solution is turn off AD authentication and use DB authentication.
<code>org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:626)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:314)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy7.publishEvent(Unknown Source)
at com.atlassian.confluence.user.ConfluenceAuthenticator.login(ConfluenceAuthenticator.java:39)
at com.atlassian.seraph.filter.PasswordBasedLoginFilter.login(PasswordBasedLoginFilter.java:59)
at com.atlassian.seraph.filter.BaseLoginFilter.doFilter(BaseLoginFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.plugin.servlet.filter.IteratingFilterChain.doFilter(IteratingFilterChain.java:46)
at com.atlassian.plugin.servlet.filter.ServletFilterModuleContainerFilter.doFilter(ServletFilterModuleContainerFilter.java:54)
at com.atlassian.plugin.servlet.filter.ServletFilterModuleContainerFilter.doFilter(ServletFilterModuleContainerFilter.java:40)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.confluence.util.ClusterHeaderFilter.doFilter(ClusterHeaderFilter.java:35)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.johnson.filters.AbstractJohnsonFilter.doFilter(AbstractJohnsonFilter.java:72)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:170)
at com.atlassian.spring.filter.FlushingSpringSessionInViewFilter.doFilterInternal(FlushingSpringSessionInViewFilter.java:29)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.util.profiling.filters.ProfilingFilter.doFilter(ProfilingFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.confluence.core.datetime.RequestTimeThreadLocalFilter.doFilter(RequestTimeThreadLocalFilter.java:34)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.confluence.util.RequestCacheThreadLocalFilter.doFilter(RequestCacheThreadLocalFilter.java:25)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.gzipfilter.GzipFilter.doFilterInternal(GzipFilter.java:81)
at com.atlassian.gzipfilter.GzipFilter.doFilter(GzipFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.plugin.servlet.filter.IteratingFilterChain.doFilter(IteratingFilterChain.java:46)
at com.atlassian.confluence.extra.webdav.servlet.filter.ReverseProxyFilter.doFilter(ReverseProxyFilter.java:427)
at com.atlassian.confluence.extra.webdav.servlet.filter.AbstractHttpFilter.doFilter(AbstractHttpFilter.java:34)
at com.atlassian.plugin.servlet.filter.DelegatingPluginFilter.doFilter(DelegatingPluginFilter.java:57)
at com.atlassian.plugin.servlet.filter.IteratingFilterChain.doFilter(IteratingFilterChain.java:42)
at com.atlassian.plugin.servlet.filter.ServletFilterModuleContainerFilter.doFilter(ServletFilterModuleContainerFilter.java:54)
at com.atlassian.plugin.servlet.filter.ServletFilterModuleContainerFilter.doFilter(ServletFilterModuleContainerFilter.java:40)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.atlassian.core.filters.AbstractEncodingFilter.doFilter(AbstractEncodingFilter.java:33)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)
</code>
Answer: Do you have the full <>/logs/atlassian-confuence.log file that I can review?
Feel free to tweet me your Support ticket number, and I can reopen and independently take a another look at what the root cause of the transaction deadlock on AD authentication failure.
Hope this helps.
Twitter: @vincent_choy
Support Team Lead - Confluence


cache.match returns undefined in my react js pwa

Question: caches.match returns undefined and delete my stored cache or my cache is being deleted for any reasons and cache.match can't match anything
i'm trying to make a working pwa, i register the service worker directly on my index.html and it succeeds, and my service worker for the moment have only this
const CACHE_NAME = 'version-1'

const urlsToCache = [
    'index.html',
    'static/js/main.a1ae2d16.js',
    'service-worker.js',
    '/manifest.json',
    '/logo192.png',
    '/favicon.ico',
]

const self = this;

self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => {
                console.log('Opened cache')
                return cache.addAll(urlsToCache)
            })
    )
})

self.addEventListener('fetch', async (event) => {
    event.respondWith(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log(cache)
                cache.match(event.request.url, {ignoreVary: true})
                    .then(response => {
                        console.log(response)
                        if (response) {
                            return response
                        }
                    })
            })
    )
})

the install event is working as expected, on my first time in the page it store in cache the listed requests, but when i refresh the page, in the fetch event occurs an error because the respondWith gets a undefined, because my cache.match returns as resposne in my callback an undefined (always) even if in the previous load of the page i saw the request stored in cache, also when i log cache it's an empty object and when i look into my stored cache again it's now empty, i don't know if it's being cleaned for any reason when i reload the page or if the cache.match don't match anything and respondWith broke the page and the cache because it receive an undefined
sorry for my grammar, if i forget to explain something useful please let me know
Answer: Try adding '/' to the cached routes.
Also you should return a fallback value like fetch(event.request.url).


How to send new message-based invites without GKMatchmakerViewController

Question: For some reasons we do not want to use the GKMatchmakerViewController. Currently we are offering the user of our App the possibility to invite their Game Center friends via a friends list displayed in our UI.
While this is still possible in iOS 10, the user will no longer have the possibility to add the GC friends. Therefore we want to use the new message-based invites introduced in iOS 10.
How can this be archived without using the GKMatchmakerViewController? I just want to display a button invite friends which opens the view to send message-based invites to anybody exactly as the button in the GKMatchmakerViewController does.
Comment: Don't know why this was voted down. I voted up. :) Any success?
Answer: It is currently (iOS 10.2) not possible to display the iMessage view without the GKMatchmakerViewController.
In my app, I'm going to still provide fully custom views for the matchmaking. Only if a player on a device with iOS 10 wants to invite a friend, I'll display the GKMatchmakerViewController. This is not a great solution but currently, it seems like the most feasible workaround.
I'll also file an issue for that in Apple's bug reporter.
Comment: can you clarify a little, you're using `GKGameSession`'s for iOS 10 games with friends and ordinary `GKMatch` with `GKPlayer`'s for other matches? I don't see any built in matchmaking mechanism for `GKGameSession`...
Answer: See GKGameSession. This class can send invite link. May be ios10 only


Linear Transformation with eigenvectors and eigenvalues

Question: Let $\;T : R_2 \to\ R_2\;$ be the linear transformation that reflects
$\left(
\begin{array}{c}
    x \\
    y \\
  \end{array}
\right)$
in the
line $\;y = mx\;$, that is, in the line $\left(
\begin{array}{c}
    x \\
    y \\
  \end{array}
\right)$
= $\;t\;$
$\left(
\begin{array}{c}
    1 \\
    m \\
  \end{array}
\right)$
for $\;t ∈ R\;$.

i) Explain why
$\left(
\begin{array}{c}
    1 \\
    m \\
  \end{array}
\right)$
and
$\left(
\begin{array}{c}
    -m \\
    1 \\
  \end{array}
\right)$
are eigenvectors of $T$ and find the
corresponding eigenvalues.
ii) Let $A$ be the matrix representation for $T$. By finding matrices $P$, $D$,
with $D$ diagonal such that $P^{−1}AP = D$, (or otherwise), find an
explicit formula for the matrix $A$.
Thank you
Comment: in i) , I can't even explain why the 2 vectors are eigenvectors of T
Comment: Hi and welcome! Can you please show some of what you tried so far?
Comment: Have you tried drawing a picture (for $m=2$, say)?
Comment: Doing basic geometry (line perpendicular to other line, middle point of a line segment, intersection point of two lines, etc.), can you prove that, provided $\;m\neq 0\;$ , a point $\;(a,b)\in\Bbb R^2\;$ is mapped by $\;T\;$ to $\;\left(a-\frac{2b}m\,,\,\,2ma+b\right)\;$ ? This is the first, basic step. Then apply this to a a basis of $\;\Bbb R^2\;$ and etc.
Answer: An eigenvector is a vector such that $T \vec v=\lambda \vec v$. This means that such a vector, when transformed by $T$, change its length but non chang its direction, i.e. $T \vec v$ stay on the same straight line as $\vec v$.
Helping with a drawing you can easily see that the eigenvectors of your transformation can only stay on the given line $r$ of equation $y=mx$ or on its orthogonal line passing by the origin, i.e. the line $y=-\frac{1}{m}x$. All other vectors in the plane, when reflected on $r$, ''jump''  on an other straight line. And since
$$
\vec v_1=
\left[
\begin {array}{ccccc}
 1\\
 m\\
\end {array}
\right]
\qquad
\vec v_2=
\left[
\begin {array}{ccccc}
 -m\\
 1\\
\end {array}
\right]
$$
are  vectors on those two lines, they are eigenvectors.
Now note that $\vec v_1$ is a fixed point of $T$ so that its eigenvalue must be $\lambda_1=1$ and $\vec v_2$ is changed by $t$ in a vector that has opposite coordinates, so that its eigenvalue is $ \lambda_2=-1$.
The matrices of your second question is:
$T=PAP^{-1}$ where $A$ is the diagonal matrix having $a_{11}=\lambda_1$ and $a_{22}=\lambda_2$, and $P$ is the matrix that have as columns the eigenvectors, so you have:
$$
P=
\left[
\begin {array}{ccccc}
 1&-m \\
 m& 1
 \end {array}
\right]
\qquad
P^{-1}=
\dfrac{1}{1+m^2}
\left[
\begin {array}{ccccc}
 1&m \\
 -m& 1
 \end {array}
\right]
$$
$$
A=
\left[
\begin {array}{ccccc}
 1&0 \\
 0& -1
 \end {array}
\right]
$$
and if you perform the product $T=PAP^{-1}$ you find the searched matrix.
To complete the exercise use  $m=\tan \theta$ to show that the matrix $T$ has the form:
$$
T=
\left[
\begin {array}{ccccc}
\cos 2\theta&\sin 2\theta \\
\sin 2\theta& -\cos 2\theta
 \end {array}
 \right]
$$
that is the general form of a reflection in the plane.


Intervals on which function is increasing and decreasing

Question: Let $p(x)=x^5-q^2x-q$ , where $q$ is a prime number. I want to understand how to determine when the function will be decreasing and increasing on the intervals given below.
We compute $p^{\prime}(x)=5x^4-q^2$ and look for the critical points.
$5x^4-q^2=0\Longleftrightarrow x=\pm \frac{\sqrt{q}}{\sqrt[4]{5}}$
Hence we have to investigate the behavior of $p^{\prime}(x)$ for each of these intervals
$(-\infty,-\frac{\sqrt{q}}{\sqrt[4]{5}})$, $(-\frac{\sqrt{q}}{\sqrt[4]{5}},\frac{\sqrt{q}}{\sqrt[4]{5}})$ and $(\frac{\sqrt{q}}{\sqrt[4]{5}},\infty)$ this will indicate when the function will be increasing and decreasing. How can this be determined when the expression $\frac{\sqrt{q}}{\sqrt[4]{5}}$ contains a prime number???
The answer should be : the function will be increasing for $x<\frac{\sqrt{q}}{\sqrt[4]{5}}$ and strictly decreasing for $-\frac{\sqrt{q}}{\sqrt[4]{5}}<x<\frac{\sqrt{q}}{\sqrt[4]{5}}$ and strictly increasing again for $x>\frac{\sqrt{q}}{\sqrt[4]{5}}$
Can someone explain this last part?
Thank you
Comment: You are asked to determine wether $p'(I_i)$ is less than or greater than zero for each one of the intervals you have determined, $I_i$.
Comment: That is exactly what I am asking for. How to determine whether the derivative will be positive or negative on these intervals?
Comment: Are there any restrictions on the value of $q$?
Comment: nope, it just says, $q$ is a prime number
Comment: Oh, you're right. I see it now in the question. Well, we know that $x=0 \in I_2 \equiv (-\sqrt{q}/5^{1/4},\sqrt{q}/5^{1/4})$ and we have $p'(0) = -q^2 < 0$ and therefore $p(x)$ is decreasing on $I_2$.
Comment: Nicely done. Do you know how to proceed with the remaining two ones?
Comment: Hi, @user124471, my guess would be: since $p''(x) = 20 x^3$, we have that $p''(x < -\sqrt{q}/5^{1/4}) < 0 $ and $p''(x > \sqrt{q}/5^{1/4} )> 0$ and therefore, $p'(x)$ is monotonically increasing on $I_3$ and monotonically decreasing in $I_1$. Since we have proved that $p'(r_i)=0$, $p'(I_1)>0$ as well as $p'(I_2)$. Then, it follows the OP's answer for the character of $p(x)$.
Comment: this makes sense, thank you
Comment: These can be nicely shown in a more intuitive way by sketching $p'(x)$ and $p''(x)$. If you want me to post this as an answer, let me know.
Answer: Assuming we have $q\gt 0$, the derivative is positive whenever $5x^4\gt q^2$, or equivalently $\sqrt 5 x^2\gt q$
This can happen two ways, either with $\sqrt[4]5x\gt \sqrt q$ if $x$ is positive, or $-\sqrt[4]5x\gt \sqrt q$ if $x$ is negative.
For a negative derivative, the inequalities are reversed.
I am not sure what you mean by "contains a prime number" - the function is presumably being taken over the real numbers, over which the [positive real] square and fourth roots of non-negative real numbers are well-defined.
Comment: Thank you, I understand it now.


Comparison of object property to string fails in Vue

Question: Conclusion: It was a typo.
I'm trying something something which seems simple, but I think I'm missing out on something fundamental to Vue. I have an id, and an object with once child property that contains an object with that id. When I loop through the object properties to compare the id, it is false. When I log the values that were compared in the else statement after the comparison, they appear to be identical in the console log.
Whatever I try it, I keep ending up on the "bad package" line.
The console shows me that the object property is there and that the id of the object at that property is correct. It looks like:
bad package  c5186ae5-1558-490b-a9d2-5fc19c0a736d  !==  c5186ae5-1588-490b-a9d2-5fc19c0a736d
I suspect it is something to do with observables in Vue, even though the log doesn't show anything as an observable.
What's the right way to do what I'm trying to do?

// newVal = '29e51254-a88a-4309-92bc-ad1d0cda1427'
collectionIdForVerification (newVal) {
         const parcelId = this.$store.state.parcels.collectionIdForVerification
         // this print the object, it looks good
         console.log('Parcels are ', this.requestedParcelsForCollection)
         console.log('local parcels are ', this.local.parcels)
         const loParcOb = JSON.parse(JSON.stringify(this.local.parcels))
         console.log('local parcels are ', loParcOb)
         console.log('does the parcel for ', newVal, ' exist? ', this.local.parcels[newVal])
         if (newVal) {
           const packages = loParcOb
           console.log('lets check ', packages, ' for ', parcelId)
           const rightPackage = loParcOb[parcelId]
           console.log('right package is ', rightPackage)
           for (let x in loParcOb) {
             let ob = loParcOb[x]
             console.log('object: ', ob)
             if (ob.id.toString() === parcelId) {
               console.log('good pagage ', ob)
             } else {
               // this shows me that the two compared things are equal
               console.log('bad package ', ob.id.toString(), ' !== ', parcelId)
             }
           }
         }
       }

Object:

// object
{
displayImage: "https://static.xxxx.co/couriers/dhl/dhl_detail.png"
expiration: 1573486971237
id: "29e51254-a88a-4309-92bc-ad1d0cda1427"
name: "MacBook from YYYY"
passcode: ""
recipient: {xxxId: "0cbf8068-a286-49c5-bdf7-7509ac953b5f", yyyId: "b925b763-992e-4ad3-98b1-ba8fba2ef37e"}
sender: {xxxId: "9cad32d0-6724-414b-a686-a8e133db2225", yyyId: "997eeab8-a698-4027-93d3-43ca5d6ee121"}
slotHeight: 2
startingSlot: 37
status: "IN_STATION"
trackingNumber: "A123456002"
}
Comment: This is unlikely to be a Vue problem. The logging has `parcelId` but the `if` check has `newVal`. Are you sure `newVal` is a string?
Comment: I've changed to use parcelId, they're the same value but form different places. no dice. I suspect it's not a string but a reactive property. I just don't know how I should compare a reactive property.
Comment: Try wrapping the logged value in `JSON.stringify`. e.g. `console.log(JSON.stringify(parcelId))`. That'll make it easier to spot common problems like trailing white-space.
Comment: I tried that as well as escape() and trim() character length is identical when they get logged, but that's the result of the getter I think, not sure
Comment: Have you not seen my answer? The ids are different.
Comment: I did eventually, thanks
Answer: The ids are different.
One contains 1558. The other has 1588.
Comment: that's the one, how did I convince myself the issue had to be complicated. I had manually copied the UUID and made a typo.


Why are "walkovers" allowed in tennis tournaments?

Question: Stan Wawrinka got a "walkover" in the third round of the U.S. open when his opponent had to withdraw from the match.
We're not talking about a situation where a player was, say, injured mid-match, but one where the opponent withdrew beforehand.
Why allow such a "bye?" Why not have aystem of "lucky losers" thatgive the last (defeated) opponent of Wawrinka's opponent the opportunity to face Wawrinka in the third round?
This would give defeated players an incentive to hang around for one more round, for the chance to be a "runner up" in case the winner can't go on. Also, it would mean that someone wouldn't get a "free pass" that would put him or her at an "unfair" advantage against other tournament competitors.
Comment: @queeg: As I remember, they had Michelle Kwan on standby in case they decided to disqualify Harding.
Comment: Nancy Kerrigan and Tonya Harding springs to mind
Comment: That wasn't quite what I had in mind - more the opportunity for dubious injuries and illnesses to occur; players falling ill with food poisoning courtesy of a 'foreign'  hotel, hampering their performance the following day, for example. (helping out the local lad knocked out the precious round)
Answer:
Why allow such a "bye?"

Because it's not really a bye per se. A "Bye" is awarded to a certain level of seeded player to allow them to advance automatically to the second round of a tournament by virtue of them having attained such a high ranking. By definition, once the tournament begins, no more byes can be awarded, only walkovers.

Why not have a system of "lucky losers" that gives the last (defeated)
  opponent of Wawrinka's opponent the opportunity to face Wawrinka in
  the third round?

The problem with that logic is, the previously defeated opponent of Wawrinka's scheduled opponent has already lost in a single elimination tournament. So they have been eliminated from the tournament. Would it be fair to force Wawrinka to play this "lucky loser" opponent if Wawrinka somehow got injured or severely fatigued during that match? Definitely not. And what if the player that withdraws only made it to that round of the tournament because their previous opponent withdrew as well? Then who would you advance - the loser of the match two rounds prior? You could technically have first round losers being asked to wait around for 1 or 2 weeks to see if a chain of walkovers somehow advances them to the final. It's just not really feasible since many early-round losers catch the soonest flight out of there so they can try to play another tournament the following week. Not to mention the expenses of hanging around in hotels for the player, maybe their coach, their trainer, etc. Who would pick up those expenses - the already cash-poor tournaments?

This would give defeated players an incentive to hang around for one
  more round, for the chance to be a "runner up" in case the winner
  can't go on. Also, it would mean that someone wouldn't get a "free
  pass" that would put him or her at an "unfair" advantage against other
  tournament competitors.

Just by hanging around another day or two, players could end up incurring expenses that are more than the extra prize money they would earn by "getting lucky" in the case you describe. It wouldn't be worth the risk for many players.
I'm also not sure how much of an unfair advantage it is - I've seen players lose in their match following a walkover because they felt a little rusty or unprepared because of not playing a match in 3 or 4 days. It can cut both ways. It's not automatically an advantage for some players as much as it may seem.


Clarification on the Equation $ \varphi^{-1}(B) = \bigcup_{n\geq 1} \left\{ \{t=n\} \cap f_{n}^{-1}(B) \right\} \in \mathcal{A} $

Question: Exercise: Let $(\Omega, \mathcal{A})$ and $(E, \mathcal{B})$ be measurable spaces, and let $(f_{n})_{n\geq 1}$ be a sequence of measurable functions from $\Omega$ to $E$. Let $t$ be a measurable function from $\Omega$ to $\mathbb{N}^{*}$. Prove that the function $\varphi$ defined by:
$$
\begin{aligned}
\varphi : \Omega &\longrightarrow E \\
x &\longmapsto f_{t(x)}(x)
\end{aligned}
$$
is measurable.
Solution: Let $B$ be an element of the $\sigma$-algebra $\mathcal{B}$. We have:
$$
\varphi^{-1}(B) = \bigcup_{n\geq 1} \left\{ \{t=n\} \cap f_{n}^{-1}(B) \right\} \in \mathcal{A}
$$
Therefore, $\varphi$ is a measurable function.
Could someone kindly explain the meaning and steps involved in the equation
$$\varphi^{-1}(B) = \bigcup_{n\geq 1} \left\{ \{t=n\} \cap f_{n}^{-1}(B) \right\} \in \mathcal{A}$$
I'm studying measure theory and would appreciate some clarification on this equality and its implications within this context.
Thank you for your assistance!
Answer: Just start from the definition of the preimage : according to the definition, given a subset $B\subseteq E$, $\varphi^{-1}(B)\subseteq \Omega $ is the set of all the $x$ in $\Omega$ such that $\varphi(x)\in B$.
So writing this more formally and replacing $\varphi$ with its definition this becomes
$$\varphi^{-1}(B) := \{x\in\Omega:f_{t(x)}(x) \in B\} $$
Now we need to unpack this definition a bit more : for a fixed $x\in\Omega$, what does $f_{t(x)}(x)\in B $ mean ?
Well, first note that $t$ takes values in $\mathbb N^*$, so there exists $n\in\mathbb N^*$ such that $t(x) = n$. So for this fixed $x$, we see that $f_{t(x)}(x)\in B $ if and only if $f_n(x)\in B $. But again, by definition of the preimage, $f_n(x)\in B$ if and only if $x\in f_n^{-1}(B)$. So what this proves is that
$$ \varphi^{-1}(B) := \{x\in\Omega:t(x) = n\text{ for some $n\in\mathbb N^*$, and } x \in f_n^{-1}(B)\} $$
But now we are almost done : indeed the set $\{x\in\Omega : \exists n\in\mathbb N^* : t(x) = n\} $ is exactly equal to $\bigcup_{n\in\mathbb N^*}\{x\in\Omega : t(x) = n\}  $ (if you're not convinced, it's a good exercise to prove it), while the set $\{x\in\Omega :x\in f_n^{-1}(B)\}$ is by definition $f_n^{-1}(B)$. Since logical "and" translates to set intersection, it follows that indeed
$$\varphi^{-1}(B) :=\bigcup_{n\in\mathbb N^*}\left\{\{x\in\Omega : t(x) = n\}\cap f_n^{-1}(B)\right\} $$
And in most cases we use the shorter notation $\{t = n\} $ for $\{x\in\Omega : t(x) = n\} $ if there is no ambiguity.
Lastly, because $f_n$ is measurable for all $n$, we have that $f_n^{-1}(B)\in\mathcal{A}$, while $\{t = n\} $ (which can also be written $t^{-1}(\{n\})$) is also in $\mathcal{A}$ for the same reason. Hence $\{t = n\} \cap f_n^{-1}(B)\in \mathcal{A}$ and so we have that $\varphi^{-1}(B)$, as a countable union of elements of $\mathcal{A}$, is also in $\mathcal{A}$. This shows that the preimage of any measurable set under $\varphi$ is measurable, which means by definition that $\varphi$ is measurable.
Does that help ?
Comment: I just wanted to say thank you for your clear and pedagogical explanations. You're a lifesaver!
Comment: you're welcome !
Comment: please check https://math.stackexchange.com/questions/4789756/stochastic-modeling-need-guidance-on-measures-sdes


C++11 thread id, Is there a easier naming convention?

Question: Having an easy naming convention can help with complex tasks and debugging large programs.
Is it possible to have a better naming convention than
<code>0x115f57000
0x115fda000
0x11605d000
0x1160e0000
</code>
For instance exception thrown on thread id 0x1035a8000! might not help much. It also does not help that the thread id will change every-time the program is run.
Comment: possible duplicate of [Give a name to a boost thread?](http://stackoverflow.com/questions/3342159/give-a-name-to-a-boost-thread) - I know you're asking about C++11, but std::thread and boost::thread are very similar and the techniques for naming threads are more about the platform (Windows vs. Linux) since there's no cross-platform solution.
Answer: You can always stop you program at start where threads are created, look in the debugger which thread does what, and take a note.


JacksonXML - Deserialize XML Comments

Question: The closest question I can find currently is this which has no conclusive answer:
I am trying to parse XML comments and map it to certain fields in Java.
Below was a simple POC I did in attempt to get this to work.
My current XML model looks something like this:
<Model>

    <Value1>foo</Value1>

    <Value2>bar</Value2>
</Model>

I have defined my Java model like so:
@JacksonXmlRootElement(localName= "Model")
@JsonDeserialize(using = CustomDeserializer.class)
final class ModelFile {

    @JacksonXmlProperty(localName = "value1")
    private String value1;

    @JacksonXmlProperty(localName = "value2")
    private String value2;

    private List<String> comments;

    // Getters and Setters
}

And my CustomDeserializer like so (Else If statement will not work, this is the part im trying to get working):
public class CustomDeserializerextends JsonDeserializer<ModelFile> {

    @Override
    public ModelFiledeserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        List<String> comments = new ArrayList<>();
        ModelFile sample = new ModelFile();
        while (p.nextToken() != JsonToken.END_OBJECT) {
            if (p.getCurrentToken() == JsonToken.FIELD_NAME) {
                String fieldName = p.getCurrentName();
                p.nextToken();
                if (fieldName.equals("value1")) {
                    sample.setValue1(p.getText());
                } else if (fieldName.equals("value2")){
                    sample.setValue2(p.getText());
                }
            } else if (p.getText().equals("\n" +
                "  <value1>foo</value1>\n" +
                "  \n" +
                "  <value2>bar</value2>\n" +
                "</yourclass>";
        XmlMapper xmlMapper = new XmlMapper();

        YourClass yourClass = xmlMapper.readValue(xml, Model.class);
        List<String> comments = yourClass.getComments();
        assertNotNull(comments);
        assertEquals(2, comments.size());
        assertEquals("this is a comment", comments.get(0));
        assertEquals("Another comment", comments.get(1));
    }

The problem as I understand it is the CustomDeserializer seems to recognize both value1 and value2 as valid fields allowing me to later map the fields directly. XML Comments however are not recognized at all.
I say XML Comments specifically because if I change this to a more standard comment type such as this:
    "<model>\n" +
    "  // this is a comment \n" +
    "  <value1>foo</value1>\n" +
    "  // another comment \n" +
    "  <value2>bar</value2>\n" +
    "</yourclass>";

Then the JsonParser in the CustomDeserializer will pick up the comments. Looking further into Jsonparser I see Features that can be enabled namely ALLOW_COMMENTS which does recognize typical Java/C++ comments or ALLOW_COMMENTS_YAML which looks specifically for # type comments.
https://fasterxml.github.io/jackson-core/javadoc/2.8/com/fasterxml/jackson/core/JsonParser.Feature.html#ALLOW_COMMENTS
My guess is considering JacksonXML extends of JSON and typically comments are not supported in JSON, this is not really viable? Considering that it could technically work for // type comments, I feel like im really close to getting this to work.
The question for this would be: How do I handle  type comments in XMLs while using jackson-databind-xml to deserialize it into POJO?
Any idea or suggestions are welcomed.
Comment: Sounds like a good lead! I'll give this a try tomorrow and feedback. Thanks for the input!
Comment: Custom deserializer could [read xml as stream (look at Consuming XML)](https://stackify.com/java-xml-jackson/) and detect [COMMENT event types](https://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLStreamReader.html)
Comment: The "//" entries are not comments as far as XML is concerned, they are ordinary application content, so of course they will be handled differently. (And sorry, I don't know if Jackson can handle XML comments. )
Answer: Ultimately, no this cannot be done it seems. Adding a @JsonDeserializer on the root Object and then having a look at the Jsonparser that is being used revealed that by the time JacksonXML attempts to process the XML, all traces of the comments has been removed (Specifically again  type comments!)
The alternative solution I did, which was suggested by user LMC was to read the xml as a stream and look for events that are Comment type. I would then take the comment and push it into a List which is eventually returned.
Really not ideal as the XML is being read twice (Once for Jackson Mapping and once more to collect the comments) however for my scenario we've decided to go that way as the performance reading it twice vs once is negligible and to read and manually populate my business object without Jackson would take a lot of time to implement.

JacksonXML - Deserialize XML Comments


Não consigo compreender o porque desse valor NaN na coluna "[letalidadeRegionalSaude]"

Question: <code>#letalidade por estado
letalidadeRegionalSaude = []
for i in range(len(regional_saude)):
    letalidadeRegionalSaude.append(regional_saude.obitosNovos[i] * 100 / regional_saude.casosNovos[i])
print(letalidadeRegionalSaude)

[0.9345794392523364,
 4.123711340206185,
 3.4618410700236035,
 1.7267267267267268,
 4.545454545454546
...]

type(letalidadeRegionalSaude[1])
numpy.float64

#Adicionando uma coluna ao DataFrame
regional_saude['letalidadeRegionalSaude'] = pd.Series(letalidadeRegionalSaude)

regional_saude.head()

nomeRegiaoSaude       casosNovos     obitosNovos    populacaoTCU2019_int    letalidadeRegionalSaude

10ª REGIAO                 428             4              22328916.0                  NaN
</code>
Comment: `letalidadeRegionalSaude` é uma série não um número, por isso o `NaN`.
Comment: Não entendi!!! Mas não é possível inserir um lista como uma coluna em um dataframe? Pois, a minha intenção é está: converte uma lista com o método "pd.Series()" e colocar esta série como uma coluna no dataframe.
Comment: Pois foi isso o que eu fiz com a coluna "populacaoTCU2019_int". Está coluna era do tipo "object", eu a converter para inteiro e inserir no dataframe.
Comment: Converta a serie para string que vai conseguir o resultado desejado.
Answer: Teoricamente o que você fez está certo, uma outra solução seria fazer da seguinte forma:
<code>for i in regional_saude.index:
    regional_saude['letalidadeRegionalSaude'] = letalidadeRegionalSaude[i]
</code>


Java Web Application Role Only Security

Question: Good day!
I try to secure my web application via a role security in a web.xml:
<security-constraint>
    <web-resource-collection>
        <web-resource-name>RESTRICTED</web-resource-name>
        <description>Resources to be placed under security control</description>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>manager</role-name>
    </auth-constraint>
</security-constraint>

<security-role>
    <description>ACCESS ROLE</description>
    <role-name>manager</role-name>
</security-role>

and as far as I use Weblogic there is a weblogic-application.xml with the following lines:
<security>
    <security-role-assignment>
        <role-name>manager</role-name>
        <principal-name>manager</principal-name>
    </security-role-assignment>
</security>

The idea is if a user is already authenticated (Web SSO), he has a role and the application must provide an access for such a user.
The problem is even if a user has the required role, an application provides a basic login form.
I've tried to add such a line:
<login-config/>

in the web.xml, relying on the fact in the article it is said that this line makes all pages public (I thought it would remove the login form, but leave the role security), but that haven't worked.
Does anybody know how to remove the login form leaving the role security?
UPDATE:
Inside my WebLogic there is a handwritten identity asserter that checks a user's token. If the token presents the asserter creates a principal and lets the user in the system.
An interesting fact:
if I use Firefox browser there is no any login form, but in Chrome the basic login form is always here...
Comment: What exactly is this Web SSO and how does the session/authentication token created by that system integrate with Weblogic? IOW, how does Weblogic know who the user is and what roles the user has? Do you have any WLS SSPI providers defined for this integration?
Comment: Actually, there is a handwritten identity asserter inside a Weblogic that creates a principal. That is why when a previously authenticated user (by some other system) wants to use my application I need to get the Principal object from a HttpServletRequest and do the processing... The problem is the basic login form is always appear which is not what I (and the user) want. I only need to get the principal (user group)
Answer: Ok, finally I've found a solution that actually is described in this article in the 'Using Identity Assertion for Web Application Authentication' section: I've added these lines into the web.xml:
    <login-config>
        <auth-method>CLIENT-CERT</auth-method>
    </login-config>

and that worked.

Java Web Application Role Only Security


Tkinter : Button in frame not visible

Question: I'm trying to implement a TicTacToe program. I am an absolute beginner in python. After viewing many tutorials and reading a few books, I have understood the basics of Python. I'm trying to get the buttons to display in a frame, but all I get is a blank window.
link for image of the resultant window
This is the code I have so far:
from Tkinter import *

class Buttons(object):

    def __init__(self,master):
        frame = Frame(master)
        frame.pack()

        self.button1= Button(frame,text="1",height=4,width=8,command=self.move)
        self.button1.pack(side=LEFT)

        self.button2= Button(frame,text="2",height=4,width=8,command=self.move)
        self.button2.pack(side=LEFT)

        self.button3= Button(frame,text="3",height=4,width=8,command=self.move)
        self.button3.pack(side=LEFT)

root = Tk()
root=mainloop()

Comment: Okay,I understood the problem,needed to put b=Buttons(root) for it to work. It would be helpful if explained why this was required? Thank you.
Comment: Ok, I'll post an answer in a couple of minutes.
Answer: You defined your Buttons class but you didn't create an instance of that class, so no buttons were actually constructed. Also, you had a typo / syntax error:
root=mainloop()

should be
root.mainloop()

Also, you didn't define the move callback method.
Here's a repaired version of your code:
from Tkinter import *

class Buttons(object):

    def __init__(self,master):
        frame = Frame(master)
        frame.pack()

        self.button1 = Button(frame, text="1", height=4, width=8, command=self.move)
        self.button1.pack(side=LEFT)

        self.button2 = Button(frame, text="2", height=4, width=8, command=self.move)
        self.button2.pack(side=LEFT)

        self.button3 = Button(frame, text="3", height=4, width=8, command=self.move)
        self.button3.pack(side=LEFT)

    def move(self):
        print "click!"

root = Tk()
Buttons(root)
root.mainloop()

However, this still has a problem: The move method has no way of knowing which button called it. Here's one way to fix that. I've also changed
from Tkinter import *

to
import tkinter as tk

It's not a good idea to use "star" imports. They make code harder to read and they pollute your namespace with all the names defined in the imported module (that's 175 names in the case of Tkinter), which can lead to name collisions.
import Tkinter as tk

class Buttons(object):

    def __init__(self,master):
        frame = tk.Frame(master)
        frame.pack()

        self.buttons = []
        for i in range(1, 4):
            button = tk.Button(
                frame, text=i, height=4, width=8,
                command=lambda n=i:self.move(n)
            )
            button.pack(side=tk.LEFT)
            self.buttons.append(button)

    def move(self, n):
        print "click", n

root = tk.Tk()
Buttons(root)
root.mainloop()

Comment: thank you so much for this post! It is immensely helpful!
Comment: @ms: My pleasure! Good luck with your program. You will probably find it easier to build your tic-tac-toe grid using the `.grid` method instead of `.pack`.
Comment: yes,I am on to that already. I am pretty sure to face a lot of bumps once i start implementing the gaming portion. Hopefully SO will help me through it :D thanks once again!
Answer: Okay the problem was I needed to add a variable at the end of the code. Something like b=Buttons(root). It's working now.

Tkinter : Button in frame not visible


When can the moment generating function be differentiated to find moments?

Question: Let $X$ be a nonnegative random variable and suppose
$$\phi(t):= E[e^{tX}] $$
exists for all $t$. For simplicity, suppose $\phi$ is infinitely differentiable on the whole real line. An easy exercise, using the mean value theorem and dominated convergence theorems, is that if $E[Xe^{tX}] < \infty$ for all $t \in \mathbb{R}$, then $\phi'(t) = E[Xe^{tX}]$. Of course, then taking $t = 0$ recovers our favorite formula $\phi'(0) = E[X]$.
To use the dominated convergence theorem, however, we needed to assume $E[Xe^{tX}] < \infty$, which may be hard to prove for a given random variable $X$.

Are there cases where $\phi(t)$ and $\phi'(t)$ exist and are finite, but $E[Xe^{tX}] = \infty?$

My motivating question is that the Laplace transform of the hitting time $T_m = \inf(t : W_t = m)$ of standard BM $W_t$ is
$$E[e^{-\alpha T_m}] = e^{-|m|\sqrt{2\alpha}}$$
for $\alpha > 0$.To compute $E[T_m]$, one differentiates both sides to obtain
$$E[T_m e^{-\alpha T_m}] = \frac{|m|}{\sqrt{2\alpha}} e^{-|m|\sqrt{2\alpha}}$$
and uses the monotone convergence theorem to send $\alpha \downarrow 0$ and conclude. But apriori, how did we know the derivative of $E[e^{-\alpha T_m}]$ was $E[T_m e^{-\alpha T_m}]$, moreover that the latter even exists?
Answer: If $Ee^{tX} <\infty $ for all $t$ then $EXe^{tX} <\infty $ for all $t$ because $xe^{tx} \leq e^{(1+t)x}$ for all $x \geq 0$. In fact, with no further assumption, $EX^{n}e^{tX} <\infty $ for all $n$ and $\phi $ is automatically infinitely differentiable.
Comment: Cool! So is it right to say that if an MGF exists in a ngbd of 0, then the r.v. has $n$ moments if and only if the MGF is $n$ times differentiable?
Comment: Yes, that statement is correct.


Table not showing the data from database in laravel vue component

Question: For the past few days, I have been following a tutorial about VUE application from a really good youtuber. I was following each and every step as it was mentioned in the tutorial when suddenly I have come to an abrupt halt. This is because the data from my database is not showing up in the frontend. The database does show that I am storing the data properly, and there are no errors whatsoever.
The video where I got stuck on is: https://youtu.be/bUXhGw4aQtA
Here is the code for the index in my controller
public function index()
    {
        return User::latest()->paginate(10);
    }

Here is the app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');
import {
  Form,
  HasError,
  AlertError
} from 'vform'

window.Form = Form;
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue').default
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue').default
  },
  {
    path: '/users',
    component: require('./components/Users.vue').default
  }
]

const router = new VueRouter({
  mode: 'history',
  routes // short for `routes: routes`
})

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
  el: '#app',
  router
});

<template>

Users Table

                    <button class="btn btn-success" data-toggle="modal" data-target="#addNew">Add new </button>

                        ID
                        Name
                        Email
                        Type
                        Registered At
                        Modify

                    {{user.id}}
                    {{user.name}}
                    {{user.email}}
                    {{user.type | upText}}
                    {{user.created_at | myDate}}

                          /

Add Users

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                    </button>

                <form @submit.prevent="createUser">

                      <input v-model="form.name" type="text" name="name"
                        placeholder="Name"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
                      <has-error :form="form" field="name"></has-error>

                      <input v-model="form.email" type="text" name="email"
                        placeholder="email"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
                      <has-error :form="form" field="email"></has-error>

                      <textarea v-model="form.bio" type="text" name="bio"
                        placeholder="Bio"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('bio') }"></textarea>
                      <has-error :form="form" field="bio"></has-error>

                      <select v-model="form.type" type="text" name="type"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('type') }">
                        <option value="">Select user Role</option>
                        <option value="user">Employee</option>
                        <option value="manager">Manager</option>
                      </select>
                      <has-error :form="form" field="name"></has-error>

                      <input v-model="form.password" type="password" name="password"
                        placeholder="password"
                        class="form-control" :class="{ 'is-invalid': form.errors.has('password') }">
                      <has-error :form="form" field="password"></has-error>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Create</button>

                </form>

</template>

Please let me know if any other code is required for me to elaborate on the query that I have here. I have tried all options that I could think of and search and couldn't get it to work. Hopefully, another set of eyes can help me figure out the problem.
I expect a full table showing all the rows from my database, and the front-end shows nothing. (Note: I did check the network tab in the developer's options in Chrome and there was only a single xhr type and it showed status 200).
Comment: Why not use developer tool to console.log result of your API call in the method for a start.That way you can be sure the front end receives the data from the backend
Comment: I would need a bit of an assistance with that because I am new to all this vue and API thing
Comment: Your user in the data should be an array, not object. Your axios call in your loadusers() function is wrong and then while iterating, its not ~user in users.data~ but ~user in users~. Check my modified answers.
Answer: I suggest you go on youtube to search for laravel/vue tutorials, there are tons of good resources there that can help you.
For what you are trying to achieve, if you have mounted your component well and can see a dummy test in the component on your browser, then you are half way done.
Inside your mounted hook of your vue component, make an api call to your backend (laravel) to fetch users like so;
axios.get('/get_all_users').then((res)=>{
  this.users = res.data
  //do a console.log(res.data) to ensure you are getting the users collection
}).catch((err) => {
  console.log(err)
});

Inside your data object, create an empty array that holds your users like so;
data(){
  return{
    users: []
  }
}

Now, inside your web.php, create a GET route for this api call;
ROUTE::get('/get_all_users', 'UsersController@FetchUsers');

Note that your controller and method necessarily not be named as above, create a controller, and inside, write a method to fetch users and use them here asap;
Inside your controller, write your method;
public function FetchUsers(){
  $users = User::latest()->get();
  return response()->json($users, 200);
}

Also note that you will need to import your User model at the top of the controller file like so;
use App\User;

Also ensure before now that you have the User model created that relates to your users table;
By now you should see the arrays of users on your browser developer tool console if everything is fine.
Then in your template, iterate through the users data like so;

  {{ user.id }}
  {{ user.name }}
  {{ user.email }}
  {{ user.created_at }}

I will be glad to help in case you need further clarifications.
Answer: You need to return your data as json. You can use Laravel [Resource]
(https://laravel.com/docs/5.8/eloquent-resources)
Create user resource
php artisan make:resource User

User Controller
use App\Http\Resources\User as UserResource;

On your Method
$user = User::latest()->paginate(10);
return UserResource::collection($user)


if else statements in mysql where clause

Question: I am trying to get user details and profile image from 2 tables using joins. The issue is that not all users have a prof image therefore i have to use an if condition in the where clause. Users without prof pic have default 0 as their prof pic image 0 does not belong to anyone the rest have their prof pic id
e.g 17 .
i.e
<code>if tb1.user_pic > 0 Then
  choose their profile image
else
   choose a default image.

SELECT tb1.user_id , tb1.full_names , tb1.user_email , tb1.user_pic , tb1.userName ,
tb2.img_id , tb2.img_format , tb2.img_by , tb2.img_album
FROM users as tb1
LEFT JOIN images as tb2
ON tb2.img_by = tb1.user_id
WHERE tb1.user_id = '$session_id' && tb2.img_id = tb1.user_pic
ORDER BY tb1.user_id
</code>
the above query will return no results  for users without prof pic which is the problem. I was thinking conditional statement might work but i have no idea how to use them in this case.
Answer: I'd like to suggest a possible alternative which will greatly simplify, and possibly speed up (though you should measure this as with all optimisation claims), your queries.
Consider assigning the default image to users when they join then simply allow them to override it. That way, every user has an image which can be extracted the exact same way regardless of whether they've configured one or not.
And, unless you're planning on millions and millions of users, the space requirements shouldn't be onerous.
You can still maintain a field in the table to state whether a real image has been chosen, even though that technically may violate 3NF. Most people don't realise but it's quite okay to do that sort of thing (usually for performance or simplification) provided you understand and/or mitigate the possible problems.
Comment: I was thinking the same but assigning every user a default will add  redundancy in the table since all default images are the same.
Comment: Yes, that was the whole point of the answer, to introduce redundancy in order to simplify the query. Few people complain about the space taken by their DB, most concerns are either speed or simplifying queries.
Comment: Thanks for the idea. I have decided to create an extra table for profile images so that every user has one row in that table for their prof pic which can be overridden(updated) when they either add , delete or change their prof pic. A default of zero is allocated for a user prof pic when they create an account, In this way the query i have will work for all users with or without prof pics.
Answer: Use sub-queries for all columns you want to retrieve from images. Don't use join there.
<code> SELECT tb1.user_id, tb1.full_names, tb1.user_email, tb1.user_pic, tb1.userName,

        IsNull((select tb2.img_id from images tb2 where tb2.img_id = tb1.user_pic and tb2.img_by = tb1.user_id), 0) AS img_id,

        IsNull((select tb2.img_format from images tb2 where tb2.img_id = tb1.user_pic and tb2.img_by = tb1.user_id), 'jpg') AS img_format,

        IsNull((select tb2.tb2.img_album from images tb2 where tb2.img_id = tb1.user_pic and tb2.img_by = tb1.user_id), 'default') AS img_album

 FROM users as tb1

 WHERE tb1.user_id = '$session_id'
 ORDER BY tb1.user_id
</code>
Although I am not sure about the existence of IsNull(,) or its syntax in MySQL. You may set a default image url for users with no profile pic.
Comment: This will work but i was avoiding using sub queries since speed of the query will be slower.


Adding target=_blank to link tag in button in react does not open new page but disables it?

Question: I'm developing a web page with React + Material UI. I want to open a new tab to the link specified and I tried this. It redirects to the link if I do not add target= _blank but it opens in the same tab. If I add target=_blank the button doesn't work at all? The react-route-dom version I have is ^5.2.0. I've tried it on edge and chrome so the problem is not browser specific. I'm using has router and the app might be deployed to with different  base url names so I want to avoid hardcoding the url with "http://...".Any help will be appreciated.
 const markLink = (
            <Link
                to={
                    {
                        pathname: "/AssessmentList",
                        search: "?groupId =" + this.state.groupId + " & unitOfferingId=" + this.state.unitOfferingId
                            + "&userId=" + this.state.userId + "&role=" + this.state.role + "&groupName=" + this.state.selectedGroup.group_name
                    }

                }
                target="_blank"
                style={{ textDecoration: "none", color: "white" }}
            >

                Mark
            </Link>);

Then I use it in my button like this
<ButtonMenu items={[]} name={markLink} working={this.state.project_archived} action={() => {
            }} />

EDIT: I also tried target={"_blank"}. I've tried the suggestions on previous posts but it seems like most pf the URL's need to be "http://" and not the relative path.I'm not sure how to pass in dynamic URLs.
Comment: Did you try ```target={"_blank"}``` ?
Comment: Yes I tried that as well
Comment: Does this answer your question? [React-Router open Link in new tab](https://stackoverflow.com/questions/30202755/react-router-open-link-in-new-tab)
Comment: No i've visited that page.Most of the answers there must input URL using "http:" and I'm not sure how to pass in a dyanamic url?
Answer: The point of using react-router is to render components depending on the url. If you are planning to open the page on a new link just use a regular a element.
const { groupId, unitOffering, userId, role, selectedGroup } = this.state;

const path = `/AssessmentList?groupId=${groupId}&unitOfferingId=${unitOfferingId}&userId=${userId}&role=${role}&groupName=${selectedGroup.group_name}`;

return (

    Mark

);

Comment: If I don't use the  tag, the route will be without the # at the beginning and this will cause the page to be not found and re routed to the index page.I'm using hash router.
Comment: Can you not add the `#` to the path variable? But my previous answer still stands, if you are opening in a new tab, there is no need to use `Link` from react-router.
Comment: However, I'm trying to style it like a button and if I embed a button tag inside the  tag, the problem still persists?
Comment: That's a different question :-)


TypeError [ERR_INVALID_REPL_INPUT] [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException` cannot be used in the REPL

Question: I am trying to test my first blockchain application.This is my code
var Contest = artifacts.require("./Contest.sol");
contract("Contest",function(accounts){
//to check if getting initialized correctly
it("initializes with two contestants", function(){
    return Contest.deployed().then(function(instance){
        return instance.contestantsCount();
    }).then(function(count){
        assert.equal(count,2);
    });
});
});

But i am getting this error:
TypeError [ERR_INVALID_REPL_INPUT] [ERR_INVALID_REPL_INPUT]: Listeners
for `uncaughtException` cannot be used in the REPL

Environment
Operating System: Microsoft Windows
Truffle v5.0.2 (core: 5.0.2)
Solidity v0.5.0 (solc-js)
Node v14.17.1

Answer: There should be no comma.
It should be:
X = faces[::-1]
y = faces[:-1:]


Why do some commands require su instead of just sudo to do?

Question: I thought that running a command with sudo was identical to logging in as the root user and executing the command.  However I have found a few commands that do not work with sudo but do work for su.
For instance,
sudo > mail.log
bash: mail.log: Permission denied

but actually typing su and executing the same command works.
Why is this?
Comment: See also http://serverfault.com/q/75522/126632
Answer: Look at what you're doing with this command.
sudo > mail.log

> in command-line before redirect stdout try to truncate mail.log file. This operation is performed by a regular user (before your sudo without arguments starts). Probably a regular user does not have write access to mail.log file.
Everything works as it should.
If you need to sudo to execute the command and write it to a file type, use the following command:
sudo "some_command with operands > mail.log"

Comment: IIRC the redirection is attempted before sudo. This means that the original user attempts the redirection and fails (no permission). Your answer has the order of operations incorrect which makes the rest of it based on that order less than useful.  Don't forget also that `>file` can be used to truncate file.
Comment: [@is the English way](http://serverfault.com/users/9517/is-the-english-way) Thanks i will improve my answer.


C++ policy based design.... base class as either sigleton or not based on template parametere.

Question: The OutputPolicy of my class sometimes goes to a static/singleton object and sometime goes to a 1-to-1 object.
Not sure if I can explain in english.. so here is the desired behavior in pseudo code:
template<
    class Algo,
    template<class> OutputPolicy
>
class AlgoBase : Algo, OutputPolicy<Algo>
{
};

class AlgoImp
{
public:
    AlgoImp(string topic) {}
    void OnData(
    {
        cout << " AlgoImp::OnData";
        if ( .... )
            NewMsg(msg);
    }
};

class AlgoImp2
{
public:
    AlgoImp2(string topic) {}
    void OnData(
    {
        cout << " AlgoImp2::OnData";
        if ( .... )
            NewMsg(msg);
    }
};

AlgoImp::OnData, does some processing and calls NewMsg. I am trying to decouple the implimentation of the NewMsg() call.
template < class T>
class OutMessageQueueTcp
{
    void NewMsg(string in)
    {
        //Should be a signgleton or static
        cout << " OutMessageQueueTcp::NewMsg";
    }
};

If OutputPolicy is OutMessageQueueTcp (above) then there should only be one instance of OutputPolicy. So I would either have to derive from a Singleton or use a static variable somewhere.
template <class T>
class OutMessageAsInput : AlgoBase<AlgoImp2, OutMessageQueueTcp>
{
    void NewMsg(string in)
    {
        cout << " OutMessageAsInput::OnData";
        AlgoBase<AlgoImp2, OutMessageQueueTcp>::NewMsg(in);
    }
};

If OutputPolicy is OutMessageAsInput (above) then the out becomes input to a sister object and then will be sent to  OutMessageQueueTcp.
Here is the main.
main
{
    AlgoBase<AlgoImp, OutMessageAsInput> myalgo1;
    myalgo1.OnData("hi");
}

And my desired output:
AlgoImp::OnData
OutMessageAsInput::NewMsg
AlgoImp2::OnData
OutMessageQueueTcp::NewMsg

What I really have is a collection of AlgoImp objects, each with its own topic and data. AlgoImp will generate outout by calling NewMsg. Sometimes these messages should be sent to a Socket, and sometimes they should be processed by AlgoImp2.
This decision will happen at compile time. There will be many Algo's each doing diff things. Seems like I am trying to do some kind of Aspect oriented stuff.
Question:
Is it possible to have a Base class be either a singleton or a normal object by making it a policy? Is there a design pattern for something like this? Maybe some kind of factory?
Thanks for the help.
Answer: To keep things simple - OutputPolicy at your algo classes level should be a simple class with simple method. Of course you can implement it with singleton or static methods from the real implementation class:
template < class T>
class OutMessageQueueTcp
{
public:
    void NewMsg(string in)
    {
       impl.NewMsg(in);
    }
private:
   static OutMessageQueueTcpImpl<T> impl;
};

Or:
template < class T>
class OutMessageQueueTcp
{
public:
    void NewMsg(string in)
    {
       OutMessageQueueTcpImpl<T>::NewMsg(in);
    }
};

For your Algo* classes: if output policy is given at compile time - make all these classes template clasess, and treat OutputPolicy as a Strategy - keeo it aggregated (as member variable) in your algo classes:
template <template <typename> class OutputPolicy>
class AlgoImp
{
public:
    AlgoImp(string topic) {}
    void OnData(
    {
        cout << " AlgoImp::OnData";
        if ( .... )
            outputPolicy.NewMsg(msg);
    }
private:
   OutputPolicy<AlgoImp> outputPolicy;
};

Comment: thanks. actually the OutputPolicy member would need to be `OutputPolicy` so I guess it will be `template< template OutputPolicy> class AlgoImp` . will try this.
Comment: @jaybny Understood and changed my answer.
Comment: getting syntax error. using `template
Comment: @jaybny thanks for pointing me out this mistake:D I updated the answer accordingly - no edit comments since this was really a small update.


Como selecionar um arquivo em Python usando o Tkinter

Question: Tenho o seguinte código em Python usando a biblioteca tkinter:
from tkinter import *

class Application:
 def __init__(self, master=None):
  self.widget1 = Frame(master)
  self.widget1.pack()
  self.msg = Label(self.widget1, text="Busque o arquivo")
  self.msg["font"] = ("Calibri", "9", "italic")
  self.msg.pack()
  self.sair = Button(self.widget1)
  self.sair["text"] = "Buscar"
  self.sair["font"] = ("Calibri", "9")
  self.sair["width"] = 10
  self.sair["command"] = self.mudarTexto
  self.sair.pack()
  self.msg2 = Label(self.widget1, text="")
  self.msg2["font"] = ("Calibri", "9", "italic")
  self.msg2.pack()

 def mudarTexto(self):
  if self.msg["text"] == "Busque o arquivo":
     #Teria que abrir a pasta do windows aqui
     self.msg2["text"] = "NOME DO ARQUIVO AQUI"

root = Tk()
Application(root)
root.mainloop()

No momento esse código apenas imprime uma mensagem quando o botão é pressionado, porém, gostaria que ao clicar no botão, abrisse uma pasta no windows para selecionar apenas um arquivo, e que após selecionado e dado o Ok, o nome do arquivo fosse impresso no programa.
Answer: from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw() # Isto torna oculto a janela principal
filename = askopenfilename() # Isto te permite selecionar um arquivo
print(filename) # printa o arquivo selecionado

Seguem outras funções que podem ser do seu interesse
Answer: Para exibir caixas de diálogo de manipulação de arquivos, use as funções do submódulo tkinter.filedialog:
from tkinter import filedialog as dlg
path = dlg.askopenfilename()

Segue abaixo uma lista das funções desse módulo, para referência:

askdirectory(**options)

Pede ao usuário por uma pasta e retorna o caminho para ela

askopenfile(mode='r', **options)

Pede ao usuário por um arquivo, e já retorna o arquivo aberto

askopenfilename(**options)

Pede ao usuário por um arquivo e retorna o caminho para ele

askopenfilenames(**options)

Pede ao usuário para selecionar vários arquivos. Retorna uma lista dos nomes dos arquivos ou uma lista vazia se o usuário cancelar a janela.

askopenfiles(mode='r', **options)

Pede ao usuário para selecionar vários arquivos. Retorna uma lista com os arquivos já abertos ou uma lista vazia se o usuário cancelar a janela.

asksaveasfile(mode='w', **options)

Pede ao usuário um nome de arquivo para ser salvo, e retorna o arquivo já criado e aberto para escrita

asksaveasfilename(**options)

Pede ao usuário um nome de arquivo para ser salvo, e retorna o caminho para ele. Se o arquivo já existir, o usuário terá que confirmar sobrescrever.


Rails 3 - Submit a single form field with JQuery

Question: Spoiler alert: this is a stupid question ;)
I have a Rails form where I display avatar images for the user to select, fetched from the services associated with the user account via Omniauth. It looks like this and it renders without any issues:
<%= form_for @user, :remote => true do |f| %>
  <% @services.each do |service| %>
    <% if service.avatar == @user.avatar %>
      <%= link_to image_tag(service.avatar), '#', :size => "48x48", :id => "current_avatar" %>
    <% else %>
      <%= f.text_field :avatar, :value => service.avatar, :type => :hidden, :class => "clickable"%>
      <%= image_tag(service.avatar, :class => "clickable") %>
    <% end %>
  <% end %>
<% end %>

The relevant part of my application.js file looks like this:
$('.clickable').live('click', function() {
  $(this).parents('form:first').submit();
});

The jquery-rails gem is installed and working ok.
The issue is that this setup obviously submits the whole form, making the user avatar be the last one on the list, no matter which one the user clicks.
Is it possible to submit only the field associated with the image clicked by the user?
I have a good understanding of Rails but JQuery is completely new to me, so I'm really lost. Googled a lot and couldn't find anything. At least nothing that I could understand ;)
Answer: One thing you can do is to use your callback function to remove all the elements with the clickable class (except for that one that was clicked) before you submit the form something along the lines of:
$('.clickable').live('click', function() {
    $(this).siblings(".clickable").remove();
    $(this).parents('form:first').submit();
});

Although in the case of your form that will likely remove all the hidden text fields you have, since the user clicks on the visible images rather than the hidden text field. So you might need to get a bit more fancy with your jquery. You would likely need to:

grab the value of the src attribute of your image tag
find the hidden text field that corresponds to it (i.e. has the same string in its value attribute)
remove all elements with the clickable class except for that one text field

Something along the lines of:
$('.clickable').live('click', function() {
    src_tag_value = $(this).attr("src");
    relevant_input = $(this).siblings("input.clickable[value='"+src_tag_value+"']");
    relevant_input.siblings(".clickable").remove();
    $(this).parents('form:first').submit();
});

Comment: Thank you very much for all this info! I marked the previous answer as correct since it fixed my problem. I hadn't reloaded the page, so I didn't see your answer. I'll try to play with it and see how it works. I'm sorry I don't have enough reputation to vote up your answer, but I thank you through this comment!
Answer: Why are you using hidden text fields for this? I think radio buttons would serve you better. Just create one radio button per avatar (with the current selection checked by default), make sure they all have the same name, and then wrap the image_tag elements in s so that people can click on something. The values for the radio buttons would be the same :value => service.avatar that you're using for the text fields.
Once that's in place, you can submit away and it's all good as the form will only return one of the avatars.
Comment: Mu, your approach is obviously the most logical and correct. Can't thank you enough. Saved the day! Thank you very very much!