How can I minimize going out of tune when using the whammy bar?

Question: Perhaps my selection of musicians is biased, but usually when I see a whammy bar used, it's usually with a locking tremolo bridge like a Floyd Rose. Everybody else seems to take the whammy bar out and never touch it again.
What I'm finding is that using the whammy bar on my Strat takes it right out of tune, which means using it in the middle of a song would be problematic. I'm assuming that this issue would not be present (or at least not as pronounced) on a guitar with locking tuners.
So do most players just ignore the fact that they'll finish out of tune? Is my guitar in need of a better setup? Am I just using it wrong overall?
Comment: Hell yes, I'm having that same problem with a brand new Fender Player series Strat.
Answer: A key issue in using the whammy bar occurs when strings become slack and therefore change position in the nut. When the whammy bar is returned to neutral, friction at the nut can prevent the strings from returning to their original, natural state, and this can be a large cause of tuning issues.
It is therefore important that the strings can move freely through their 'V's in the nut. There are two key things you can do to help this:

Rubbing graphite, e.g. lead from a very soft pencil, into the V in the nut can help reduce the friction.
Ensure the 'V's are not too narrow for the strings (causing them to become trapped). This is particularly for the wound strings. If they seem to be 'gripping' the strings too much, you could try widening the slots with a small file (caution—at your own risk!) or taking the guitar to a guitar shop for a professional job.
Comment: Scott Henderson talks about it here: http://www.youtube.com/watch?v=Sm_VSjadCiU#t=11m15s
Answer: The nut material can make a big difference, as can the width of the slots.
Binding can occur because the slots are too tight. As @Bill said, you can use graphite. You can use powered teflon. I have been known to pop the string out of the slot and fold a piece of very fine sand-paper into a V and slide it through the slot once or twice, then retrying the whammy bar. Repeating that eventually gets the nut slot opened enough to avoid binding. BUT, you have to be careful to not make the slot deeper; You only want it a tiny bit wider.
You can replace the nut with various materials, like teflon, which should reduce the problem a lot. See your local guitar tech about that.
You can replace the nut with a roller-nut, which has little rollers under the strings as they cross the nut. Again, your tech is the man to see.
As far as people doing some radical tremolo-bar work, watch the videos of Jeff Beck using his Strat for things like "Somewhere over the Rainbow", from his induction to the hall of fame. He plays entire parts of the melody using only the tremolo. Of course, after the song he might hand it off to his tech, but if he was suffering from out-of-tunedness, it would hit immediately after using the tremolo. So, even on a Strat it's possible to do what you want.
Comment: It's set up to be floating, meaning he has a gap on either side of the tremolo block, allowing him to bend up or down. It's nothing unconventional, it's just different than some people set up their guitars. I have two that are set up that way, and one set up with it blocked by string tension so I can only go down.
Comment: Beck can do some ridiculous things with his whammy bar, no doubt.  But he's also got it set up very unconventionally.  At rest, it's set at some crazy angle, so that he can pull it up as much as down.  I wonder if that helps keep it in tune.
Answer: prior to getting hold of floyd rose bridges, Eddie Van Halen used to wind his strings up the tuning peg rather than down as most of us do to reduce the angle that the string comes back at as it passes over the nut. this was done alongside making sure that the nut slots were loose enough and lubed with graphite as mentioned in other answers. all of these tricks added up to reduce sticking over the nut as much as possible.
Answer: The other thing not yet mentioned, which I have on all my guitars that have floating bridges is a locking nut. This basically locks the strings at the nut so they don't move back and forth across the nut, which removes the problem entirely.
May not be appropriate in looks for a strat, but it works.
Answer: Beyond the tricks mentioned above (to recap, nut lubing with graphite, proper nut slot cutting, winding up not down to reduce the angle), there's one I've seen that sounds good is Carl Verheyen's trick of setting the claw in back to parallel the tension of the strings. He goes into it on Youtube.
I'm a Tele guy, so I don't really know from tremolos, but if it works for you, I'm happy.
Answer: Nobody's mentioned the bridge.  For years I struggled with these issues and constantly blamed the nut and then the penny dropped. The G string was actually being pulled sharp over the bridge saddle which also cause the low E to go sharp. My solution is to thread the G string through a piece of the plastic insulation found on electrical wire and make sure it is placed between the string and the bridge saddle. Bingo, no more issues, and I'm pretty aggressive with the whammy, so if it works for me it might just work for you.
Comment: hi this is intriguing but I dont quite underastand it - how was the g-string being pulled sharp after using the whammy bar ? not sure what you mean by "bridge saddle" ?
Answer: Get a roller trem, I only play gretsch, es335 and the likes but roller bridges are the way I've gone with every guitar and I've never had an issue.
Answer: i have a parker fly classic and is the first guitar i have that never goes out of tune using the whammy---it has locking tuners and if you break a string all you do is push the whammy down and at the back of guitar where there is a slide--lock which holds the tuning until you change the string---takes only a minute -the parker has a leaf spring not the old three or four home-hardware barn door junk that never goes back in tune---the guitar is all one piece and weights 4 lbs i had it for about 12 years without any problems
Comment: Hi there - this doesn't actually help the OP figure out how to minimise going out of tune with their strat. Whammy work can be kept in tune on all guitars using techniques outlined in other questions (and the Fly uses a couple of these, but is by no means unique)


Where is the location of developer/globals.php

Question: It's documented on the drupal website here but this path does not exist in the drupal installation.
Answer: That is because there is no such file in the codebase. It is documented separately. When the API site is built, it combines documentation from code comments in Drupal core and the documentation project.


Prove that the relative interior of the closure of a convex set is the same as the relative interior

Question: If $C$ is a convex set then clearly its relative interior is contained in the relative interior of its closure, as it has the same affine hull as its closure. Hence it suffices to show if $x \in$  ri cl $C$ then $x \in$ ri $C$.
By definition $x \in$ ri cl $C$ means there exists $\varepsilon > 0$ such that every point $y \in B(x;\varepsilon) \cap$ aff $C$ is a limit point of $C$ which I guess means $C$ is dense in $B(x;\varepsilon) \cap$ aff $C$? I think from this you can construct line segments in the ball and show that $x \in C$, but I'm still not sure how to show that it is in the relative interior.
According to the book I'm reading and a pdf I found online there should be an easier proof that resembles the proof (in that they both use the line segment principle) that cl ri $C = $ cl $C$. The proof goes as follows:
It suffices to show the cl $C \subset$ cl ri $C$ so suppose $x$ is in cl $C$ and $y \in \text{ri} C$. The line segment principle tells us all the points along the line segment between $x$ and $y$ are in the relative interior of $C$, making $x$ a limit point of the relative interior as desired.
Try as I might, I can't seem to use  a similar proof to get the result I want. Any ideas?
Comment: Are we operating in finite dimensions here?
Comment: Finite dimension, yes.
Answer: Suppose $x \in \text{ri cl } C$. Then by definition there exists an $\varepsilon > 0$ ball around $x$ whose intersection with the affine hull is contained in cl $C$.
The relative interior of $C$ is non-empty so let $y \in \text{ri } C$, $\delta:= \frac \varepsilon {\| x - y \|}$, and define
$$ z:= \Big( 1 + \delta \Big) x - \delta y$$
Clearly $z$ is an affine combination of points in $\text{cl } C$, and it is easy to verify it is within $\varepsilon$ distance of $x$, so we may conclude $z \in \text{cl } C$.
Finally we have
$$ x = \frac 1 {1+\delta} z + \frac \delta {1 + \delta} y$$
i.e. $x$ is a convex combination of $z$ and $y$. Since $z$ is in the closure and $y$ is in the relative interior, by the line segment principle $x$ is in the relative interior, as desired.


Jackson desearialize a list of Strings coming from Redis as a generic type

Question: I have a piece of Kotlin code that looks like this:
val objs = results.map {
            if(it == null) return@map null
            val typeRef: TypeReference<T> = object : TypeReference<T>() {}
            jacksonObjectMapper().readValue(it, typeRef)
        }

I want my method to return a List<T?> where T is a generic type in the signature of the code.
While it "kinda" works, its not specifically what I am looking for.
For instance, when I call my method like this :
 myMethod<MyDTO>get(keys: List<String>) // ---> I want to get a list of MyDTO

the methods returns a list of LinkedHashMap instead of a list of MyDTO.
What am I doing wrong?
Answer: Well, I have just found a way.
I can pass an extra parameter to my method:
ofClass: Class<T>

So my method now looks like this:
 val objs = results.map {
            if(it == null) return@map null
            jacksonObjectMapper().readValue(it, ofClass)
        }

and carry the type information with it.
Works like charm.


Changing for loop to while loop for regex

Question: How do I change this for loop to while loop?
String [] strArray = testcontent.split(Pattern.quote("SolrDocument{content=["));

for (String str : strArray) {
  System.out.println("TestSplit: " + str);
}

I am new to Java.
Comment: google `how to iterate over array using while loop in java`. Have some research efforts then post the question here.
Comment: All for-loops are essentially glorified while-loops - and a for-each loop is a glorified for-loop. Convert it to a normal for-loop first, then it should be evident.
Answer: int index = 0;

while(index < strArray.length)
{
  system.out.println(strArray[index]);
  index++;
}


Why do I expect $\operatorname{Spec}(\Bbb Q(i)\otimes_{\mathbb Q} \Bbb Q(i))$ contains 2 points?

