Tensor product, wedge product, Hodge product, dyad, or what?

Question: Suppose I have two vectors $\mathbf{u} = (u_1, u_2, u_3)$ and $\mathbf{v} = (v_1, v_2, v_3)$ in $\mathbb{R}^3$. I can regard $\mathbf{u}$ as a $3 \times 1$ matrix, and $\mathbf{v}$ as a $1 \times 3$ matrix, and then I can form their product to get a $3 \times 3$ matrix, which is sometimes denoted by $\mathbf{u} \otimes \mathbf{v}$:
$$
\mathbf{u} \otimes \mathbf{v} =
\begin{bmatrix}
u_1v_1 & u_1v_2 & u_1v_3 \\
u_2v_1 & u_2v_2 & u_2v_3 \\
u_3v_1 & u_3v_2 & u_3v_3 \\
\end{bmatrix}
$$
It seems like this thing would be very useful in writing vector formulae in 3D geometry, which is what interests me.
So, my specific questions are:
(1) What is this thing called? The names "tensor product", "wedge product", and "Hodge product" all seem related somehow, but none of them seem to fit perfectly. Outer product or dyad, maybe?
(2) Where can I find a systematic account of its algebraic properties? There must be many relationships between this thing and the plain old vector dot and cross products. It's very interesting that $(\mathbf{u} \cdot \mathbf{v})\mathbf{w} = \mathbf{u} (\mathbf{v}\otimes \mathbf{w})$ for example.
(3) Is there any geometric intepretation (as there is with dot and cross products)?
I'm interested in 3D geometry, not in abstractions, so simple concrete answers would be preferable, please.
Answer: This is the tensor product of the vectors $u,v$. The tensor product operation is quite general, but in the case of $2$ vectors the simpler name "outer product" is sometimes used.
The algebraic properties you want to know come from the properties of the tensor product. For example, to see that
$$(u \cdot v)w = u(v \otimes w)$$
Pick a fourth vector $z$. Then
$$u(v \otimes w)z^{T} = (u \cdot v)(w \cdot z) = (u \cdot v)w z^{T}$$
So that both sides define the same linear map, and hence must be the same.
Lastly, regarding geometric intuition, the tensor product is a general algebraic tool that does not always have a geometric explanation. However, one can say that these objects are useful in geometry because a tensor is a linear object that behaves nicely under a change of coordinates, so it is always useful to develop geometric constructions around the framework of tensors and tensor products.
Comment: Thanks. So, is it safe to assume that this outer product is neither a "wedge" product nor a "Hodge" product (in which case I can forget about those)?
Comment: I'm still looking for geometric interpretation. I found some myself -- if $\pi$ is a plane containing the origin with unit normal $\mathbf{N}$, then, for any given vector $\mathbf{V}$, we can see that $\mathbf{V}(\mathbf{I} - \mathbf{N}\otimes \mathbf{N})$ is the the projection of $\mathbf{V}$ onto $\pi$, and $\mathbf{V}(\mathbf{I} - 2\mathbf{N}\otimes \mathbf{N})$ is the reflection of $\mathbf{V}$ through $\pi$, and so on. This is nice, because it gives us a way to express projections and reflections via matrix multiplications.
Comment: I'm not really interested in proving the algebraic relationships, I'd just like to have a nice tidy list of them. But, in passing, how did you know that $u(v \otimes w)z^{T} = (u \cdot v)(w \cdot z)$?
Comment: Geometry again -- there must be some relationship to distance from a point to a line, too, because these outer products show up when computing moments of inertia.
Answer: As @Elchanan Solomon said, the object $u \otimes v$ is the tensor/outer product of the two vectors $u$ and $v$, also written as $uv^T$ in $\mathbb{R}^n$
With regards to geometric intuition, one can think of the specific case of the outer product of a vector $v$ with itself $v \otimes v$ as a projection operator, that when applied onto another vector $w$, will produce the vector projection of $w$ onto $v$
$$ (v \otimes v)w \propto \vec{\text{Proj}}_{v}(w) $$
The relationship is a proportionality due to the norm of $v$. If $v$ was normalized, we'd have the equality
$$ (v \otimes v)w = \vec{\text{Proj}}_{v}(w) $$
If $v$ was not normalized, we'd end up with an additional factor of the inner product $v \cdot v$ to "cancel out" the norms of $v$ in the outer product,
$$ \frac{(v \otimes v)}{v \cdot v}w = \vec{\text{Proj}_{v}(w)} $$
To see where this comes from, consider the projection operator in quantum mechanics which is constructed as an outer product,
$$ P_i = \vert i \rangle \langle i \vert $$
Where $\vert i \rangle$ is the set of orthonormal basis vectors and $\langle i \vert$ are the corresponding bras from the dual space. Since the bras are the adjoints (basically transpose-conjugates) of the kets, if the ket $\vert i \rangle$ was a column vector, then the bra $\langle i \vert$ is a row vector so $\vert i \rangle \langle i \vert$ is the product of a column vector and a row vector (in that order), the result of which is a matrix (operator).
From this, we have the completeness relation for a finite dimensional Hilbert space:
$$ \sum_{i} P_i = I $$
$$ \sum_{i} \vert i \rangle \langle i \vert = I $$
Which tells us that adding up all the vector projections of a vector along all the basis vectors is equivalent to reconstructing the vector itself, hence the presence of the identity operator.
Now, applying the projection operator to any vector $\vert v \rangle$ from the Hilbert space, we see that,
$$ P_i\vert v \rangle = \vert i \rangle \langle i \vert v \rangle $$
$$ P_i\vert v \rangle = \langle i \vert v \rangle \vert i \rangle $$
Where $\langle i \vert v \rangle$ is the inner product of $\langle i \vert$ with $\vert v \rangle$. If we translate the vector operations and bra-ket notation present here, it's clear that this is the same as the vector projection of $v$ onto $e_i$ in geometric vector spaces such as $\mathbb{R}^n$,
$$ \vec{\text{Proj}}_{e_i}(v) = (e_i \cdot v)e_i$$
When we're not dealing with projections onto normalized vectors, we'd have to account for the norms via
$$ P_{u}\vert v \rangle = \frac{\langle u \vert v \rangle \vert u \rangle}{\langle u \vert u \rangle}$$
And,
$$ \vec{\text{Proj}}_{u}(v) = \frac{(u \cdot v)}{u \cdot u}u $$
Where $ u $ is the vector being projected onto.
Rearranging, we can see that
$$ P_{u}\vert v \rangle = \frac{\vert u \rangle \langle u \vert v \rangle }{\langle u \vert u \rangle} $$
If you allow me to extract out the quantity operating on $ \vert v \rangle $,
$$ P_{u}\vert v \rangle = \left(\frac{\vert u \rangle \langle u \vert }{\langle u \vert u \rangle} \right) \vert v \rangle $$
By comparing,
$$ P_{u} = \frac{\vert u \rangle \langle u \vert }{\langle u \vert u \rangle} $$
Doing the same for $\mathbb{R}^n$,
$$ \vec{\text{Proj}}_{u}(v) = \frac{(u \cdot v)}{u \cdot u}u $$
$$ \vec{\text{Proj}}_{u}(v) = \frac{u(u \cdot v)}{u \cdot u} $$
$$ \vec{\text{Proj}}_{u}(v) = \frac{(u \otimes u)v}{u \cdot u} $$
$$ \vec{\text{Proj}}_{u}(v) = \frac{u \otimes u}{u \cdot u}v $$
Therefore,
$$ \vec{\text{Proj}}_{u} = \frac{u \otimes u}{u \cdot u} $$
With this knowledge in hand, we can understand OP's statement about how the projection and reflection of a vector onto/via a plane involves the outer product.


How to setup log4j2 asyncQueueFullPolicy

Question: I am using log4j-core-2.5 for my logging and I would like to Discard items when the logging queue is full. I have determined that this could be applied by using the log4j2.asyncQueueFullPolicy configuration property in log4j.
Could somone please help me with how to apply this configuration in my application.
I am using a file configuration like so...
Configurator.initialize("", "log4j-node.xml");

My config file looks somthing like this
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{dd-MMM HH:mm:ss.SSS} %logger{1}.%t %-5level] %msg%n"/>
        </Console>

        <RollingFile name="DefaultFile" fileName="../logs/app.log"
                 filePattern="../logs/app-%d{MM-dd-yyyy}-%i.log" bufferedIO="true" bufferedSize="32000" immediateFlush="false">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            ...

        </RollingFile>

        <Async name="AsyncFile">
            <AppenderRef ref="DefaultFile"/>
            <LinkedTransferQueue/>
        </Async>

        <Async name="AsyncConsole">
            <AppenderRef ref="Console"/>
            <LinkedTransferQueue/>
        </Async>

    </Appenders>

    <logger name="org.hibernate">
        <level value="debug" />
    </logger>

    <Loggers>
        <Root level="TRACE">
            <AppenderRef ref="AsyncConsole"/>
            <AppenderRef ref="AsyncFile"/>
        </Root>
        <Logger name="org.hibernate.SQL" level="error" />

        <Logger name="org.hibernate.type" level="error" />

        <Logger name="org.hibernate.tool.hbm2ddl" level="error" />

        <Logger name="org.hibernate.pretty" level="error" />

        <Logger name="org.hibernate.cache" level="error" />

        <Logger name="org.hibernate.transaction" level="error" />

        <Logger name="org.hibernate.jdbc" level="error" />

        <Logger name="org.hibernate.hql.ast.AST" level="error" />

        <Logger name="org.hibernate.secure" level="error" />

        <Logger name="org.hibernate" level="error" />

    </Loggers>
</Configuration>

Cheers
Answer: First, please upgrade to Log4j 2.10, which fixed an important issue in this area where log events no longer appear out of order in the log file when the queue is full.
You can configure Log4j2's behaviour via system property log4j2.AsyncQueueFullPolicy. See AsyncQueueFullPolicy and AsyncQueueFullPolicyFactory. The "Discard" policy with some log level may be of interest.

Property log4j2.AsyncQueueFullPolicy controls the routing
  behaviour. If this property is not specified or has value "Default",
  this factory creates DefaultAsyncQueueFullPolicy objects.
If this property has value "Discard", this factory creates
  DiscardingAsyncQueueFullPolicy objects. By default, this router
  discards events of level INFO, DEBUG and TRACE if the queue is full.
  This can be adjusted with property log4j2.DiscardThreshold (name of
  the level at which to start discarding).


What does "surface area of a sphere" actually mean (in terms of elementary school mathematics)?

Question: I know what "surface area" means for:

a 2d shape
a cylinder or cone

