Dúvida simples com JQuery, suavizar efeito

Question: Estou com dificuldades para suavizar um efeito que fiz.
Ele está muito estático, após clicar no link, o objetivo é fazer com que após o clique entre a tela de menu de uma forma suave... da opacidade 0 ao 1.
Abaixo vou deixar o código funcionando:

$(document).ready(function() {
  $(".btn-nav").click(function() {
    $(".nav ul").toggleClass('nav-show');
  });
});
.nav ul {
  display: none;
}

.nav-show {
  display: block !important;
  position: fixed;
  left: 0;
  top: 0;
  background: #066;
  width: 100%;
  height: 100%;
  z-index: 99999;
  opacity: 1 !important;
}

  Clique aqui para Abrir

    Clique aqui para Fechar

Contato

Edição Atual

Answer: Você pode obter esse efeito alterando o CSS e usando o fadeToggle:

$(document).ready(function(){
 $(".btn-nav").click(function(){
  $(".nav ul").fadeToggle("slow", "linear");
 });
});
.nav ul {
  display: none;
}
.nav-show {

  position: fixed;
  left: 0;
  top: 0;
  background: #066;
  width: 100%;
  height: 100%;
  z-index: 99999;
}

Clique aqui para Abrir

        Clique aqui para Fechar

Contato

Edição Atual

Comment: Obrigado amigo, eu desconhecia esse método usando 'fadeToggle'


Prove that a subset is an interval.

Question: I'm stuck on a homework question.
"Let $f :\mathbb R \to\mathbb R$ be a continuous function and let $I$ be an interval in $\mathbb R$. Show that $f(I)$ is an interval."
What I've done so far is tried to prove that $f(I)$ is an interval by proving the interval is convex (by the completeness axiom). I then used the intermediate value theorem but I don't know where to go from there.
(https://i.stack.imgur.com/JbLm9.jpg)
Any help would be appreciated.
Answer: Suppose that $f(I)$ is not an interval. Then, there exist numbers $x<y<z$ such that $x, z \in f(I)$ but $y \notin f(I)$.
Note that if $x,z \in f(I)$, then there are $a,b \in I$ such that $x=f(a),z=f(b)$. Hence, $f(a)<y<f(b)$, and $f$ is continuous. By the intermediate value theorem, it follows that $\exists c \in (a,b)$ such  that $f(c) =y$. Since $I$ is an interval, for any $a,b \in I$, every point between $a$ and $b$ (and hence $c$) is in $I$. So, $y=f(c) \in f(I)$, this is a contradiction.
Hence, $f(I)$ is an interval.

Prove that a subset is an interval.


writeToURL not working

Question: I am trying to use
NSString *myString  = @"NO";
[myString writeToURL:[NSURL URLWithString:@"http://example.com/text.txt"] atomically:YES];

But am having no luck. myString is set to NO and example.com is set to the correct website. The only issue I could see would be text.txt already existing? Can writeToURL even write to http? I can always go back to using NSTask and curl but that was a nightmare. :)
Thanks for any help
Answer: I'm not sure about the NSString version of writeToURL:atomically:, but the NSData version says that it only works with file:// URLs, so I wouldn't be shocked if the NSString version was the same.
Edit to add: the NSString version of writeToURL:atomically: is deprecated.  You're supposed to use writeToURL:atomically:encoding:error: instead.  Try it and see if the error result tells you anything.
Comment: Hmmm Okay well it looks like its back to curl. Thanks for the part about it being deprecated xcode didn't tell me.

writeToURL not working


Build ARIMA model equation with exogenous variable or regressors

Question: I have a ARIMA model with three regressors as follow
<code>> fit_arima.reg
Series: sales.ts
Regression with ARIMA(5,1,3) errors

Coefficients:
         ar1      ar2      ar3      ar4      ar5      ma1     ma2
      0.1806  -0.7205  -0.2697  -0.3786  -0.4372  -0.8307  0.5047
s.e.  0.0786   0.0521   0.0614   0.0277   0.0469   0.0849  0.0920
          ma3  pholid  sholid     temp
      -0.1397  0.0413  0.1192  -0.0015
s.e.   0.0662  0.0313  0.0180   0.0015

sigma^2 estimated as 0.02461:  log likelihood=412.15
AIC=-800.3   AICc=-799.96   BIC=-742.11
</code>
The data is posted here (only the values of two independent variables are missing) and I also referred four links of previous posts related to this topic. I built the equation, but the fitted values by hand (from equation) and the ones generated by R do not match. I would appreciate your help for the solution.
This is what I did:
<code>fitted <-fit_arima.reg$x - (fit_arima.reg$coef["pholid"]*xregg$pholid) - (fit_arima.reg$coef["sholid"]*xregg$sholid) - (fit_arima.reg$coef["temp"]*xregg$temp)

detach("package:dplyr", unload=T)
library(tsDyn)
lag1.fit <- lag(fitted,-1)
lag2.fit <- lag(fitted,-2)
lag3.fit <- lag(fitted,-3)
lag4.fit <- lag(fitted,-4)
lag5.fit <- lag(fitted,-5)
lag6.fit <- lag(fitted,-6)

residuals <- fit_arima.reg$x-fitted # are those the residuals?

lag1.res <- lag(residuals,-1)
lag2.res <- lag(residuals,-2)
lag3.res <- lag(residuals,-3)

fitted_equation <-  fit_arima.reg$coef["pholid"]*xregg$pholid+
  fit_arima.reg$coef["sholid"]*xregg$sholid+
  fit_arima.reg$coef["temp"]*xregg$temp+
  fit_arima.reg$coef["ar1"]*lag1.fit+
  fit_arima.reg$coef["ar2"]*lag2.fit+
  fit_arima.reg$coef["ar3"]*lag3.fit+
  fit_arima.reg$coef["ar4"]*lag4.fit+
  fit_arima.reg$coef["ar5"]*lag5.fit+
  lag1.fit-
  fit_arima.reg$coef["ar1"]*lag2.fit-
  fit_arima.reg$coef["ar2"]*lag3.fit-
  fit_arima.reg$coef["ar3"]*lag4.fit-
  fit_arima.reg$coef["ar4"]*lag5.fit-
  fit_arima.reg$coef["ar5"]*lag6.fit-
  fit_arima.reg$coef["ma1"]*lag1.res-
  fit_arima.reg$coef["ma2"]*lag2.res-
  fit_arima.reg$coef["ma3"]*lag3.res

> tail(cbind(fitted_equation,fit_arima.reg$fitted))
Time Series:
Start = c(2019, 210)
End = c(2019, 215)
Frequency = 365
     fitted_equation fit_arima.reg$fitted
2019.573        3.469460             3.426007
2019.575        3.833233             3.623222
2019.578        3.309229             3.507476
2019.581        3.617242             3.418212
2019.584        3.067797             3.196589
2019.586        3.195247                   NA
</code>
Answer: Similar to Build SARIMA model equation with exogenous variable or regressors  . you have the following equation  which leads to this after clearing fractions .. multiplying out etc ...

Note that by ordinary convention the ma coefficients are presented differently than what you have seen with your references BUT the answers would be the same.
The data I used had 200 historical observations BUT that doesn't change the way the coefficients are re-presented in a "regression type form " and without the often ( to some !) confusing polynomials and differencing operators.
Comment: Thank very much for your constant feedback and help!


How to do a listing and justify numbers?

Question: I am looking to get some help with this assignment. From the list below, I should find numbers greater than 0, the numbers are written to the file right justified in 10 spaces, with 2 spaces allowed for
the fractional portion of the value, and finally write them into a file.
Here is what I've got so far:
def formatted_file(file_name, nums_list):
    '''
    Test:
    >>> formatted_file('out1.txt', [1, 23.999, -9, 327.1])
    >>> show_file('out1.txt')
          1.00
         24.00
        327.10
    <BLANKLINE>
    >>> formatted_file('out1.txt',[-1, -98.6])
    >>> show_file('out1.txt')
    <BLANKLINE>
    >>> formatted_file('out1.txt',[])
    >>> show_file('out1.txt')
    <BLANKLINE>
    '''
    with open('out1.txt', 'w') as my_file:
        for x in nums_list:
            if x > 0:
                a = list()
                a.append(x)
            if len(a) > 0:
                my_file.write(f'{i:10.2f}\n')

def show_file(file_name):
    with open(file_name, 'r') as result_file:
        print(result_file.read())

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose = True)

When I run this function, the file that I get is blank. I got it working last night in pycharm, but when I ran it to IDLE it didn't work. And now it's throwing a bunch of error in pycharm as well.

Thanks both for your suggestions. Unfortunately none of the methods writes the output in the file :(
The test passes in IDLE though.
Comment: how does the file look?
Comment: The fie is blank, as I am trying to write the output of the numbers list to it.
Comment: `the numbers are written to the file right justified in 10 spaces, with 2 spaces allowed for the fractional portion of the value, and finally write them into a file.`   is confusing  - - I m not the one who downvoted
Comment: No problem, no I commented to another person who thinks is funny. I didn't comment that for you. Sorry for the confusion, there's no file, really. The show_file('out1.txt') would be the command that I need to run after the code to make sure that I get the output shown below that command.
Comment: What is ```i``` here ```my_file.write(f'{i:10.2f}\n')```? Seems to me that it is undefined? You probably want to write ```a``` into the file? Or am I missing something?
Comment: This piece of code:
 a = list()
                a.append(x)
            if len(a) > 0:
Is not supposed to be there. Sorry, I was just doing some testing last night.
Answer: If you use a string.format, you must put the value in the format function. I also do not understand what len(a) or a in particular a is used for here.
This is your function with my modification, which passed the first test (I think the other two were just for debug)
def formatted_file(file_name, nums_list):
    '''
    Test:
    >>> formatted_file('out2.txt', [1, 23.999, -9, 327.1])
    >>> show_file('out2.txt')
          1.00
         24.00
        327.10
    <BLANKLINE>
    '''
    with open(file_name, 'w') as my_file:
        for x in nums_list:
            if x > 0:
                my_file.write('{:10.2f}\n'.format(x))

def show_file(file_name):
    with open(file_name, 'r') as result_file:
        print(result_file.read())

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose = True)

Trying:
    formatted_file('out2.txt', [1, 23.999, -9, 327.1])
Expecting nothing
ok
Trying:
    show_file('out2.txt')
Expecting:
        1.00
        24.00
        327.10
    <BLANKLINE>
ok
2 items had no tests:
    __main__
    __main__.show_file
1 items passed all tests:
2 tests in __main__.formatted_file
2 tests in 3 items.
2 passed and 0 failed.
Test passed.