Question: This is related to Iitaka's Algebraic Geometry Chpt 1, Sec 20, Example 1.27.
Let $X=\operatorname{Spec}(\Bbb Q(i))$ where $\Bbb Q$ is rational numbers. Then $X\times_{\operatorname{Spec}(\Bbb Q)}X=\operatorname{Spec}(\Bbb Q(i)\otimes_{\Bbb Q}\Bbb Q(i))$.
$\textbf{Q:}$ If I am a normal person, I would expect fiber product of one point with another point over a point is a point.(i.e. If $X=\{pt\}$ instead and given $X\to\star$ map where $\star$ is another point, then $X\times_\star X=\{(\text{pt},\text{pt})\}$.) For the scheme category, this yields 2 points as can be seen $\Bbb Q(i)\otimes_{\Bbb Q}\Bbb Q(i)\cong \Bbb Q(i)\times \Bbb Q(i)$. Why does this happen or what is the intuitive reason that I would expect the fiber product have 2 points? It seems this is due to the fact that scheme category does not behave like set category or topological space category as it has extra information contained in sheaves.
Comment: From the algebraic perspective, the tensor product of a nontrivial field extension $k\subset K$ with itself, $K\otimes_kK$ is never a field, and if $k$ is perfect, this is reduced, so it's spectrum must be multiple points. The reason you would expect something like this is that the fiber product in schemes is very far from pullbacks in $\textbf{Set}$ or $\textbf{Top}$.
Answer: From what I understand the fiber product for affine schemes $Y=Spec(R),Z=Spec(S)$ is the affine scheme $Spec(S\otimes_T R)$ for some subring $T$ of both $S,R$ (more generally two subrings $T_1,T_2$ together with an isomorphism $T_1\to T_2$)
Here
$$X = Spec(\Bbb{Q}[t]/(t^2+1))$$
$$X\times_{Spec(\Bbb{Q})}X = Spec(\Bbb{Q}[t]/(t^2+1) \otimes_\Bbb{Q} \Bbb{Q}[s]/(s^2+1)) = Spec(\Bbb{Q}[t,s]/(t^2+1,s^2+1))$$
$$= Spec(\Bbb{Q}[t,s]/(t^2+1,(s+t)(s-t))$$
It is not hard to see that $\Bbb{Q}[t,s]/(t^2+1,(s+t)(s-t))$ has two prime ideals $(s+t)$ and $(s-t)$.
Comment: Because the $\times$ doesn't mean product of set of prime ideals but tensor product of local rings ? $R \otimes_T S$ is universal for the bi $T$-linear homomorphisms from $R\times S$ so that's where we take the product of the fibers
Comment: I could prove the fiber product of schemes in this case contains 2 points. Instead of proof, I am looking for a heuristic reason why it must contain 2 points from geometric point view. In other words, what makes fiber product of schemes in scheme category so different from topological fiber product in topological space category or correspondingly set category.
Comment: Were there any geometric explanations for such phenomena? Algebraic explanation is easy as tensor product of local is not necessarily local. Or consider $B_1,B_2$ 2 banach algebras over complex number and $B_1\otimes_C B_2$ as analogue. Now $B_i\cong C(M_i,C)$ from Gelfand-Naimak where $M_i$ are maximal spectrum. So the question is whether even $C(M_1,C)\otimes_CC(M_2,C)=C(M_1\times M_2,C)$?
Answer: It's just not very accurate to think of $\text{Spec } \mathbb{Q}(i)$ as being "a point," for exactly this kind of reason. In this context a more accurate picture is that it's "two points related by a Galois action."
More generally, if $X$ is a scheme over $\mathbb{Q}$, rather than look at its Zariski spectrum we can consider the set of points $X(\overline{\mathbb{Q}})$ over the algebraic closure of $\mathbb{Q}$, equipped with the action of the absolute Galois group $\text{Gal}(\overline{\mathbb{Q}}/\mathbb{Q})$. IMO this is a much more geometrically sensible notion of "point" to consider; among other things, unlike the Zariski spectrum it preserves finite products.
If we apply this recipe to $X = \text{Spec } K$ where $K$ is a number field, say $\mathbb{Q}[x]/f(x)$, then $X(\overline{\mathbb{Q}})$ consists of $\dim K$ points, one for each root of $f$ over $\overline{\mathbb{Q}}$, together with the Galois action that factors through the action of the Galois group of $f$ on its roots. Since $f$ is irreducible this Galois action is transitive, and the Zariski spectrum can only see the orbits of this action, rather than the action itself.
I mentioned that this functor preserves finite products, so now let's apply it to the product of two copies of $X = \text{Spec } \mathbb{Q}(i)$. We can think of $X$ as being the two points $i, -i \in \overline{\mathbb{Q}}$, related by complex conjugation. (Here I'm secretly thinking about the embedding of $X$ into the affine line given by the quotient $\mathbb{Q}[x] \to \mathbb{Q}[x]/(x^2 + 1)$.) So $X \times X$ is four points $(\pm i, \pm i)$, which are divided into two orbits by complex conjugation: $\{ (i, i), (-i, -i) \}$ and $\{ (i, -i), (-i, i) \}$. Again, the Zariski spectrum only sees the orbits of this action, which is less information.
Comment: People think that the fiber product is mysterious but really it's more that the Zariski spectrum isn't very well-behaved.


What's the difference between explicit and implicit Runge-Kutta methods?