but I don't know what it actually means for a sphere.
For a 2d shape
Suppose I'm given a 2d shape, such as a rectangle, or a triangle, or a drawing of a puddle. I can cut out a 1cm by 1cm piece of paper, and trace that piece of paper on the shape. Many full 1 cm squares will be traced on the shape, and there will likely be many partial squares traced on the edges of the shape. Suppose I can accept that I can "combine" the partial squares into full squares. Then I count the total number of full squares, to find the surface area.
For a cone or cylinder
I can convert a paper cone into two 2d shapes. The bottom of the cone is a circle. I can then cut the curved (ie not-bottom) part of the cone using scissors, and unfold that part into a flat 2d shape.
Similarly, I can convert a cylinder into flat 2d shapes: two circles and a rectangle.
For a sphere
But the above methods for understanding surface area don't work for a sphere. I can't lay a 1 cm by 1 cm piece of paper onto a sphere in a flat way. I can't even trace a square centimetre onto the sphere using that piece of paper!
People might say, "suppose you have an orange, and you peel the orange. Then you can lay the peel flat onto the table, into a flat 2d shape". But they're lying! The orange peel can never be mashed down perfectly flat onto the table!
So, I don't know what "surface area of a sphere" even means, if you cannot measure it using flat square pieces of paper!
What does "surface area of a sphere" even mean?
Comment: Your backyard (if you have one) is on a curved surface (our globe). Does is strike you as problematic to talk about its area?
Comment: @eps If someone's asking about the nature of surface area, then I *promise* you ... showing them Banach-Tarski is NOT going to help them gain a better understanding.
Comment: You say you know the surface area of a flat shape or one that can be flattened... but what is the area of a disk? You have the same issue here as with the sphere. You cannot tile a disc exactly with squares except as a limit with infinitesimal squares.
Comment: The one dimensional analog of your question is: what does it mean to talk about the perimeter of a circle? Can you see how constructing a parameterization of a straight line (in the colloquial sense) to a circle allows us to make sense of it? Can you adapt this to a sphere?
Comment: @DerekAllums The difference is that the cut string is not an approximation; when you pull it taught, you get a straight line and you can measure it. But cutting up a sphere always approximates, and the number of pieces governs the accuracy of the approximation. That leads to the need for calculating the limit (i.e. calculus).
Comment: @DerekAllums actually, the perimeter of a circle was taught to me as "consider a piece of string, that you curl around the outside of a circle. what is the length of that piece of string?" and that satisfied me. it fit well into the precise idea of measuring a 1D line on a ruler. but sadly, i can't adapt this to a sphere; a piece of string can be wrapped along a circle; but no piece of flat paper (or plastic, or whatever) can be "wrapped around" a sphere!
Comment: @YvesDaoust i might argue that if the definition of "area" that i was taught only talks about covering surfaces with pieces of paper that are all a unit square big, then the surface of a sphere *doesn't* have an area; i.e. that you cannot apply this definition of "area" to a sphere!
Comment: I answered this question for myself like this: you need some amount of paint to cover the surface of sphere, right? So, the "surface area of a sphere" is real, not just some abstraction.
It is possible to convert this answer into a strict definition of what is a surface area of arbitrary set of points (via the volume of the region close to our points) - but I am afraid it's possible to construct some weird surfaces such that this definition will be good for them.
Comment: @JohnColeman this is interesting. i think that when i look at my backyard, it looks completely flat. but i were to zoom out far enough to see the entire globe, things feel problematic. i'm starting to realize that if i'm given a sphere i can hold in my hands, that i also want to use a square unit that's about one square cm big; and that using "one square millimetre" (ie, more the size of a backyard compared to a globe) is unsatisfying; my grade 3 brain has trouble visualizing any understanding of such small units of measurement. it wants to continue to think in the bigger square cm unit.
Comment: Rather than try to *explain* this in terms of elementary-school mathematics, you should *use* this elementary question as motivation for calculus. More generally, calculus is what you naturally get when trying to generalize ideas from flat things to curved things (an important question here is "What is a curved thing?" -- the answer is "something that looks flat when you zoom in").
Comment: You might benefit from this (and, less directly other) 3Blue1Brown videos:  [But why is a sphere's surface area four times its shadow?](https://www.youtube.com/watch?v=GNcFjFmqEc8).
Comment: The sphere is not a *ruled* surface meaning that you cannot apply a sheet of paper to it. If you take a definition that *requires* the surface to be ruled to have an area, then indeed there is no area. Or the definition is inappropriate.
Comment: While I think for this case there are ways to "intuitively" visualize a sphere's surface area, realize that as you get to higher level math such an exercise becomes irrelevant and counterproductive.  A 19 dimensional (hyper)sphere also has a surface area as well but good luck trying to come up a visual aid for it and why even bother with trying to conceptualize it in the first place.  Personally, working with high dimensional objects got a lot easier once I realized trying to smash it down to the 3d world was pointless and just accepted it as an abstract concept with certain properties.
Comment: Lol just do $\int _{0}^{2\pi }\int _{0}^{\pi }r^{2}\sin \theta \,d\theta \,d\varphi =4\pi r^{2}.$ and that's the surface area :)
Comment: @AbhimanyuPallaviSudhir admittedly, this /could/ be used as a motivation for calculus, for students who are ready/interested in the ides of calculus. calculus gives the precision required to describe what's happening in a very mathematically rigorous by-sets-of-axioms way. i know that i've always been interested in explanations, though, that give the *intuitions*/approximations of the insights, especially ways that very young students could understand. admittedly, the measure of how effective these intuitive explanations is far more subjective, but i think it's an interesting avenue of inquiry
Comment: The fact that you are unable to "manufacture" a sphere doesn't mean that it does not have a surface and that this surface does not have an area.
Comment: @silph But think about it further and it's the same issue: if you believe you can approximate a curved line by bending a straight one, why not approximate a curved surface by bending a flat one? Better explanations of this intuition are below in other users' answers.
Comment: You cannot apply a piece of paper on any curved surface, because the two faces would have different areas. This explains why **a cylindre cannot have a surface area**.
Comment: See gauss baynet theorem, and intrinsic curvature. A plane and cylinder are of the same genous but a sphere is not. They are not isometric and they require tearing or deformation to map one to other. Also can see poincare conjecture and ricci flow.
Comment: @silph Right, and I'm saying these insights/intuition should be equated to the discipline of calculus.
Comment: I've been somewhat annoyed that mathematically, a "sphere" is a 2D object (a circle is 1 dimensional).  Technically, it's the 2D surface of a "ball" that they're talking about.  Or just "the area of a sphere".  This dichotomy of terms is annoying as hell when trying to figure out what physicists mean.  For instance, a simplified universe model is commonly "a 4 dimensional surface of a 5 dimensional sphere".  ......No, not really.  What they meant was either a 4 dimensional sphere (which no one would understand) or a 4D surface of a 5D ball.  *OY!*
Comment: Perhaps an intuitive way to visualize area is to imagine covering each shape with paint to the same thickness. The area is then the volume of paint used divided by its thickness. Very spiky shapes become problematic due to discontinuities, but when the when the thickness is small compared to the shape (i.e. tends to zero), the ratio tends to the correct value.
Comment: Isn't this asking how to define the integral (in this case, two dimensional).
Comment: The question of what area means is to be understood in terms of "utility". For example, until area was "invented" people measured equivalence of plots of land in terms of their perimeter. It may seem bizarre to us, but intuitively it does conform to the idea that increasing the length or the width of a rectangle increases its size "linearly". So the answer must start with answering the question "What purpose does the area serve?" In that respect @YvesDaoust has given an answer which should be developed into a full answer.
Answer: This is actually an interesting question. It involves how to define "area" on a curved surface. The examples you have provided are surfaces that are developable (can be flattened onto a plane) after a few cuts. And you can compute the flattened area. You can never do this to a sphere, because no matter how small a patch from a sphere is, it can never be flattened onto a plane. The idea is to break down the sphere to small patches such that each is flat enough and you compute the area as if it is flat, and then add up the areas of the patches.
Mathematically, suppose $S$ is a sphere. The above procedure is stated as:

Break up $S$ into patches $P_1,\dots,P_n$, where each $P_i$ is a patch that is flat enough, and $n$ is the number of patches you have.
Compute $\operatorname{Area}(P_i)$ as if each $P_i$ is flat. As suggest by levap, one way to do it is to project each patch onto one of its tangent planes. Note that I am not saying this is the only way to approximate a patch, and I am also not saying that one way that would seem correct at first glance would really be correct, see Update 2 for an example, there's also discussion about this in the comments.
Use $\operatorname{Area}(P_1)+\dots+\operatorname{Area}(P_n)$ as an approximation of the area of $S$.
If the patches are small enough, then the approximation should be a good one. But if you want better precision, use smaller patches and do the above again.
This is to make the math precise, I can't guarantee that a third-grade student can understand this: As you take smaller and smaller patches, the value of the approximation above should tend to a fixed number, which is the mathematical definition of the area.

P.S. For a visualization of this approximation, you can search online for sphere parametrization, or simply think of a football (soccer ball).

Update 1: Thanks to Leander, we have a visualization:

One might notice that this visualization is slightly different from cutting up a sphere; it takes sample points on the sphere and attach triangles to these sample points. I want to remark that there is no essential difference between this and my method. The idea is the same: approximation.

Update 2: A comment (by Tanner Swett) mention that the method of using a polygon mesh may be flawed. Indeed, the example of Schwarz lantern shows that some pathological choice of the polygon mesh may produce a limit different from the surface area. The following explanation should be helpful:
As I have mentioned in step 2 above, if we are not careful with how we approximate the areas of the patches, the approximation may not work. The Schwarz lantern is an example where a careful choice of the approximating triangles can lead to the following result: Suppose $T$ is a triangle we use to approximate a patch $P$, then it is possible ${\rm Area}(T)/{\rm Area}(P)\to a\neq1$. To illustrate this, consider a single triangle on the Schwarz lantern:

We assume the cyclinder has total height $1$ and radius $1$. We take $n+1$ axial slices, and on each slice $m$ points. The area enclosed by the red curves is a patch on the cylinder, and the triangle enclosed by the blue dashed lines is the one used to approximate the patch. Let $P$ and $T$ denote the patch and the triangle respectively. We see that the bottom edge of $P$ and $T$ has ratio $1$ as $m\to\infty$. What really makes a difference is the ratio of their heights. Suppose along the vertical direction the height of $P$ is
$$h=1/n$$
Then the height of the triangle is
$$h_T=\sqrt{1/n^2+a^2}$$
By a simple computation we know $a=1-\cos(\pi/m)\approx(\pi^2/m^2)/2$. Therefore,
$$h_T/h=\sqrt{1+\frac{\pi^4n^2}{m^4}}$$
If $n$ has higher order than $m^2$, then the limit is bigger than $1$, and consequently ${\rm Area}(T)/{\rm Area}(P)\not\to1$.
This problem would have a smaller probability of occurring in practice. Imagine if you do cut the cyclinder into patches, you'd use $h$ instead of $h_T$ to estimate the area. But again, it is hard to make this (what approximation is acceptable) precise without using the language of calculus.
Comment: upon further reflection, i'm wondering if it makes sense to an elementary school student to say "yes, the orange peel doesn't lie flat. but we can kind of measure it as if it was flat. but if we break the orange peel into smaller bits, it would lie more flat. if we then measure the area of this *now*, the surface area will be just slightly bigger.", and then somehow find some metaphor that gives insight about doing the limit of this.
Comment: @silph If you want to try it yourself, do it with three oranges, but use big, medium and small-sized pieces depending on the orange, and notice there's a value you're getting closer to as the pieces are shrink.
Comment: How sure are you about the area of your puddle? Obviously you have some partially filled squares on your big grid, in order to figure out how much that is you will need to measure the area of them...so you use a smaller grid. Now your smaller grid will have some partially filled squares, rinse, repeat. For a physical puddle eventually you reach physical particles and you're done, but if your puddle was mathematically a fractal you could go forever. Yet your puddle clearly has an area, you can say it's no bigger than x and no smaller than y. (You can even do this for distances with rivers.)
Comment: @user3067860 it's interesting how my grade-three brain is able to "accept" this intuitive idea of a limit (ie, the area of a puddle tending towards a unique answer, when using smaller and smaller squares to measure it) for a 2d shape. that is, my grade 3 brain can "accept" placing a grid of 1cm x 1cm squares, and for each edge square, acceptng tht there is a unique correct "answer" to its area. but it's curious that, in contrast, my grade 3 brain has trouble visually accepting a similar idea for a 1cm x 1cm piece of paper, applied to sphere! i will have to think more about the intuitive chasm.
Comment: @user3067860 I can't really quantify this without introducing calculus on surfaces. Let's just say in real life you can trust your eyes to tell whether something is flat enough.
Comment: @DDD4C4U There's no contradiction, though it may be written somewhat unclearly. The answer is saying that it's not possible to get a sphere *perfectly* flat, but it is possible to get it flat *enough*.
Comment: @trisct I'm not sure if this contradicts your answer, but I proposed an edit with a visualization to help the grade 3 brain.
Comment: I forgot to mention that this method suffers from the [Schwarz lantern](https://en.wikipedia.org/wiki/Schwarz_lantern) problem. Even if you approximate the sphere using only triangles whose vertices lie on the sphere, no matter how small an upper bound you place on the size of the triangles, it's possible for the triangles to have an arbitrarily *large* surface area. So as much as "value of the approximation above should tend to a fixed number", it *doesn't* tend to a fixed number. (But the desired number is probably the [limit inferior](https://en.wikipedia.org/wiki/Limit_inferior).)
Comment: forgive me for asking: i actually don't have much more than a high school background of mathematics, so i don't understand the notation used in #1. what does the "S squared" and "Big U with subscript n" mean?

At any rate, i'm thinking also about how to take this idea of "approximate a unit square onto the sphere" in a way that would make sense to a third grader (or even to my own brain!).
Comment: @silph Yes, I realized my notations can be disturbing if you don't have much background. I edited my answer to make the notations more friendly.
Comment: @silph To your second comment: not necessarily "slightly bigger", I only know it should be "slightly different". Whether this can make sense to third graders may depend on the individual. Some may not even realize this could be a problem.
Comment: @silph : These are variable symbols: you assign them on the spot a meaning and then they stand for that thereafter. So when he says, "let $S$ be the sphere", it means now that whenever you see $S$, that references that particular sphere (versus any other sphere).
Comment: @trisct Sorry, the question mark there was rhetorical. I just thought it would be an illuminating concept for the OP to see that this applies in lower dimensions, too.
Comment: This paragraph is contradictory

". You can never do this to a sphere, because no matter how small a patch from a sphere is, it can never be flattened onto a plane. The idea is to break down the sphere to small patches such that each is flat enough and you compute the area if as it is flat, and then add up the areas of the patches."

You can't make patch small enough to make it flat then u say you can..
Comment: @Leander That is exactly what I've been looking for to put in my answer.
Comment: I think this won't work as it is written. You need to introduce some restrictions on how to choose those patches, otherwise one can come up with a 3D version of [this](https://i.stack.imgur.com/znQDV.png) (proof that pi is 4 by "extruding" parts of a square repeatedly).
Comment: @FedericoPoloni I've seen the same fake proof used to prove that the diagonal of a square has twice the side length. I stated in my answer that each patch should be flat enough. But if you use an "approximation" analogous to the fake proof you cited, you would notice that the patches you've chosen are never flat enough, and thus don't meet my requirements.
Comment: @FedericoPoloni Similarly, for the 2d version of the fake proof, you notice that you are using two line segments intersecting at a right angle to approximate an arc. As we go to infinitesimal, the arc would seem more straight", but the approximating line segments do not, as they always form a right angle.
Comment: All patches are squares, or line segments in the 1D version, so they are "flat enough" by themselves. (At least that's how I interpret that word.) You need to add a requirement on how they are joined one to the other.
Comment: @silph "in contrast, my grade 3 brain has trouble visually accepting a similar idea for a 1cm x 1cm piece of paper, applied to sphere" - perhaps it's better to think of it in a different way. Let's say that you're not applying peaces of paper to the sphere - suppose instead that you have a perfect sphere made of some material. Then you cut it up into small pieces - they are so small that they are almost flat, but they aren't really. But you can't tell the difference. 1/2
Comment: @silph You then place them on the floor, and then you measure each one's surface (as if flat), then add them up (maybe you have some sort of an overhead scanner that can do that automatically). You get a number. You then cut them up even further, repeat the measurement, and you get a number that's slightly higher. You keep going. The result ever so slightly increases, approaching some limit, but never goes over it. Mathematically, you don't do it literally that way, but there's a formal way of doing it that amounts to the same thing, and produces that limit as the result. 2/2
Comment: @TannerSwett Thanks for mentioning this interesting example. But I don't think ithe desired number is the limit inferior, since the limit may exist, but fail to be the desired number. And when a limit exists, limit = limit inferior.
Comment: @trisct: I don't want to ruin the party in being pedant but your answer has a serious logical flaw. You argue correctly that no matter how small you take your patch $P_i$, it can never be flattened but then you say that you take $P_i$ to be small enough and compute $\textrm{Area}(P_i)$ "as if" each $P_i$ is flat. Since $P_i$ is never flat, you can't really compute its area as you run down into the same problem that you had with the original surface $S$ because you don't know in advance how to compute the surface area of something curved, **no matter how small it is**.
Comment: This is a real non-trivial issue which is really different from the issue you encounter if you want to define the area of a planar shape. There, you can use approximation by squares (whose areas you **really** know how to compute) but here there aren't any "pieces" you can actually use.
Comment: This issue arises also in the case of curves in a simpler form. How can you define the length of something curved? You divide it into small pieces $P_i$ but then again you don't know how to compute their length. So instead, you **replace** each piece with a line connecting the two endpoints and get a polygonal approximation whose length you can actually compute and sum everything. This is the meaning of "compute $\textrm{Length}(P_i)$ as if each $P_i$ is flat" part.
Comment: You might expect that the same would work for surfaces (and it does) but the Schwartz lantern example shows that you really need to be careful on how exactly you do it. It is wrong to say that "the Schwarz lantern problem shouldn't arise in method 1" because the pieces "were originally on the surface" because it really doesn't help - you don't know how to compute their surface area.
Comment: Now, one can make your story precise by specifying how you compute the area of each $P_i$ as if it is flat. One way is to project $P_i$ onto the tangent plane at one of the point and then you get a planar shape which lies on the tangent plane (but not on the surface!) and you can compute its area (again, approximating using squares) and sum everything up but this not what the most common definition "does". Instead, it "replaces" each piece completely with a small planar parallelogram and sums the areas. In any case, you must use "pieces" which are not originally on the surface.
Comment: @levap You are absolutely right. Projecting onto the tangent plane is exactly how calculus deals with curved area. I didn't want to mention that because I was mainly focusing on the idea of cutting the surface into smaller pieces. As for how to compute the areas of the pieces, even though projecting onto a tangent plane is a viable solution, there's no guarantee that this is the *only* viable solution. If I put that in my answer I'd somehow have to introduce a criterion on what kind of approximation is viable and what is not.This criterion, if it exists, is what I meant by hard to make precise
Comment: @trisct: The point of my (overly lengthy) comment was to emphasize that in your description there are really two separate issues: the approximation part and the "as if" part and both are equally important. Since things stay curved, no matter how small they are it doesn't help to emphasize that the pieces were originally on the surface because, in the end, you need somehow to "take them off the surface and make them planar". Other than that, great answer. +1 :)
Comment: @levap I've taken your suggestion and edited the answer. Actually I have thought about the issue before but decided to avoid it. But now with your comments I think it is better to mention it rather than ignoring it. Thanks!
Comment: The Schwarz problem is described and analyzed in RADO: "WHAT IS THE AREA OF A SURFACE?" https://doi.org/10.1080/00029890.1943.11991341 where he shows that the proper definition is the limit inferior of the surface area of the inscribed polyhedron. He credits Lebesgue for the definition.
Answer: Take a sphere (or any other shape), and paint it blue. The amount of paint required is just proportional to the surface area. This is a way to measure it.
Comment: One problem with this is in practice is that paint has a thickness. For a very large sphere, each 1cm^2 is sufficiently flat that it's nearly equivalent to painting 1cm^2 on a flat piece of paper. But if you paint a very small sphere, the curvature will make a difference. If your sphere has a radius of only 1mm, a paint thickness of 1mm makes a big difference. The ratio of paint needed to surface area increases the smaller your sphere is - in practice, it is not a constant ratio as you suggest. This doesn't solve the OP's "paper" problem that you cannot equate a curved area and a flat one.
Comment: @trisct Yes, you can get asymptotically close to the correct answer as the paint shell becomes infinitesimally thin. But in practice, this method works no better than laying overlaying 1cm x 1cm squares onto the surface of the sphere, which is where the OP started - if the sphere is large compared to the square/paint, it will work "well enough". Your formulation is exactly correct, the surface area of a sphere is the volume/thickness of an infinitesimally thin shell around the sphere. Whether that's more intuitive than the sum of infinitely small flat patches of area is anybody's guess.
Comment: @NuclearWang: if you want to play the fool, think that paper has thickness and cannot be folded because that would change its area, which is impossible. So a cylindre has no area.
Comment: See also [How do I experimentally measure the surface area of a rock?](https://physics.stackexchange.com/q/512834/224105)
Comment: @YvesDaoust Gabriel's Horn is interesting. [Here](https://en.wikipedia.org/wiki/Gabriel%27s_Horn#Painter's_paradox) it says "The paradox is resolved by realizing that a finite amount of paint can in fact coat an infinite surface area — it simply needs to get thinner at a fast enough rate. (Much like the series 1/2^N gets smaller fast enough that its sum is finite.) In the case where the horn is filled with paint, this thinning is accomplished by the increasing reduction in diameter of the throat of the horn."
Comment: @YvesDaoust Did you think about FakeMod's example at all (when you wrote he/she was clearly wrong)? It has finite area, but for any constant thickness of a layer of paint you need an infinite amount of paint.
Comment: @doetoe: this is ridiculous. Gabriel' Horn has infinite area, and will OF COURSE require an infinite amount of paint.
Comment: @YvesDaoust Sorry, I didn't read it well and had the following in mind (should have looked up what actually is Gabriel's Horn), my bad. I was thinking of a cusp like one that could be obtained as a surface of revolution of the graph of $e^{-x}$ for positive $x$. This has finite area and will require an infinite amount of ink.
Comment: i'm trying to think of how i could apply this idea when explaining it to my own third grade brain. the difficulty i'm experiencing is that "flat square pieces of paper" is tangible, and a precise definition. in contrast, "liquid covering a surface" doesn't allow for actual measurement, and it's hard for me to visualize how liquid actually lays itself down to "measure" a rectangle (or sphere) surface. -- but thanks for the idea, anyways.
Comment: oh, i mean that the paint idea doesn't allow me to arrive at a number to say "the area is ___ square centimetres". i'd have to start saying something like "the area is 36 mL", but then again, i have trouble actually visualizing how one mL of paint lays itself down as it covers a 2d rectangle (or surface of a sphere).
Comment: Yes you can arrive at a number. Paint 1 cm², taking 0.1 ml. Paint the sphere, taking 3 ml. The area is 30 cm². Think out of your box.
Comment: Assuming a paint thickness of 1 unit, this plot shows the ratio of the volume of paint needed to the area of the sphere. When the paint thickness is 1/100 the sphere radius, you're off by 2%, when it's 1/10 of the radius, you're off by a full 10%. The ratio approaches 1 for large spheres, but there's always some error: https://www.wolframalpha.com/input/?i=plot+%28%284%2F3+pi+%28x%2B1%29%5E3%29+-+%284%2F3+pi++x%5E3%29%29%2F%284+pi+x%5E2%29+from+x+%3D+0+to+100
Comment: @NuclearWang This is easy to resolve. Let $V(r,\varepsilon)$ be the volumn of paint needed to paint a sphere of radius $r$ if we paint with thickness $\varepsilon$. Assuming the sphere has area $S(r)$, the relation $V(r,\epsilon)=S(r)\varepsilon$ approximately holds when $\epsilon$ is small. Then $S(r)=\lim_{\epsilon\to0}V(r,\epsilon)/\epsilon$ is the area.
Comment: @trisct Why don't you differentiate between $\epsilon$ and $\varepsilon$?
Comment: @Allawonder Sorry 'bout that...It was a typo.
Comment: @NuclearWang If you paint both sides of the sphere, then the thickness makes you use extra paint on the outside but save paint on the inside. According to [Weyl's tube formula](https://en.wikipedia.org/wiki/Weyl%27s_tube_formula) those effects cancel out... almost. Well, not exactly for a sphere, but exactly for a torus :) (Yes it's terrible as an answer to "what is surface area". But since the comments section has already left that station, I'm just remarking that the problem of paint of finite thickness covering a curved surface has had surprisingly serious study.)
Comment: @FakeMod: the amount of paint is proportional to the area. Sorry, you are clearly wrong.
Comment: @FakeMod Isn't it the other way around? Gabriel's Horn has infinite surface area but finite volume.
Comment: @doetoe: errare humanum est, perseverare diabolicum. You are drowning.
Comment: @doetoe if one fills the horn with a finite amount of paint, and then empties the finite amount (less a little left on the surface) out again, one has painted the entirety of the surface. This works for any object with a finite volume.
Comment: @Tim That's true (nice argument btw), but the amount of paint will not be proportional to the area. For that you will need a layer of a fixed thickness (and then you would need to take the limit for the thickness going to 0). But such a horn (not of the shape given by the $1/x$ of Gabriel's horn (which has infinite area), but $e^{-x}$ or $1/x^2$, etc, whose area also is finite, will require an infinite amount of paint for any layer thickness.
Comment: @yves for the skeptics you can spell out the grade-school math to calculate the area: if a can of paint can cover $1m^2$, how many cans (or what fraction of a can) does it take to cover the sphere? That's how you measure the area.
Comment: @alexis: the OP doesn't seem to agree.
Answer: A circle of radius $r$ has area $\pi r^2$ and perimeter $2\pi r$. If we run a very thin line of pencil around the perimeter of thickness $\delta$, the graphite area will approximate $2\pi r\delta$.
A sphere of radius $r$ has volume $\frac43\pi r^3$ and surface area $4\pi r^2$. If we cover the surface with a very thin layer of spray-paint of thickness $\delta$, the volume of paint lost from the can will approximate $4\pi r^2\delta$.
Note that in both cases there are two formulae, one for how much space is inside the shape, and how much of a different kind of space, with one lower dimension, is on the edge of the shape. Basically, the edge size is how quickly the interior size grows as the shape widens.
(Edited to link to somewhat more detailed explanations.)
Answer: Imagine a perfect sphere the size of the Earth, perfectly smooth, and that you've got a vast number of perfect little centimeter-square tiles and a large army of bored quarantined kids to lay them out and count them.
On that huge sphere, each tiny tile will seem to lay flat, and to fit perfectly with the tiles on all four sides, and cover the planet with no visible gaps; and after you tally them all you can say that the surface area of the earth is so-many square centimeters. It will be a very (very!) large number, but it'll be a definite number and that's the surface area.
For a smaller sphere, like a beach ball or an orange or a ping-pong ball, a square-cm tile isn't going to fit well at all. So use a smaller tile: one a mm square, or a micron, or Angstrom, or smaller. Give your kids tweezers and magnifying glasses and get them to work. Eventually you'll have the surface area of your sphere, in sq mm, or square Angstroms, or barns (yes, that's a unit of area!) or whatever.
So to conceptualize the surface area of a curved surface, just think smaller and smaller until your hypothetical tile is so much smaller than the curvature of the surface that it seems to lie flat and join perfectly with the tiles surrounding it. And get ready to count to very large numbers.
Comment: wow, my grade 3 brain is (surprisingly!) completely okay with this visualization. it builds upon my already-present grade 3 brain's acceptance of what a square centimetre is, and my acceptance that the Earth is a globe. what a sneaky way to get my brain to visualize very tiny units of measurement on a very large surface!

this visualization, combined with the approximation idea in trisct's answer, of cutting an orange into big patches, then smaller patches (ie, while continuing to think in terms of unit cntimtre squares), gives enough for my grade 3 brain to undrstnd both limits and aprxmtn!
Comment: It's not quite as simple as that. Suppose we start by laying out a row of tiles along the equator, and work our way northwards. Every so often, we will have to reduce the number of tiles as the lines of latitude get shorter; and when we do this, there is no way to avoid significant mismatches, of maximal size (i.e. of the order of half a centimeter). This contradicts your claim that the tiles will seem to fit perfectly on all four sides. And this is not just a consequence of the way that I chose to lay out the tiles; it is a topological certainty....[cont'd]
Comment: ...Your idea is not without merit, by the way; it's just not quite as straightforward as it seems.
Comment: Perhaps, imagine a collection of hexagons and pentagons, arranged in a sort of geodesic configuration instead.  the area of each of these can easily be calculated, and can also get progressively smaller.  Or, measure the triangles between the rows as separate items.  I imagine you could imagine the rest...  Or just use triangles!
Comment: @TonyK That's a good point. In fact to fill the surface of a sphere as per CCTO's suggestion you need **two** types of tile: round ones and complementary-round ones. Squares wouldn't do the trick at all.  Even with round ones you would have to decide how to position them relative to one another: there is no positioning pattern (e.g. vaguely hexagonal) that is "natural" or "ideal", and I think only some numbers would work at all. Plus, taking a simple example, with a 12 points evenly distributed throughout the sphere's surface, the "complementary" shapes would actually take up a lot of area.
Comment: @TonyK The error will be in the same order of magnitude as the one introduced by the fact that you can emphatically *not* tile any part of the Earth with flat, rectangular tiles. In other words, the error will be just as negligible if the tiles are small enough. Your particular error can also easily be avoided by making the width of the tiles the proper fraction of the respective latitude length -- the concept here does not really depend on all tiles being evenly sized.
Comment: @Peter: I agree entirely. See my second comment.
Answer: I would first introduce approximating the area of a shape and pi via the method of exhaustion

The area or circumference is approximately the average of the two, but not quite..
Once students understand this for a two-dimensional shape, it should seem clear both

pi exists and is a transcendental number
it is illogical to try and represent the area or circumference of a circle without it

With this out of the way, you could pose using Exhaustion with an N-faceted polygon (perhaps beginning with a cube inside a cube?). Ideally this will lead them to discover again that they will need pi to find the true surface area, while also subtly preparing them for calculus.
Plausibly you could purchase or fashion an object to show this, but I suspect some graphics simulation software will aid you (and also trivialize discovering the area of the contained and surrounding solids)
Comment: Beyond that objection, I also feel this isn't a good approach to *defining* area (the OP's interest), the reason being that the intuitive feel of this picture is precisely the same as that of this well-known false proof that $\pi=4$: https://math.stackexchange.com/questions/12906/the-staircase-paradox-or-why-pi-ne4 (the same method can start with an inscribed square and seem to demonstrate $\pi = 2 \sqrt{2}$). If one's only conception of the definition of circumference came from this picture, you'd be hopeless in discerning why your picture works and the false proof above doesn't.
Comment: This strategy works well to describe a circle's circumference (though I rather doubt that it makes clear that $\pi$ is transcendental), but I'm not convinced it's a viable strategy for surface areas in any higher dimensions. The method of exhaustion makes explicit use of the existence of infinitely many regular polygons, and the higher dimensional analog is resoundingly false-- there are only finitely many regular polytopes in every dimension $n>2$. That isn't to say the method can't salvaged, but you quickly lose the intuitive appeal when invoking non-regular approximating polytopes.
Comment: Erratum: I believe I spoke too quickly when claiming that starting with an inscribed square can seem to demonstrate $\pi = 2 \sqrt{2}$, though the objections still stand.
Answer: All the solid shapes whose surfaces you are able to understand are finitely rectifiable -- that is, you can think of a finite number of transformations such that the areas (if we agree that areas are additive) can be transformed from covering a solid to lying entirely in one plane.
However, there's no reason to think that this will always be possible for all surfaces which clearly posses an area (albeit intuitively). That would be tantamount to the naive assumption of the Pythagoreans that all quantities can be measured using only integers and ratios of integers -- hence their intense shock on discovering the irrationality of the diagonal of a square!
The general lesson is that elementary methods aren't always sufficient to capture everything we would like to capture -- we have to extend our elementary methods and notions in a way that accommodates objects that wouldn't fit in the earlier scheme, while still preserving their logical character. This is precisely the triumph of the infinitesimal calculus over finite calculus. Many things may be done (with more and more difficulty) with only the latter, but sooner or later one has to admit that one cannot escape using infinitesimal analysis, for even some very basic things.
So, again, the point boils down to an extension, a rising I'll say, from finite methods to infinite methods. That one has to do this doesn't mean that the objects that only admit of infinite methods don't have the properties analogous to those objects that can be conquered using only finite methods -- after all, those old objects can be consistently analysed using the new infinite methods as well.
So, how to understand the surface  of a sphere? Accept that it may be impossible to rectify in only a finite number of steps, and accept therefore that you would need infinitely many operations to completely rectify it. Accept that this is not strange, since in the end you'll have a definite quantity for your area. Finally, since we have only finite brains, how do you think of this process -- just cut the sphere into smaller and smaller pieces (one way is to go along the longitudes), and continue ad infinitum. As you continue this process, you see that the strips become thinner and thinner, and so more and more rectifiable, although they still contain a tinge of curvature. This curvature will never disappear after any finite number of thinning steps, but it gets arbitrarily smaller, so that we know that it approaches a definite rectified form. This is the approach of limits. In the approach of infinitesimals, one would say that after infinitely many such operations the strips become infinitely thin, and flexible, so that the curvature may be completely removed.
Then the sum of the areas of all these strips, gives the area. In the limit approach, you'd have to approximate the area of each strip at each stage of the process, and note that the approximations get arbitrarily close to a certain quantity, which is the desired area.
Comment: Precisely. The only way for an "elementary school brain" to grasp the meaning of the surface of a sphere (and think about it non-casually) is to progress beyond "elementary" territory, or at least glimpse that other territory, which may either excite, baffle or appall. Or maybe all three.
Answer: There is a conceptually simple way to think of this: Build a hollow sphere out of some rigid material such as metal, or plastic. This material will have some thickness, say $d$. Suppose its inner radius is $r$ and its outer radius is $R$ (so we have $R=r+d$).
Now get out your kitchen scales and weigh the thing. Suppose it mass is $W$ grams; and suppose further that the weight of a unit square of your stiff material is $w$ grams. Then the surface are of the sphere is about $W/w$.
I say "about", because of the finite thickness $d$ of the spherical shell. But we know that the inner surface area is less than $W/w$ and the outer surface area is greater than $W/w$. And in the limit, as the thickness $d$ tends to zero, this value $W/w$ will tend to a limit, which is the area of the outer curved surface.
Answer: Consider a "convex polyhedron":

You can start with a simple pyramid or cube, but, as the polyhedron gets more and more complex, it can be made more and more like a sphere.  At each step along the way you can measure the dimensions of each flat surface, add the surface areas together, and come up with an estimate of the surface area of the equivalent sphere.  As the polyhedron is made with more and more pieces, it becomes a closer approximation to the sphere.
There is this mathematical concept known as a "limit" where the approximation, after an infinite number of refinements, essentially becomes a sphere, and the sphere's surface area is determined.
Answer: If the surface area of a sphere is $1\text{cm}^2$, that means that if you cut a sphere into very very very tiny pieces, so tiny they are almost perfectly flat, then the total area of those pieces will be very very very close to $1\text{cm}^2$.
Comment: And, moreover, the tinier (and thus flatter) you make the pieces, the closer the area would be to $1$ square centimeter.
Answer: You already got great answers. I wanted to emphasize that already for flat surfaces you are accepting to approximate your area by small rectangles. And I think it's clear to you that there will always be a small error, that you can diminish but never get rid of (unless you do calculus, and that's one of its magical traits).
With the sphere it's not different really. The leap you need to make is to accept that, instead of "missing area" just by the sides of your rectangles, now you will be "missing area" by not being able to set your paper rectangles flush against the surface. But it should be clear that, the smaller the rectangle, the better the approximation.
One visualization that might help is to draw a circle with some plotting app (Desmos, to name one) and start zooming in. You will see that the more you zoom, the more the circle looks like a line. With the sphere, a 3d version of that phenomenon happens.
Answer: First, I'm a new contributor, so try not to jump on me!  :-)
Secondly, the o/p has asked how this problem might be explored in terms of elementary school math. I'm sure, at least, that we've all been there! Maybe we can approach this in terms of elementary grade math?
I was taken with the idea suggested of painting the surface area, and working out how much paint was required to paint the sphere's complete surface.
If we knew how much paint we started with, and how much we had left afterwards, we could calculate the surface area of the sphere if we measured the thickness of the layer of paint now coating the sphere.
We might go mad and measure the diameter of the sphere before painting it, and after painting it, in order to use good old elementary grade subtraction to calculate the added diameter of the sphere with its fresh coat of paint. That would tell us the thickness of the coat of paint.
How about then looking at the problem from a new point of view? Still with our pot of paint, how about we actually dunk the sphere in it, in order to coat it with paint? And doesn't that suggest an additional test? How would it be if we measured the amount (volume) of paint displaced by the sphere?
Perhaps the paint pot might be completely full, so that immersing the sphere in the paint would cause paint to be displaced from the pot, and thus it could be measured as it flowed into a measuring vessel held beneath the pot, so that the volume of liquid displaced by the sphere would thus be measured. That would also give us a measurement of the volume of the sphere, which must be equivalent to the volume of liquid displaced.
Seems to me I learned about Archimedes in elementary school! Our grade school teacher's favorite joke was that 'Eureka' is Greek for 'this bath is too hot'!
Once we know the volume of the sphere, along with such certain (measured) properties as its radius and its circumference, we can make some calculations of its surface area. Perhaps if we made a series of such experiments, with spheres of differing surface area, we could eventually use simple multiplication or division to arrive at the well-known formula of 4 Pie R Squared.
And nothing has to be flattened onto a plane.  :-)
Answer: This is a very good question, with very good answers, so I'll just chime in with a comment.  Some years ago, a researcher came to me asking how to compute the surface area of a coffee bean.  I responded that it is very hard to get a really good answer.  Like others have said, you need to get a triangulation of the surface, and then add the areas of the triangles.  But if there are lots of small bumps on the coffee bean, it is hard to get a good approximation.
A similar question is "how long is the coast of England", which was originally asked by Benoît Mandelbrot.  The trouble is, as you focus closer and closer in to the surface, the answer gets longer and longer.
Now if he had asked for the volume of the coffee bean, that would have been easy.  Dunk it in liquid, and see how much spills over.  I could have told him to paint the coffee bean, and see how much paint he had to use, but it is hard to apply an even coat when the surface is bumpy.
Answer: Archimedes showed that the surface area of a cylinder (without the top and bottom) is equal to that of the inscribed sphere.  Further, the areas cut off by any planes perpendicular to the cylinder's axis are also equal.  This makes intuitive sense as follows.  The angle at which the sphere "recedes" at any "latitude" gives you MORE surface area than the cylinder slice.  However, the smaller radius of the slice of the sphere at that "latitude", gives you LESS surface area than the cylinder slice.  By drawing some triangles, I was able to convince myself that the MORE and the LESS offset each other exactly.