Comment: His ```f```-strings are fine ([f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings))?
Comment: @Timus Yes, right, sorry for that. Only the wrong variable. The notation ".format()" has been always more catchy for me so i changed it. Not very Pythonic, I know.
Comment: For me it's exactly the opposite, I'm so happy about the ```f```-strings :))
Comment: Thanks both for your suggestions. Unfortunately none of the methods writes the output in the file :(

The test passes in IDLE though.
Comment: @CasperNe; do you have write permission on the folder you are writiing? Any errors? I did a little modifacation just a min ago and add the "file_name" in open statment arguments.


Show that its inverse, denoted by $h^{-1}$, is also a strictly increasing function.

Question: Let h be a strictly increasing continuous function. Show that its inverse, denoted by $h^{-1}$, is also a strictly increasing function.
How to approach this question?
Comment: How is this related to probability?
Comment: Just use the definition of a strictly increasing function. Write down what it means that $h$ is strictly increasing. Then write down what you want to prove, i.e. $h^{-1}$ being strictly increasing. Then you should see that the latter follows from the former.
Answer: Hint: If $x<y$ (in co-domain of $h$) and $h^{-1}(x)\geq h^{-1}(y)$, then by applying $h$ (increasing) we get $h(h^{-1}(x)) = x\geq h(h^{-1}(y))=y$, contradiction. (No need for continuity etc.)
Comment: still do not quite get it...could you flush out a little more...why $h^{-1}(x) \ge h^{-1} (y)$? and why applying h (strictly increasing) we get $h(h^{-1}(x)) = x \ge h(h^{-1}(y)) = y$?
Comment: Let $x<y$. We want to prove that $h^{-1}(x) < h^{-1}(y)$. We will do this by contradiction. So, lets assume $h^{-1}(x) \geq h^{-1}(y)$. As $h$ is strictly increasing, then $h(h^{-1}(x)) \geq h(h^{-1}(y))$. This is equivalent to $x\geq y$, contradicting our starting given inequality $x<y$.
Comment: what if h(x) and h(y) are zeros?
Comment: $h(x)$ and $h(y)$ don't play any role here; remember that $x$ and $y$ belong to the co-domain (image) of $h$, so $h$ can't act on them. The only way $h$ is used is by its property $h(h^{-1}(z)) = z$ for all $z$ (in its image) and by its property of being strictly increasing: if $a<b$ in its domain, then $h(a) < h(b)$ (note that if $a=b$, then obviously $h(a)=h(b)$, just by the fact that $h$ is a function).
Comment: what is the relationship between $x < y$ and $h^{-1} (x) \geq h^{-1} (y)$? If so, how do you know that relationship? My understanding for this relationship is I think of x and y as numbers. However, if x = any negative number and y = positive number, then $x < y$ and $h^{-1} (x) \leq h^{-1} (y)$ ... if x or y = 0 , the inverse does not even exist....correct me if I am wrong
Comment: In our reasoning, $x<y$ is GIVEN. ASSUMING $h^{-1}(x) \geq h^{-1}(y)$ leads to a contradiction (via $h$ and its two properties I mentioned).
Comment: I know $h^{-1} (x) \geq h^{-1} (y)$ is your assumption...However, how do you know this is true given that we take $x < y$ for granted
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12806/discussion-between-ir7-and-afsdf-dfsaf)


Relation between primeness and co-primeness of integers

Question: I wonder what this stunning formal analogy between the definitions of being co-prime (for two integers) and being prime (for one integer) might reveal – and how:

$\alpha, \beta$ are co-prime iff
$$(\forall x)\ \alpha|x \wedge \beta|x \leftrightarrow \alpha\beta|x$$
$\alpha$ is prime iff
$$(\forall xy)\   \alpha|x \vee \alpha|y \leftrightarrow \alpha|xy$$

Note that and how the two definitions are equivalent modulo swapping

$\wedge$ and $\vee$ on the left side
constants and variables on the right side together with
the direction of divisibility $|$ with respect to the product [thanks to user Wojowu]
the direction of inference $\rightarrow$ [thanks to user Roll up and smoke Adjoint]
Comment: Note you also swap the direction of divisibility. This is an interesting observation, but I don't think there is any "stunning" meaning behind it.
Comment: Note that you can also replace $\rightarrow$ with $\leftrightarrow$ since each of those propositions on either side are in isomorphism with one another.
Comment: There is most likely a nice interpretation in the language of lattices/filters.
Comment: In the poset category for integers dividing one another $\text{Hom}(X,Y)$ consists of a single point or is empty.   Let $(X \mid Y)$ denote the nonempty hom-set. Notice that multiplication by an element $\alpha \in \Bbb{Z}$ is a functor from the poset category to itself since $(X \mid Y) \implies (\alpha X \mid \alpha Y)$ and so on proves the functoriality of multiplication.
Answer: In the poset category of integers dividing one another we write sometimes write $\alpha \to x$ instead of $\alpha \mid x$.
The "product" $\alpha \beta$ of two coprime objects $\alpha, \beta$ is such that $\alpha \to \alpha \beta \leftarrow \beta$ and for any object $x$ such that $\alpha \to x \leftarrow \beta$ then there is a unique arrow $\alpha \beta \to x$.  That is precisely the definition of coproduct in a general category.
Thus when $\alpha, \beta$ are coprime, then the category definitely has a coproduct for them.
Thus $\wedge$ is encoded in the fact that $\alpha \to x \leftarrow \beta$, ie. both morphisms exist simultaneously.  I believe product is $\gcd(\alpha, \beta)$.

Actually, it turns out that the coproduct exists for any two integers and it's $\text{lcm}(\alpha, \beta)$.

Primality is difficult because of the $\vee$.  So create a new definition.  An arrow into a coproduct is prime when there exists a morphism into at least one of the coproduct's components such tha the relevant triangle commutes.
Notice we used coproduct here which is $\text{lcm}(\alpha, \beta)$ since the definition of prime is equivalent to $p \mid \text{lcm}(\alpha, \beta) \implies p \mid \alpha \vee p \mid \beta$.

So take the contrapositive of that.  $p \nmid \alpha \wedge p \nmid \beta \implies p \nmid \text{lcm}(\alpha, \beta)$.
Form the "negated" poset category of integers not dividing one another.  It's formed by mapping each hom-set to $\varnothing$ when it's nonempty and vise-versa, so it's not a functor from the original category.
Answer: The second can become:$$(\forall xy)\alpha\mid xy\to\alpha\mid x\lor\alpha\mid y$$ The first is: $$(\forall x)\alpha\beta\nmid x \to \alpha\nmid x \lor \beta\nmid x \lor \alpha\beta \gt x\lor(\alpha,\beta)^2\nmid x$$ Not sure it reveals much though.


Estimating the percentage of a specific factor being related to a condition