Question: I have been working on numerical analysis, just as a hobby. I am only aware of the basic fourth order Runge-Kutta method in order to solve problems. When I was digging deep into it, I found there are types, mainly explicit and implicit, but I was finding it hard to understand them. I did try reading through this article, but it still couldn't help me much.
I would be glad if you could explain in layman's terms.
Answer: Runge-Kutta methods are methods for numerically estimating solutions to differential equations of the form $y^\prime=f(x,y)$. One is interested in both explicit and implicit methods, as they have quite different applications.
To simplify things, I'll consider the two simplest Runge-Kutta methods that are usually ascribed to Euler.
The (usual) Euler method is the simplest example of an explicit method:
$$y_1=y_0+h\;f(x_0,y_0)$$
The backward Euler method is the simplest implicit method:
$$y_1=y_0+h\;f(x_1,y_1)$$
To explain the notation: $(x_0,y_0)$ is the initial point, from which the Runge-Kutta method "launches" itself to generate a new point, $(x_1,y_1)$, where $x_1=x_0+h$ and $h$ is a so-called "step size".
The Euler method is an explicit method in that the expression for $y_1$ depends only on $x_0$ and $y_0$. On the other hand, backward Euler is an implicit method, since the right-hand side also contains $y_1$; that is, $y_1$ is implicitly defined.
Why would we need to consider both, when the explicit methods look simpler? That is because the implicit methods are in fact the most efficient way to handle so-called stiff differential equations, which are differential equations that usually feature a rapidly decaying solution. Explicit methods need to take very tiny values of $h$ to accurately estimate the solution, and this takes lots of time. Implicit methods allow for a more reasonably sized $h$, but you are now required to use an associated method for solving the implicit equation, like Newton-Raphson. Even with that overhead, implicit methods are more efficient for stiff equations.
Of course, if the equations are not stiff, one uses explicit RK methods.
Comment: P.S. I would recommend reading [the book by Hairer, Nørsett, and Wanner](http://books.google.com/books?id=F93u7VcSRyYC) if you wish to delve further into RK methods.
Answer: First of all, you have to analyze your equations before using RK methods. There are three types of equations, suitable for Runge-Kutta methods.
1. The system is leading into equilibrium (Heat equation or any system
    with enthropy grow)
2. The system is unstable (if you try to solve heat equation back in time or put a broom into labile position)
3. The system is time-symmetric (Almost any particle dynamics, harmonic oscilator, Keppler problem)
There is a common rumour that implicit methods are better than explicit, but this verdict may be misleading.
The first type of equations is something what is identified as "stiff-problems". We expect exponential dynamical decay into some particular solution. Backward Euler is very suitble for this kind of equations. The problem of Euler method is in its exponential error grow. Specially backward Euler has ability of exponential decay of systems energy. This kind of inconvenience is not problematic in this type of equations. It just come to equilibrium little bit faster.
The second type of equations is really problematic. There is not much hopeful approaches to obtain trustble solution since whole system is rapidly growing and higly sensible to initial values. The only one advice is to use as much higher-order method as you can (no need to be implicit), however you still have to manage inital value sensitivity problem.
The third type needs symmetric method. Like mid-point rule, trapezoid rule or some Gauss-Legendre quadrature method. Just try to satisfy condtition of time symmetry: If you use the same method into final solution and turn back time, you have to get intial values again. This methods are usable in some orbital mechanics in astronomy for example. Euler or Backward Euler are comletely improper in this kind of equations. On example of a simple harmonic oscilator, the Euler cause exponential grow of the amplitude and the Backward Euler cuse exponential decay of the amplitude. And if you use an implicit mid-point rule, the amplitude will be stable even if your simulation runs in billion oscilator periods. I reccomend to try make your own simulation of Euler and Backward Euler on harmonic oscillator equations. Its illustrative as well.
The theorem "implicit methods are better" (which should not to be pure theorem) is seen in case 3 of symmetric problems. All symmetric Runge-Kutta methods must be implicit. Hovewer, its a reason why Runge-Kutta is not so popular here. Much better approach is the Verlet integration (https://en.wikipedia.org/wiki/Verlet_integration) which has comparable results as symmetric implicit RK methods and its much easier to implement and its explicit in many cases.
If you are interested in first type of equaations like heat equation or maybe many equations in fluid dynamics, the "L-stable" methods are for you. This is truly the place where theorem "implicit methods are better" is resonable. But you must be careful! You may obtain equilibrium solution just becouse of decay of the L-stable methods even if the exct solution will never reach some equilibrium state. The stability analysis of equations must be made before numerical implement of any L-stable method and you have to be sure that your equations are actually "stiff". Yust remember. Your methods must be L-stable here. Its true that all L-stable RK methods are implicit but not all implicit methods are L-stable.


Trying to add a URL Auto redirect every 120 seconds in Swift

Question: I am very new to coding so any help would be appreciated.
I am attempting to gather some basic survey data about video conferencing technology I am testing at work and the paid solution I am using routes to an advertisement page after the survey is completed. Since I won't be able to re-launch the web url every time the survey is taken, I would like for the page to automatically redirect back to the initial URL page every 2 minutes. Below is my existing code.
Thanks.
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://Mysurveypage/1234")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }
}

Answer: var timer = Timer.scheduledTimer(timeInterval: 120.0, target: self, selector: #selector(ViewController.toDoTask), userInfo: nil, repeats: true)

func toDoTask()
 {
    let url = URL(string: "https://Mysurveypage/1234")!
    webView.load(URLRequest(url: url))

 }

First time can call toDoTask() in viewDidLoad()
Answer: You can try this code:
import UIKit
import WebKit

class HomeViewController: UIViewController, WKNavigationDelegate{

    var webView = WKWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.navigationDelegate = self
        view = webView
        let url = URL(string: "https://Mysurveypage/1234")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }

    override func viewDidAppear(_ animated: Bool) {
        //Uncomment the following line of code to reload the webview currently on top of navigation stack, or in plain words, current browser tab showing in mobile window, Comment the other timer code if you intend to do this
        //Timer.scheduledTimer(timeInterval: 2 * 60, target: self, selector: #selector(reloadWebView), userInfo: nil, repeats: true)

        // Following line of code reloads the initial url i.e. "https://Mysurveypage/1234"
        Timer.scheduledTimer(timeInterval: 2 * 60, target: self, selector: #selector(redirectToInitialUrl), userInfo: nil, repeats: true)
    }

    @objc private func reloadWebView() {
        webView.reload()
    }

    @objc private func redirectToInitialUrl() {
        let url = URL(string: "https://Mysurveypage/1234")!
        webView.load(URLRequest(url: url))
    }
}

PS: Apple documentation says, here:

You should never call this method directly.

It's usual to do all one time functions/operations, that one wants to do in UIViewController's life-cycle, in viewDidLoad() method.
Comment: The OP wasn't calling `loadView`. There is nothing wrong with the code posted by the OP.
Answer: Thanks so much for the responses. So unfortunately I am so new to coding, I did not know where to enter Jagdeep's code, but copying naeemjawaid's code worked great. I did have to delete the word "Home" from the class ViewController line. After that, all works great. Thanks again for the assistance.


What is it called when the note pattern is the same in each bar but the actual pitch and note are different?

Question: I have a question for music theory asking me about what I notice about the rhythm in bars 3-6 and the note pattern is the same : crotchet, 4 quavers, crotchet, minim. But the actual name of the note varies (e.g the first note in bar 3 is an A but in bar 4 it is a G and every note is different like this). There is a particular term for this but I really can't remember it. Any suggestions?
Comment: If the intervals are the same also just the starting note is different, that might be sequence.
Comment: Looks somewhat like a fugue subject.
Answer: If the melodic contour is similar, either exactly transposed or adjusted to retain the shape but remain diatonic in the prevailing key, it's a sequence. If the contour of the melody changes, it's a rhythmic mode.
Edit: Now that I see the example, ms.3-6 form a (mainly) diatonic melodic sequence in D minor. I say "mainly", because you get the usual sharping of the leading tone in m.6.
Comment: There are four repetitions in her example, @Tim. Ostinati can be used for small sections of, say, phrase length (as here). In this case, though, we do have a melodic sequence. (It really does look like a fugue subject.)
Comment: Another possibility if the rhythms are the same, but the pitches are different could be a rhythmic motif.
Comment: Or a rhythmic ostinato, which is why I'm asking for clarification. The differences between these and rhythmic mode are fairly small, though.
Comment: @Patrx2 - ostinato is something that continues, rather than gets repeated once or twice.
Comment: @Tim Agreed with Patrx2 here an ostinato is any repeated rhythmic figure.  Also agreed that we have a descending tonal (as opposed to real) melodic sequence.  I have to say though, that the lack of dynamics is kind of bugging me.
Comment: @jjmusicnotes, yeah, I'd expect at least some "resets" of the dynamic levels after the crescendi. If this an opening subject (and it looks to be), its dynamics are "shooting to the top" very early as it is currently notated.


cursor position in custom function

Question: Is there any way to get cursor position in custom function? I also know that the example bellow able to get the x and y.
$(".myelement").mousemove(function (e) {
    var y = e.pageY - $('.myelement').offset().top;
    console.log(y);
});

However my html is come from an ajax, so example is not working. So I was thinking about a custom function. But custom function not able to set an event, am I right? Is there any suggestion or other way to get cursor position in an element (div) ?
Comment: `my html is come from an ajax, so example is not working` In this case you need to use a delegated event handler. See the question I marked as duplicate for a full explanation of the problem and several solutions.
Answer:
However my html is come from an ajax, so example is not working.

This means the Element is added in dynamically into the DOM. To make Jquery work on the elements added dynamically we must make use of event delegation
$(document).on("mousemove",".myelement",function (e) {
        var y = e.pageY - $('.myelement').offset().top;
        console.log(y);
    });

Comment: this put inside document ready?
Comment: no, put it outside from document ready
Comment: @ImHappy you can put this anywhere.
Answer: You simply need to delegate that event from a higher element, even possibly the document itself. That way it will work even for your dynamically loaded content.
Then you save the x andy position in a variable for use in your function
$(function(){

    var y;
    $(document).on('mousemove','.myelement',function(){
        y = e.pageY - $('.myelement').offset().top;
    });

    // use `y` elsewhere

});

cursor position in custom function


How to solve a differential equation problem?

Question: I want to find the solution of the following differential equation
$$\frac{dy}{dx}+y^m=1.$$
For example, if $m=1$, then $y=1-e^{-x}.$
If $m=2$, we have $y=\tanh(x)$, but for $m\ge 3$, $y=?$.
Comment: Is there any initial condition? In both the examples you solve you implicitly assume that $y(0)=0$.
Comment: You get $x$ as a function of $y$ viz. $\int dx=\int\frac{dy}{1-y^m}$. If you factorise $1-y^m$ over $\Bbb R$ using its roots in $\Bbb C$, the rest is an exercise in partial fractions.
Comment: Yes, we assume y(0)=0.
Answer: We have that $dx =\frac{1}{1-y^m}dy$, so $x=\int \frac{1}{1-y^m}dy$, which has no elementary representations. (Can still be expressed in terms of hypergemoetric or incomplete beta, but I don't think that was what you were looking for.)


I need help on some problems of geometry . How do I find the missing length on a triangle side

Question: This is what the triangle looks like, I need help finding the missing number which is right now replaced by 'x'
Comment: Have you learned about Pythagoras' theorem?
Answer: We have: $x^2 = 6^2 + 8^2$. You can take it from here.


How do i dynamically import changing feed links within a feed

Question: I am uncertain how to approach this.
I have a feed with housing cases that is changing constantly. The feed consists of a case number and a feed link to that particular house. Each house has so much information that it has its own feed. Over time, more will be added and these feed links will change.
For each of these feed links, I want to create a single node. My issue is that I don't really see a solution on how to create these dynamic feeds from the one "main" feed.
It's going to be about 75-150 feeds within the "main" feed. So I have this list of changing feed links that I need to dynamically import.
This is in Drupal 8 and I have been trying to use the module feeds to accomplish this.
Answer: It sounds like you need a custom implementation that will dynamically add feed importers based on a particular "Master feed import".
Personally I would do this with the migrate API instead of feeds as it gives you much higher flexibility for data manipulation and queue control for large datasets.
Comment: Thanks, I will try to look into migrate API.

By custom implementation, do you suggest a custom module to handle it through Migrate API?
Comment: @MortenH yes.  When using Migrate, you always have to write a custom module.
Answer: If each feed has the same structure, you would only need to create one feed type and then  one feed of that type for each house.
You could write a custom module to dynamically create the feed entities, or to dynamically update them.
Of course, you could also look into Migrate. Migrate does indeed have a larger feature set, but also a steeper learning curve and almost no UI.


Validação de entrada de dados permitindo TAG HTML

Question: Preciso fazer uma validação, sempre valido no lado do cliente/JS e servidor/PHP, e permitir que o usuário digite algumas TAGs para formatação do resultado final, alguma dica de como fazer isto? Melhor usar um campo do tipo textarea ou usar um editor?
Algumas TAGs que quero permitir:
h1 a h6

<address>

Answer: você pode utilizar desta função nativa do php strip_tags($texto, $tags_permitidas);
por exemplo:
strip_tags("texto a ser filtrado", '');

desta forma o resultado seria:
texto a ser filtrado

para maiores informações veja a documentação:
http://php.net/manual/pt_BR/function.strip-tags.php
Answer: Criei a função abaixo para salvar os dados do usuário, fiz alguns testes e consegui executar o filtro e salvar com sucesso.
function fDescribe() {
        functions::startSession();
        if($_POST['token'] == $_SESSION['token']) {
            $this->describeC = strip_tags($_POST['textarea'],
             '

<address>
');

            $this->conn = parent::getCon();
            $this->pQuery = $this->conn->prepare("update table set description=? where user_id=? limit 1");
            $this->pQuery->bindParam(1, $this->describeC);
            $this->pQuery->bindParam(2, $_SESSION['id']);
            $this->result = $this->pQuery->execute();
            unset($this->conn);
            if($this->result == true) {
                functions::generateJsonMsg('success', null, null, null, null);
                exit();
            } else  {
                functions::generateJsonMsg('fault', 'queryFault', null, null, null);
                exit();
            }
    } else
        return false;
}


H1 estilizado com borda central com css

Question:
Olá, queria colocar  uma borda da mesma maneira que está na imagem. Não sei como chama este tipo de borda, então fica difícil pesquisar.

 Destaques

-------------------------------- Destaques --------------------------------
Sei que é possível fazer isto com css, pois já usei vários temas bootstrap que usam isto com css. Porém quero saber como fazer manualmente.
No caso percebi que não pode sobrepor uma imagem, pois se tiver um background-image ficaria com a letra riscada no fundo.

E se tirasse o background color e colocasse transparente ficaria assim:

Mas teria que ficar assim:

Igual a este site aqui:  http://adtrends.com.br/sobre.php
Comment: o site de exemplo utiliza os `::before` e `::after`, utilizar o inspetor de elementos do Chrome e Firefox (botão direto > inspecionar elemento) pode ajudar
Comment: Opa Amigo acho que o que você esta procurando é uma div para ficar em volta desse cabeçalho faz o teste, você pode colocar essa div e por o mesmo plano de fundo , tirando as bordas e posicionado ela encima da linha, e se você for usar esse titulo como link link fica até maior a área de contato.
Answer: Amigo, não sei se você está falando da borda dos produtos, ou sobre esse HR junto ao destaques.
Mas caso seja sobre os produtos, é um simples
border: solid 1px;

Os destaques eu faria um HR normal, e colocaria o texto dentro de uma div sobrepondo o HR, usando position.
Comment: Estou falando dos destaques.
Comment: Sabe como se chama este efeito?
Comment: O Diego Souza mandou um exemplo acima: http://jsfiddle.net/btxdm6ut/
Comment: Mas, acredito que seja sobreposição de objetos.
Comment: Não é apenas sobreposição, existem várias maneiras de fazer isto. E sobreposição é apenas uma maneira de fazer. E acredito que não seja a correta pois com um fundo transparente não iria funcionar.
Answer: Veja esse exemplo:
http://jsfiddle.net/btxdm6ut/
Com position: absolute.
A borda está com valor solid, mas se quiser colocar tracejada pode usar dotted ou alguma imagem e colocar como background-image.

Veja com fieldset.
http://jsfiddle.net/bLoz10by/1/
Comment: Então explique melhor na sua pergunta e poste uma imagem de exemplo.
Comment: Tem um erro, no caso e se o fundo tiver um background image? Não teria como a letra ficar transparente.
Comment: `background-color: transparent` no H3, onde eu defini branco.
Comment: Mas na verdade não tem um erro. Eu respondi o que você perguntou. Agora é apenas um adendo.
Comment: A questão é que não pode ficar com a imagem por cima, pois daria bug caso alguém quisesse colocar um background-image.  Tendo respondido ou não, não posso aceitar a resposta pois está errada. teria que ser como este site aqui.  http://adtrends.com.br/sobre.php

No caso o que está sendo feito só funciona no fundo branco ou do fundo da mesma cor. Porém se tiver uma textura daria errado.
Comment: Melhorei a explicação da pergunta
Comment: Adicionei um LINK a minha resposta.
Comment: Já que você respondeu primeiro, coloquei como resolvido.
Answer: Uma maneira de fazer sem precisar de sobreposição é usar os pseudo-elementos after e before, segue o exemplo:

h1 {
  text-align: center;
  position: relative;
}
h1:before,
h1:after {
  content: "";
  width: 35%;
  height: 1px;
  background: #555;
  position: absolute;
  top: 50%;
}
h1:before {
  left: 0;
}
h1:after {
  right: 0;
}

Meu título

Answer: Existe um exelente tutorial sobre o assunto no seguinte link:
Create Headings with Lines in CSS
Das soluções propostas, a minha referida é utilizando Flexbox:

h1 {
  display: flex;
  flex-direction: row;
  justify-content: center;
  text-align: center;
}
h1:before, h1:after {
  background-color: #ddd;
  content: '\a0';
  flex-grow: 1;
  height: 1px;
  position: relative;
  top: 0.5em;
}
h1:before {
  margin-right:10px;
}
h1:after {
  margin-left:10px;
}

Destaques

H1 estilizado com borda central com css


Variance Estimation of MA(1) with known autocovariance function

Question: I haven't worked with time-series in a while now and stumbled upon them in a different setting.
Given $X_t\sim\mathcal{N}(0,\sigma^2)$ for $t=1,\ldots,n$ and the process $Y_t$ for $t=1,\ldots,n-1$ defined by:
$$ Y_t = X_{t+1} - X_t$$.
Imagine I only observe $Y_t$ and now want to estimate $\sigma^2$ from these observations. It seems $Var(Y)=2\sigma^2$, but I have problems deriving this theoretically. I want to be able to show that the properties of a consistent estimator for the variance of $X$ also work for $Y$, especially the Mean Absolute Deviation $MAD$.
$Y_t$ can be interpreted as a $MA(1)$ process with known autocovariance function, but I have problems deriving this result.
Any help or hint how to assess this would be greatly appreciated.
Answer: I assume that $X_t$ are iid normal distributed with mean $0$ and variance $\sigma^2$. $Var(Y_t) = Var(X_{t+1}-X_t) = Var(X_{t+1})+Var(X_t)-2Cov(X_{t+1},X_{t}) \\= Var(X_{t+1})+Var(X_t) = \sigma^2 + \sigma^2 - 0 = 2\sigma^2$.
Comment: Hey, thank you very much for the reply. I considered the same, but was wondering the following: Is the sample variance still an unbiased estimator then, despite the dependence of the $Y_t$ ?
Comment: Sure. Let's have a little diffrent look at your question: Assuming $X_t \stackrel{iid}{\sim} N(0,\sigma^2)$. This means $Y_t \stackrel{iid}{\sim} N(a,b)$ with $a=E(X_t-X_{t-1})=0$ and $b=Var(X_t-X_{t-1})=\sigma^2+\sigma^2$. Now it should be obvious.
BTW: With the sample variance you get an estimator for the variance of $Y_t$, not $X_t$
Comment: But for $Y_t$ constructed the described value, the assumption that $Y_t$ is iid does not hold, as for each $t\in{2,\ldots,n-2}$ the conditional properties $\mathbb{P}(Y_t\leq x|Y_{t-1}) \neq \mathbb{P}(Y_t\leq x)$ $\mathbb{P}(Y_t\leq x|Y_{t+1}) \neq \mathbb{P}(Y_t\leq x)$.
I'm confused on wether this has an effect on the unbiasednes of the estimator of variance of $Y_t$.
If we had independent realizations of $Y_t$, I would not have an issue of that. One thing I thought about was deriving estimator properties from a partition of the $Y_t$ like in
Comment: W Stadje (1984) A note on sample means and variances of dependent normal variables, Series
Statistics, 15:2, 205-218, DOI: 10.1080/02331888408801759
Comment: Right, my inattention, the $iid$ shouldn't be there, because the autocorrelation function $\rho(k) = .5$ with $k=|1|$ and $0$ when $|k|>=2$.
Let $\gamma(k):=E(Y_t\cdot Y_{t+k})$ be the autocovariance function ($Y_t$ is weakly stationary with mean $0$) and let $(Y_1,\dots,Y_N)$ be your sampled vector. Then $\hat{\gamma}(k)=\frac{1}{N}\sum_{t=1}^{N-k}(Y_t-\bar{Y})(Y_{t+k}-\bar{Y})$ with $k\geq 0$. The bias of this estimator converges to $0$ when $N$ goes to infinity: According to my notes you have
$E(\hat{\gamma}(k))=\gamma(k)-\frac{k}{n}\gamma(k)$. For $k=0$ you are unbiased.


Total conversions vs individual feature conversion

Question: I have a new website and an old website with 5 features. All features have been updated in the new website.
The old checkout page has a 10% conversion rate.
The new checkout page has a 9% conversion rate.
If the user clicks on feature A,
On the old checkout page, conversion rate is 23%
On the new checkout page, conversion rate is 18%
If a user clicks on feature A, all other parts of the checkout page are still involved. Think about it as a popup that gives additional information, so the conversion rate after clicking on the popup is still affected by other features on the checkout page.
Is it possible to calculate if feature A is better on the new checkout page vs the old checkout page? Is it as simple as yes because the difference is just 5% when the feature is clicked vs 10% in all scenarios?
I do not have any additional information.
Thanks
Answer: This is standard A/B testing. Since you do not have a version of the new website with ONLY feature A changed (and the rest as in the old website), you cannot make any conclusions about the impact of changing only feature A. It is possible that A got better but that there are some interaction effects with the other changes that reduces its performance as a whole.


Como exibir dados de um usuário em uma página através do ID?

Question: estou desenvolvendo um site onde o administrador pode visualizar os dados cadastrais de todos os usuários que estão cadastrados no sistema, e esses dados são exibidos em uma tabela.
A tabela só exibe alguns dados (id, nome e email) e eu quero fazer um link onde o administrador pode clicar para ver as informações completas do usuário selecionado. Por exemplo, se ele clicar no link "ver mais" do usuário com ID 1, a tela exibe todos os dados dele (id, nome, rg, cpf, email, data de nascimento).
Meu código por enquanto é esse:
<?php
    $consulta = "SELECT * FROM adms";
    $con = mysqli_query($con, $consulta) or die (mysqli_error);
?>

        ID
        Nome
        E-mail

    <?php while($dado = $con->fetch_array()){ ?>

            <?php echo $dado['id'] ?>
            <?php echo $dado['nome'] ?>
            <?php echo $dado['email'] ?>
            Ver mais

    <?php } ?>

A tabela fica assim:

Minhas principais dúvidas são:
1) A linha Ver mais está declarada do jeito certo? Estou em dúvida por causa do $dado[id], não sei se vai funcionar desse jeito
2) Para criar a página de exibição dos dados, o nome dela seria adm_vermaisAdm.php?id='$dado[id]' ?
3) Para exibir esses dados, como eu faço pra pegar o ID da URL?
Desde já agradeço a todos que responderem
Answer: Opa! tudo bom?
Acho que consigo lhe ajudar. Na ordem das dúvidas:
Primeira dúvida
A forma como está escrito não vai funcionar. Lembre-se que a tag  é HTML e que para interpolar dados php em sua declaração, você deve novamente abrir a tag do php. Segue exemplo:
<a href="adm_vermaisAdm.php?id='<?php echo $dado['id']?>'">Ver mais

Isso já irá garantir que a sua âncora esteja apontando para a página "adm_vermaisAdm.php", passando na url o parâmetro id, com valor igual ao que está armazenado na váriavel $dado['id'].
Segunda dúvida
A resposta é não!
A página (arquivo php) que você está apontando na âncora é a "adm_vermaisAdm.php" e é assim que o arquivo deve ser nomeado.
adm_vermaisAdm.php

Terceira dúvida
Para pegar o id que veio pela sua URL, tu podes fazer o seguinte:
<?php $id = $_GET['id']; ?>

Assim você já terá em mãos o id para realizar a consulta no e exibir todos os dados referentes ao mesmo.
Espero ter ajudado :D!
Comment: Muito obrigada! Consegui exibir os dados sem problemas :)