Execute a python script stored on a server/network location on a user's local machine using PHP

Question: I have a webserver running IIS (Machine A) that is running PHP for me. When a user points their browser to a web page that is hosted on the webserver with a PHP script on it, they need to populate a few forms, and then hit a button that will then run the PHP script, which will fire off a python script I've already built. I am using the exec() command in PHP to call my Python script which is stored locally on the webserver (still Machine A). The idea here is that any user on any machine (with python installed on it) can run the script when they navigate to the webpage.
Unfortunately, one of the forms that is needed for the python script to work is a path to an external drive plugged into the user's machine (Machine B).
My question then is: Is there a way that PHP can execute a python script (stored on Machine A) that is then ran locally (on Machine B) so that when the user has entered in the location of the drive (Win: F:\, Linux: \dev\sda2\, etc ), the python script will know to be looking at the user's local machine (Machine B) rather than the server the script is stored on (Machine A)?
EDIT: Hopefully I have clarified the question above.
Comment: http://code.google.com/p/php-py/
Answer: The question is not exactly clear, but from my understanding, you're trying to execute code on the local user's machine and you can't do that via Python.
Your best bet is to write JavaScript that will do the job for you (a few browsers only as you're working with local storage due to HTML5), or you can have your user upload the files.
Comment: Problem is that I am dealing with 500+GB of data, and so uploading them to the server is not the best way to go. I'm trying to avoid the javascript route since it may not completely satisfy what it is I am trying to do.
Comment: @dralex: "I am dealing with 500+GB of data" that you don't want to upload?  This, then, is your real question.  Please ask your **real** question.  You might want to **update** your question to actually cover your real question.
Comment: Well in that case you could make the end user download your program. Again JavaScript is the easiest way. Rule of thumb when processing data from the server: Get the data and process on server, or send the program and process on client.
Answer:
Is there a way that PHP can execute a python script (stored on Machine A) that is then ran locally (on Machine B)

Never.  The browsers forbid this kind of security hole.


Neo4j do multiple task on an identifier

Question: in a Cypher query i have multiple MATCH i will pass an id with WITH to second part of my query
 s
MATCH user-[:friend*2..3]-other
WHERE NOT user-[:friend]-other
WITH user,other
MATCH user-[:played_in]->uni<-[:played_in]-other
CREATE UNIQUE user-[k:may_know]-other
SET k.w = (k.w) + 1

MATCH user-[:friend*2..3]-other
WHERE NOT user-[:friend]-other
WITH user,other
MATCH user-[:lives_in]->c<-[:lives_in]-other
CREATE UNIQUE user-[k:may_know]-other
SET k.w = (k.w) + 1

in second part i should examine result with another MATCH and do some update task for each match
i can repeat first part for each second part but is there any way to avoid changing result from first part and reuse it several times?
something like copying result in another identifire or something?
Comment: I'm not sure what you are asking. Can you provide a more precise example?
Answer: If you want to match on multiple relationships, e.g. played_in, lives_in, you can do this I think :
MATCH user-[:friend*2..3]-other
WHERE NOT user-[:friend]-other
WITH user,other
MATCH p=user-[r1:played_in|:lives_in]->(l)<-[r2:played_in|:lives_in]-other
WHERE l:University or l:City
WHERE type(r1) = type(r2)
FOREACH (path IN p |
    MERGE startNode(path)-[k:may_know]-endNode(path)
    ON CREATE SET k.w = 1
    ON MATCH SET k.w = (k.w) +1
    )

Neo4j do multiple task on an identifier


pandas data reader google finance for australian stock exchange

Question: Unable to get quotes from google finance using pandas and the new data reader module for tickers specifically on the australian stock exchange.
the relevant google finance page for each stock lists them as:
commonwealth bank asx:cba
billabong international asx:bbg etc
however pandas datareader does not except the ticker in format asx:stock_code such as asx:cba
import pandas
from pandas_datareader import data
import datetime
start = datetime.datetime(2016, 5, 27)
end = datetime.datetime(2016, 5, 27)
f = web.DataReader('bbg:asx', 'google', start, end)

pandas datareader module on github
pandas datareader functionality is now separated from pandas library itself
pandas datareader read the docs
What syntax must be used so the google finance module of pandas datareader returns a pandas dataframe of stock prices for an australian stock on the ASX?
Answer: Google Finance, as Yahoo Finance, places some limits on data offered through their website available via GET request. You can see that for ASX:BBG (and other ASX stocks), the 'export to spreadsheet' option is missing on the historical prices site (compare to NASDAQ:GOOGL, for instance).
You can also check that the ticker syntax ASX:BBG is correct using:
import pandas as pd
url = 'https://www.google.com/finance/historical'
params = {'q': 'ASX:BBG'}
r = requests.get(url=url, params=params)

pd.read_html(r.content)[2]

which yields the first 30 of the paginated results:
               0     1     2     3      4       5
0           Date  Open  High   Low  Close  Volume
1   May 27, 2016  1.44  1.46  1.40   1.46       0
2   May 26, 2016  1.36  1.48  1.36   1.46       0
3   May 25, 2016  1.38  1.40  1.36   1.38       0
4   May 24, 2016  1.38  1.39  1.35   1.38       0
5   May 23, 2016  1.33  1.42  1.32   1.42       0
6   May 20, 2016  1.33  1.35  1.32   1.33       0
7   May 19, 2016  1.39  1.40  1.33   1.34       0
8   May 18, 2016  1.38  1.40  1.37   1.39       0
9   May 17, 2016  1.36  1.38  1.36   1.38       0
10  May 16, 2016  1.38  1.38  1.32   1.36       0
11  May 13, 2016  1.36  1.40  1.35   1.38       0
12  May 12, 2016  1.33  1.38  1.33   1.36       0
13  May 11, 2016  1.32  1.39  1.32   1.35       0
14  May 10, 2016  1.26  1.33  1.26   1.32       0
15   May 9, 2016  1.30  1.32  1.27   1.27       0
16   May 6, 2016  1.30  1.32  1.28   1.32       0
17   May 5, 2016  1.31  1.31  1.28   1.30       0
18   May 4, 2016  1.30  1.32  1.26   1.30       0
19   May 3, 2016  1.32  1.33  1.24   1.32       0
20   May 2, 2016  1.36  1.36  1.29   1.33       0
21  Apr 29, 2016  1.32  1.37  1.30   1.36       0
22  Apr 28, 2016  1.35  1.36  1.28   1.30       0
23  Apr 27, 2016  1.38  1.40  1.34   1.36       0
24  Apr 26, 2016  1.40  1.41  1.37   1.38       0
25  Apr 22, 2016  1.42  1.43  1.41   1.42       0
26  Apr 21, 2016  1.44  1.46  1.42   1.42       0
27  Apr 20, 2016  1.48  1.48  1.42   1.46       0
28  Apr 19, 2016  1.48  1.52  1.44   1.46       0
29  Apr 18, 2016  1.50  1.52  1.48   1.48       0
30  Apr 15, 2016  1.50  1.54  1.49   1.50       0

Hence, you could modify params like this
from datetime import date
params = {'q': 'ASX:BBG', 'startdate':date(2016,4,1), 'enddate':date(2016,5,1)}

to iterate through the different time periods:
               0     1     2     3      4       5
0           Date  Open  High   Low  Close  Volume
1   Apr 29, 2016  1.32  1.37  1.30   1.36       0
2   Apr 28, 2016  1.35  1.36  1.28   1.30       0
3   Apr 27, 2016  1.38  1.40  1.34   1.36       0
4   Apr 26, 2016  1.40  1.41  1.37   1.38       0
5   Apr 22, 2016  1.42  1.43  1.41   1.42       0
6   Apr 21, 2016  1.44  1.46  1.42   1.42       0
7   Apr 20, 2016  1.48  1.48  1.42   1.46       0
8   Apr 19, 2016  1.48  1.52  1.44   1.46       0
9   Apr 18, 2016  1.50  1.52  1.48   1.48       0
10  Apr 15, 2016  1.50  1.54  1.49   1.50       0
11  Apr 14, 2016  1.50  1.54  1.48   1.52       0
12  Apr 13, 2016  1.47  1.52  1.47   1.48       0
13  Apr 12, 2016  1.49  1.54  1.46   1.48       0
14  Apr 11, 2016  1.50  1.54  1.46   1.54       0
15   Apr 8, 2016  1.51  1.52  1.48   1.50       0
16   Apr 7, 2016  1.52  1.56  1.52   1.54       0
17   Apr 6, 2016  1.59  1.60  1.51   1.52       0
18   Apr 5, 2016  1.66  1.66  1.58   1.60       0
19   Apr 4, 2016  1.78  1.80  1.66   1.68       0
20   Apr 1, 2016  1.81  1.82  1.76   1.77       0


Performing multiple deletion in REST API

Question: I have the pages and history table and I am using redis as the database.
I want to delete a history. However, for this, I want the page_id too. Now, in REST, how do you perform the deletion where two different ids are required?
Currently, I am thinking to do the following:
https://www.example.com/api/:history_id/delete?page=:page_id
I also thought to perform the action in POST request but will the DELETE operation be valid under POST request? I mean we generally create in POST request.
Comment: Why exactly do you want your page_id as well? Are you trying to delete both a page and a history, or is the history part of a specific page or the other way around and do you just want to delete the nested resource? How are your page and history related?
Comment: I have a redis stream which looks like `pages::histories`. This contains all the histories of a certain page. Now, to delete a record from the stream, I need the history id so that I can do `XDEL pages::histories history_id`. So that's the case.
Answer: If you don't have an identifier for the resource you want to delete, you are not in standard REST. REST is made for CRUD operation on a specific resource. The operation you want to perform, it is more like a business action.
So, you can send it in POST and specify the business operation as query string parameters, header, or body...or you can adopt another standard like JSON-RPC.
So, you can force REST for business operation or you can adopt another standard.


How to pass additional arguments in $form['#after_build']

Question: function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';

}