Question: I am working on a medical research project where I am trying to find the associations between specific maternal factors and neonatal limb ischemia (NLI) to declare the maternal factors as "risk factors for NLI". I am trying to find a way to estimate the percentage of a specific maternal factor being associated with NLI, but I am having a hard time figuring out how to make the estimates.
The data is only on NLI patients. In terms of associations between maternal factors and NLI, the factors include maternal health problems, maternal age, maternal ethnicity, previous pregnancies and births, and maternal substance use (smoking, drinking, drug use, medications).
I have a bit of a background in stats, but I am not sure what the best way is to calculate the estimates. I have a lot of data of 120 patient cases from around the world retrieved from papers. I have made an Excel of all the relevant information regarding each patient. The data is not perfect since it all comes from different papers, but I've tried to make an Excel where the information is organized in a consistent manner. I have an idea of what trends seem to show within my data sample but I don't know how to validate these trends by conducting an estimate.
I have tried to think of ways to do the estimate, but I am not a stats expert. I thought that clustering might be helpful here to group the data, but I'm not sure what to do with the groups and if clustering would even help develop the estimate of the percentage. I am also still learning how to cluster, so I am hesitant to go this way.
Are there any suggestions for simple techniques I should employ for the estimate?
Comment: Could you please edit the question to define "NLI"? Also, when you edit, please say more about the data that you have collected: in particular, do you only have data on NLI cases, or do you have corresponding information on other cases? How many maternal factors are you evaluating?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: @EdM thank you for the response, I have made the edits. I listed the maternal factors being looked at and the data is only on NLI cases.
Answer: Without data on situations without NLI, you won't be able to answer your question adequately.
For a trivial but important example of the problem with evaluating maternal factors just within NLI data: all mothers of your NLI cases were females. That would be the strongest association with NLI in your data set, even though it's also true of all births without NLI.
Even if you found clusters of less-trivial maternal factors within the NLI cases, you wouldn't know whether those clustered similarly in births without NLI. At the least, you need to find some distributions of values in normal cases for comparison.
Then you could try to examine whether the distribution of one or more maternal factors among NLI cases differs from that in normal cases, although the multi-cultural distribution of NLI cases in your data set will even make that a challenge. You would probably need to find normal cases with the same geographic distribution as your NLI cases.
That said, there's nothing wrong with presenting a summary of multiple case reports as you seem to have accumulated, including the distributions and associations of maternal factors in your data. On that basis alone, however, you can't call those "risk factors for NLI."
Comment: @eddie visualizing the data extensively is critical. Instead of histograms, which use arbitrary choices of cutoffs to make bins, use density plots (sort of a smoothed histogram). "Pairs plots" are convenient ways to examine pairwise associations of multiple variables at once. The [`ggpairs()` function](https://ggobi.github.io/ggally/reference/ggpairs.html) of the [`GGally` package](https://cran.r-project.org/package=GGally) in R is one implementation that allows you to compare both continuous and categorical variables.
Comment: so the data I have on the 120 cases of NLI will not be enough to declare a specific maternal factor as a risk factor for NLI? I would need to do a comparison with normal healthy births in order to actually extrapolate? I was wondering if there would be a recommended way to graph the data or find a way to better understand and explain the distributions? I made bar graphs and line graphs, but should I try to make histograms?


Computing $\int_0^\pi \sin(x) \; dx$ using the definition.

Question: A colleague of mine and I, in the course of teaching integral calculus for the umpteenth time, were wondering if we could expand the class of examples that our students are exposed to when computing Riemann integrals from the definition. Most such examples involve polynomial functions, and they work nicely because we have some well-known formulas, like
$\displaystyle\sum_{i=1}^n 1 = n$,
$\displaystyle\sum_{i=1}^n i = \frac{n(n+1)}{2}$,
and $\displaystyle\sum_{i=1}^n i^2 = \frac{n(n+1)(2n+1)}{6}$. (And certainly, there are others.)
But we wanted to expand the class of examples beyond polynomial functions, and started to think about trig functions. We came up with a computation for $\int_0^\pi \sin(x)\;dx$ using the definition of the Reimann integral, which I provide below.
Question: Is the computation below in the literature somewhere? If so, where?
Computation:
Using a Riemann sum with right endpoints, we have
$$\int_{0}^\pi \sin(x)\; dx = \lim_{n \to \infty}\sum_{i=1}^n \sin(x_i) \Delta x$$
where $\Delta x = \frac{\pi}{n}$ and $x_i = i\Delta x$.
The trick is to rewrite the Riemann sum $\sum_{i=1}^n \sin(x_i) \Delta x$ as a telescoping sum using the difference of cosines identity:
$$\cos(b) - \cos(a) = 2 \sin\left(\frac{a+b}{2}\right)\sin\left(\frac{a-b}{2}\right)$$
Setting $a = \frac{2i+1}{2}\Delta x$ and $b = \frac{2i-1}{2}\Delta x$ yields
$$\cos\left(\frac{2i-1}{2}\Delta x\right) - \cos\left(\frac{2i+1}{2}\Delta x\right) = 2 \sin\left(i \Delta x\right) \sin\left(\frac{\Delta x}{2}\right)$$
Solving for $\sin(i \Delta x)$ gives
$$\sin(i \Delta x) = \frac{\cos\left(\frac{2i-1}{2}\Delta x\right) - \cos\left(\frac{2i+1}{2}\Delta x\right)}{2 \sin\left(\frac{\Delta x}{2}\right)}$$
The Riemann sum now is
$$\sum_{i=1}^n \sin(i \Delta x) \Delta x = \frac{\frac{\Delta x}{2}}{\sin\left(\frac{\Delta x}{2}\right)} \sum_{i=1}^n \left[\cos\left(\frac{2i-1}{2}\Delta x\right) - \cos\left(\frac{2i+1}{2}\Delta x\right)\right]$$
The latter sum is telescoping, and so
$$\sum_{i=1}^n \sin(i \Delta x) \Delta x = \frac{\frac{\Delta x}{2}}{\sin\left(\frac{\Delta x}{2}\right)}\left[ \cos\left(\frac{\Delta x}{2}\right) - \cos\left(\frac{2n+1}{2}\Delta x\right)\right]$$
Now recalling that $\displaystyle \Delta x = \frac{\pi}{n}$ and taking $n \to \infty$ we have
$\begin{align} \int_0^\pi \sin(x)\;dx &= \lim_{n \to \infty} \frac{\frac{\Delta x}{2}}{\sin\left(\frac{\Delta x}{2}\right)}\left[ \cos\left(\frac{\Delta x}{2}\right) - \cos\left(\frac{2n+1}{2}\Delta x\right)\right]\\
& =  1 \cdot \left[ \cos(0)-\cos(\pi)\right]\\
& = 2
\end{align}$
One nice thing about this computation is that you can replace $\pi$ with an arbitrary upper limit of integration $c$ and compute that $\int_0^c \sin(x) \;dx = 1 - \cos(c)$.
From there, one can easily compute
$$\int_a^b \sin(x) \; dx = \int_0^b \sin(x) \; dx - \int_0^a \sin(x) \; dx = -\cos(b) + \cos(a)$$
(as predicted by FTC).
Question: Is the computation above in the literature somewhere? If so, where?
Comment: I don't know, but our teacher made us do this. $\int_a^b \sin(x)\,dx$ from reimann sum I mean.
Comment: [This answer](http://math.stackexchange.com/a/424942/17751) contains telescoping ideas.
Comment: I haven't seen it in a textbook or anywhere else, but I did it once myself in order to see how the limit $\sin x/x \rightarrow 1$ would play into the calculation.
Comment: Not exactly "literature", but the sum $\sum \sin(n)$ is telescoped using a similar trick in this [answer](http://math.stackexchange.com/questions/36732/is-the-sum-of-sinn-n-convergent-or-divergent) in order to apply the Dirichlet test to the series $\sum \frac{\sin(n)}{n}$.
Answer: Below are some references I found in my "math library" at home this morning. Before posting just now, I quickly searched to see which were online and I've included links for those I found. The Boyer paper URL is a JSTOR item I don't have access to, but I've included the URL anyway because many here are probably at colleges/universities that have JSTOR access.
At the risk of pointing out the obvious, this method doesn't prove the Riemann integrability of ${\sin x},$ since equal length partitions are used along with endpoint evaluations. For instance, under this restriction the limit of the Riemann sums of the characteristic function of the rationals on a given compact interval exists. What this calculation does is give the value of the (Reimann) integral on a given compact interval under the assumption that the integral exists.
Direct quotes from original sources are indicated by italics. Within such a quote: (1) italics in the original is indicated by non-italics here; (2) brief additions and/or words of further explanation by me are indicated by non-italics between square braces "[stuff by me]"; (3) omissions in the original are indicated using "$[\dots]$".
[1] [Author not known], Sur la sinussoide [On the sinusoid], Question D'Examen, Nouvelles Annales de Mathématiques (1) 7 (1848), 436-437.

The (net) area above the $x$-axis and below the graph of $y = \sin{x},$ between $x = x_1$ and $x = x_2$ is found. The interval $[x_1, \, x_2]$ is divided into $n+1$ many abutting intervals each of length $h,$ so that $x_2 - x_1 = (n+1)h,$ and the identity $$h [\sin{x_1} + \sin{(x_1 + h)} + \sin{(x_2 + 2h)} + \cdots + \sin{(x_1 + nh)} \;\; = \;\; \frac{h \sin \left(x_1 + \frac{nh}{2}\right) \sin \frac{h}{2}(n+1)}{\sin{\frac{h}{2}}}$$ along with $\frac{nh}{2} = \frac{x_2 - x_1 - h}{2}$ is used to obtain the value $2\sin{\left(\frac{x_2 + x_1}{2}\right)} \sin{\left(\frac{x_2 - x_1}{2}\right)},$ which equals $\cos{x_1} - \cos{x_2}.$ Note: There is a typo at one point in the original, in which $\sin{(x_2 + h)}$ appears instead of $\sin{(x_2 + 2h)}.$ Also, the text only observes that the area's expression in terms of the sine function reduces to $1 - \cos{x_2}$ when $x_1 = 0.$

[2] William Elwood Byerly, Elements of the Integral Calculus, 2nd edition, Ginn and Company, 1892, xvi + 339 + 11 + 32 pages.

See Chapter VIII, Article 81, p. 76, Examples (2): By the aid of the trigonometrical formulas $$\cos{\theta} + \cos{2\theta} + \cos{3\theta} + \cdots + \cos{(n-1)\theta} = \frac{1}{2}\left[\sin{n\theta} \cot{\frac{\theta}{2}} - 1 - \cos{n\theta}\right],$$ [and] $$\sin{\theta} + \sin{2\theta} + \sin{3\theta} + \cdots + \sin{(n-1)\theta} = \frac{1}{2}\left[(1 - \cos{n\theta}) \cot{\frac{\theta}{2}} - \sin{n\theta}\right],$$ prove that $\;\;\int_{a}^{b}\cos{x}.dx = \sin{b} - \sin{a},\;$ and $\;\int_{a}^{b}\sin{x}.dx = \cos{a} - \cos{b}.$

[3] Carl Benjamin Boyer, History of the derivative and integral of the sine, Mathematics Teacher 40 #6 (October 1947), 267-275.
[4] Mark Bridger, A note on areas under a sine curve, The Pentagon 18 #1 (Fall 1958), 24-26.

At the time Mark Bridger was a student at the Bronx High School of Science (New York).

[5] Richard Courant and Fritz John, Introduction to Calculus and Analysis, Volume I, John Wiley and Sons (Interscience Publishers), 1965, xxiv + 661 pages.

See Chapter 2.2.e (Integration of $\sin x$ and $\cos x$), p. 135.

[6] Godfrey Harold Hardy, A Course of Pure Mathematics, 10th edition, Cambridge University Press, 1952, xii + 509 pages.

See Chapter VII, Article 164, p. 320, item 3. Calculate $\int_{a}^{b}x^2 \, dx,$ $\int_{a}^{b} \cos{mx} \, dx$ and $\int_{a}^{b} \sin{mx} \, dx$ by the method of Ex. 1. Note: Hardy's reference to "the method of Ex. 1" is simply the method of partitioning the interval $[a,b]$ into finitely many equal length subintervals, forming the relevant Riemann sum, and taking a limit. The needed trigonometric identities are not given as a hint, but I do notice that a closely related identity appears in Exercise 4 at the top of p. 323 for another purpose.

[7] Kenneth Sielke Miller and John Breffni Walsh, Elementary and Advanced Trigonometry, Harper and Brothers, 1962, xii + 350 pages.

See Chapter 10.3 (Solution of the Area Problem), pp. 215-217: (begins) We now turn to the second problem mentioned at the beginning of the chapter, namely, that of finding the area under one arch of a sine curve.

[8] Isidor Pavlovich Natanson, Summation of Infinitely Small Quantities, Topics in Mathematics, D. C. Heath and Company, 1963, viii + 59 pages.

See Chapter 6 (The Sinusoid), Articles 26-35, pp. 46-57. Specifically, see Article 29 (A trigonometric sum), Article 30 (A subsidiary inequality), Article 31 (The sine of an infinitely small angle), and Article 32 (The quadrature of the sinusoid) on pp. 46-51. The remaining articles in this chapter involve applications, mainly in calculating the volume of a rotating sinusoid and calculating effective (electrical) current.

[9] John Meigs Hubbell Olmsted, Intermediate Analysis. An Introduction to the Theory of Functions of One Real Variable, The Appleton-Century Mathematics Series, Appleton-Century-Crofts, 1956, xiv + 306 pages.

See Chapter 5, Article 503, p. 145, Exercise #19 & 20. The reader is asked to show that $\int_{a}^{b}\sin x \, dx = \cos{a} - \cos{b}$ and $\int_{a}^{b}\cos x \, dx = \sin{b} - \sin{a}$ by using equal length partitions of $[a,b].$ The relevant trig. identities are indirectly provided (by means of a hint, the reader is led to obtain these identities).

[10] Michael David Spivak, Calculus, 3rd edition, Publish or Perish, 1994, xiv + 670 pages.

See Chapter 15, p. 320, Problem 33.

[11] Isaac Todhunter, A Treatise on the Integral Calculus, 6th edition, MacMillan and Company, 1880, viii + 408 pages.

See Chapter IV, Article 38, pp. 52-53: (begins) Suppose we wish to find the integral of $\sin x$ between limits $a$ and $b$ immediately from the definition. By Art. 4 we have to find the limit $[\ldots]$ Note: The copy I found online is dated 1863, but what I've quoted seems to be the same calculation and it's in the same location in the book.

[12] Edwin Bidwell Wilson, Advanced Calculus, Ginn and Company, 1911, x + 566 pages.

See Chapter I, p. 30, Exercise 9. With the aid of the trigonometric formulas $[\ldots]$ show $(\alpha) \; \int_{a}^{b} \cos{x}\,dx = \sin{b} - \sin{a},\;\;$ [and] $\;\;(\beta) \; \int_{a}^{b} \sin{x}\,dx = \cos{a} - \cos{b}.$

(ADDED 3 DAYS LATER) I thought it would be useful to archive in my answer some references for evaluating definite integrals of other functions by Reimann sums. However, because I want to get this finished during my lunch hour and I don't want to substantially increase the length of this already long answer, I will use briefer citations.
Harding/Barnett, Solution to Calculus Problem #369, Amer. Math. Monthly 22 #6 (June 1915), 208-210.

Two solutions for the evaluation of $\int_{a}^{b} \ln{x}\,dx$. The second solution makes use of Fermat's method of geometric subdivision of the interval $[a,b].$

Barnett, Solution to Calculus Problem #366, Amer. Math. Monthly 22 #5 (May 1915), 168-169.

One solution for the evaluation of $\int_{a}^{b}{\sin}^{-1}x\,dx.$

Eli Maor, On the direct integration $\int_{a}^{b}x^{n}\,dx,$ Int. J. Math. Educ. Sci. Technol. 5 (1974), 199-200.

The method involves working with the sum of the left endpoint sums and the right endpoint sums. The method might be similar to what Otto Dunkel does in Note on the quadrature of the parabola, Amer. Math. Monthly 27 #3 (March 1920), 116-117.

Finally, the following are similar to the kind of things found in Natanson's Summation of Infinitely Small Quantities:
W. R. Longley, Some limit proofs in solid geometry, Amer. Math. Monthly 31 #4 (April 1924), 196-202.
Joseph B. Reynolds, Some applications of algebra to theorems in solid geometry, Mathematics Teacher 18 #1 (January 1925), 1-9.
Jos. B. Reynolds, Finding plane areas by algebra, Mathematics Teacher 21 #4 (April 1928), 197-203.
Comment: This is a great list of references! Thanks!
Answer: I suspect Tom Apostol's calculus textbook has this (i.e., finds $\int_0^\pi\sin x\,dx$ by using limits of Riemann sums without the fundamental theorem).
I question the place of Riemann sums in the curriculum.  Rigorous definitions are unsuitable for a calculus-for-liberal-education course unless the students are unusual.  Such a course should acquaint students with the reason why calculus is important in the course of human events over recent and coming centuries, and with the fact that it overcame difficulties like how to define $\text{rate} = \dfrac{\text{distance}}{\text{time}}$ when the distance and the time are both $0$, and how to to find $$\sum\text{force}\times\text{distance}$$ when there are infinitely many infinitely small distances, each with its own value of "force".  The conventional calculus course is a watered-down version of a course for students who come in with a prior desire or a pre-identified need to understand calculus, rather than for students who are there in order to pay a price in homework for a grade to impress employers, and whom one should be trying to seduce into another course of action.
If you expect students to marvel at the fact that it's possible to find this integral by using limits of Riemann sums, I expect the way they will think of it and remember it is "We did some technical stuff and turned it in and got graded", and if you have them plod through finding the integral by antidifferentiating and substituting endpoint values, then the way they will think of it and remember it is "We did some technical stuff and turned it in and got graded", and they won't know the difference.  (I'm hoping for a malpractice suit against every university that knowingly encourages unqualified students to take calculus, to the point where those are 99.9% of the ones who show up.  They bring in tuition money.)
Another occasion for Riemann sums is numerical integration, but that doesn't seem to be your purpose.
Comment: Apostol's book gives the formulas for $\int_a^b \sin(x)\;dx$ and $\int_a^b \cos(x)\;dx$ followed by the statement "we shall not prove these formulas at this stage because they will be derived by an easier method in Chapter 2, with the help of differential calculus."
Comment: @wckronholm : OK.  Apostol's book may still be a place to look if anyone wants similar material.  Also, maybe Otto Toeplitz' "genetic approach" calculus book.
Comment: $99.9\%$ may be unduly pessimistic. Perhaps I will be accused of being a rosy-eyed optimist, but $95\%$ seems more reasonable.
Comment: @AndréNicolas : Depends on which institution.  There are colleges that think of themselves as selective, at which the students are hard-working and intelligent, but have attitudes about math courses: They exist in order to provide an opportunity to show that they can follow instruction and work hard and get a grade, and they've always gotten "A"s in math, and they demand their right to get a course consisting of algorithms for them to follow to get an "A".
Comment: @MichaelHardy I actually had my class run through this computation in small groups in class today. While it's true that many of them were longing for the Fundamental Theorem of Calculus they "learned" in high school and could give them the answer in about 5 seconds, there were more than a few who really were appreciating all of the pieces that went into the computation.

In general, I think students benefit from exposure to this sort of activity because of the potential to broaden their reasoning skills.
Comment: @wckronholm : OK, it does depend on which institution. And on how it's presented. I've seen the situation I described above, so sometimes I'm more pessimistic.
Comment: Michael Hardy: I don't think it's in Otto Toeplitz's book, at least I didn't see it in my copy when I looked this morning. However, I was looking pretty quickly through some of my books (this one being one such) and it may have been there and I missed it.
Comment: @wckronholm I am reading through the second edition of Apostol's book. I cannot find the statement; he did, in fact, prove the formulas without the fundamental theorem. See pages 97-102.
Answer: Alternatively, you can use $e^{i \theta} = \cos(\theta) + i \sin(\theta)$ and the partial sum formula for Geometric series. Using left endpoint approximation instead, the  sum we want to evaluate is
$$ \sum_{k=0}^{n-1} \sin(k \, \Delta x)\,\Delta x$$
where $\Delta x = \frac{\pi}{n}$. Note that $\sum_{k=0}^{n-1} \sin(k \,\Delta x)$ is the imaginary part of $\sum_{k=0}^{n-1} e^{i k \,\Delta x}$, that is $\sum_{k=0}^{n-1} z^k$ where $z = e^{i \,\Delta x}$. This last sum has the closed form $\frac{1-z^n}{1-z} = \frac{2}{1-z}$ using $z^n = e^{i \pi} = -1$. We get
$$ \sum_{k=0}^{n-1} \sin(k \,\Delta x)\,\Delta x =\mathrm{Im}\left( \frac{2}{1-e^{i\, \Delta x}} \right) \,\Delta x =  \mathrm{Im}\left( \frac{2\,\Delta x}{1-e^{i \,\Delta x}} \right).$$
Finally, letting $n \to \infty$ so that $\Delta x \to 0$ we get
$$\lim_{\Delta x \to 0} \frac{2\,\Delta x}{1-e^{i \,\Delta x}} = -2\left( \lim_{\Delta x \to 0 } \frac{e^{i \,\Delta x} - 1}{\Delta x} \right)^{-1} = -2\left( \frac{d}{dt} e^{it} \big|_{t=0} \right)^{-1} = -2i^{-1} = 2i$$
so that
$$ \lim_{n \to \infty} \sum_{k=0}^{n-1} \sin(k \,\Delta x)\,\Delta x = \operatorname{Im}(2i) = 2.$$
Comment: Thanks. We were aware of this method already, and wanted to find an approach which did not rely on complex numbers.
Comment: @wckronholm: That makes sense, just thought I'd add it.
Comment: @wckronholm: It has probably occurred to you already, but if you don't want to use complex numbers, you can still do integrals like $\int_0^1 e^x \ dx$ using geometric series.
Comment: Thanks, that has indeed occurred to me, and I will be showing this to my students in about 20 minutes!


Vertical score positioning in LilyPond

Question: I'm writing a drum sheet template for LilyPond and I'd like to place a drum key box to the left of the header. Here is what I've done so far:

LilyBin link for fiddling with my markup: http://lilybin.com/yx9viw/1
The problem I'd like to solve is vertically positioning the score or the DrumStaff inside the box, to remove all the blank space at the top. I figure removing the Stem_engraver would help (and is also desirable, since I only want to show the note heads in the drum key), but it doesn't really work (see line 63 on LilyBin), and while \hide-ing the stems does work, it doesn't eliminate the vertical space occupied by them.
So, does anyone know how I can:

Remove (not hide) the stem engraver from the score inside the \box (line 60 on LilyBin), and
Vertically position the entire score so it stays at the top of the \box, thus eliminating all that whitespace?
Comment: If you use \omit Stem instead of \hide Stem, you will get rid of the stems (and they won't take up any space), but I have no idea about what is making that whitespace. Nor why the stems are rendered when Stem_engraver is removed...
Comment: @Ramillies thank you, I didn't know the `\omit` function =). Eliminating the stems I figured the whitespace is generated by the `\markup` texts I use to label the note heads. Even when I override the `TextScript` position using `#'extra-offset`, the text leaves behind the whitespace it should have occupied without the override. (http://lilybin.com/yx9viw/3)
Answer: Hm, is there any reason why you have the markups with the labels connected to invisible notes on the left and the right? Why not just put it in a line like this: http://lilybin.com/yx9viw/4 .
What I did is \box { \line { \raise #something \left \score { ... } \raise #something \right } }. It works OK it seems. (The #something's were chosen to make the labels match with the note columns.)
(This is better because you can \raise the labels into the right places (this command generally works only for moving a part of markup relative to the rest of the markup).)
Comment: I used invisible notes because I didn't know any better =) Thank you so much, this is a cleaner solution than I was expecting for LilyPond, and the knowledge that the `\line` function can contain whole `\score`s opens up a lot of possibilities!
Comment: @nunks.lol: Yeah, the markup system is very general and powerful. `\line` just grabs some markups and puts them into a line :—). And a markup can contain `\score` (it's "just" a markup command in the same way as e. g. `\italic` is). (Maybe you can see why I like Lilypond so much? :—))

Vertical score positioning in LilyPond


How to handle with null web service response?(axis2)

Question: I'm set up the web service by java、axis2,
there two response type : XML and JSON,
It's run when I call the webservice which having data,
but when the webservice response null data, the exception occurd.(following two picture)
and there is one part of my webservice function:
<code>    public ViewStockHelpBuySheet[] getHelpBuySheet(String userid){
    Stock my=new Stock();

    ViewStockHelpBuySheet[] allStock=my.getHelpBuySheet(userid);
    allStock=new ViewStockHelpBuySheet[allStock.length];
    allStock=my.getHelpBuySheet(userid);
    return allStock;
}
</code>
so, how can I handle my null result ? did axis2 provides some way to handle that?
thanks
error picture:
http://ppt.cc/fcEt
http://ppt.cc/mWIL
Comment: I would guess you need to check for a null result before returning the response. The stack trace shows it cannot implicitly convert from a string(null) to a JSON object. Maybe create the JSON object first, then assign the values when you know it is not null.
Answer: Webservices are your programs..There is nothing special..You need to have your logic defined in it to handle your NPE exception or other type of exceptions..


How does the NFL distribute their content online?

Question: Ordinary television shows have sites like Hulu where their content can be viewed online.  However, for the NFL, their online content distribution strategy seems less clear.
What is the league's current policy for online content distribution, and are there currently any official online distribution channels for regular season games?
Comment: Better...it sounds more like you're asking about how the NFL handles streaming vs. looking for a link to watch the game. Nonetheless, i have reopened and added the "rules" tag.
Comment: There have now been a few games streamed online for free ([Yahoo](http://www.businessinsider.com/yahoo-nfl-game-online-2015-10), [Twitter](http://www.mirror.co.uk/sport/other-sports/american-sports/twitter-stream-first-live-nfl-8842324)), and this year Amazon Prime will stream ([source](http://www.nfl.com/news/story/0ap3000000797854/article/nfl-amazon-prime-announce-tnf-streaming-deal)) but they are pay.  I believe NBC has also freely offered a wide range of streams on their website including multiple angles for their Sunday Night Football.
Answer: There is no "legal" way to watch live streaming NFL games online without going through a cable provider. NFL does not allow any websites, even their own, to stream live NFL games. This is due to the huge contracts that the NFL has with CBS, FOX, NBC, and ESPN. If the NFL were to stream live games online, it would take viewers away from these stations, resulting in a loss of advertisement revenue.
If you want to watch full game replays online, after they have happened, NFL offers NFL Game Rewind. This requires a paid online subscription.
If you have you heart desired to stream a live NFL game on your computer, you can buy a special package with most of your cable providers that allows you to watch live TV on your computer. This doesn't affect the contracts that NFL has with certain stations because it is the exact picture you would be seeing if you were watching on a TV, thus giving CBS, FOX, NBC, and ESPN their view rankings and advertisement revenue.
In summary:

There is no way to watch live NFL games online unless you buy a package from your cable provider.
There is no free service which allows you to watch full game replays other then NFL Game Rewind.
Answer: There is an "official online distribution channel for regular season games".  It's called NFL GamePass but is only available outside the US.
Within the US, games are locked up by the contracts with the broadcast networks with the exception of NFL Network games - these are sometimes available live through NFL.com (or have been in the past).
Answer: It appears that this year (2016) at least that some games will be available via Twitter.
https://nflcommunications.com/Pages/2016-'Thursday-Night-Football'-Broadcast-Schedule-Announced.aspx


I need a handy jQuery tool (plugin) to work with the map

Question: I need a handy jQuery tool (plugin) to work with the map.
The project has narisovanaya map with cities marked on it, the possible routes.
Example

I want to:

To apply the route (in this example it is shown in green) on top of the map (img)
Display a small div with information about city

Now inclined to think that would work to implement the map through the canvas, but is not sure whether it is convenient to display the div with information about the city.
Maybe someone encountered a similar problem and help me avoid mistakes.
Comment: Hi @Shaliko, please go to your profile and accept some answers.
Answer: It would be easier to use a Canvas. jQuery can't provide much help in this instance. I suppose you could use jQuery to absolutely position divs over the routes and nodes, but that would be a lot of work.
Answer: I have recently had a similar concept. I decided that the best way to show routes on maps was to Hook into the Google Maps API. This is a complex system and will take a great deal of reading, learning and trying to get it right, but it gives your users full control over the map, allowing them to zoom, move, and calculate routes. You can even put placemarkers on the map.


Extract values from a data frame in one line

Question: I have a data frame with xy coordinates of a polygon, such as
head(df)
         x        y
1 -80.59264 40.88406
2 -80.50539 40.91076
3 -80.41909 40.93284
4 -80.32967 40.94047
5 -80.24228 40.93894
6 -80.16811 40.93434

I try to extract it to obtain something like this:
df
(-80.59264 40.88406, -80.50539 40.91076, -80.41909 40.93284, -80.32967 40.94047, -80.24228 40.93894, -80.16811 40.93434...)

i.e. each line is separated by a comma and column values with a space.
This is possible to do this in R?
Thank you for your suggestions.
Answer: Perhaps use paste
do.call(paste, c(df, collapse = ", "))


How to break lines properly which contain both CJK and english characters in WordPress?

Question: I found that CJK article in my wordpress4.7 can't break  lines properly,which contain both CJK and english characters.
Here is the article before publish.

All the lines breaked properly before publish.

Now it displayed as below after published.
All lines messed ,breaked bad-formatted as unexpected way.

I had tried to fix it this way.
vim  /var/www/html/wp/wp-content/themes/twentysixteen/style.css
.site-inner {
    margin: 0 auto;
    max-width: 1320px;
    position: relative;
}

.site-content {
    word-wrap: break-word;overflow:hidden;
    word-break:break-all;white-space:pre-wrap;
}

To restart  apache and wordpress,no effect at all.
My wordpress version is 4.7,theme is twentysixteen.
Answer: try to add this code in your functions.php theme file
    function my_tinymce_fix( $init )
    {
        // html elements being stripped
        $init['extended_valid_elements'] = 'div[*], article[*]';

        // don't remove line breaks
        $init['remove_linebreaks'] = false;

        // convert newline characters to BR
        $init['convert_newlines_to_brs'] = true;

        // don't remove redundant BR
        $init['remove_redundant_brs'] = false;

        // pass back to wordpress
        return $init;
    }
    add_filter('tiny_mce_before_init', 'my_tiny_mce_fix');

Answer: Try word press plugin.
TinyMCE Advanced
There is option to disable automatically remove of br tag and p tag from setting page of plugin.
Answer: Install Don't Muck My Markup
Don't Muck My Markup is a plugin that will allow you to

disable all auto-generated HTML markup from your posts and pages on a page-by-page basis.

It adds a small box in the default WordPress editor to turn off automatic markup / formatting for that page/post
This means that can keep all other pages the same and just disable the automatic formatting only for the page / post you're currently editing
Then,
when you have a page/post with mixed content, disable the automatic formatting for that page/post and manually add html mark up like

 and so on


Webpack dev server DO reload, but page not change

Question: Here is my package.json file:
{
  "name": "postronix",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "transpile": "webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.14.0",
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "css-loader": "^0.24.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "node-sass": "^3.9.0",
    "sass-loader": "^4.0.1",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.15.1"
  },
  "dependencies": {
    "babel-polyfill": "^6.13.0",
    "jquery": "^3.1.0"
  }
}

webpack.config.js:
const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: './src/app.js',
    output: {
        path: './bin',
        filename: 'app.bundle.js',
    },
    module: {
        loaders: [
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'react', 'stage-0'],
                'plugins': ['react-html-attrs']
            }
        },
        {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract('css!sass')
        }
        ]
    },
    plugins: [
    new ExtractTextPlugin('public/style.css', {
        allChunks: true
    })
    ]
}

i run this command:
webpack-dev-server --content-base ./ --hot

whenever i make changes to my app.js file, this log shown in gitbash:
Version: webpack 1.13.2
Time: 183ms
           Asset      Size  Chunks             Chunk Names
   app.bundle.js    532 kB       0  [emitted]  main
public/style.css  84 bytes       0  [emitted]  main
chunk    {0} app.bundle.js, public/style.css (main) 496 kB [rendered]
    [0] ./src/app.js 1.1 kB {0} [built]
     + 300 hidden modules
webpack: bundle is now VALID.

in chrome web browser, i opened http://localhost:8080/webpack-dev-server/, the page screen DO reload every i modify app.js, but no any change to the page, it's like the app.js just the same as before i make change.
its just compiled only with webpack --watch.
please help
Answer: Finally found an answer.
i put publicPath: "/assets/" in webpack.config.js
and in index.html i add "assets" path for referring script:

<link rel="stylesheet" type="text/css" href="assets/public/style.css">

now, its compile and reload perfectly.


One reader, many writers

Question: Related: How to catch exceptions from a ThreadPool.QueueUserWorkItem?
I am catching exceptions in background threads started by ThreadPool.QueueUserWorkItem(), and propagating them to the main thread via a shared instance variable.
The background threads do this:
try
{
    ... stuff happens here...
}
catch (Exception ex1)
{
    lock(eLock)
    {
        // record only the first exception
        if (_pendingException == null)
            _pendingException = ex1;
    }
}

There are multiple potential writers to _pendingException - multiple background threads -  so I protect it with a lock.
In the main thread, must I take the lock before reading _pendingException?   Or can I simply do this:
if (_pendingException != null)
    ThrowOrHandle();

EDIT:
ps: I would prefer to NOT take the lock on the reader thread because it is on the hot path, and I'd be taking and releasing the lock very, very often.
Comment: Your describing zdnet aren't you?
Comment: Are you doing anything with the exception that's passed back? Or could you use a bool to flag that an error has occurred?
Comment: zdnet?  No.  I don't even know what that is.  Umm, lessee... am I using the exception... well, yes.  I rethrow it from the main thread.
Answer: You will not be able to get away this easy. You will lose exceptions if another thread throws it before the reader dealt with the existing one. What you need here is a synchronized queue:

try
{
    ... stuff happens here...
}
catch (Exception ex1)
{
    lock(queue)
    {
        queue.Enqueue(ex1);
        Monitor.PulseAll(queue);
    }
}

And to process it:

while(!stopped)
    lock (queue)
    {
        while (queue.Count > 0)
            processException(queue.Dequeue());
        Monitor.Wait(queue);
    }
Comment: I really just want the first exception - it's a fail fast approach.  No recovery.  So I don't care if I miss exceptions 2..n.  I just want the first one.
Answer: Reads and writes to references are atomic (See C# Spec) and I'm nearly certain that lock does create a memory barrier so yes what you are doing is probably safe.
But really just use the lock around your read.  It's guaranteed to work; if you every see it accessed not in a lock you know something is wrong, if the lock is causing you performance issues then you're checking the flag way too often, and it's just the "right thing to do."
Comment: Problem is, the main thread is the one doing the read of that _pendingException field.  I would prefer to NOT take the lock on the reader thread because it is on the hot path, and I'd be taking and releasing the lock very very often.
Comment: Why do you not want to use the lock on the main thread?  Have you tried it and found it to be too slow or is this premature optimization?  If it is causing you a problem then your polling that flag way too often and should choose a different notification strategy, e.g. call a delegate on error rather than polling a flag.
Answer: Even though you may only care about the first exception, you may still want to use lock for at least two reasons:

In multi-core CPUs, without making a variable volatile (or performing any memory barrier operation) , there might be a moment when threads running on different cores may see different values. (I am not sure calling lock(queue) in a worker thread will cause any memory barrier operation though). (update) Calling lock(queue) in a worker thread will cause memory barrier operation as pointed out by Eric in the comment below.

2. Please keep it mind that References are not addresses (by Eric Lippert) (if you are assuming references are 32-bit addresses in 32-bit CLR that can be read atomically).  The implementation of references can be changed to some opaque structures that may not be read atomically in future release of CLR (even though I think it is not likely to happen in foreseeable future :)) and your code will break.
Comment: This is NOT CORRECT. The specification clearly states that reads and writes of references must be atomic in all implementations of C#. See section 5.5 of the spec for details.
Comment: Updated (striked out) the wrong information pointed by Eric Lippert. Thanks for the correction and I am sorry for this late response :).  If the number 1 is still incorrect, please let me know.  Again, thanks!

One reader, many writers


Somebody have a responsive CSS template for Emails (newsletters)?

Question: I'm designing an HTML newsletter that is supposed to load nicely including on mobile devices.
I found these links to sites that show blank templates:

http://www.emailology.org/
http://htmlemailboilerplate.com/#f2

But with both I didn't succeed in showing responsive design on my mobile Android 2.3.3
Does someone have a live example for such responsive email, so I can learn from it?
I tried to look for one on the web but couldn't find one...
Comment: i recently coded responsive email templates at mojo themes
http://www.mojo-themes.com/item/shopmail-product-offer-responsive-email-template/
Answer: Reading up on responsive HTML emails my self, I stumbled upon your question. Even though a bit late, I though I'd take the time to share what I've found so far.
I've found a couple of good resources to read, both provided by email newsletter web services.

Campaign Monitor provide a pretty extensive guide on how to design responsive HTML emails. It discusses different approaches to take, things to think about and shows a few handy "hacks". In the guide, they also reference a few downloadable examples of responsive emails that you can use as a starting ground, and build your own email upon.
MailChimp also has a guide on email for mobile devices. It has a broader focus and discuss everything from statistics to user behavior and best practices, but it also has a section on various design approaches.

To get live examples to learn from, I suggest you sign up for newsletters by some of the major companies, that has spent time on developing their newsletters. I'm not going to market any company in particular, but I know that both above referenced guides mention a few companies that they think have great HTML newsletters, that could be worth having a look at.
Answer: HTML emails are a different beast all together. There are a couple of websites dedicated to having HTML clients support standard markup, but that day is not anywhere close to becoming a reality. I doubt many email clients (if any) support the media queries needed for responsive CSS to work. My suggestion would be to make an HTML email template that is adaptable enough to work at a mobile resolution and still look good in an normal desktop resolution. Maybe some liquid widths.
For help with which clients support what and how well the support HTML / CSS features, check these two links out.

Email Standards Projects
Campaign Monitor Email CSS Support
Comment: you didn't add any helpful information... if you have any evidence that responsive newsletter can't be done, you'll need to explain the two site's above which I gave the links to.
Comment: From one of your sites it states "Media queries will not work for mobile versions of Gmail." And I'd assume there's all sorts of issues in all the different mobile clients. I guess what I was trying to say is that writing templated emails isn't an exact science and I don't think there's a one solution fits all plug your html in and press send. I linked what I did to help you figure out what is supported in email clients and what isn't. I'll take a look at those templates and see if I can get some working examples.
Comment: yes, the issue is that those sites gave Allegedly dummy-proof templates, and it didn't worked for me, some i figured i might be missing something here...
Answer: I have a superb solution for this issue. Solution is that - you can opt to create HTML email newsletter using fluid technique. I mean that you should build it in percentages - so that all the devices out there can fit your email.
I have a tutorial on creating: Fluid responsive email newsletter.
Hope this helps many people out there.
Thanks!

Sumesh M.S


Data from the Form Submit vs Data from Ajax

Question: I'm trying to implement reCAPTCHA in my MVC site, but it doesn't Validate unless I submit it from a form, like this:
    @using(Html.BeginForm("VerifyCaptcha", "Signup") )
    {
        @ReCaptcha.GetHtml(theme: "clean", publicKey: "6LcnfAITAAAAAAY--6GMhuWeemHF-rwdiYdWvO-9");
        <input type="submit" id="btnVerify" value="Verify" />
    }

    [HttpPost]
    public ActionResult Index(PolicyModel model)
    {
        var result = ReCaptcha.Validate(privateKey: "THE_KEY");
        return View();
    }

I don't want to use form submission because I don't want to return a new view. All my data is being pushed around with ajax in json form. What I'd like to do is:
$.ajax({
    url: 'verifyCaptcha',
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded",
    type: "POST",
    async: false,
    success: function (response) {
        alert(response);
    },
    error: function(response) {
        alert('There was a problem verifying your captcha. Please try again.');
    }
});
return valid;

        [HttpPost]
        public ActionResult VerifyCaptcha()
        {
            var result = ReCaptcha.Validate(privateKey: "THE_KEY");

            return Json(result);
        }

The ajax call gets to the controller, but the Validation method completes immediately, almost as if it doesn't even get to making the request. I'm not sure why the validation always fails if the captcha isn't in a form - is it perhaps losing information like it's public key or something? Is there a workaround to this?
Edit: Added the ajax controller action method without model.
Comment: change the button type to button and in your ajax assign a valid url, write ajax inside your button click event
Comment: so you set `type : 'POST'`in your ajax code? putting you code in a completed state make easier to help you
Comment: ok, your ajax request reach the `Action`or does not ?
Comment: Yes, it does. I have a feeling it loses the public key or something, because it ALWAYS returns false, so quickly that it seems as though it's not even submitting the request.
Comment: you have to send the public key in the data property as a json
Answer: Just use serializeArray() or serialize() and change your ajax request to
$.ajax({
    url: 'verifyCaptcha',
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded",
    type: "POST",
    async: false,
    data: $('form').serializeArray(), // $('form').serialize(),
    success: function (response) {
            alert(response);
        }
});

You haven't added the data part in your request. That seems to be the problem
Comment: Simple reason. You need `data` to validate the request. But since you want it as a form response, you need to build your data object and send it via AJAX. And since you are using jQuery, you can use the built-in functionality to get the data from your form.
Comment: You Sir, are the person who has made my Monday bearable. Works perfectly - thanks a ton! Can you perhaps shed some light as to why I actually need to pass the form as data?
Answer: You need to set the Ajax Request with all parameters for a form request. For example the content-type as application/x-www-form-urlencoded.
Look at this: application/x-www-form-urlencoded or multipart/form-data?
UPDATE:
...and yes ...you must do a POST request, and not a GET.
UPDATE:
$.ajax({
    url: 'verifyCaptcha',
    contentType: "application/x-www-form-urlencoded",
    type: "POST",
    success: function (response) {
        alert(response);
    },
    error: function(response) {
        alert('ERROR', response);
    }
});

Comment: Ok, just saw you edit. It's more complete but still wrong: try with `content-type: "application/x-www-form-urlencoded"`
Comment: Okay, I did that. Still a problem.
Comment: Check what `alert('ERROR', response);` show. In that `response ` there's the code of the error and then you could find more info about the problem.
Comment: Nothing is wrong my ajax call. The server-side call for Validate always just returns false.


2 UICollectionViews in 1 View Controller working with swift and xcode

Question: So i am working in xcode with swift
on my storyboard I have only 1 view controller
on that view controller i have 2 separate collection view cells, top 1 will show certain images and the bottom shows a different array of images
my problem is that when i connect dataSource and delegate to viewcontroller for both of the views the program crashes and i get the following error:

[OF.ViewController collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 0x7b662cc0
  Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[OF.ViewController collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 0x7b662cc0'

and if i disconnect both dataSource and ViewController then the app runs but nothing shows up in the collection cells
the functions:
func topsCollectionView(topCollectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return topImages.count
}

func bottomsCollectionView(bottomCollectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return bottomImages.count
}

Answer: Your app is crashing because OF.ViewController doesn't implement collectionView:numberOfItemsInSection:.
Instead you have: topsCollectionView:numberOfItemsInSection: and bottomsCollectionView:numberOfItemsInSection:. To fix this problem, implement the dataSource method collectionView:numberOfItemsInSection:. Then, you can differentiate between the top and bottom UICollectionViews by way of comparison.
Ex.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger numberOfItems = 0;

    if (collectionView == self.topCollectionView)
        numberOfItems = [self.topImages count];
    else if (collectionView == self.bottomCollectionView)
        numberOfItems = [self.bottomImages count];

    /* OR, if you prefer one line*/
    numberOfItems = (collectionView == self.topCollectionView ? [self.topImages count] : [self.bottomImages count]);

    return numberOfItems;
}

P.S. I apologize, I don't know Swift.


Installed Views Module but It did not appeared in Structure

Question: I installed a fresh Drupal 7.22 on my localhost and installed Ctools and Views modules.
When i go to Structure i dint find Views link
I also cleared all cache but still same problem.
This is not my first Drupal experience, I created many views.
Here are the screen shots.
Answer: You have to enable Views UI in order for it to show up under Admin -> Structure.
Answer: If you are still not seeing after enabling Views-UI and IF YOU USING ADMIN MENU module to generate Admin Menus, You have to clear cache.
To do that,
Home Icon -> Flush all caches -> Administration menu
Home Icon -> Flush all caches -> Menu
Comment: This is not an answer to the question actually asked here. Also, questions that can be answered with a mere cache clear are not even on-topic here.
Comment: That was my experience. Because I have enabled View and View-UI and it didnt appear on the Structure block.


How to prove that $S=\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{2n+1}}{(2n+1)^2}=\frac{\pi^2}{16}-\frac{1}{4}\log^2(\sqrt{2}-1)?$

Question: How to prove that

$$S=\displaystyle\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{2n+1}}{(2n+1)^2}=\frac{\pi^2}{16}-\frac{1}{4}\log^2(\sqrt{2}-1)$$

My attempt:
We have for $|x|\leq1$ $$\tanh^{-1}(x)=\displaystyle\sum_{n=0}^{\infty}\frac{x^{2n+1}}{2n+1}$$
and :
\begin{align*}
\displaystyle\int_0^{\sqrt{2}-1}\frac{\tanh^{-1}(x)}{x}\ \mathrm{d}x&=\displaystyle\int_0^{\sqrt{2}-1}\frac{1}{x}\displaystyle\sum_{n=0}^{\infty}\frac{x^{2n+1}}{2n+1}\mathrm{d}x\\
&=\displaystyle\sum_{n=0}^{\infty}\frac{1}{2n+1}\displaystyle\int_0^{\sqrt{2}-1}x^{2n}\mathrm{d}x\\
&=\displaystyle\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{2n+1}}{(2n+1)^2}\\
&=S\\
\end{align*}
So :
\begin{align*}
S&=\displaystyle\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{2n+1}}{(2n+1)^2}\\
&=\displaystyle\int_0^{\sqrt{2}-1}\frac{\tanh^{-1}(x)}{x}\mathrm{d}x\\
&=\displaystyle\int_0^{\sqrt{2}-1}\frac{1}{2x}\left(\log(1+x)-\log(1-x)\right)\mathrm{d}x\\
&=\frac{1}{2}(J_1-J_2)
\end{align*}
Where:
\begin{align*}
J_1&=\displaystyle\int_0^{\sqrt{2}-1}\frac{\log(1+x)}{x}\mathrm{d}x\\
&=\displaystyle\sum_{n=0}^{\infty}\frac{(-1)^n}{n+1}\displaystyle\int_0^{\sqrt{2}-1}x^n\mathrm{d}x\\
&=\displaystyle\sum_{n=0}^{\infty}\frac{(-1)^n(\sqrt{2}-1)^{n+1}}{(n+1)^2}\\
\end{align*}
And:
\begin{align*}
J_2&=\displaystyle\int_0^{\sqrt{2}-1}\frac{\log(1-x)}{x}\mathrm{d}x\\
&=\displaystyle\int_0^{\sqrt{2}-1}-\displaystyle\sum_{n=0}^{\infty}\frac{x^n}{n+1}dx\\
&=-\displaystyle\sum_{n=0}^{\infty}\frac{1}{n+1}\left[\frac{x^{n+1}}{n+1}\right]_0^{\sqrt{2}-1}\\
&=-\displaystyle\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{n+1}}{(n+1)^2}\\
\end{align*}
Finally we find :
$$S=\frac{1}{2}\left(\displaystyle\sum_{n=0}^{\infty}\frac{(\sqrt{2}-1)^{n+1}((-1)^n+1)}{(n+1)^2}\right)$$
But I could not find a way to calculate $S$.
Any help please? and thank's in advance.
Comment: Let $$\chi(x) = \sum_{n\geq 0}^\infty \frac{x^{2n+1}}{(2n+1)^2}$$ then $\chi'(x) = \frac{1}{2x}\log((1+x)/(1-x))$, so one checks easily, by differentiating both sides: $$\chi\left(\frac{1-x}{1+x}\right) + \chi(x) = \frac{\pi^2}{8} - \frac{1}{2}\log x \log\left(\frac{1-x}{1+x}\right)$$  for $x=\sqrt{2}-1$, $x = (1-x)/(1+x)$. (c.f. *Legendre's Chi-Function*)
Comment: [Avoid](https://math.meta.stackexchange.com/questions/9687/guidelines-for-good-use-of-rm-latex-in-question-titles) displaymode in titles please.
Comment: See [Legendre Chi Function](https://mathworld.wolfram.com/LegendresChi-Function.html).
Answer: I shall be continuing from the last two integrals of your work $$\int_0^{\sqrt 2-1} \frac{\tanh^{-1}x}{x} dx =\frac{1}{2}\int_0^{\sqrt 2-1} \left(\frac{\log(1+x)}{x}-\frac{\log(1-x)}{x}\right)dx$$  These two integrals posses non-elementary antiderivatives in terms of special function Dilogarithm function so by definition we have $$=\frac{1}{2}\left(\operatorname{Li}_2(x)-\operatorname{Li}_2(-x)\bigg|_0^{\sqrt 2-1}\right)=\frac{1}{2}\left(\operatorname{Li}_2\left(\sqrt2 -1\right)-\operatorname{Li}_2\left(1-\sqrt 2\right)\right)\cdots(1)$$ Using the last identity [3] we have
$$\operatorname{Li}_2(1-\sqrt 2)= -\frac{\pi^2}{6}-\frac{1}{2}\ln^2(\sqrt 2-1)+\operatorname{Li}_2\left(\frac{1}{1-\sqrt 2}\right)=\frac{\pi^2}{6}-\frac{1}{2}\ln^2(\sqrt 2-1)-\operatorname{Li}_2(-1-\sqrt 2)$$ plugging the obtained   to $(1)$ we have then $$\frac{\pi^2}{12}+\frac{1}{4}\ln^2(\sqrt 2-1)+\frac{1}{2}\left(\operatorname{Li}_2(\sqrt 2-1)+\operatorname{Li}_2(-\sqrt 2-1)\right)\cdots(2)$$ let $u= \sqrt 2-1 $ and $v=-1-\sqrt 2$ also $uv= -(\sqrt 2-1)(\sqrt 2+1)=-1$.
Using the Abel identity $$\operatorname{Li}_2(u)+\operatorname{Li}_2(v)=\operatorname{Li}_2(uv)+\operatorname{Li}_2\left(\frac{u-uv}{1-uv}\right)+
\operatorname{Li}_2\left(\frac{v-uv}{1-uv}\right)+\ln\left(\frac{1-u}{1-uv}\right)\ln\left(\frac{1-v}{1-uv}\right)$$  plugging the assigned values  of $u$ and $v$ we have $$\operatorname {Li}_(\sqrt 2-1)+\operatorname{Li_2}(-1-\sqrt 2)=-\operatorname{Li}_2(-1)+\color{red}{\operatorname{Li}_2\left(\frac{1}{\sqrt 2}\right)+\operatorname{Li}_2\left(-\frac{1}{\sqrt 2}\right)}+\ln\left(\frac{\sqrt 2-1}{\sqrt{2}}\right)\ln\left(\frac{\sqrt{2}+1}{\sqrt 2} \right) =-\frac{\pi^2}{12}+\frac{1}{2}\operatorname{Li}_2\left(\frac{1}{2}\right)-\ln^2(\sqrt {2}-1)+\frac{1}{2}\ln^2(2)=-\frac{\pi^2}{12}+\color{red}{\frac{\pi^2}{24}-\frac{1}{2}\ln^2(2)}-\ln^2(\sqrt 2-1)+\frac{1}{2}\ln^2(2)=-\frac{\pi^2}{24}-\ln^2(\sqrt 2-1)\cdots(2)$$ plugging back to $(2)$ we have $$\frac{\pi^2}{12}+\frac{1}{4}\ln^2(\sqrt 2-1)+\frac{1}{2}\left(-\frac{\pi^2}{24}-\ln^2(\sqrt 2-1)\right)=\frac{\pi^2}{16}-\frac{1}{4}\ln^2\left(\sqrt 2-1\right)$$

We use identity
$$\color{red}{\operatorname{Li}_2(z)+\operatorname{Li}_2(-z)=\frac{1}{2}\operatorname{Li}_2(z^2)}$$ and for $z=\frac{1}{\sqrt 2}$ we have $$\color{red}{\frac{1}{2}\operatorname{Li}_2\left(\frac{1}{2}\right)=\frac{1}{2}\left(\frac{\pi^2}{12}-\ln^2(2)\right)}$$
Comment: +1. Nice job. I was unable to move from $\displaystyle\mathrm{Li}_{2}$ toward the final answer. I tried different combinations of the $\displaystyle\mathrm{Li}_{2}$ identities without any success !!!.
Comment: Thank you, @Felix Marin Sir. I too got stuck to solve later dilog form of $(1)$.  :)
Answer: No need a sledgehammer to crack a nut.
\begin{align}
J&=\int_0^{\sqrt{2}-1} \frac{\text{arctanh } x}{x}\,dx\\&=-\frac{1}{2}\int_0^{\sqrt{2}-1}\frac{\ln\left(\frac{1-x}{1+x}\right)}{x}\,dx\\
&\overset{y=\frac{1-x}{1+x}}=-\int_{\sqrt{2}-1}^1 \frac{\ln y}{1-y^2}dy\\
&=\int_0^{\sqrt{2}-1} \frac{\ln y}{1-y^2}dy-\int_0^1 \frac{\ln y}{1-y^2}dy\\
&\overset{\text{IBP}}=\frac{1}{2}\left[\ln\left(\frac{1+y}{1-y}\right)\ln y\right]_0^{\sqrt{2}-1}+\frac{1}{2}\int_0^{\sqrt{2}-1} \frac{\ln\left(\frac{1-y}{1+y}\right)}{y}dy-\int_0^1 \frac{\ln y}{1-y^2}dy\\
&=-\frac{1}{2}\ln^2\left(\sqrt{2}-1\right)-J-\int_0^1 \frac{\ln y}{1-y^2}dy\\
\end{align}
And,
\begin{align}\int_0^1 \frac{\ln y}{1-y^2}dy&=\int_0^1 \frac{\ln y}{1-y}dy-\int_0^1 \frac{u\ln u}{1-u^2}du\\
&\overset{y=u^2}=\int_0^1 \frac{\ln y}{1-y}dy-\frac{1}{4}\int_0^1 \frac{\ln y}{1-y}dy\\
&=\frac{3}{4}\int_0^1 \frac{\ln y}{1-y}dy\\
&=\frac{3}{4}\times -\frac{\pi^2}{6}\\
&=-\frac{\pi^2}{8}
\end{align}
Therefore,
$\displaystyle \boxed{J=\frac{\pi^2}{16}-\frac{1}{4}\ln^2\left(\sqrt{2}-1\right)}$
NB:
I assume that $\displaystyle \int_0^1 \frac{\ln x}{1-x}dx=-\frac{\pi^2}{6}$
and, observe that if $\alpha=\sqrt{2}-1$ then $\displaystyle \dfrac{1-\alpha}{1+\alpha}=\alpha$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
S & \equiv \sum_{n = 0}^{\infty}{\pars{\root{2} - 1}^{2n + 1} \over
\pars{2n + 1}^{2}} =
\sum_{n = 1}^{\infty}{\pars{\root{2} - 1}^{n} \over
n^{2}}\,{1^{n} - \pars{-1}^{n} \over 2}
\\[5mm] & =
{1 \over 2}\sum_{n = 1}^{\infty}{\pars{\root{2} - 1}^{n} \over n^{2}} -
{1 \over 2}\sum_{n = 1}^{\infty}{\pars{1 - \root{2}}^{n} \over n^{2}}
\\[5mm] & =
{\mrm{Li}_{2}\pars{\root{2} - 1} - \mrm{Li}_{2}\pars{1 - \root{2}}
\over 2}
\approx 0.4226
\end{align}
$\ds{\mrm{Li}_{s}}$ is the Polylogarithm function.

$\color{red}{\tt\large See}$ the nice ${\tt @Naren}$ answer who already worked out the details toward the final answer

$\ds{\bbox[10px,#ffd,border:2px groove navy]{{\pi^{2} \over 16}
- {1 \over 4}\,\ln^{2}\pars{\root{2} - 1}}}$


Change the order of a sort criteria in views to a custom hierarchy

Question: I have a content type called Technique that contains a title field, a description field, and a node reference called "belt level" referencing a content type called Curriculum level. The content in Curriculum level are as follows:

Yellow belt
Orange belt
Blue belt
Brown belt
Red belt
Black belt

I have created an Integer field in the Curriculum level content type called level int. I have set "yellow" to 1, "orange" to 2, "blue" to 3, "brown" to 4, "red" to 5, and "black" to 6. Now I have a view of techniques, in which I want the sort criteria to display results based on the level int field value of the content that the node reference field (called "belt level") in the technique was referencing. The problem I am running into is that I have no way of connecting the two. If I use the belt level field to try to set the sort criteria, I can only sort it alphabetically based on the title. How can I sort it based on the level int field instead?
Answer: Add a relationship Content: belt level (or whatever your node reference field is called) to the view.
Then add a new sort, choose Content: level int (or whatever the integer field is called) and under 'relationship' choose the one you just added.
That should do it.
Comment: The reverse one is for retrieving content which references that node, rather than the content which that node references. So in this case, `Content: level int` would return the belt level's integer value, whereas `Content: level int - reverse` would return all the `Technique`s that reference the belt level.
In this case it's useless but it could be used, for example, on a page listing all the belt colors in order to display a list of techniques belonging to each belt. (Although that's a bad example as it could be done better using grouping).
Comment: I used the relationship `Content: level int` and it worked, but I noticed that right underneath it was a relationship called `Content: level int  - reverse`. What is the difference between the two?


How to use the angle bisector properties to solve this question?

Question:
Given that $TQ$ is an angle bisector, the question asks whether the length of $ST$ is equal to $SQ$ or $(SR+SQ)/2$?
I was able to use the tangent secant theorem ($ST*ST=SR*SP$). However, I couldn't make much use of the fact that $TQ$ is an angle bisector. Please guide if/when free.
Try 1: I assumed $ST$ equal to $SQ$ and found that I need to show that $RQ*SQ=SR*QP$, or that $RQ/QP=SR/SQ=TR/TP=SR/TS$, but I couldn't prove any ratio equal to any other.
Try 2: I assumed $ST$ equal to $(SR+SQ)/2$ and found that I need to show that $RQ*RQ=4*SR*QP$, which seems incorrect to me, so I concluded that $ST$ is probably equal to $SQ$ instead of the other option.
Please help if/when free.
Comment: Find a way to compare $\angle STQ$ with $\angle SQT$.
Answer: Hints:

$\angle STP = \angle SRT$
$\angle STR + \angle SRT = 180^\circ - \angle S$
$\angle STQ = \dfrac{\angle STP + \angle STR}{2}$ by the definition of angle bisector of $\angle PTR$
$\angle STQ + \angle SQT = 180^\circ - \angle S$
Answer: The point to note is that $\angle STR = \angle P$. This is in fact one of the approaches to prove tangent-secant theorem (by showing $\triangle SPT \sim \triangle STR$).

Now to show that $\angle STR = \angle P$,
$\angle TOR =  2 \angle P \ $ ($O$ is the circumcenter)
$ \implies \angle OTR = \cfrac{180^0 - 2 \angle P}{2} = 90^0 - \angle P \ $
As $\angle OTS = 90^0, \angle STR = \angle P$
That leads to $\angle STQ = \angle P + \cfrac{\angle T }{ 2}$
You also know, $\angle SQT = \angle P + \cfrac {\angle T }{ 2} $
That should lead you to the right answer.
Answer: Given $ST$ is tangent to the circle at $T$, and $TQ$ bisects $\angle PTR$.
$\angle PTQ = \angle RTQ$ ... (given angle bisector)
$\angle TPS = \angle RTS$ ... (angles in the same segment)
$\angle PTQ + \angle TPS = \angle RTQ + \angle RTS$
$\angle TQS = \angle QTS$
$TS = QS$ ... (sides of $∆STQ$ opposite equal angles)


Uncaught SyntaxError: Invalid or unexpected token ( code getting included in script file)

Question: I have written a very simple index.html file where I have included scripts and also styles
<code>    <!DOCTYPE html>
<html>

<head>
    <title>Image Gallery</title>
    <meta name="viewport" content="width=device-width">
    <link rel="icon" href="images/favicon.ico" type="image/gif" sizes="16x16">
    <link rel="stylesheet" type="text/css" href="css/mediaQuery.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>

<body>
    <script src="js/searchComponent.js"></script>
    <script src="js/service.js"></script>
</body>

</html>
</code>
searchComponent.js:
<code>   function Search() {

}
Search.prototype.fnInitialiseSearchComponent = function() {
    var header = document.createElement("div");
    header.class = 'header';
    $('body').get(0).appendChild(header);
    header.innerHTML = '<input type="text" name="search" id="search-text" placeholder="search images">';
}
</code>
When trying to run the application the unicode is getting appended from somewhere and throwing an error

Any help would be appreciated.
Comment: Well, we can't tell where the Unicode BOM is getting inserted from if you can't...
Comment: Have you tried removing everything inside the curly braces?
Comment: You already know the cause of the problem and where it is. All you need to do is delete that character. I'm not sure exactly what you're asking here
Answer: There is an extra character in your code. Remove it and try again. You can see this if you copy the code and past in jsfiddle
Answer: Try this:
Delete the entire Search function and retype it.
This will remove any hidden unicode character.
I hope it helps.

Uncaught SyntaxError: Invalid or unexpected token (â€‹ code getting included in script file)


Automorphisms of the unit disc

Question: Define $$\phi_a(z) = \frac{z-a}{1-\overline{a}z}, \qquad \rho_\alpha(z) = e^{i\alpha}z,$$ with $|a|<1$ and $\alpha \in \mathbb{R}$, so that $\phi_a \circ \rho_\alpha$ is a holomorphic automorphism of the unit disc.
There are then three questions:
(I) Find $c$ and $\gamma$ such that
$(\phi_a \circ \rho_\alpha)\circ(\phi_b \circ \rho_\beta) = \phi_c \circ \rho_\gamma$.
(II) Compute $(\phi_a \circ \rho_\alpha - \rho_\alpha \circ \phi_a)(z) $.
(III) Using knowledge of the automorphisms of the unit disc, describe the automorphisms of the upper half plane $\mathbf{H}$ as fractional linear transformations.
I mistakenly thought that part (I) would come down to just some simple algebraic manipulation, but I've gone through about a dozen pages of attempts and I just can't seem to get it in the form required to extract a suitable $c$ and $\gamma$. I'm really hoping that there's some neat trick that will make the answer just fall out.
For part (II), I've gone through it and obtained a fairly horrendous answer, but I was wondering whether there is actually a tidy answer, namely one tidier than:
$$(\phi_a \circ \rho_\alpha - \rho_\alpha \circ \phi_a)(z)=\frac{\overline{a} e^{i\alpha} z \left( e^{i 2 \alpha} z - z - a e^{i 2 \alpha}\right) + a \overline{a} z + a e^{i \alpha} - a}{1 - \overline{a}z - \overline{a}e^{i \alpha}z + (\overline{a})^2 e^{i \alpha} z^2}.$$
Finally, for (III), I looked it up and the automorphisms of the upper half plane are $$z \mapsto \frac{az+b}{cz+d}, \quad ad-bc=1.$$
However, my interpretation of the question is to map the upper half plane to the unit disc, apply an automorphism and then map it back, i.e. for any $f \in \text{Aut}(\mathbf{H})$, $f = (\xi^{-1} \circ g \circ \xi) (z)$. So what I did was define $\xi(z) = \frac{z-i}{z+1}$, $g(z) = e^{i \alpha} \frac{z-a}{1-\overline{a}z}$, and then of course $\xi^{-1}(z) = \frac{z+1}{i z - i}$. Unfortunately for me, though, when I perform this composition I can't get it in a form commensurate with what I already know to be the answer.
Comment: Both the automorphisms of the unit disc and the automorphisms of the upper half plane are groups (under composition) that are isomorphic to groups of matrices (under matrix multiplication). So, when computing long compositions of transformations, it is the same to simply multiply the corresponding matrices. I think this may help with part (I).
Answer: Concerning (I) and (II), I second the advice given by John Adamski: it is easier to multiply matrices of the form $\begin{pmatrix} a & b \\c & d \end{pmatrix}$ then to compose maps of the form $\dfrac{az+b}{cz+d}$. The result is the same, see   here.
Concerning (II), I am surprised that someone wanted to know $\phi_a \circ \rho_\alpha - \rho_\alpha \circ \phi_a$. Subtracting two automorphisms of the unit disk does not look like a natural operation to me. Maybe they meant the multiplicative commutator,  $\phi_a \circ \rho_\alpha \circ (\rho_\alpha \circ \phi_a)^{-1}$?

So what I did was define $\xi(z)=\dfrac{z−i}{z+1}$

A typo here: $\xi(z)=\dfrac{z−i}{z+i}$ would be correct. Not sure if this is where the problem was. Anyway, as in (III) it is better to work with matrices and compute
$$\begin{pmatrix} 1 & -i \\1 & i \end{pmatrix}^{-1} \begin{pmatrix} a & b \\c & d \end{pmatrix}\begin{pmatrix} 1 & -i \\1 & i \end{pmatrix} $$

Automorphisms of the unit disc


Discontinuous maps taking compacts to compacts

Question: It's commonly known that in general topology, a continuous map $f$ from a topological space $(X, \tau)$ to another topological space $(Y, \tau')$ will send every compact set to another compact set. Moreover, I'm aware that the converse does not hold, as so long as $\# Y \geq 2$, we can pick some set $S \subseteq X$ and define
$$f(x) = \begin{cases}
y_{1} & x \in S \\
y_{2} & x \in S^{\complement} .
\end{cases}$$
This would send not only compact sets to compact sets, but all sets to compact sets because $f(X)$ is finite, and thus compact (as are all its subsets). But this map could easily not be continuous.
NOTE: Understand for the rest of this post that $f: X \to Y$ is surjective.
My question is if there are more interesting counter-examples. Say $X = \mathbb{R}$ with the Euclidean metric; then what would be an example of such a discontinuous map $f: X \to Y$ where $Y = \mathbb{N}$ (with the usual metric), or $Y = \mathbb{Q}$ (again with the usual topology). What about $\mathbb{R}$, or $\mathbb{R} \setminus \mathbb{Q}$? Is there perhaps a limit on how large in cardinality $Y$ can be (with respect to $X$)? I'm curious to see less trivial counterexamples to the converse. Thanks!
EDIT: Many of the examples I'm getting still rely on compact sets having finite image. So a problem I might find more interesting: Can I construct a discontinuous counterexample where $f$ is also injective?
Comment: Do you want a function that maps compact sets into non-compact sets?
Comment: No: Compact to compact.
Answer: You could define $f:\mathbb R\rightarrow\mathbb Z$ such that $f(x)=\lfloor x\rfloor$. Since every compact subset of the reals has only a finite number of integers in it, this sends compact sets to compact sets.
You could define $f:\mathbb R\rightarrow\mathbb Q$ be letting $f(x)$ be the closest member of the (compact) sequence $\{1/n\}\cup\{0\}$ (choose the larger element if there are two points of the sequence equidistant from $x$). This works because compact sets in the reals are closed.
You could define $f:\mathbb R\rightarrow\mathbb J$ where $J$ is the cantor set in a similar way: $f(x)$ is the closest member of the cantor set to $x$. This works again because the cantor set is compact.
Comment: For $f:\mathbb R\to\mathbb Q$, you should project onto $\{ 0 \} \cup \{ 1/n \mid n\in\mathbb N \}$. Otherwise the set is not closed and not compact.
Comment: Of course, thank you.
Comment: Just miss it. Projections are continuous!
Answer: Consider the identity map $i:\mathbb{R} \rightarrow \mathbb{R}'$, where the topology on the first $\mathbb{R}$ is the usual, and at $\mathbb{R}'$ you add to the usual topology the set $\{0\}$ with the necessary unions to make this family a topology. This is a bijection from a Haussdorf space to another, that carries every compact space to compact space (and moreover, inverse images of compact sets still being compact sets), and $f$ is not a continuous function, since $f^{-1}(\{0\})$ is not open in $\mathbb{R}$ (but $\{0\}$ is in $\mathbb{R}'$).
A fun fact: the topology at $\mathbb{R}'$ doesn't have the Heine-Borel property: for example the set $(0,1]$ is closed and limited, but it's not compact.


Coding standards for long strings?

Question: I've been looking for some official guidelines on how to format long strings in module code, but the closest thing I've found is an ambiguous section on indenting long SQL queries which suggests any of the following styles:
$text = '
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
';

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula'
. 'odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer'
. 'hendrerit varius felis id dignissim.'
;

$text = <<<TEXT
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
TEXT;

The Drupal Coding Standards talk about how to use the concatenation assignment operator:
$string .= 'Foo';
$string .= $bar;
$string .= baz();

but they don't actually state whether single long strings should be broken up that way.
To add further confusion, the Coder module handles long strings differently again in its "good.php" test file:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ' .
        'ligula odio, hendrerit consectetur porta vitae, sollicitudin sit ' .
        'amet eros. Integer hendrerit varius felis id dignissim.';

Personally, I've just been doing it like this until now:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula
        odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros.
        Integer hendrerit varius felis id dignissim.';

However, I'd like to start doing it the "right" way (if there is one). Does anyone have a definitive answer?
Comment: If it's not already in the coding standards, then there's no definitive answer for the "right" way. That's why you're seeing seeing people's personal preferences, and advice that says "any of these are fine". This one's really more about common sense and making sure long strings are readable than having anything standardised. Personally I prefer HEREDOC if the SQL goes over 80 chars, but that's kind of the point - there's no right or wrong, go with you gut
Comment: @Clive Fair enough, I see your point. My gut would be to follow the way the Coder module does it, but then I go and read something like [this](https://www.drupal.org/node/2039579#comment-7743143) which says we can't do it that way for a string being passed through t() and implies the string should remain on one long unreadable line of code! The alternative then is to pointlessly define a string variable and pass it to t() via a placeholder just to make our code readable, which seems rather silly.
Answer: Drupal does not restrict the usage of long strings in code. It is advisable to concatenate each line ($output .= '...';) for a readable code, but as you can see in Drupal code, long strings are not broken up, especially when used with t():
function field_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.field':
      $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('The Field module allows custom data fields to be defined for entity types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the Field UI module user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the online documentation for the Field module.', array(':field-ui-help' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', ':field' => 'https://www.drupal.org/documentation/modules/field')). '
';
      $output .= '
' . t('Terminology') . '
';
      $output .= '
';
      $output .= '
' . t('Entities and entity types') . '
';
      $output .= '
' . t('The website\'s content and configuration is managed using entities, which are grouped into entity types. Content entity types are the entity types for site content (such as the main site content, comments, custom blocks, taxonomy terms, and user accounts). Configuration entity types are used to store configuration information for your site, such as individual views in the Views module, and settings for your main site content types.') . '
';
      $output .= '
' . t('Entity sub-types') . '
';
      $output .= '
' . t('Some content entity types are further grouped into sub-types (for example, you could have article and page content types within the main site content entity type, and tag and category vocabularies within the taxonomy term entity type); other entity types, such as user accounts, do not have sub-types. Programmers use the term bundle for entity sub-types.') . '
';
      $output .= '
' . t('Fields and field types') . '
';
      $output .= '
' . t('Content entity types and sub-types store most of their text, file, and other information in fields. Fields are grouped by field type; field types define what type of data can be stored in that field, such as text, images, or taxonomy term references.') . '
';

I would stick with this drupal usage, this is the best compromise for usage and good readability. Your first examples looks good, but adds extra line feeds. The second example is not good to read and the third is often used in scripts, but not very common in php code.
Comment: This is helpful. My question actually stems from the problem of what to do with a long string in a t() call, so seeing from your example that a core module just leaves it all on one line, I'm satisfied enough to accept this answer. I guess when we're not limited by the use of t() it just comes down to personal preference, as Clive commented above.
Comment: Clive is right about that, if you don't like the concatenating of drupal, heredoc is the best solution, because this does not add unwanted whitespace. But it does not work well with indentation. I think this is the reason, that it is used more in scripts and not so often in well structured code.

Coding standards for long strings?


Correct way to hide/suppress the sustainOff symbol?

Question: In Lilypond, I'm engraving a chunk of piano music which uses the Ped. symbol, but does not use the corresponding * to end the pedalling.
Here's a chunk of code which gets the right visual result:
\version "2.18.2"
upper = \relative c'' {
  \clef treble
  a4 b c d
}
lower = \relative c {
  \clef bass
  a2 c
}
pedal = {
 s4\sustainOn s s s\sustainOff
}
\score {
  \new PianoStaff <<
    \new Staff = "upper" \upper
    \new Staff = "lower" \lower
    \new Dynamics = "pedal" \with {
      pedalSustainStrings = #'("Ped." "*Ped." "")
    } \pedal
  >>
  \layout { }
}

Note the #'("Ped." "*Ped." "") bit.
But that also produces a warning:
warning: SustainPedal has empty extent and non-empty stencil.

I've got 7 pages of music with pedaling every 2-3 measures. I'm not going to make it to the end with that many warnings popping out every time. Is there some better/more correct way of suppressing that symbol?
Comment: Why can't you just ignore the warnings? They are just *warnings*, after all: they indicate that something could be wrong, but here it is clearly your intent. If you fear that you will be flooded with the warnings, run Lilypond with the command switch `-l ERROR` .
Comment: A handful wouldn't be a problem, but dozens will make it harder to scroll around in the Frescobaldi log window, which would make my life a bit harder while working on this piece. Plus Lilypond is close enough to programming that my aversion to compiler warnings kicks in. :)
Answer: If you want the to release the sustain pedal, but to not display a symbol for it:
Instead of typing \sustainOff, use \hide\sustainOff.
NB: you won't need that \with ... statement
EDIT
Using \omit is probably better than \hide.
This is because \omit doesn't print anything at all, whereas \hide effectively prints an invisible symbol and consequently makes spacing alterations that would be necessary as if the symbol were visible.
Answer: I poked at it some more, and did some wild guessing in conjunction with my Scheme knowledge, and I tried:
pedalSustainStrings = #'("Ped." "*Ped." #f)

That is, a #f for "false" instead of the zero-length string "". That seems to still produce the visual result that I want, without any warnings being emitted. I've got no idea if this is expected behavior from Lilypond though.
Answer: This is not an answer to the OP, but a reply to a comment that's too big to post there.
If you are in a situation when you need to suppress several warnings that you know aren't important but that obfuscate other warnings and errors, you can use this function.
% ly:expect-warning only works to suppress once.  This function allows
% you to specify the number of times a warning appears.
#(define ly:expect-warning-times (lambda args
   (for-each (lambda _ (apply ly:expect-warning (cdr args)))
         (iota (car args)))))

#(ly:expect-warning-times 33 "omitting tuplet bracket")


Determine if mobile user scanned QR code or typed URL in browser?

Question: Is it possible to determine with HTML 5 or javascript (or via another method) whether a user entered a URL into a mobile browser by typing or scanned a QR code which then opened the URL in a browser?
Answer: No, this isn't possible. Depending on whether you have control over the content of the QR-codes, you can use a deeplink that redirects to the original page (e.g. http://www.yoursite.com/qrcoderedirecting to http://www.yoursite.com) and thereby "track" the usage of the QR-code.
Comment: That or [Google Analytics URL parameters](https://support.google.com/analytics/answer/1033867?hl=en)  like `utm_medium=qr`