Ouput Node Reference Field Title in Drupal 7

Question: When creating templates in Drupal 6 I can output just the title for the value of a node reference field like so:
echo $node->field_example[0]['safe']['title'];

I'm trying to do the same thing in Drupal 7 - I've tried many variations like the examples below but the output is always blank or throws an error:
print $content->field_example['und']['0']['node']['title'];

print $content['field_example']['#object']['field_example']['und']['0']['node']['title'];

Any help on how to grab the 'title' value is much appreciated.
Comment: Have you tried debugging the `$node` and `$content` variables to see what you've got available?
Comment: possible duplicate of [Correct way to display a custom field in a custom content type page template](http://drupal.stackexchange.com/questions/34301/correct-way-to-display-a-custom-field-in-a-custom-content-type-page-template)
Answer: print $field_example[0]['node']->title;

This ended up being the syntax needed to pull just the title from the value of a node reference field.


Deleting The Last Character in A String Livecode Language

Question: I need to delete last character in a string Livecode.
I have wrote this below in English.
on mouseUp

   replace last character with Backspace in field"dialed"

end mouseUp

I am a newbie, so please use simple answers :)  Thank you.
Comment: Hi Tim and thank you I have tried the above code:  I have looked in dictionary in livecode, but it is no help, I also googled, cant find code for a simple delete char button. sigh.  I am super new
Answer: Deleting the last character of a field is very simple:
on mouseUp
  delete the last char of fld "Dialed"
end mouseUp

Comment: Thank you so very much, and doesn't even need code to handle if the string is empty!!  Wow thank you!
Comment: If the answer is useful, please click on the Accept icon on the left. That keeps people answering your questions.
Comment: Ok I might be dense, but there isn't a "Accept" button for me to click.  I do appreciate the answer it works flawlessly.
Comment: Okay, that's weird but if there isn't one so be it.
Answer: If you think that is nice, what about:
delete character 2 of word 3 of line 4 of fld "dialed"

Comment: Jamal is soooo right! Also, this is not a solution to the given problem.


Arc length of function - confused about particular u-substitution in integral

Question: I am trying to teach myself how to compute the arc length of a function through a textbook, and I am stuck on how they did a particular integral substitution in a worked example.
I'll provide the specific line of working I am stuck to provide relevant information quickly. I'll follow with my working, and then provide the context of the question below if necessary.
Where I am stuck
I am unsure how to get from:
$$\int_1^3\sqrt{1+4t^2}\,dt$$
to, as the book puts it exactly:
$$\int{\frac{1}{2}\cosh^2u \,du}$$
They say they are
putting $2t$ = $\sinh u$.
I am unsure of how to get to this line using that substitution. (I am also unsure why the bounds of integration are gone, I originally assumed out of convenience but different bounds due to the substitution are being used later in the example.)
My attempt
$\int_1^3\sqrt{1+4t^2}\,dt$
Using $2t$ = $\sinh u\Rightarrow2\,dt = \cosh u \Rightarrow dt = \frac{\cosh u}{2}\,du$.
$\int_1^3\frac{1}{2}\sqrt{1+\sinh^2 u} \cosh u \,du$
Using $\sqrt{1+\sinh^2 u} \equiv \cosh^2 u$:
$\int_1^3\frac{1}{2}\cosh^2u \cosh u \,du$
$\frac{1}{2}\int_1^3\cosh^3u \,du$
Clearly there is an issue here, as I have arrived at $\cosh^3u$ instead of $\cosh^2u$ (and potentially different bounds of integration.) I'm not sure if there's an error in my working and/or if there's some different integration technique that I need to apply here.
More context
The example relates to finding an arc length of the function $y = x^2$ from $(1, 1)$ to $(3, 9)$. This length $s$is being worked out using: $$\frac{ds}{dt} = \sqrt{\left(\frac{dx}{dt}\right)^2 + \left(\frac{dy}{dt}\right)^2}$$
The function is parameterised: $x = t$, y = $t^2$. I am then confident in using this to find that:
$$s = \int_1^3\sqrt{1+4t^2} \,dt$$
If there is any more information I should provide please do not hesitate to answer. (Also, I've not posted here much so if there is any error in my MathJax formatting please correct it as well as telling me what I should have done instead. Thank you.)
Answer: Note the correction: $$\sqrt{1+\sinh^2(u)} \equiv \cosh^{\color{red}{1}} (u)$$as $\cosh^2(u)-\sinh^2(u)=1$.
Comment: @Robin Happens with most people.
Comment: @Robin You're welcome.
Comment: Ah, thanks. Silly mistake!
Comment: Just approved the answer, it made me wait a while before doing it. Thanks again.


Unhandled promise rejection in Docker with 'opn' npm module

Question: UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): Error: Exited with code 3