I need to pass $element across #after_build function, how I can implement it?
Answer: Most of callbacks like #after_build will received automatically 2 arguments: $elements and $form_state, like this :
my_callback_after_build($element, &$form_state){
//...
}

So you simply have to push your var in the form_state var from where you add your callback :
function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   $form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';
   $form_state['foo'] = 'bar';
}

And you'll get it in the form_state var of your callback like this:
function custom_third_level_auto_suggest_widget_selection_afterbuild($form, &$form_state){
   var_dump($form_state['foo']); //will print "bar"
}


Javascript deconstruction console.log causing error

Question: I tried to deconstruct an array in a recursive method. Below is a simplefied example. Everything is working just fine.
function createNode(index, node) {
    let next = node+ 1
    if (next < 100) {
        for (let i=0; i < 5; i++) {
            [index, next] = createNode(index, next)
        }
    }
    return [index, next]
}
createNode(0, 0)

However when I add console.log to the for loop it crashes.
 for (let i=0; i < 5; i++) {
     console.log(next)
     [index, next] = createNode(index, next)
 }

Uncaught TypeError: Cannot set property '99' of undefined
The problem isn't getting around it. I just want to understand and know what is causing it. I've been searching for a while now and to be honest, I have no idea yet.
Comment: This reminds me of the [Great Semicolon Debacle of 2012](https://github.com/twbs/bootstrap/issues/3057).
Comment: Please add semicolons and Eslint or any other linter on your project! you will avoid having this kind of issues and problems in the future.
Answer: You omitted the semicolon
See https://stackoverflow.com/a/2846298/4023734
This is the primary reason your code is not working.
Usually you can get away with that because JavaScript automatically inserts the semicolons for you.
But in this case the sentence is followed by another which starts with the character [
so,
console.log(next)
[index, next] = createNode(index, next)

is actually the same as
console.log(next)[index, next] = createNode(index, next)

and javascript will evaluate console.log(next) (which returns undefined) and then try to get [index, next] of it. since the expression inside [] index, next is a comma separated expression it evaluates to the last expression, so it effectively the same as just next
the reason the error mentions 99 is because when evaluating this:
console.log(next)[index, next] = createNode(index, next)

the right side needs to be evaluated before the assignment is done, and since it has a recursive call, only after the terminal case will the first assignment be done (after next < 100 evaluates to false)
so when it errors it is trying to evaluate:
undefined[99] = [0, 100]


Inline entity form complex and cardinatlity

Question: I am adding an ief type field to my form with the following
    $form['inline_entity_form'] = [
        '#type' => 'inline_entity_form',
        '#op' => 'add',
        '#entity_type' => 'my_ent_type',
        '#bundle' => 'my_bundle',
    ];

I am sure this is something under my nose that i am missing but how do i force this to complex and set a cardinality for this instance?
Grateful for any pointers
Mathew
Answer: Try changing the type to inline_entity_form_complex so that you have the following;
$form['inline_entity_form'] = [
    '#type' => 'inline_entity_form_complex',
    '#op' => 'add',
    '#entity_type' => 'my_ent_type',
    '#bundle' => 'my_bundle',
];

Got the pointer from the following answer. https://drupal.stackexchange.com/a/207582/9906


How to optimise an automatic ARIMA-model selection?

Question: I've been using statsmodels.tsa.arima_model to fit the residual component of some data.
I've written an algorithm to automatically select the ARIMA model.
Results are not quite as good as I had hoped,
so I am looking for suggestions on how could I improve things.
Please find below a description of what I've tried thus far.
I am dividing the data into a training and a forecasting/testing set.
Up to this point, I've based my choice of the ARIMA model only on the training set.
I allow the ARIMA parameters p and q to run from 0 to 7.
This choice of range is arbitrary.
The d parameter is allowed to be either 0 or 1. This function tries each of them and storages the results:
def iterative_ARIMA_fit(series):
""" Iterates within the allowed values of the p and q parameters

Returns a dictionary with the successful fits.
Keys correspond to models.
"""
ARIMA_fit_results = {}
for AR in ARrange :
    for MA in MArange :
        for Diff in Diffrange:
            model = ARIMA(series, order = (AR,Diff,MA))
            try:
                results_ARIMA = model.fit(disp = -1, method = 'css')
                RSS = sum((results_ARIMA.fittedvalues - series)**2)
                if RSS > 0:
                    ARIMA_fit_results['%d-%d-%d' % (AR,Diff,MA)]=[RSS,results_ARIMA]
            except:
                continue
return ARIMA_fit_results

Next, I look for the model that miminises RSS (total squared residual) using:
def get_best_ARIMA_model_fit(series):
""" Returns a list with the best ARIMA model

The first element on the list contains the squared residual
The second element on the list contains the fit results
"""
if t.isstationary(series)[0]:
    ARIMA_fit_results = iterative_ARIMA_fit(series)
    best_ARIMA = min(ARIMA_fit_results, key = ARIMA_fit_results.get)
    return ARIMA_fit_results[best_ARIMA]

I had initially tried to use as much data as possible for training.
To my surprise, despite using up to x6 more data, the fitting quality worsens.
I made a scan of the training set length, plotting for each the total squared residual and the total squared residual per unit of training set. This is shown in 1. Here, clearly, the fit quickly deteriorates the more data I use, up to some point, where the ARIMA-fit-residual stabilizes.
Also here, the best ARIMA model is consistently the highest-order available MA model. 0-0-7.

Summarising, my optimisation strategy yields an ARIMA fit that:

(Fixed) Consistently (stubbornly) selects the MA model with of the highest available order
Does not improve with the size of the dataset

Do any of you know whether this is somehow expected?
Has any of you tried something different?

Update
The rejection of all the AR models was due to an error on the first function.
These models return statsmodels.tsa.arima_model.ARMAResults.fittedvalues with less entries than the original series and, hence, the RSS returns nan.
These new function does the trick:
def iterative_ARIMA_fit(series):
""" Iterates within the allowed values of the p and q parameters

Returns a dictionary with the successful fits.
Keys correspond to models.
"""
ARIMA_fit_results = {}
for AR in ARrange :
    for MA in MArange :
        for Diff in Diffrange:
            model = ARIMA(series, order = (AR,Diff,MA))
            fit_is_available = False
            results_ARIMA = None
            try:
                results_ARIMA = model.fit(disp = -1, method = 'css')
                fit_is_available = True
            except:
                continue
            if fit_is_available:
                safe_RSS = get_safe_RSS(series, results_ARIMA.fittedvalues)
                ARIMA_fit_results['%d-%d-%d' % (AR,Diff,MA)]=[safe_RSS,results_ARIMA]

return ARIMA_fit_results

Plus this extra one:
def get_safe_RSS(series, fitted_values):
""" Checks for missing indices in the fitted values before calculating RSS

Missing indices are assigned as np.nan and then filled using neighboring points
"""
fitted_values_copy = fitted_values  # original fit is left untouched
missing_index = list(set(series.index).difference(set(fitted_values_copy.index)))
if missing_index:
    nan_series = pd.Series(index = pd.to_datetime(missing_index))
    fitted_values_copy = fitted_values_copy.append(nan_series)
    fitted_values_copy.sort_index(inplace = True)
    fitted_values_copy.fillna(method = 'bfill', inplace = True)  # fill holes
    fitted_values_copy.fillna(method = 'ffill', inplace = True)
return sum((fitted_values_copy - series)**2)

The results are much better, albeit the overfitting. Here 2 is the updated plot showing the residuals and model choices.
Answer: You are overfitting. If you have the choice between an MA($q$) and an MA($q+1$) model, the larger model with more degrees of freedom will almost always fit the data better and yield smaller residual sums of squares. (I would have expected the same to happen for the AR orders, but that this does not happen may be due to the fact that you are modeling residuals.)
ARIMA models are typically selected based on information criteria, like aic, AICc, or bic, after deciding on whether to difference or not based on a statistical test. The documentation for the auto.arima() function in the forecast package for R may give you some inspiration as to what to look at.
Edit: Cagdas Ozgenc correctly notes that increasing the MA order will not necessarily always reduce the residual sums of squares, because the conditional sum of squares estimation is not convex. To illustrate this effect, I simulated 10,000 white noise time series of 100 realization each, fitted MA($q$) models for $q=0, \dots, 7$ and noted the RSS. Below are boxplots of
$$\Delta(q) := \text{RSS}_{\text{MA}(q)}-\text{RSS}_{\text{MA}(q-1)}$$
against $q$. Out of the $10,000\times 7=70,000$ possible differences, $69,851 = 99.8%$ were negative, i.e., a larger model yielded smaller RSS - although there were zero moving average dynamics in the simulated series.

R code:
rm(list=ls())
library(forecast)

n.series <- 1e4
nn <- 100
ma.max <- 7

rss <- matrix(NA,nrow=n.series,ncol=ma.max+1)

pb <- winProgressBar(max=n.series)
for ( ii in 1:n.series ) {
    setWinProgressBar(pb,ii,paste(ii,"of",n.series))
    set.seed(ii)
    xx <- ts(rnorm(nn))
    for ( kk in 0:ma.max ) {
        model <- Arima(xx,order=c(0,0,kk),method="CSS")
        rss[ii,kk+1] <- sum(model$residuals^2)
    }
}
close(pb)

differences <- apply(rss,1,diff)
boxplot(t(differences),main="RSS differences between MA(q) and MA(q-1) models",xlab="q")
abline(h=0)

sum(differences<0)/prod(dim(differences))

Comment: Why do you think a higher order model will "always" fit the data better? Always is a very strong word. The fitting procedure is not convex, only for that reason a complex model may end up fitting worse. If it were convex, then I am more inclined towards your argument, but would be nice if you could provide a few pointers to such a proof.
Comment: @CagdasOzgenc: thank you for your patience. I have edited the answer to include your point.
Comment: Even in the convex case your argument is probably true only for a set of hierarchical linear models (which is the case here with ARMA without gaps in lags). If the more complex model is not subsuming the less complex model, it will not work. Also for non-linear models even if the fitting is convex I am not sure what will happen. Do you know any proofs or results?
Comment: That may well be, but I'm only discussing nested models here, which is the situation the OP is in. No, I don't have any general proofs or results about time series overfitting "in general".
Comment: Thanks @StephanKolassa. Found the reason for any AR order being rejected. For future reference, I've added a second version of the example code and figure.


Find out if the number of selected items > 1 in a multiple select box using prototype

Question: Is there a way I can find out if there are more than one items selected in a multiple select box?
I know it can be done in a linear fashion by going through each option individually, but I would like to avoid that because I am just going to enable or disable a UI component based on the number of items selected.
As this operation does not really require the values nor text value of the selected items, I am looking for a simple way like using pluck or something similar. Any help would be greatly appreciated.
Comment: 59% over 87 questions. Remember to mark your questions as answered.
Answer: In jQuery you can use the descriptor;
<code>$('.select-box:selected')
</code>
to return a list of all the selected items in a multiple select box. You can then use .size() to tell you how many there are.
<code>if ( $('.select-box:selected').size() > 1 ) {
   // do stuff
}
</code>
Comment: Change the `$` to [`$$`](http://api.prototypejs.org/dom/dollar-dollar/) and it works for Prototype too.
Comment: `$('.select-box:selected').length` will give you number of options selected.
Comment: Sorry I was editing to include `.size()`. `.length` would work too.
Comment: At all times I am getting the select size as zero even if there are a lot of items selected. I think when it is a multiselect select box there is no "selected" at all??
Comment: It is actually $$('.select-box option:selected').size() > 1 where .select-box is the css class


Finding solutions of $x$ for $(\sin x -1)(\sqrt{2} \cos x +1)=0$ in the given interval $0 \le x \le 2\pi$

Question:
Finding solutions of $x$ for $(\sin x -1)(\sqrt{2} \cos x +1)=0$ in the given interval $0 \le x \le 2\pi$

Firstly, $\sin x - 1=0 \implies x= \frac{\pi}{2}$
Next, $(\sqrt{2} \cos x +1)=0 \implies x= \frac{3\pi}{4}$
Why is this solution wrong? Is there more than one $x$ value for $\sin x - 1=0$ or $(\sqrt{2} \cos x +1)=0$ in the given interval? How do I know that?
Comment: $x=\frac{5\pi}{4}$.
Comment: Typesetting tips:  You can produce $\implies$ by typing `$\implies$` and $\to$ by typing `$\to$`.
Answer:
Can you find out where did you miss? Look at the blue graph. It's the graph of $y=\sqrt{2} \cos x + 1$. So, the root of the blue graph should be $x=\pi \pm \dfrac{\pi}{4} \Rightarrow x = \dfrac{3\pi}{4}, \dfrac{5\pi}{4}$.
Comment: @user307640 It's not. the period of the cosine graph is $2\pi$, but the root is different. The reason why the root of the red graph is unique is that the graph is tangent to the x-axis. but when the graph of (co)sine has root and isn't tangent to the x-axis, you have 2 roots in the interval $0 \leq x \leq 2\pi.$
Comment: isn't the general solution of a cosine graph is $x=2\pi + \delta$ where $\delta$ is $\frac{\pi}{4}$
Answer: Your overlooked the fact that there are two values of $x \in [0, 2\pi]$ such that $\sqrt{2}\cos x + 1 = 0$.
As we can see from the sine graph, there is only one value of $x \in [0, 2\pi]$ such that $\sin x = 1$.

A number $x$ is a solution of the equation $\sqrt{2}\cos x + 1 = 0 \iff \cos x = -\frac{1}{\sqrt{2}} = -\frac{\sqrt{2}}{2}$.  As we can see from the cosine graph, since
$$-1 < -\frac{\sqrt{2}}{2} < 1$$
there are two values of $x$ in the interval $[0, 2\pi]$ such that $\cos x = -\frac{\sqrt{2}}{2}$.

The interval $[0, 2\pi]$ contains the coterminal angles $0$ and $2\pi$, so there are two values of $x$ such that $\cos x = 1$, namely $0$ and $2\pi$.
However, if we were to instead consider the interval $[0, 2\pi)$, the equations $\sin x = 1$ and $\sin x = -1$ each have one solution, while the equation $\sin x = y$ has two solutions whenever $-1 < y < 1$.  Similarly, in the same interval, the equations $\cos x = 1$ and $\cos x = -1$ each have one solution, while the equation $\cos x = y$ has two solutions whenever $-1 < y < 1$.
Next, consider the diagram below.

When does $\sin\theta = \sin\varphi$?
Two angles have the same sine if the $y$-coordinates of the points where their terminal sides intersect the unit circle are equal.  Clearly, this is true if $\theta = \varphi$.  By symmetry, it is also true when $\theta = \pi - \varphi$.  Moreover, it is also true for any angles coterminal with these angles.  Hence, the general solution of the equation $\sin\theta = \sin\varphi$ is
\begin{align*}
\theta & = \varphi + 2k\pi, k \in \mathbb{Z} & \theta = \pi - \varphi + 2m\pi, m \in \mathbb{Z}
\end{align*}
Now, consider the equation $\sin x - 1 = 0$.
\begin{align*}
\sin x - 1 & = 0\\
\sin x & = 1
\end{align*}
A particular solution of this equation is
$$x = \arcsin(1) = \frac{\pi}{2}$$
Thus, the general solution of this equation is
\begin{align*}
x & = \frac{\pi}{2} + 2k\pi, k \in \mathbb{Z} & x & = \pi - \frac{\pi}{2} + 2m\pi, m \in \mathbb{Z}\\
  & & & = \frac{\pi}{2} + 2m\pi, m \in \mathbb{Z}
\end{align*}
Since we want a solution in the interval $[0, 2\pi]$, we must take $k = 0$ and $m = 0$, which yields the unique solution
$$x = \frac{\pi}{2}$$
When is $\cos\theta = \cos\varphi$?
Two angles have the same cosine if the $x$-coordinates of the points where their terminal sides intersect the unit circle are equal.  Clearly, this is true if $\theta = \varphi$.  By symmetry, it is also true if $\theta = -\varphi$.  Moreover, any angles coterminal with these angles have the same cosine.  Thus, the general solution of the equation $\cos\theta = \cos\varphi$ is
\begin{align*}
\theta & = \varphi + 2k\pi, k \in \mathbb{Z} & \theta = -\varphi + 2m\pi, m \in \mathbb{Z}
\end{align*}
Now, consider the equation $\sqrt{2}\cos x + 1 = 0$.
\begin{align*}
\sqrt{2}\cos x + 1 & = 0\\
\sqrt{2}\cos x & = -1\\
\cos x & = -\frac{1}{\sqrt{2}}\\
\cos x & = -\frac{\sqrt{2}}{2}
\end{align*}
A particular solution of this equation is
$$x = \arccos\left(-\frac{\sqrt{2}}{2}\right) = \frac{3\pi}{4}$$
Thus, the general solution of the equation $\sqrt{2}\cos x + 1 = 0$ is
\begin{align*}
x & = \frac{3\pi}{4} + 2k\pi, k \in \mathbb{Z} & x & = -\frac{3\pi}{4} + 2m\pi, m \in \mathbb{Z}
\end{align*}
Since we seek solutions in the interval $[0, 2\pi]$, we must take $k = 0$ and $m = 1$, which yields the solutions
\begin{align*}
x & = \frac{3\pi}{4} & x & = 2\pi - \frac{3\pi}{4} = \frac{5\pi}{4}
\end{align*}


What chords do you play when playing worship pads?

Question: I'm just starting out playing pads during worship at church after coming from a piano background. When playing along with a lead pianist do I follow along with the chords he/she is playing exactly? I feel that it is moving too fast for a background pad. Or do I just pick four chords from the key the song is in and just play softly?
Thanks for your help!
Answer: You can pick some chords and play softly - but it will sound not good when you change chord and the others don't. Follow the chart that's being played, and change chords when the others change. You can keep them simple - triads will suffice, but be careful to use minors and majors when appropriate. Also be aware thhat when there's a ♭5 chord, you shoulddn't be playing the normal 5 for that - it's flat.
Eventually, if you want to add in some extra notes, as in changed chords with extensions, or slash notes, they can go into the mix.
But initially, ask the lead pianist what he prefers under what he plays - and that might vary a lot number to number. Always listen to what's going on, and be prepared to play something that adds to the song rather than fills it too much.
Comment: "be prepared to play something that adds to the song rather than fills it too much." That's a good jam thinking also!
Answer: "chord" is likely too much. Think "interval", like fifths and octaves. Likely the root of the key. Get to know the sustain pedal but keep listening. And ask the pianist and worship leader for more instruction; that's what they're there for.
Comment: I will try that. What I'm wondering is, do I follow the chord progressions or is there a way to play a pad that does not need to be on tempo or chord progressions specific? I really appreciate your help!
Comment: Good idea! Just play the 3rd and 5th or try a counterpoint.
Answer: It is difficult to improvise an accompaniment during a  sermon,  because you never know what chords the pianist or organist are playing. (Some chorales change the chord on each syllable, while worship songs usually have simpler harmonizations easy to accompany.)
You must ask the liste of the songs in program and exchange a lead sheet for coordination with the other musicians before the service. Then it doesn't matter how differentiated yours arrangements are: you can accompany most songs with tonic, subdominant, dominant,  secondary dominant and relative chords I IV V ... V/V, vi and V7/vi
If you "play" a rest when the harmony changes to quickly this will make your accompaniment more interesting.
Comment: I appreciate all the input. I will try all of your suggestions. Thanks
Answer: Please do not use a lengthy single chord as it only reminds me of a former organist whose belly used to sit on the organ keys playing continuously without her recognizing what was happening. This happened on numerous occasions and I just can't stand it now!


If $x$ is a càdlàg function and $f$ has compact support, how can we approximate $\sum_{s\in(a,\:b]}f(\Delta x(t))$?

Question: Let $E_i$ be a normed $\mathbb R$-vector space and $x:[0,\infty)\to E_1$ be right-continuous. Assume $$x(t-):=\lim_{s\to t-}x(s)$$ exists for all $t\ge0$ and let $\Delta x(t):=x(t)-x(t-)$ for $t\ge0$.
Let $f:E_1\to E_2$ be continuous with $0\not\in K:=\operatorname{supp}f$ and $b>a\ge0$. Moreover, let $$S_\varsigma:=\sum_{i=1}^kf(x(t_k)-x(t_{k-1}))$$ for $\varsigma=(t_0,\ldots,t_k)$, where $k\in\mathbb N$ and $a=t_0<\cdots<t_k$. Set $$|\varsigma|:=\max_{1\le i\le k}(t_i-t_{i-1}).$$

How can we show that $$S_\varsigma\to\sum_{t\in(a,\:b]}f(\Delta x(t))\tag1$$ as $|\varsigma|\to0$?

The idea is pretty clear. Since $0\not\in K$, $$r:=\operatorname{dist}(0,K)>0.$$ Moreover, $$I:=\{t\in(a,b]:\left\|\Delta x(t)\right\|_{E_1}\ge r\}$$ is finite and hence equal to $\{t_1,\ldots,t_n\}$ for some $n\in\mathbb N_0$ and $a<t_1<\cdots<t_n\le b$ ($n=0$, if no jump has size greater than or equal to $r$).
Now we can clearly choose $\delta>0$ such that $|\varsigma|<\delta$ implies $$\left|(t_{i-1},t_i]\cap I\right|\le1\tag2$$ for all $i\in\{1,\ldots,k\}$.
Next, I guess we need to choose $\delta$ even smaller to ensure that $s,t\in(a,b]$ with $0<t-s<\delta$ and $(s,t]\cap I=\emptyset$ implies $\|x(s)-x(t)\|_{E_1}<r$. Can we show this? (I've asked for that separately.)
But even when we are able to show this, I struggle to conclude. So, how do we need to argue?
Answer: First, as you assumed your function is càdlag, for all $c>0$ there are a finite number of $t \in [a,b]$ such that $|\Delta x(t)| > c$. You can see a proof here.
Note that the function $t \mapsto x(t) - \sum \limits_{s \le t}\Delta x(s)$ is continuous, so it is uniformly continuous on $[a,b]$. In what follows, I'm going to keep your notation $r = \mbox{dist}(0, K)$. Denote $z_1, ..., z_m$ all $z \in [a,b]$ such that $|\Delta x(z)| > r$. Let $\varepsilon > 0$.
Because of the uniform continuity, there exists $\delta > 0$ such that for all $a \le s < t \le b$ such that $|t-s| < \delta$, $|x(t)-x(s) - \sum \limits_{s < z \le t} \Delta x(z)| < r$.
Also, since the function $(x_1, x_2) \mapsto f(x_2-x_1)$ is continuous at $(x(z_k-), x(z_k))$ for all $k$, and using that $x(t) \underset{t \to z_k-}{\to} x(z_k-)$, $x(t) \underset{t \to z_k+}{\to} x(z_k)$, the function $(t_1, t_2) \mapsto f(x(t_2)-x(t_1))$ is continuous at $(z_k-, z_k)$ for all $k$. Hence there exists $\delta' > 0$ such that for all $k \in [\![1,m]\!]$, for $t_1 \in [z_k-\delta', z_k[$ and $t_2 \in [z_k, z_k+\delta'[$, $|f\big(x(t_2)-x(t_1)) - f\big(x(z_k)-x(z_k-)\big)| < \frac{\varepsilon}{m}$.
Remark: at this point you should make sure that the two previous arguments convince you, because the conclusion follows from them.
Then for $(t_k^n)_{0 \le k \le n}$ with $a = t_0 < \cdots < t_n = b$, such that $\varsigma = \max\limits_{0 \le < n} |t_{k+1}^n - t_k^n| < \min(\delta, \delta')$, $$ \sum \limits_{i=1}^n f\big(x(t_i^n)-x(t_{i-1}^n)\big) = \sum\limits_{\overset{i=1,...,n}{\exists k: t_{i-1}^n < z_k \le t_i^n}}  f\big(x(t_i^n)-x(t_{i-1}^n)\big)$$
Indeed, for those $i$ such that there is no $z_k \in ]t_{i-1}^n, t_i^n]$, by our assumption on $\delta$, $|x(t_{i-1}^n) - x(t_i^n) - 0| < r$, so by definition of $r$, $f\big(x(t_i^n)-x(t_{i-1}^n)\big) = 0$.
Then, for simplification we can also assume that $\varsigma$ is strictly less than $\min(z_1-a, \min z_k-z_{k-1}, b-z_m)$ so that there is exactly one $i_k$ such that $t_{i_k-1}^n < z_k \le t_{i_k}^n$ for every $k$. By our second assumption on $\delta'$, for $k=1,...,m$, $$\big|f\big(x(t_{i_k}^n)-x(t_{i_k-1}^n)\big) - f\big(x(z_k)-x(z_k-)\big)\big| < \frac{\varepsilon}{m}$$
Summing over all $k$, we get $$\Big| \sum \limits_{i=1}^n f\big(x(t_i^n)-x(t_{i-1}^n)\big) - \sum \limits_{k=1}^m f\big(\Delta x(z_k)\big) \Big| < m \frac{\varepsilon}{m} = \varepsilon$$
Comment: Thank you for your answer. I'm sorry for the late response. I wasn't able to think about this until now. How do we see that $t\mapsto x(t)-\sum_{s\le t}\Delta x(s)$ is continuous? And why does the sum $\sum_{s\le t}\Delta x(s)$ even exist?
Comment: I think instead of $\sum_{s\le t}\Delta x(s)$ we need to consider $\sum_{i=1}^m1_{[z_i,\:\infty)}(t)\Delta x(z_i)$. Using this, the function $\tilde x(t):=x(t)-\sum_{i=1}^m1_{[z_i,\:\infty)}(t)\Delta x(z_i)$ is still not continuous; but càdlàg. And we can show that there is a $\delta>0$ with $\|\tilde x(s)-\tilde x(t)\|_E<r$ for all $s,t\in[a,b]$ with $|s-t|<\delta$.
Comment: But please correct me, if I'm missing something.


T-SQL function to convert int to varchar with plus/minus sign

Question: While I've been troubled by annoying SQL operations, I've got another T-SQL problem.
I have to convert some Int variables into zero-filled varchar with plus/minus sign.
I have tried RIGHT() and CONVERT() functions so far,
RIGHT('000000' + CONVERT(value1 AS VARCHAR(6)), 6)

but I couldn't figure out what the best way to convert them.
What I would like to see is:
If value1 = 305 then  '+000305'

If value1 = -110 then '-000110'

Is there any simple function to achieve this? Or should I have to create my own function for this?
I know it's stupid question, but my current task requires a lot of such non-sense tasks to Stored Procedures (database-side) rather than 'application-side'.
Thanks.
Answer: You want to use CAST instead of CONVERT when you structure it that way.  There's no standard function that will do what you want, but you could create an expression like this to get what you need:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + RIGHT('000000' + CAST(ABS(value1) AS VARCHAR(6)), 6)

If you want to use CONVERT it would look like:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + RIGHT('000000' + CONVERT(VARCHAR(6),ABS(value1)), 6)

Just for fun, here's another way you could do it:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + REPLACE(STR(ABS(value1),5),' ','0')

Comment: Thank you for your answer Brian, and it worked very beautifully!! It saved my time.
Answer: For SQL 2012 and above, you can use FORMAT().
DECLARE @yourTable TABLE (nums INT);
INSERT INTO @yourTable VALUES (305),(-110);

SELECT  RIGHT('+' + FORMAT(nums,'00000#'),7) AS formatted_nums
FROM @yourTable

Results:
formatted_nums
--------------
+000305
-000110

Comment: Thank you for your answer! Unfortunately, my current projects are using legacy SQL Server 2008... But I will try it on my home project!
Answer: may be this one can achieved in both ways using REPLACE or Replicate function.
DECLARE @t TABLE (Num INT)

INSERT @t
SELECT 305
UNION SELECT -110

SELECT CASE WHEN Num < 0 THEN '-' ELSE '+' END +
replace(RIGHT('00000'+ CONVERT(VARCHAR,Num),8),'-','0') AS NUM
FROM @t

SELECT CASE WHEN Num < 0 THEN '-' ELSE '+' END +
RIGHT(Replicate('0',6) + CONVERT(VARCHAR,Abs(Num)), 6)
FROM @t

Comment: Thank you for your answer! I didn't even know such a lot of ways to achieve the same result, in SQL programming. Also, your example has similarity with what I'm currently required tasks (editing columns within SELECT), so it really helped me.