I apparently get this error when I open links using the module in Docker container. I tested the code in my local before I put the code on my server which uses Docker. And It literally works well in my local that doesn't use Docker. So I assume that something is wrong with docker but there's actually no way to figure out what the problem is. Is there anyone who has ever used 'opn' module with Docker?
app.use('/:encoded_id', function(req, res) {
let base58Id = req.params.encoded_id;
let id = base58.decode(base58Id)
Url.findOne({ _id:id }, function(err, doc) {
    if (err) console.error(err);
    if (doc) {
      opn(doc.long_url[i]);
     }
    else res.redirect(config.webhost);
 })
});

Comment: You're going to have to be a _lot_ more specific with this question; where's your code that calls `opn`? Add a `process.on('unhandledRejection', err => { console.error(err.stack); throw err; });` so you can see the actual error.
Comment: @Jacob I just added the code. By the way, after I set node version of my server to the same as my local one, It doesn't says the promise error anymore but still doesn't open any links.
Comment: @Jacob I'm going to try to add your code but I'm not sure where should I put the code in.
Comment: It should just run during startup. My code is for logging the error, not fixing anything (since I have no idea what's broken); what error do you see?
Comment: @Jacob http://pastebin.com/uAEW8JCT this is what I got
Answer: Exit code 3 means that:

A required tool could not be found.

You say that the goal is to "open links", so the Docker container probably does not have a browser (or at least a default browser, anyway).
If you are sure that the required software is installed, it is probably a configuration issue. In this case, you can work around it by specifying the app option. But try to avoid using it if you can, as it is platform dependent and so will make your code less portable.
Comment: Why does the Docker suppose to have a browser? I just want people to open links when they enter my website not the docker.
Comment: `opn` is for opening files/URLs/etc _in a desktop environment_; what are you trying to do? I'm confused what you mean by "open links." You mean hyperlink `` tags?!
Comment: @Jacob I'm making a website that compress multiple links to one link. and If I try to open multiple links in client-side(using javascript), popup blocker prevents to open multiple links. but If I use `opn` module in server-side, It helps me to avoid the popup blockers. so basically this is why I use `opn`
Comment: Oh man... `opn` works on your _local_ machine because it's opening links on your own computer; it won't let a remote server open links on a client's desktop!
Comment: @Jacob Is there any way to do what I want to do?
Comment: The `opn` module on npm is basically a JavaScript API equivalent of the `open` command in your terminal. E.g. if I go to my terminal and run `open package.json` it opens [Sublime Text](https://www.sublimetext.com/) because that is my default text editor. And if I run `open http://example.com` it opens Google Chrome, because that is my default browser. This is what `open` does and also what [opn](https://www.npmjs.com/package/opn) does. It just opens stuff for you, on your own machine.
Comment: @PhillipYS first you should visit [npmjs.com](https://npmjs.com) or [npms.io](https://npms.io) and try to find other projects that do what you want. If you really can't find anything, come back here and post a new question.


GPS coordinates of android device are not getting

Question: I am working in android.
i want to get GPS coordinates of my android device.
I am using this code to get my coordinates:-
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Location location = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            if(location!=null) {
               myLongitude = location.getLongitude();
               myLatitude= location.getLatitude();
            }
            else {
               myLongitude =0;
               myLatitude= 0;
            }

           LocationListener mlocListener;
           mlocListener = new MyLocationListener();
           mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);

and this the class:-
 public class MyLocationListener implements LocationListener
 {
    @Override
    public void onLocationChanged(Location loc)

    {
        myLatitude= loc.getLatitude();
        myLongitude=loc.getLongitude();
    }
}

but all the time i get latitude and longitude to zero only. please suggest me what mistake i have done.
Thank you in advance.
Comment: Will this help?

http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-a/3145655#3145655
Comment: you want co-ordinate using Network provider in device or in emulator?
Answer: Make sure you put the permission in Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>


Koa GET return result immediately to the client and do something afterward

Question: I'm writing an io.js and Koa API and I have a GET route that I use to pass data to the API and return OK to the user immediately. Basically I don't care about the result that the GET request will return, I just want to pass the data. This is why I want to return "OK" to the client then he makes the GET request as soon as possible and then process the data from the request.
My code so far is as follows:
app.use(route.get("/passData", function*(){
    this.body = "OK";
    yield doSomeWork(this.query);
});

function *doSomeWork(query){
   // do work
   // the code below should be triggered when the client receives the OK message
}

Is there a way to do this?
Comment: If I remove `yield` `doSomeWork` is not executed.
Answer: You do not want to yield on doSomeWork--that tells Koa to wait, which is exactly what you do not want.
app.use(route.get("/passData", function*(){
    this.body = "OK";
    doSomeWork(this.query); // REMOVE YIELD
});

Since doSomeWork is just a plain old asynchronous function now, it's shouldn't be a generator. (If you leave the * there, you'll be calling a generator, which does absolutely nothing other than to create an iterator which will then be thrown away.)
function doSomeWork(query){ // REMOVE ASTERISK
   // do work
   // the code below should be triggered when the client receives the OK message
}

Comment: Don't quite understand. If you put a `yield` before `doSomeWork`, then Koa will wait for it to finish. As I understand your question, you do not want that. If `doSomeWork` is a generator yielding promises that you want to execute in sequence, then invoke it with `co`.
Comment: Is there a way to do this without removing `yield`? Inside the `doSomeWork` function I am using  a generator functions to insert data into my database, so if I do not use `yield` it will not work, or I'll have to rewrite a lot of code.


What a bandleader should do? [ROCK BAND]

Question: I am wondering what is the role of a rock band leader ? What are limits ?
Is it his role to bring rules ? Make the objectif and say : if you're not happy, leave the band ?
Comment: I think this is a very interesting and serious question (+1) the down votes may be as it was not telling what band OP was meaning ...
Comment: Every band is different. There can be no one answer to this question.
Comment: There is no specific answer to be given for this question. There can be different answers.
Answer: Rock bands don't typically have leaders in the way that classic orchestras/ensembles do.
Rock bands can have a manager/managers, who organise the administration side of things and triage tasks away from the band members (amongst other things).
Some bands might have overbearing members who assert themselves as leaders and almost lead the band as a dictatorship (see someone like Axl Rose in the original Guns N Roses days for a good example if you're interested) but this is not a defined role, nor does one have to exist.
The internal culture and atmosphere of typical rock bands should be one of "everyone is equal". Sure, there might be exceptions where someone gets self-important and tries to boss people about, but that is typically something you should try to avoid if you want a healthy band relationship. Big Egos Break Bands.
Comment: A decent band should always have a leader. It's a nice idea to have a democracy, but it doesn't work in the real world. After all, someone has to fire the drummer...
Comment: Having been in all kinds of situations like these, it all depends. A lot. Democracies are great in theory, but so much time can get wasted 'discussing' all sorts, from which numbers, to which gigs, which rehearsals etc. Having a designated leader is great when potential problems occur - "See Jim, he's our bandleader." But Jim has to be a special sort of person, who knows his stuff, will stand up and be counted, and is a responsible guy. I won't be told what to do by someone I have no faith in, musically particularly, whereas if someone really knows their stuff, I'll sit down and shut up!
Comment: We were 18, 15, 14 and 13 years. Each of us was speaking of "my band". We tried to live together in a democracy but finally we decided to throw out the drummer (13) as he came always too late to the band practice or forgot it, or he forgot his sticks, or he missed the timing. Well, at least this was a great chance for him: He has been the drummer for about 20 years in one of the most famous bands of our nation :)
Comment: @Tetsujin - sadly, maybe not for the victims, GB isn't punching anyone any more. RIP.
Comment: Case in point - Ginger Baker. If he's not happy, he punches someone… anyone. [Google "ginger baker angry" for many refs ;)
Comment: @PeteCon I guess so, in the same way that a group of friends who get together regularly might have one or two people who make more of the decisions or have more prominent personalities. IRL, I don't think the leader's role should be to say "if you're not happy, leave the band" though as OP suggests...
Comment: @JamesWhiteley In my experience of playing in bands semi-professionally for a long (long!) time, saying "if you're not happy, leave the band" is exactly one of the leaders jobs, as well as organizing subs, clients, gigs, set lists, rehearsals, transport... a lot of the things that a manager would do if we were busy enough to warrant one. In a band, you're with those people for more time than anyone else apart from (maybe) your spouse - so anyone who isn't happy, isn't going to be a good fit.
Comment: @PeteCon makes sense. I guess I read it in a kind of authoritarian "my way or the highway" voice. In my experience having someone to do that kind of administrative work is healthy, but as soon as someone asserts themselves as the leader and stops consulting the rest of the band for decisions, that's when the band falls apart. Maybe I'm lucky and tasks are usually delegated out or people volunteer to do those kinds of jobs in bands I've been in. At the very least, while people might take the lead on specific tasks there hasn't been a set-in-stone permanent leader.
Comment: Then there's   [someone famous] And the E-Street Band.  No doubt who was in control.
Comment: @PeteCon All those jobs that you've seen a band leader do, I've seen done by various members of the band at various times. In my experience, some bands have multiple leaders, one leads on booking, one leads on writing, one leads on business matters, etc. I've definitely seen leaders who were never called leaders with no discussion of who is the leader but there is one anyway,. It just depends. IMHO this question does not have one objective answer. I was in a three-piece that had no clear leader and was essentially a democracy, but three is a much easier number to manage.
Answer: I would discuss and define the rules before I enter in a band. The rules can be  defined by all members  - like we know from a democracy-institution, they should be  accepted and respected like  a couple living in a married  couple-ship. (Do you call this The commitment?)
The role of leadership can also be discussed:
The leader role can change

each session (like in a meeting or conference)
each season
depending of the piece (may be the lead-singer or the composer)

but once chosen by the other group members the bandleader can define his own style of leadership like in a company.
It is advantageous to be so good that the others can't renounce on you.
Answer: Both @Albrecht Hügli and @James Whiteley have good points in their answers.
I would say that it is very similar to classic chamber music like a string quartet. The similarity is that it is a small group where you can all be creative and discuss things. I have played a lot of chamber music of various kinds and we never "announced" a leader. Well you do agree on who sets the tempo which in a string quartet is typically the first vilolinist, so in that moment he is the leader, but there isn't usually an overall leadership, and there can be many sections in the music where someone else better set the tempo.
I have also played electric violin in a rock group and my experience is that it is a similar situation.
But it doesn't always hold water that there is no leader. You can find groups with a clear leader whether it is a rock group or a classic chamber music group. You can also find groups where there is a temporary leader, like someone has the leadership on a particular piece, but another one might lead another piece. So I guess there are no set standards that you have to follow.
In general a small group is like @Albrecht Hügli said in his answer: A kind of married couple-ship. You get very close in such a group just like in a marriage.
Answer: If you just mean the power structure of the band then it depends. I was in a band where myself and another musician had more knowledge of booking shows, recording, promoting, writing, etc. - so we both shared duties. In another band I was playing strictly guitar and backups - I didn't make decisions that didn't involve my parts or my playing. As far as playing music - I say the drummer is the 'bandleader'.
You can choose to run your band like a dictator like Frank Zappa - but most of the time it's collaboration. Sometimes there are one or two creative 'leaders' and the rest of the band members are there to play. Sometimes the entire band is involved with every decision made. It really depends, and there has to be mutual respect.
Answer: I'm the band member who fronts a band, owns the PA, finds the gigs, creates the sets, communicates/coordinates/negotiates/promotes on behalf of the band, and who does the administration and accounting. Regardless, we were a democracy and everyone had a say, but no clear leader. One member took a leadership role to direct musically and another had graphic arts skills. This democracy was working because it empowered people.
However eventually, this got out of hand when one band member wanted to change an agreed-to process to accomodate him. The situation went south when that member was disrespectful and I fired him. At that point, I appointed myself as the leader. Not having a leader will get the band mired in discussions and negotiation. There has to be a clear leader to break ties and arbitrate and guide the direction IMO.


Is there a specific name for the arpeggio symbol?

Question: Is there a specific name for the squiggly arpeggio symbol? If so, are there different names for arpeggio symbols that point up or down or spans both clefs?
I find having to write out "arpeggio symbol" so much gets old, but I'm guessing there isn't a better way.
This does seem like a pointless question, but some symbols have their own names aside from the names of what they stand for.
Comment: Both Wikipedia and Dolmetsch  just call this the 'arpeggio' or 'broken chord' symbol. I'm not sure what you're after -- e.g. what would you call a quarter rest other than "quarter rest symbol" ?
Comment: @Carl It does seem like an odd question, but I was thinking this might be similar to a coda or other symbol that uses a foreign word.
Comment: This is the relevant internal documentation from the ultimate music engraver, lilypond: http://www.lilypond.org/doc/v2.19/Documentation/notation/expressive-marks-as-lines#arpeggio Nowhere do they call the line anything else than "arpeggio".
Answer: The symbol is just called an arpeggio as you can see here on Dolmetsch where it is specifically called an arpeggio sign.
This may seem odd, but there are many examples of this. You would play staccato on a staccato mark, you play a note accented when there is an accent mark, you use your pedal when there is a pedal mark.


Agrupar Últimos Ida Retornados pelo Insert no banco

Question: Nesse Script a baixo eu faço um laço onde dentro dele realizo insert no banco.
ao final de cada insert ele me retorna o ID da linha gravado no banco peça variavel (.$sql->insert_id .) até aqui tudo OK
if (isset($_POST['nome'])) {

foreach ($_POST['nome'] as $key => $value) {
echo 'nome='.$nome = mysql_real_escape_string($value);  // data da saida
echo 'id='.$id_produtos2 = mysql_real_escape_string($_POST['id_produtos'][$key]);
echo 'valor='.$valor = mysql_real_escape_string($_POST['valor'][$key]);

$bd = new MySQLiConnection();
$sql = $bd->prepare("INSERT INTOcotacao(chave,id_transfer,id_empresa,para2,tipo,status) VALUES (?,?,?,?,?,?)");   // Atribui valores às variáveis da consulta
$sql->bind_param('isssss', $chave,$id_transfer,$id_empresa,$subcli,$off,$status,);
if($sql->execute()){
print 'ID da linha gravado : ' .$sql->insert_id .'
';
echo $id_retornado = $sql->insert_id;
}else{
die('Error : ('. $bd->errno .') '. $bd->error);
}
$sql->close();

Meu problema é... em um loop de 3 , em cada insert, retornando um id novo
como grava-los em uma variável, todos os ids que me retornaram
  Segue a logica
  3x Loop{

  Insert
  retorno id 1 ...

 }

  $todos_ids_retornados = "1,2,3" ; // Isso que eu quero fazer e não sei como

Answer: Dentro do laço de repetição salve os id's em um array utilizando o array_push.
if (isset($_POST['nome'])) {

    $cotacao_id = []; //adicione esta linha
    foreach ($_POST['nome'] as $key => $value) {

        if ($sql->execute()) {
            array_push($cotacao_id, $sql->insert_id); //adicione esta linha
        } else {
            die('Error : (' . $bd->errno . ') ' . $bd->error);
        }
        $sql->close();
    }
}

Depois basta percorrer o array $cotacao_id com outro foreach.
foreach ($cotacao_id as $id) {
    //sua logica aqui
}


Numerically verify a matrix is positive semidefinite

Question: I am trying to numerically (in Julia) verify that

A symmetric matrix $\mathbf{A}$ is positive semidefinite if and only if it is a covariance matrix.

Then I need to verify in both directions, i.e.

Given a positive semidefinite matrix $\mathbf{A}$, show that it is a covariance matrix.
Given a covariance matrix, show that it is positive semidefinite.

However, I am not sure

What properties should a matrix have to be a covariance matrix.
I know I could generate a covariance matrix using the following and I know that cov is positive semidefinite if and only if all of its eigenvalues are non-negative. But it turns out that minimum(eigvals(cov)) is a negative number close to 0 (on the order $\sim 10^{-15}$), I am not sure if I could conclude that cov is positive semidefinite since numerical reasons.

n = 100
u = randn(n);
cov = u * u'

Any input will be appreciated.
Answer: Maybe it's easier to verify that a covariance matrix is a Gram matrix (and vice versa) and to verify that a p.s.d. matrix is a Gram matrix (and vice versa).  The numerical linear algebra step could then be the Cholesky decomposition.
But with any  demonstration of this result on a computer whose computational model is some flavor of floating point arithmetic and not $\mathbb R$ arithmetic will suffer from roundoff error at some place or other.
Answer: The term "covariance matrix" comes from Probability Theory not from Linear Algebra. So, any positive semidefinite matrix can be assumed to be a covariance matrix of some distribution.
As for precision issue, having a minus eigenvalue in the order of 1e-15 is not problem because "double type" has a precision which is less than 15 digits. However, since matrices you are dealing with are positive semidefinite, i.e.:
$$C = UU^T \Rightarrow x^TCx = \|U^Tx\|_2^2\geq 0 \quad \forall x$$ singular values will be equal to eigenvalues. Therefore you can use SVD which produces more stable and correct results.


Equivalent definition of Riemann integrals

Question: Given the following definition of the Riemann upper integral:
$$\bar{\int_{a}^{b}}f =\inf \{ U(f;P): \text{ P is a partition of
        [a,b] } \}$$
Where $U(f;P)=\sum\limits_{i=1}^{n} M_{i}(f)\Delta x_i$ and $M_{i}(f)=\sup\{f(y): x \in [x_{i-1}, x_i] \}$.
I want to show that this definition is equivalent:
$$\bar{\int_{a}^{b}}f =\inf \{ U^o(f;P): \text{ P is a partition of
    [a,b] } \}$$
Where $U^o(f;P)=\sum\limits_{i=1}^{n} M_{i}^{o}(f)\Delta x_i$ and $M_{i}^{o}(f)=\sup\{f(y): x_{i-1}<y<x_i\}$.
I noticed that in my textbook the discussion of Riemann integrals is the characterized by picking the supremum of an open interval whereas in class we have discussed it in terms of supremum's of a closed interval.  We were asked as a non-homework exercise to prove they are equivalent.  Our hint was to let $\alpha = \inf\{U^o(f:P)\}$ and show that $\alpha=\inf\{U(f;P)\}$.
I don't see how this proof is straight forward because my thinking is $\sup\{[a,b]\} \geq \sup\{(a,b)\}$.
Answer: The definitions are not exactly equivalent. The $U^0$ definition can 'avoid' a finite number of points at which $f$ could be infinite, whereas if $f$ is infinite at a single point, then the $U$ integral will be infinite.
However, if $f$ is bounded, then the integrals are the same. So, I will assume $f$ is bounded on $[a,b]$.
First, it should be clear that $U^0(f;P) \leq U(f;P)$ (always, even if $f$ is unbounded).
Now let $P = (a=x_0,x_1,...,x_n=b)$ be a partition. Let $\epsilon>0$ such that $x_{k}+\epsilon < x_{k+1}-\epsilon$, and let $P_\epsilon = (x_0,x_0+\epsilon, x_1-\epsilon, x_1+\epsilon,...,x_n-\epsilon, x_n)$. Then
\begin{eqnarray}
U(f;P_\epsilon) &=& \sup_{x \in [x_0,x_0+\epsilon]} f(x) \epsilon + \sup_{x \in [x_0+\epsilon,x_1-\epsilon]} f(x) (x_1-x_0-2 \epsilon)+\cdots \\
&\leq& \sup_{x \in [x_0,x_0+\epsilon]} f(x) \epsilon + \sup_{x \in (x_0,x_1)} f(x) (x_1-x_0)+\cdots \\
& = & U^0(f;P)+ 2\epsilon(\sup_{x \in [x_0,x_0+\epsilon]} f(x) + \sup_{x \in [x_1-\epsilon,x_1+\epsilon]} f(x) \cdots) \\
& \leq & U^0(f;P)+ 2\epsilon (n+1) \sup_{x \in [x_0,x_1]} f(x)
\end{eqnarray}
So, in particular, we have for all $\epsilon>0$, for all partitions $P$, there exists a refinement $P'$ such that $U(f;P') \leq U^0(f;P)+\epsilon$.
 If $\cal P$ is the collection of partitions of $[a,b]$, it follows that $\inf_{P \in \cal{P}} U(f;P) =\inf_{P \in \cal{P}} U^0(f;P) $.
Comment: There are two groups of terms on line 3, 'small' brackets around points of the partition $P$, and 'the rest'. $U^0(f;P)$ is larger than 'the rest' and the $2 \epsilon(\cdots)$ term upper bounds the sum of the 'small' brackets. Line 4 is just a coarse upper bound on the latter sum. Hopefully this clarifies...
Comment: In line 2 of your inequalities are you missing an $\epsilon$?
Comment: @emka: I don't think so, the idea is to replace $\sup_{x \in [x_0+\epsilon,x_1-\epsilon]} f(x) (x_1-x_0-2 \epsilon)$ by $\sup_{x \in [x_0,x_1]} f(x) (x_1-x_0)$. Is this where you think the $\epsilon$ is missing?
Comment: @cooper.hat Sorry it took me a while to get to this.  I posted that only after a cursory reading.  After a careful reading I understood everything.
Comment: No problem, glad to help!
Comment: Actually, I do have a question now.  What is happening computationally in lines 3 and 4 of your inequalities?
Comment: Specifically this is the proof that a Darboux integral is equivalent to a Riemann integral (if they exist).


How to (dis)prove Mahalanobis $ d^2 $ is non decreasing?

Question: I have been studying multivariate analysis and hypothesis testing , and came across this question in back exercise

Define Mahalabonis measure of distance squared between
two populations with a common positive definite dispersion matrix and show
that it is a non decreasing function of the number of characteristics.

I searched this on Google,  and read that mahalanobis $ d^2 $ indicates the correlation , and since correlation increases as the number of characteristics increase,  so can we write this as the explanation to the question?
I am confused about how to properly prove this thing on paper .
Comment: Thank you.  This is *not* what is usually meant by "Mahalanobis distance" and it is not a measure of correlation (unless perhaps the "populations" have been pre-processed by centering each of them separately).  One way to interpret the question that makes it correct is to suppose that "characteristics" are components of $n$-vectors and that the "common pd dispersion matrix" is an $n\times n$ matrix where you contemplate what happens when you zero out its last row and column (to eliminate a "characteristic").
Comment: The result is a direct consequence of the positive-semidefinite property of the matrix.
Comment: Without more context and explanation this question is indecipherable.  What are "characteristics" (variables perhaps?) and in what way does their number increase?  What is "Mahalanobis $d^2$"--would it be the Mahalanobis distance?  If so, between what and what, based on what distribution??
Comment: @whuber I have added the complete question of the back exercise, kindly help if you know ..
Comment: If I would zero out its last row , then its rank changes (decreases ) , also determinant might change , but how to put this on paper , I would have a 15 marker question on this , I dont think this theory would be that effective
Comment: I suggest closing this question because it is explicitly mentioned in the bounty that it is an "exam" question.  No answer should be given for it would be unfair for other students who took the same exam.
Answer: One way to define a Mahalanobis distance for two points (your populations?), $\vec{x}$ and $\vec{y}$ is
$$d(\vec{x},\vec{y},D) = \sqrt{(\vec{x}-\vec{y})^T D (\vec{x}-\vec{y})}$$
with $D$ the dispersion matrix.
With a characteristic less this could mean that one of the indices is zero. If it is like that then the Mahalanobis distance is not necessarily a non-decreasing function of the number of characteristics.
Counterexample
Take for instance the following case with two features/characteristics
$$D, = \begin{bmatrix}1&-0.9\\-0.9&1\end{bmatrix} \qquad \vec{x} = \begin{bmatrix}1\\1\end{bmatrix} \qquad \vec{y} = \begin{bmatrix}0\\0\end{bmatrix}$$
then $$d(\vec{x},\vec{y},D) = \sqrt{0.2}$$
But with one characteristic less
$$D, = \begin{bmatrix}1&-0.9\\-0.9&1\end{bmatrix} \qquad \vec{x} = \begin{bmatrix}1\\0\end{bmatrix} \qquad \vec{y} = \begin{bmatrix}0\\0\end{bmatrix}$$
then we have a larger distance $$d(\vec{x},\vec{y},D) = \sqrt{1}$$


Question about $l_\infty$ as a complete metric space

Question: I have question about the answer by Brian M. Scott to this question Is the set of all bounded sequences complete?
In his answer, $\langle x^n : n \in \mathbb{N} \rangle$ is a sequence object. $x_n$ is a single real number. Therefore, I don't understand the concept of writing $x^n = \langle x_k^n : k \in \mathbb{N} \rangle$ as another sequence object.
I know that a real number is an equivalence class of Cauchy sequence of rational numbers but I don't think that is what is happening here since he defines $x^n = \langle x_k^n : k \in \mathbb{N} \rangle$ as a sequence in reals.
I know he is right; I confirmed this from other places. I just cannot understand the underlying concept.
Answer: What Brian writes is this:

he is working with a sequence $\langle x^n:n\in\mathbb N\rangle$ of elements of $\ell^\infty$; so, each $x^n$ is an element of $\ell^\infty$;
if you fix a $n\in\mathbb N$, then, since $x^n\in\ell^\infty$, $x^n$ is a sequence$$\left\langle x_k^n:k\in\mathbb N\right\rangle$$of real numbers.

The fact "that a real number is an equivalence class of Cauchy sequence of rational numbers" is not used at all in Brian's answer.


What is a good name for the following definition pattern?

Question: I am often in the following situation. I have a category $\mathbb C$ and a functor $F$ out of it. Sometimes it happens that there is an object $X$ in $\mathbb C$ such that for any other object $Y$ the map of sets $\operatorname{Hom}_\mathbb C(X,Y)$ to $\operatorname{Hom}(FX,FY)$ is a bijection. What is a good way to say that this is the case (in informal language, not symbols)?
I am tempted to say that in this case $X$ is freely generated by its $F$. Examples:

Take the category of schemes and the functor $\mathcal O:Sch\to Ring$ which sends a scheme to its ring of regular functions $\mathcal O(X) = \operatorname{Hom}_{Sch}(X,\mathbb A)$. I would say that $X$ is cofreely generated on its ring of regular functions if and only if for any other scheme $Y$, the morphism between the sets $\operatorname{Hom}_{Sch}(Y,X)$ and $\operatorname{Hom}_{Ring}(\mathcal OX,\mathcal OY)$ is an isomorphism. Those are precisely the affine schemes.

Take the category of $\mathcal O_X$-modules in the little topos $Sh(X)$ of a scheme. There is a global section functor $\mathcal O_XMod \to \mathcal O(X)Mod$, and I would say that an $\mathcal O_X$-module $\mathcal F$ is freely generated by its global sections if and only if for each other $\mathcal O_X$-module $\mathcal G$ we have that $\operatorname{Hom}_{\mathcal O_XMod}(\mathcal F,\mathcal G)\to \operatorname{Hom}_{\mathcal O(X)Mod}(\mathcal F(X),\mathcal G(X))$ is a bijection. In the case that $X$ is affine, those are precisely the quasicoherent $\mathcal O_X$-modules (if I am not mistaken).

What is a good name for my definition pattern. The trouble is that $X$ is freely generated by $S$ normally means that $X = FS$ for some left adjoint functor $F$, and I do not want to confuse the concepts.
Comment: If this held for all pairs $X,Y$, one would say that the functor was *fully faithful*.  So, I suppose I'd say "$F$ acted fully faithfully on $X$" though I would take care to explain what I meant by that.
Comment: Maybe I can say *$X$ is cofreely determined by its ring of regular functions*? But that also sounds weird.
Comment: @lulu ahh, not bad. I like it :)
Comment: @lulu I leave the question open in case there are more good ideas!
Answer: I don't know a name for this condition unless $F$ has a left adjoint, which to avoid confusing myself I will name $H$. Then the condition is equivalent, by the Yoneda lemma, to the condition that the counit $H(F(X)) \to X$ of the adjunction is an isomorphism on $X$; in this case one says that $X$ is a fixed point of the adjunction.
A standard fact about adjunctions is that every adjunction restricts to an equivalence of categories between the fixed points on each side; when applied to the example of the adjunction between schemes and affine schemes this recovers the equivalence of categories between affine schemes and, well, affine schemes. Similarly for quasicoherent $\mathcal{O}_X$-modules on affine schemes, I think.
Note that this condition implies that $\text{Hom}(F(X), F(-))$ preserves limits, and the easiest way for that to happen is that $F$ itself preserves limits, and the easiest way for that to happen is that $F$ has a left adjoint, so the extra condition that $F$ has a left adjoint is pretty mild here and likely to hold in examples where this condition holds anyway.


Calculate the unit group of a ring

Question: Let $k$ be an algebraically closed field and $R$ a noetherian (as ring) $k$-algebra. we denote by $N$ the ideal of nilpotent elements. assume we know that $R = k + N$.
I want to figure out that the structure of unit group of $R$ is $$R^*=k^*(1+N)$$
partial solution: the "$k^*(1+N) \subset R^*$" inclusion is simple: $k \to R$ is injective, therefore $k^*$ is embedded in $R^*$ as multiplicative subgroup.
let $n \in N$ then there exist a minimal natural $k \in \mathbb{N}$ with $n^k=0$. then the element $r := \sum_{0 \le j \le k-1} (-n)^j$ inverts $1+n=1-(-n)$. this implies $(1+N) \subset R^*$.
therefore I need only to show the intractable "$R^* \subset k^*(1+N) $"  inclusion. does anybody see the argument?
Answer: Suppose $x\in R^*$. Because $x\in R=k+N$, we know we can write $x=a+n$ for $a\in k$ and $n\in N$. If we can show $a\in k^*$, i.e. $a\neq0$, then we will have $x=a(1+a^{-1}n)$ and since $a^{-1}n\in N$ we will have $x$ in the desired form.
Now you just need to notice that if $a=0$ then $x\in N$, but then $x$ cannot possibly be a unit in $R$ (why?)
Comment: ...since nilpotents can't be units. thank you

Calculate the unit group of a ring


on Linux, is there any way(tools) to know which application cached data and what the data is?

Question: On my linux system I find that the free memory is continuously reduced.I use free -m to get the free memory size.
But after I execute
echo 3 > /proc/sys/vm/drop_caches

the size of free memory returned to a normal value.
I know this command is used to free pagecache, dentries and inodes.
But is there any way to know which application cached data and what data I freed?
Comment: I don't think the kernel keeps track of which program was responsible for a given page being cached.  It'd incur a lot of memory overhead, and what would it do when there are several processes accessing the same data (and thus *all* contributing to it being cached)?  But if the amount of free memory on the "-/+ buffers/cache" line is going down, that's not cache usage, it's something else.  Maybe a memory leak in an app.
Comment: Thank you. I really misinterpreted free. But both the "/+buffers/cache" are reducing and I still want to get the way to print the cache content
Comment: Don't do that. Having a lot of data cached is a *Good* Thing, as it makes that data immediately available if it should be needed, while the cache can be immediately reallocated to another process if the memory is needed elsewhere. Empty memory is wasted, so let the kernel cache as much as it wants to.
Answer: The short answer is no.
The slightly longer answer is that the caches you free when writing to /proc/sys/vm/drop_caches aren't really linked to applications. They are created by the kernel and various kernel subsystems (typically the vm, block and fs subsystems) that have no real notion of applications.
The good news is that you shouldn't have to worry about them at all under normal use as the kernel will try to cache as much as possible in every situation unless it is explicitly told not to and then drop the cache as soon as it needs the memory for something else.


McNemar test or Two proportion z-test?

Question: Consider an experiment where a group of 200 people were asked before and after what is their preference, with possible outcomes being A and B. The research question is:
Is there a difference between rate of change of preference from A to B and rate of change of preference from B to A?
Consider this table, where rows represent preferences before the experiment and columns represent preferences after the experiment:

Before/After
A
B

A
150
20

B
20
10

I could do a McNemar test to compare a proportion of preference A before the experiment to a proportion of preference A after the experiment, with non significant result, as frequencies 20 and 20 are the same (McNemar test takes into consideration just the discordant pairs).
However, that is not consistent with the research question. Let me think out loud: "Out of 170 people, who preferred A before the experiment, 20 people changed their preference to B, which is 20/170x100=11,8 %. Out of 30 people, who preferred B before the experiment, 20 person changed their preference to A, which is 20/30x100=66,7 %. The rate of change of preference is 11,8 % for A->B and 66,7 % for B->A." These two rates are clearly different and I think it may be tested using two proportions z-test, with first population being people who prefer A before the experiment and second population being people who prefer B before the experiment. Then the group of 170 people can be considered as random sample from the first population and the group of 30 people can be considered as random sample from the second population. Then comparison of proportions 0,118 and 0,667 using z-test for two proportions answers my research question, with the result that the difference is statistically significant (z=-6,93, p=0,000).
Is that conceptually correct? Does it make sense? Because the data are paired in a sense that the same group of people were measured before and after the experiment and for paired nominal data McNemar is usualy used. However, with this specific research question I believe that two proportion z-test is appropriate.
Answer: The data is not paired because a participant chooses either A or B at their original preference. Compare with testing whether a patient has a disease with two different procedures A and B.
So McNemar's test is not applicable to begin with.
You can do a test for equality in proportions as you suggest. Alternatively, you can look at the odds ratio of the probabilities to change preference.
library("broom")
library("emmeans")

first_choice <- c("A", "B")
participants <- c(170, 30)
switch_choice <- c(20, 20)

Test if the probabilities to switch preference are equal:
tidy(prop.test(switch_choice,
               participants))
#> # A tibble: 1 × 9
#>   estimate1 estimate2 statistic  p.value parameter conf.low conf.high method
#>       <dbl>     <dbl>     <dbl>    <dbl>     <dbl>    <dbl>     <dbl> <chr>
#> 1     0.118     0.667      44.7 2.33e-11         1   -0.744    -0.354 2-sample …
#> # … with 1 more variable: alternative <chr>

Estimate the odds ratio of the switch probabilities:
fit <- glm(
  cbind(switch_choice, participants - switch_choice) ~ first_choice,
  family = binomial
)

emmeans(
  fit, pairwise ~ first_choice,
  type = "response"
)
#> $emmeans
#>  first_choice  prob     SE  df asymp.LCL asymp.UCL
#>  A            0.118 0.0247 Inf    0.0772     0.175
#>  B            0.667 0.0861 Inf    0.4835     0.810
#>
#> Confidence level used: 0.95
#> Intervals are back-transformed from the logit scale
#>
#> $contrasts
#>  contrast odds.ratio     SE  df null z.ratio p.value
#>  A / B        0.0667 0.0303 Inf    1  -5.957  <.0001
#>
#> Tests are performed on the log odds ratio scale

Created on 2022-06-18 by the reprex package (v2.0.1)

McNemar test or Two proportion z-test?


How to count the element present in-between that starting and ending value?

Question: I need some logic from your side.I want to count the number of element present
n-between that starting and ending value
Like
Input :Starting point in 1
          end point is :10

Search :2

count :1(only 2)

Input :Starting point in 1
          end point is :20

Search :2

count :3(only 2, 12 ,20)
function(var start,var end,var searchItem){
for(var start;start<=end;start++)

}

Comment: Possible duplicates: http://stackoverflow.com/questions/3895478/does-javascript-have-a-range-equivalent
Comment: no..i think you not understand my question
Comment: Am I understood your question correctly.?
Comment: So please improve your question with consistent example
Comment: Downvoted until you improve your question and show us what you've got so far.
Answer: Try,
function search(start, end, searchItem) {

    var xCnt = 0;

    for (var start = 0; start <= end; start++) {

        if ((start + '').indexOf(searchItem + '') >= 0) {
            xCnt += 1;
        }

    }
    return xCnt;
}

DEMO
Comment: @user944513 logic will be the same, search for index of character in string. But wait, aren't you confusing javascript with java?
Comment: correct but can you explain this logic?if((start+'').indexOf(searchItem+'') >=0)
Comment: @user944513 For example x.indexOf(y) will return the index of y in any substrings of x. If it do not find anything, it will return -1. For More reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
Comment: @user944513 Ok so now explain why is this question is tagged with jQuery and Java when obviously is none of them?
Comment: @user944513 you should have tagged this with javascript obviously. And i don't think you want extra comma


Can You Solve This?

Question: Here's the equation I need to solve (for $x$)...
$$r\sqrt{x^{2}-r^{2}}+\left(\frac{1}{b}-r^{2}\right)\left(\arccos\left(\frac{r}{x}\right)\right)=\frac{\pi}{2b}$$
is there a solution in terms of the constants $r$ and  $b$?
Hmm...
Comment: Solve $\large \sqrt{\vphantom{\Large A}x^{2} - 1\,} + \mu\,\arccos\left(1 \over x\right) = \nu$ first. $\large\mu \equiv {1 \over br^{2}} - 1$ and $\large\nu \equiv {\pi \over 2br^{2}}$.
Answer: Start by writing $$x=r\sec t$$ This eliminates the square root and the inverse cosine in terms of $\tan t$ and t.

Can You Solve This?


Firebase not sending sendPasswordReset email

Question: I've been trying to get Firebase to send a Password Reset Email with the following code:
let email = "firstname.lastname@example.com"

@IBAction func changePasswordTapped(_ sender: Any) {

       Auth.auth().sendPasswordReset(withEmail: self.email) { (error) in
           print(self.email)
       }
    }

The console prints out my email address as per the print(self.email), but I haven't received any emails after multiple attempts and waiting more than a day. I've checked all of my email folders, including spam.
Is there something else that needs to be implemented for this to work?
I really appreciate any help/guidance!
Comment: Well, your not checking to see if there's an error so the code will just silently fail and you won't know why. You should add error handling within the closure like `if let err == error {  print(err.localizedDescription) }` and see if it prints and error. Then' you'll know what the issue was.
Comment: Does this answer your question? [Firebase Reset Password Swift](https://stackoverflow.com/questions/35808352/firebase-reset-password-swift)
Comment: Thank you @Jay! That helped me dig deeper. Hard-coding the email address didn't work as a test because Firebase couldn't associate it with the user. So just setting the email as `let email = Auth.auth().currentUser?.email` worked.
Answer: Firebase did not allow for me to hard-code the email address. I was getting this error:
There is no user record corresponding to this identifier. The user may have been deleted.

Once I set the email address to the currentUser, it worked:
let email = Auth.auth().currentUser?.email

@IBAction func changePasswordTapped(_ sender: Any) {

       Auth.auth().sendPasswordReset(withEmail: self.email) { (error) in
           print(self.email)
       }
    }


Can a foul be overriden before it is taken?

Question: Consider the following situation: a player for Team A is ruled offside (or, if you prefer, commits a foul on a Team B player). Before the ensuing indirect free kick can be taken, one of the players of Team B has a moment of madness and blatantly kicks the hell out of a player of Team A. Obviously, the Team B player is going to get a red card, but what happens with the ball? Do Team B get to keep the indirect free kick, or is it overridden with a free kick (or penalty kick, if inside the area) in favor of Team A?
Answer: Fouls are called only for offences which are committed by a player on the field of play while the ball is in play. (See Interpretations of the Laws of the Game and Guidelines for Referees, page 117.)
If the ball is out of play because the play was stopped by the referee because of a previous offence, no free kick is given, only the persons involved in the misconduct may be cautioned or sent off. So, in your example, the Team B player will be sent off, however, the play will be restarted with the original free kick for Team B.
(Similarly, free kicks are not awarded for misconduct by e.g. a manager, nor for a misconduct of a player outside the field of play. If the referee needs to stop the play because of such misconduct, no team will be given a free kick, and the play will be restarted with a dropped ball at the position of the ball at the time the play was stopped.)


Sorting table rows based on column class names using pure Javascript

Question: Very similar to this question: Sort table rows based on their Class Names - but need it to be in pure javascript instead of JQuery.
It needs to be able to sort by class names.
Consider the following table:

       Column

           High

           Medium

           Low

The functions need to sort the table by high, medium and low in that particular order.
Comment: Does this answer your question? https://www.w3schools.com/howto/howto_js_sort_table.asp
Comment: Thank you for replying. Not really as it needs to be in a certain order. I shall rephrase my question.
Answer: You can do this as follows:

get the rows of the table body
sort the array according to the className of the first column of each row
update the innerHTML of the table body by joining the html content of the resulted sorted list of row elements

const tableBody = document.getElementById("tableBody");
const rows = tableBody.rows;
const weights = {"Low":0, "Medium":1, "High":2};

const sortedRows = [...rows].sort((a,b) =>
  weights[a.children[0].className] - weights[b.children[0].className]
);

tableBody.innerHTML =[...sortedRows].map(row => row.outerHTML).join("");

       Column

           High

           Medium

           Low

Comment: Perfect, thank you. Is there any way to do this without the tbody? Could i just replace it with the table id, if i don't have a tbody?
Comment: @Matthew98 you are welcome, yes you can set the ``id`` to the ``table`` but in this case it will take the rows of the header as well.


Between- and within-person level effects when using multilevel modelling for longitudinal data in R

Question: I'm using nlme package in R for analysing longitudinal data. The aim is to understand if changes in need satisfaction (TNS) and need frustration (TNF) predict changes in well-being (WBtot) over time (Tim) in participants (ID). The model with predictors:
model4 <- lme (WBtot~Tim + TNS +TNF, random = ~ Tim|ID, data = longit, method = "ML", na.action = "na.omit")

As I understand, the fixed effects in the output show how Tim, TNS and TNF are related to WBtot on each measurement occasion. My issue is I need to see between-person effects of TNS and TNF on WBtot (e.g., to see if individuals with higher TNS have greater WBtot) and within-person effects (e.g., would individuals have greater WBtot at time points when they have greater TNS?).
Can anyone advise how to look at between and within-person level effects of predictors in R?
Comment: Any particular reason why you don't use `lmer` from the `lme4` package ? Also, why is `Tim` specified as a random slope, yet absent from the fixed effects ?
Answer:
model4 <- lme (WBtot~RetTim + TNS +TNF, random = ~ Tim|ID, data = longit, method = "ML", na.action = "na.omit")

As I understand, the fixed effects in the output show how Tim, TNS and TNF are related to WBtot on each measurement occasion

Yes, although there is something strange in the model - I wonder if RetTim and Tim are the same variable ? Anyway, your the interpretation of the fixed effects is basically correct. Each estimate is the association between that variable and the outcome, with the other fixed effects remaining constant. When you fit random slopes (for example Tim in ~ Tim|ID) then you allow for the fixed effects of that variable to vary between subjects.

My issue is I need to see between-person effects of TNS and TNF on WBtot (e.g., to see if individuals with higher TNS have greater WBtot) and within-person effects.

One way to do this is to mean-centre the variables within groups/subjects/IDs and include the group means as level-2 predictors. So you would create new variables for the mean of each variable within each group and then subtract this from the individual level values, and then also include the mean of each group in the model along with the offseted variables.
lme(WBtot ~ RetTim.mean + RetTim.cent + TNS.mean + TNS.cent + NF.cent + TNF.mean, random = ~ Tim|ID)

The estimates for the centred variables will be within-subject and the estimates for the means will be between.
This is sometimes referred to as "contextual effects"
The other approach is to fit random effects for each of the fixed effects - so that each subject has their own slope (offset from the global fixed effect). However this assumes they are normally distributed and is probably not what you want here.
Comment: Thank you so much, Robert! Yes, Tim and RetTim  is the same, it was a spelling mistake. I did what you suggested for TNS and TNF, and it seems to work. I've chosen nlme because it was easier to see p-values than in lme4. Is lme4 better? Sorry, I'm very new to multilevel modelling...
Comment: No problem, I thought that's what happened. It's OK to use `nlme`. But there is a reason `lme4` doesn't poduce them: p values are the Devil's work - don't use them ! `lme4` is better supported. `nlme` is quite old now.