My try of the Birthday Paradox

Question: I have seen the solution of the paradox on Wikipedia, but before that I tried it out myself. But I got my answer wrong with my approach.
To calculate the probability of no two people in a group of 23 having the same birthday, I divided {the number of ways 23 different days in 365 days can be taken} by {the number of ways 22,21,20,...,2,1 different days can be taken multiplying with the number of ways 23 people can have 22,21,20,...,2,1  birthdays respectively}
I think that would make it a bit harder to understand what I wanted to convey.
And, I find using MathJax a bit tough as I'm new to this. So the link provides the image of what I tried on desmos:My expression of what I tried
Comment: Even if I went by your logic, you select $23$ days out of $365$ in numerator but where are you assigning these $23$ days to $23$ people? There are $23!$ ways to do that. I do not understand your denominator at all. Is it not possible that all $23$ have the same birthday? Denominator will have all possible birthday combinations for $23$ people.
Comment: OK I see what you are doing in denominator but it is wrong. Please check $i = 23$ as an example. Why will you choose $23$ birthdays and find only $23$ ways to assign to $23$ people? Isn't it $23!$ ways to assign?
Comment: I know it is wrong. I just couldn't find where I was wrong. Thank you. I get my mistake
Comment: You are welcome. For every number of birthday you choose from $365$, it is going to be a nightmare to find number of ways in which they can be assigned to $23$ people. Take example of $5$ birthdays. Now you have to make sure all $5$ birthdays are assigned  (otherwise it will have cases when you choose $4$ birthdays too) to people and it will require some serious P.I.E. We need to do this for $23$ birthdays :(
Comment: Yeah I got it when you first mentioned that. Thanks again for the effort to clarify it.
Answer: You have written $$1-\dfrac{{365\choose 23}}{\sum\limits_{i=1}^{23} i^{23-i}{365 \choose i}}$$ presumably as the probability that there are at least two people sharing a birthday, with $i$ iterating over the possible numbers of distinct birthdays.
Both the numerator and the denominator raise issues.  The numerator is a combination count but if you are counting equally likely events then you want permutations: if there are two people, it is twice as likely that one has a birthday on January 1 and another on January 2 compared with both having birthdays on January 1. So you should have $\frac{365!}{(365-23)!}$ as the numerator.
The other problem is the denominator.  It gives the correct number when $i=1$ of $365$ but not for other $i$.  For example when $i=2$ it gives $2^{22} {365 \choose 2}$ when the number of ways of allocating $23$ people between two days with both used  is $(2^{23}-2){365 \choose 2}$, almost twice as high.  But you do not need a sum over $i$ anyway: the number of equally likely ways of allocating $23$ birthdays (possibly duplicated) over $365$ days is $365^{23}$.
Putting these together means the probability of at least two people out of $23$ sharing a birthday  is $$1-\dfrac{\frac{365!}{(365-23)!}}{365^{23}} \approx 0.5073$$ i.e. just over a half.

My try of the Birthday Paradox


"Since $x$ is near-gaussian, its PDF can be written as..."

Question: Short question: Why is this true??
Long question:
Very simply, I am trying to figure out what justifies this first equation. The author of the book I am reading, (context here if you want it, but not necessary), claims the following:

Due to the assumption of near-gaussianity, we can write:
$$ p_0(\xi) = A  \; \phi(\xi) \; exp( a_{n+1}\xi + (a_{n+2} +
 \frac{1}{2})\xi^2 + \sum_{i=1}^{n} a_i G_i(\xi)) $$

Where $p_0(\xi)$ is the PDF of your observed data that has maximum entropy, given that you had only observed a series of expectations, (simple numbers) $c_i, i = 1 ... n$, where $c_i = \mathbb{E}\{G_i(\xi)\}$, and $\phi(\xi)$ is the PDF of a standardized gaussian variable, that is, 0 mean, and unit variance.
Where all this is going is that he uses the above equation as a starting point for making the PDF, $p_0(\xi)$ simpler, and I get how he does it, but I do not get how he justifies the above equation, ie, the starting point.
I have tried to keep it brief to as not to obfuscate anyone, but if you want additional details please let me know in the comments. Thanks!
Answer: (Note: I've changed your $\xi$ to $x$.)
For a random variable $X$ with density $p$, if you have constraints
$$
  \int G_i(x)\,p(x)\,dx=c_i \, ,
$$
for $i=1,\dots,n$, the maximum entropy density is
$$
  p_0(x)=A\exp\left(\sum_{i=1}^n a_iG_i(x)\right) \, ,
$$
where the $a_i$'s are determined from the $c_i$'s, and $A$ is a normalization constant.
In this context, the Gaussian approximation ("near-gaussianity") means two things:
1) You accept to introduce two new constraints: the mean of $X$ is $0$ and the variance is $1$ (say);
2) The corresponding $a_{n+2}$ (see bellow) is much bigger than the other $a_i$'s.
These additional constraints are represented as
$$
  G_{n+1}(x)=x \, , \qquad c_{n+1}=0 \, ,
$$
$$
  G_{n+2}(x)=x^2 \, , \qquad c_{n+2}=1 \, ,
$$
yielding
$$
  p_0(x)=A\exp\left(a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, ,
$$
which can be rewritten as (just "add zero" to the exponent)
$$
  p_0(x)=A\exp\left(\frac{x^2}{2} - \frac{x^2}{2} + a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, ,
$$
leading to what you want:
$$
  p_0(x)=A'\,\phi(x)\exp\left(a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, ;
$$
ready to be Taylor expanded (using the second condition of the Gaussian approximation).
Doing the approximation like a Physicist (which means that we don't care about the order of the error term), using $\exp(t)\approx 1+t$, we have the approximate density
$$
  p_0(x) \approx A'\,\phi(x)\left(1+a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, .
$$
To finish, we have to determine $A'$ and the values of the $a_i$'s. This is done imposing the conditions
$$
  \int p_0(x)\,dx=1 \, , \qquad \int x \,p_0(x)\,dx=0 \, , \qquad \int x^2 \,p_0(x)\,dx=1
$$
$$
\int G_i(x)\, p_0(x)\,dx=c_i \, , \quad i=1,\dots,n \, ,
$$
to obtain a system of equations, whose solution gives $A'$ and the $a_i$'s.
Without imposing additional conditions on the $G_i$'s, I don't believe that there is a simple solution in closed form.
P.S. Mohammad clarified during a chat that with additional orthogonality conditions for the $G_i$'s we can solve the system.
Comment: Zen, thanks very much. I (somewhat) understand now. What is not clear to me though, is when you say _"In this context, the Gaussian approximation ("near-gaussianity") means that you accept to introduce two new constraints: that the mean of X is 0 and the variance is (say) 1."_ , I dont understand, why for something to be 'near gaussian', means for it to have $\mu=0$ and $\sigma^2=1$. What if it was just another r.v. that happened to have those same values?
Comment: Hi Mohammad. I've added more information to the answer. To get the former expression of $p_0(x)$ you use only what I've called the first condition of the Gaussian approximation. You will use the second condition when you do the Taylor expansion of this $p_0(x)$. I hope this helps.
Comment: Would you mind posting as a comment the final expression for the $p_0(x)$ after you do the remaining computations? Thanks.
Comment: yes, he is saying that the final expression is: $p_0(z) \approx \phi(z) (1 + \sum_{i=1}^{N} c_i F_i(z))$
Comment: I think there is a typo in the last equation?... $a_{n+1}x$ is happening twice?...
Comment: Typo corrected!
Comment: Thank you. I guess then the question becomes, why are we allowed to make the assumption that anything can be near gaussian?
Comment: Consider $\textbf{all}$ random variables with support on the real line that have $0$ mean and unity variance. We have seen that among those random variables, the one with density $p_0(x)=A\exp(a_2x^2+a_1x)$ has largest entropy, and this is clearly a Gaussian density (complete the square on the exponent if you want).
Comment: That is why the Gaussian approximation makes sense: if you are looking for the maximum entropy density in a situation where you have additional constraints, it is reasonable to suppose that the maximum entropy density will be "close" to the Gaussian one described above. Does that make sense to you?
Comment: Yes... I see it... I think.
Comment: I don't see how can you get your "final expression" in your comment above without some additional conditions imposed on the $G_i$'s. I can't...
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4673/discussion-between-mohammad-and-zen)


Determine CDF and PDF from quantiles

Question: I would like to determine CDF and PDF from quantiles that I have determined via quantile regression.
I have read here in the forum (Find the PDF from quantiles) that it is possible to interpolate this via the integral of a B-spline The PDF should then be determined via a normal evaluation.
Unfortunately I did not understand why I have to use the integral of the B-spline, how can I ensure that the CDF is monotonically increasing and how I then get to the derivative (the PDF)? Can someone help me please?
This is how it currently looks for me:
import scipy.interpolate
import numpy as np

x = np.array([ 38.45442808,  45.12051933,  46.85565437,  47.84576924,
        49.50084204,  50.09833301,  51.3717386 ,  54.85307741,
        59.91982266,  63.11786854,  66.90037244,  67.84446378,
        72.96120777,  73.92993279,  81.63075081,  85.42178836,
        90.70554533,  91.2393176 , 110.03872988])

y = np.array([0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95])

t,c,k = scipy.interpolate.splrep(x, y)
spline = scipy.interpolate.BSpline(t, c, k, extrapolate=False)
d_spline = spline_.derivative()

N = 100
xmin, xmax = x.min(), x.max()
xx = np.linspace(xmin, xmax, N)

fig, ax = plt.subplots(2,1, figsize =(12, 8))

ax[0].plot(x, y, 'bo', label='Original points')
ax[0].plot(xx, spline(xx), 'r', label='BSpline')

ax[1].plot(xx, d_spline(xx), 'c', label='BSpline')

My approach doesn't really work well unfortunately and I can't find any numerical examples to help me. I am grateful for all comments and remarks!
Thank you!
Comment: Welcome to CV. The link includes the crucial proviso "with the condition that all B-spline coefficients are nonnegative."  Without suggesting a B-spline is a good solution (I think it's not in general), you can find how to create such splines by searching our site for [monotonic spline](https://stats.stackexchange.com/search?q=monotonic+spline).
Comment: "I have read here in the forum that it is possible to interpolate this via the integral of a B-spline The PDF should then be determined via a normal evaluation." Can you provide a link?
Comment: Yes sorry, I edited a link.
Comment: Thank you! I think i find a solution I think I found through your link to a scipy library. https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.pchip_interpolate.html
Answer: Thank you for pointing this out. I think I have been able to solve the problem for me.
from scipy.interpolate import pchip_interpolate

import numpy as np

x = np.array([ 38.45442808,  45.12051933,  46.85565437,  47.84576924,
        49.50084204,  50.09833301,  51.3717386 ,  54.85307741,
        59.91982266,  63.11786854,  66.90037244,  67.84446378,
        72.96120777,  73.92993279,  81.63075081,  85.42178836,
        90.70554533,  91.2393176 , 110.03872988])

y = np.array([0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95])

x_observed = x
y_observed = y
x = np.linspace(min(x_observed), max(x_observed), num=100)
y = pchip_interpolate(x_observed, y_observed, x)
y_d = pchip_interpolate(x_observed, y_observed, x, der=1)

fig, ax = plt.subplots(1,2, figsize=(12,6))
ax[0].plot(x_observed, y_observed, "o", label="observation")
ax[0].plot(x, y, label="pchip interpolation")
ax[1].plot(x, y_d, label="pchip interpolation derivative")
fig.legend()
plt.show()

Comment: Do you trust your own pdf?
Comment: Continuing the comment by @Nick, that's scarcely a plausible estimate of the pdf.  It arises because *you are not accounting for the estimation errors in the quantiles.*  Any reasonable procedure would do so and as a result would definitely not exhibit such extreme spikes -- it would surely result in a far smoother estimated density.
Comment: @whuber: If I understood it correctly from the comments, then I would have to account for the estimation errors of the quantiles. Unfortunately, I cannot find a procedure for this. Can you help me with this? Are there any approaches that take this into account? Thank you very much.
Comment: See https://stats.stackexchange.com/a/34894/919 or https://stats.stackexchange.com/a/68238/919 for explanations and examples.

Determine CDF and PDF from quantiles


Ruby conditional map and replace

Question: I'm trying to conditionally map an array I have:
Array that looks like [ "a", "b", "c" ]
I want to map it inline (using map!) to change anything that matches /b/ and change it to "bb". This doesn't seem to work though, it doesn't seem to be changing the array.
I want it to look like this [ "a", "bb", "c" ]
define the array:
irb(main):001:0> a = [ "a", "b", "c" ]
=> ["a", "b", "c"]

Try with a select chained to a map!, and it shows the changed value for the one element, and it didn't change the original array.
irb(main):002:0> a.select { |e| e =~ /b/ }.map! { |e| e = "bb" }
=> ["bb"]
irb(main):003:0> p a.inspect
"[\"a\", \"b\", \"c\"]"

So I tried doing the same thing, but assigning it to a new array, this only creates an array with any changed elements - not what I want
irb(main):004:0> cc = a.select { |e| e =~ /b/ }.map! { |e| e = "bb" }
=> ["bb"]
irb(main):005:0> p cc.inspect
"[\"bb\"]"
=> nil

What am I missing here? I'm missing some Ruby fundamental knowledge here I think.
Comment: I find it annoying when people down vote a question without putting a comment explaining what the problem is. People would learn from the comment.
Answer: You call select on a, which returns new instance of Array, on which in the next step you call map!, modifying this new instance (not the original one). To achieve what you want, you can do:
a.map! { |e| e =~ /b/ ? 'bb' : e }

Answer: The correct logic looks like this:
results = a.map { |e| if e =~ /b/ then "bb" else e end }

The same logic using the ternary operator:
results = a.map { |e| e =~ /b/ ? "bb" : e }

If you really need to do the replace in-place then use ! like this:
a.map! { |e| e =~ /b/ ? "bb" : e }

Here's why your code in your post isn't working the way you expect:

Your select is returning a new array, then map! is modifying the new array. That's one issue.
More important, the select method doesn't work the way you're using it. The select method returns only the items that match.

In general, don't use ! for map unless you have a really good reason, and you understand it better, because Ruby ! methods that modify objects in place tend to be a bit harder to debug and test reliably.
Comment: @awojo it's ternary operator.
Comment: If I knew a ton about ruby, I wouldn't have asked the question. Is stackoverflow not about learning and sharing knowledge? ...Thanks for the tip though, Marek Lipka.

Ruby conditional map and replace


Embed media in Ckeditor field for drupal 7

Question: I'm looking for a plugin for the latest version of CKeditor (3.6.3) so that I can add youtube videos (and other embedded media) to a text area that uses ckeditor.
I found several proposed plugins but most of them are not on the drupal.org site or are simply very old and do not seem to work with drupal 7.
There are a lot of questions on this subject but none that are recent or deal with drupal 7.
I know I can just turn off the rich editor and then embed the code in full html mode but I'd like something simpler for my client. Does such a module exist?
I've also found the media module (that is listed on drupal.org - http://drupal.org/project/media_youtube) but I don't think it integrates with CKeditor.
To clarify I'm looking for something like this: http://www.fluidbyte.net/embed-youtube-vimeo-etc-into-ckeditor but that works with drupal 7. (This one doesn't seem to work?).
EDIT: I am using the standalone CKEditor module
Comment: A combination of Media, Media Youtube and [`Media Browser Plus`](http://drupal.org/project/media_browser_plus) will provide that functionality pretty much out-of-the-box (with a small amount of configuration)
Comment: Thanks, I know that by using the media module I could do it but I would like to integrate it in the CKeditor module. So that my user can place it somewhere (anywhere) in a blog post. Adding an extra field would mean that I would have to style it to appear in a fixed position.
Comment: The media module has support for WYSIWYG, so as long as you're using that module (and not the standalone CKEditor module) it will do exactly what you've asked for
Comment: I am using the standalone CKEditor module, but perhaps it is worth giving the WYSIWYG module a try instead. Thanks
Answer: The standalone version of ckeditor module comes with a plugin called media embed. Ensure you have:

Enabled the media embed plugin for Ckeditor
Added the media embed input filter to a text format that your uses have access to (and is not filtered or tag limited in anyway)
Added the media embed button to the toolbar for the above text format

And that is it. In order to embed a youtube video (or anything for that matter), you get the  embed code from youtube, and paste it into the media embed dialog popup.
Comment: This works only with Ckeditor version 3. http://ckeditor.com/release/ckeditor-365. See more instructions here https://www.drupal.org/node/1882314
Answer: There is different ways to go about this. The easiest way for you would be using Ckeditor youtube.
You could also use the  solution, such as with the following markup.
`

You can use the Media module; see Post YouTube Videos with Media + Media: YouTube.
Comment: I already tried the CKeditor plugin and, being about a year and a half old, it doesn't seem to work with the latest version. The iframe solution could be a good option and one I overlooked so I'll keep that as my back-up. Thanks ;-)
Answer: In Drupal 6 and 7 you can use this module: https://www.drupal.org/project/wysiwyg_mediaembed which works with the media embed plugin, CKEditor and Wysiwyg module. (I am a co-maintainer and it seems to be working reasonably well for people)


Forçar download de texto em formato aceito pelo MSWord com PHP?

Question: Gostaria de saber como forçar o download de um arquivo, com alguma extensão aceita pelo Microsoft Word, através da função header.
Pesquisei algumas vezes, testei os MIME types que encontrei, como os que se encontram nesta lista da Microsoft, mas não obtive sucesso.
Este código funciona para forçar o download de um arquivo com extensão .txt, mas se tentar com .doc, ocorrerá um erro ao tentar abrir, pelo word, o arquivo baixado.
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-disposition: attachment; filename="' . uniqid(time()) . '.txt";');
header('Content-Length: '. filesize($filename));
readfile($filename);

Exemplo completo:
<?php

$file = tmpfile();

$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent a vehicula mi, eu lacinia sem. Donec pellentesque egestas pulvinar. Donec ultricies risus vitae tellus tincidunt sagittis sed a odio. Curabitur vitae egestas metus, sit amet consectetur nisi. In pellentesque, mauris consequat ornare ullamcorper, mi nunc condimentum leo, ac feugiat lectus metus in nulla. Nulla ac vestibulum lacus. Donec sit amet felis pulvinar, vestibulum metus at, mattis lorem. Duis efficitur, velit vitae ullamcorper blandit, erat quam vehicula risus, dignissim volutpat nulla orci quis augue. Donec nisi velit, sagittis sed consectetur vitae, ornare eget turpis. Vivamus tincidunt, ligula sit amet aliquet iaculis, sapien risus rutrum purus, a sollicitudin nunc lacus sit amet purus. Pellentesque lacinia, tortor ut rhoncus molestie, eros nisl venenatis turpis, eget elementum quam ligula eget eros. Phasellus aliquam neque blandit scelerisque mattis. Maecenas purus erat, sodales at tincidunt eu, facilisis non velit. Quisque blandit arcu non dolor efficitur hendrerit.

Morbi ultricies arcu tempor, convallis sem non, faucibus risus. Praesent ut nunc sit amet quam placerat iaculis non at nibh. Maecenas imperdiet aliquam risus, ut sodales justo consequat id. Donec sollicitudin maximus cursus. Sed placerat, mauris a ornare hendrerit, ipsum enim ornare augue, non efficitur magna nulla auctor mi. Praesent sodales sed erat non luctus. Aliquam erat volutpat. Duis eget semper augue. Suspendisse pellentesque condimentum vehicula. Aliquam tempor arcu non leo vehicula, vitae ornare tortor sagittis. Vivamus posuere nibh massa, et dapibus nisl viverra quis. Phasellus tincidunt tellus id vehicula varius. Cras efficitur libero vitae accumsan tincidunt.

Nam molestie enim non nulla imperdiet interdum. Ut eget tortor venenatis, lobortis est a, consequat leo. Quisque consequat pellentesque velit eget vulputate. Integer pharetra felis sed hendrerit tristique. Donec tempus gravida diam, non maximus metus semper ac. Nulla ultrices egestas turpis. Fusce at dui ligula. Nam eget ligula sit amet quam tincidunt mollis. Mauris vitae dapibus lectus. Vestibulum id purus lacus. Proin tincidunt felis ac suscipit tristique.

Maecenas ullamcorper quis risus nec suscipit. Nam sodales tincidunt laoreet. Mauris interdum auctor massa, sit amet blandit nulla ullamcorper hendrerit. Curabitur ante libero, feugiat id iaculis quis, vestibulum ut eros. Morbi eleifend leo vitae mi laoreet eleifend. Ut vel accumsan mi. Cras sit amet bibendum tortor, nec vestibulum risus. Vestibulum suscipit rutrum turpis eu lacinia. Mauris porttitor maximus eros. Nullam augue arcu, sodales et porttitor eget, hendrerit eu odio. Vestibulum suscipit nisi sed commodo posuere. Proin volutpat nunc non neque accumsan posuere. Duis consequat, leo nec dictum sodales, neque leo congue nisl, eget consequat odio dolor eget nunc. Proin accumsan enim nisi.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam egestas hendrerit nisi, tristique pretium velit condimentum vel. Etiam sit amet purus nec risus finibus finibus auctor in metus. Integer nec risus mauris. Fusce aliquet egestas purus sed venenatis. Fusce non finibus sapien. Integer eu augue ligula. Sed urna sapien, hendrerit et pharetra sed, posuere eu elit. Sed a nibh id ipsum scelerisque iaculis. Vestibulum convallis sollicitudin erat ut blandit. Integer scelerisque odio vel nisl ullamcorper, vel feugiat nibh pretium. Sed et lectus vulputate, feugiat lacus vitae, lobortis sem.";

fwrite($file, $content);
fseek($file, 0);

$metadata = stream_get_meta_data($file);
$filename = $metadata["uri"];

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-disposition: attachment; filename="'. uniqid(time()) . '.docx";');
header('Content-Length: '. filesize($filename));
readfile($filename);

Comment: Não sei se entendi... Vc quer transformar um aquivo `.php` em `.doc` pra depois disponibilizar pra download? Se for isso tem o [PHPWord](https://github.com/PHPOffice/PHPWord)...
Comment: Então, mas explique melhor como quer fazer isso. Função específica no PHP acho que não existe, tenho quase certeza que vc vai precisar do PHPWord mesmo... dá uma olhada.
Comment: @gustavox rsrsrs pois é... vou deixar em aberto aqui, ver se surgem mais sugestões
Comment: @gustavox estranho que o teu segundo comentario diz a resposta (vc vai precisar do PHPWord mesmo), agora que eu vi, nao entendi porque nao adicionou isto a resposta. O exemplo do autor nao vai funciona justamente por isto, ele esta tentando enviar um texto simples pro output e forcar mas com a extensao `.doc`, no entanto softwares como MSword e LibreOffice nao conseguem ler isto. O arquivo docx por exemplo 'e um arquivo zip que contem varios arquivos, dentre eles o principal e um xml (office open xml https://en.wikipedia.org/wiki/Office_Open_XML_file_formats) :)
Comment: Obrigado @gustavox :)
Comment: @gustavox Não, quero pegar um texto qualquer, pode ser vindo do banco de dados ou não, e exportá-lo em .doc
Comment: With PHPWord, you can create DOCX, ODT, or RTF documents dynamically using your PHP 5.3+ scripts. Below are some of the things that you can do with PHPWord library: [...] **Create header and footer for each sections**
Comment: @gustavox Ok, irei dar uma olhada nessa classe, mas "ouvi dizer" que dava pra forçar o download da mesma forma q um arquivo txt, não sei...
Comment: Tomara que tenha mesmo, seria útil pra mim tbm... :-)
Comment: nah, esqueça tudo o que eu disse antes... veja [isso](http://stackoverflow.com/questions/11487365/http-header-for-downloading-microsoft-word-and-excel-files).
Comment: @ThomersonRoncally Sempre adicione um exemplo funcional do problema, assim facilita as pessoas detectarem a falha, recomendo que leia: http://pt.stackoverflow.com/help/mcve, removi a parte "se precisarem do codigo comentem" pois sempre coloque o codigo, nao precisa ser completo, ele so precisa "funcionar" e precisa reproduzir o problema (ele deve ser Mínimo, Completo e Verificável) --- Espero que a resposta lhe ajude :) Ate mais.
Comment: Sim @GuilhermeNascimento, eu já tinha olhado esta biblioteca, é muito boa, mas na época achei meio complicada pra mim... e como o ap falou que era possível, achei que seria muito mais simples usar só o header, já que uma parte do que preciso é só texto mesmo (o PHPWord vai ser melhor se eu conseguir porque ele rendriza todo html né..)... Mas enfim,  então não tem jeito mesmo né, porque no Open Office ele abre, mas ele tá abrindo em asc II né, e o word  do windows não abre assim... saquei. Valeu por enquanto! Abraços. +1
Comment: Em tempo: Eu consegui instalar certinho, e já gero os exemplos que vem na pasta, mas ainda não consegui fazer funcionar com o código gerado dinamicamente do meu formulário, mas acho que isto já seria outra pergunta... Valeu.
Answer: O seu problema não é com a extensão do arquivo ou com o header passado, o problema é que você está tentando forçar softwares como o Microsoft Word a ler um arquivo simples de texto ASCII como se fosse um .doc.
Arquivos .docx e .docm são arquivos zipados que usam o Office Open XML, os quais contêm os arquivos (por exemplo) [Content_Types].xml, docProps/core.xml, word/document.xml e a pasta _rels que "formam" o arquivo do Word.
Já o arquivo .doc é um documento binário que segue um padrão próprio, e existem variações para cada versão do Word, de como ele gera tal documento e a extensão também já foi usada por outros softwares e possuíam formato diferente.
Portanto nem .doc e nem .docx são arquivos de texto comuns.

Nota: Programas como Abiword e OpenOffice (como citado pelo @gustavox) funcionaram pois eles próprios tentam recodificar os arquivos de texto puro para arquivos do tipo doc ou odt e por isto foi possível visualizar.

Se deseja criar um arquivo .docx de verdade com PHP sera necessário uma biblioteca. Uma biblioteca que pode lhe ser útil e o PHPword.
Requisitos pra usar o PHPWord

PHP 5.3+
Extensão Zip
XML Parser
Extensão XMLWriter (usado pra escrever documentos DOCX e ODT)
Extensão GD (opcional, pra quando adiciona imagens ao documento)
Extensão XSL (opcional, pra aplicar estilos com XSL)
dompdf (opcional, usado pra escrever PDF)

Usando o PHPWord
Exemplo pra gerar um arquivo .docx e fazer download dele:
<?php
require_once 'src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();

$filename = 'helloWorld.docx';

$phpWord = new \PhpOffice\PhpWord\PhpWord();

$section = $phpWord->addSection();
$section->addText(
    htmlspecialchars('Ola mundo!')
);

//Texto com Tahoma e fonte tamanho 10
$section->addText(
    htmlspecialchars('Ola 2'),
    array('name' => 'Tahoma', 'size' => 10)
);

$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText(
    htmlspecialchars('"Teste test." (Texto customizado)')
);
$myTextElement->setFontStyle($fontStyle);

//Salva o documento como word2007 (ou docx)
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($filename);

header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-disposition: attachment; filename="' . uniqid(time()) . '.docx";');
header('Content-Length: '. filesize($filename));
readfile($filename);

Comment: Realmente, o jeito foi utilizar esta biblioteca, PHPWord, para gerar um arquivo .docx sem corrompê-lo. Agradeço a atenção de todos que responderam... @gustavox, por ter citado a biblioteca PHPWord e pelo empenho nos testes, e ao Guilherme, pelo esclarecimento sobre o problema e como utilizar a biblioteca. Obrigado :)
Answer:
UPDATE

Estava tendo alguma dificuldade pra utilizar o PHPWord chamando arquivos HTML externos, e durante a pesquisa por conta de alguns erros acabei encontrando esta biblioteca sensacional.
A utilização é bastante simples. Após fazer o download, descompacte dentro do seu projeto e está pronto. Ela já vem com os arquivos necessários (PHPWord etc, mas vc pode querer baixar as versões atualizadas, o que pra mim complicou então deixei com as que vem por padrão - veja abaixo).
Dentro da pasta há um arquivo example.php no qual é preciso alterar apenas esta linha:
// HTML fragment we want to parse:
$html = file_get_contents('../arquivo.html');

Pra pegar arquivos criados dinamicamente, criei um while na página de entrada pra pegar o id do arquivo HTML gerado, e no arquivo example.php pego o id pela URL pra escolher o arquivo certo:
$numberfile = (int)$_GET['id'];

E então:
$html = file_get_contents('../arquivo'.$numberfile.'.html');

E é só. Claro que este é um exemplo básico, que existem muitas configurações possíveis, e que só vai funcionar com códigos HTML simples, mas é muito mais fácil do que qualquer coisa que encontrei até agora.
(traduzido pelo Google Tradutor)
Descrição do Projeto
Este código converte HTML para documentos do Word (formato docx). O código é escrito em PHP, e trabalha com PHPWord.
Este conversor é especialmente projetado para tirar HTML simples - o tipo de HTML tipicamente produzido por editores WYSIWYG (como TinyMCE) ou que possam ser incluídos em um blog - e converte-os em um documento do Word docx.
O resultado é um documento familiar para a maioria das pessoas que usam documentos do Word e, portanto, fáceis de usar. Não se pretende de maneira alguma recriar complexos layouts de páginas web em um documento do Word.
Este conversor requer SimpleHTMLDom e PHPWord * para a função - cópias de ambos estão incluídos nesta versão (embora você possa querer baixar as últimas versões destes).
Este conversor foi desenvolvido através do projeto Commtap que apoia as pessoas que trabalham com crianças com deficiência de comunicação.
Se você gosta deste conversor,sinta-se livre para doar!

/UPDATE

Os headers corretos são:
para Excel (*.xlsx):
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

para Word (*.docx):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;filename="' . $fileName . '"');

*Traduzido desta resposta do SOen.
Update: Com o Content-Disposition da forma acima não estava funcionando, mas seguindo neste ponto a outra resposta dessa mesma pergunta, consegui baixar em .doc aqui desta forma:
<?php
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Disposition: attachment; filename=\"{$No}_{$Name}_{$Test}.docx\"");

Comment: Tentei aqui utilizando esses MIME types e não rolou :/ peço que dê uma conferida no [código que disponibilizei no ideone](https://ideone.com/uDNMVm) para, se for o caso, testar aí. Pois ele faz o download do arquivo em `.docx`, mas dá erro ao abrir no word. :/
Comment: @ThomersonRoncally Ah, maldito Windows cara :P, porque aqui no Ubuntu 14.4, usando tanto o Abiword quando o OpenOffice, o arquivo abre perfeitamente usando o código que postaste no ideone... PS: será que o problema não é com alguma configuração do seu Word?
Comment: Só pra constar, quando abro no OpenOffice ele abre uma telinha ASCII Filter Options, com a pré configuração sugerida assim: Unicode:UTF-8 / Default-Fonts: Times New Roman / Language - Português-BR... e clicando com essa pré-configuração mesmo ele abre normalmente... o problema no seu Word pode ser com o Unicode....


Menu dropdown vertical - Bootstrap

Question: Estou fazendo uma página onde tem um menu dropdown e cada item do menu altera o conteúdo da div à esquerda. Meu problema é que quando clicar neste menu e ele mostrar seu submenu, ele deve jogar a "Calibração de Equipamentos" e "Segurança do Trabalho" para baixo, em vez disso ele fica por cima. Já tentei alterar position e outras coisas, mas nada funcionou. O trecho do código é este:

    .menu{
      top: 135px;
      left: 35px;
      li {
        background-color: rgba(0, 0, 0, 0.70);
        margin-right: -10px;
        &:hover{
          background-color: rgba(32, 44, 98, 0.81);
        }
        a {
          width: 360px;
          height: 55px;
          color: #FFF ;
          text-decoration: none;
          margin-bottom: 15px;
          text-align: right;
          border-radius: 0;
          font-family: "Roboto Condensed", sans-serif;
          font-size: 25px;
          padding-right: 60px;
        }
        .btn_monit{
          background: url("../img/btn_monitoramento.png") no-repeat right;
        }
        .btn_calibracao{
          background: url("../img/btn_calibracao.png") no-repeat right;
        }
        .btn_seguranca{
          background: url("../img/btn_seguranca.png") no-repeat right;
        }
      }
    }//Fim menu

Monitoramento Ambiental

Emissão

Análise

Vibração

Ruído

Calibração de Equipamentos

Segurança do Trabalho

Answer: Consegui solucionar o problema. Quando o li é clicado, adiciona a class=open. No CSS aumentei o margin-bottom para 310px nesta classe.
Problema resolvido :D. Espero que futuramente isto ajude alguém.
Comment: Olá fabricio, não precisa fechar a pergunta (lembrando que você mesmo pode fazer isso). Basta postar como resolveu e marcar sua própria pergunta como certa
Comment: Não somos um fórum, não é necessário fechar a pergunta, somos um Q&A, quando passar o período de "carência" da pergunta você poderá marcar a sua própria resposta como correta.
Comment: Guilherme e Randrade, desculpem pelo vacilo. Ainda não tinha certeza se tinham que fechar a pergunta. Obrigado pelo esclarecimento.

Menu dropdown vertical - Bootstrap


What is the function computed by this zero inflation model?

Question: Consider this made-up data
require(ggplot2)
require(pscl)
require(visreg)

set.seed(23)
y = c(1005,987,784,1487,0,13,1340,451,0,784,0,451,0,0,123,754, 0, 320,0,12,0,0,87,0,0,0)
d = data.frame(
    y = y,
    x = 1:length(y) + runif(length(y),0,2)
)
ggplot(d, aes(y=y,x=x)) + geom_point() + geom_smooth(method='lm')

I am running a zero inflation model on this data
m = zeroinfl(y~x, dist='negbin', data=d)
print(m)
Call:
zeroinfl(formula = y ~ x, data = d, dist = "negbin")

Count model coefficients (negbin with log link):
(Intercept)            x
     7.4524      -0.1054
Theta = 1.181

Zero-inflation model coefficients (binomial with logit link):
(Intercept)            x
    -2.3405       0.1453

With these four estimates, it should be possible to compute a function to display but I am not sure how. What is my function computed by the zeroinfl function?
When I try to plot the model I get
visreg(m)

Feels about right. What function is this?
Answer: The function is simply expectation of the zero-inflation model, see Equation 8 in vignette("countreg", package = "pscl"). This is what ?predict.zeroinfl computes by default (see also Appendix C in the vignette).
To make sure you can try:
visreg(m)
points(d$x, predict(m))

However, the data do not really seem to be count data (or if they are the counts are so large that they are almost continuous). Thus, instead of a zero-inflated count model one could also simply use a Gaussian linear regression, censored at zero (aka tobit model). As pointed out in the post Censored regression in R the model can be fitted with the AER package (interfacing the survreg package) and then one can compute the latent mean, the conditional mean, and the unconditional mean of the response:
library("AER")
fit <- tobit(y ~ x, data = d)
mu <- fitted(fit)
sigma <- fit$scale
p0 <- pnorm(mu/sigma)
lambda <- function(x) dnorm(x)/pnorm(x)
ey0 <- mu + sigma * lambda(mu/sigma)
ey <- p0 * ey0

This yields the following curves for the latent mean (red) and the unconditional mean (blue):
plot(y ~ x, data = d)
abline(fit, col = 2, lwd = 2)
lines(d$x, ey, col = 4, lwd = 2)

A heteroscedastic version of the tobit model is also available in the crch package.


Accessing the promise object from within the then function

Question: I am using the Q library of node.js . I am trying to print a report which would print the query name and the result . This is what I have . The code prints "In function undefined . How do I access the value of the promise object from within the "then" function ?
var queries = ["2091 OR 2092 OR 2093",
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = new Array();
for (var i=0; i<queries.length; i++) {
    promises[i]=performSearch(queries[i]);
    promises[i].query = queries[i];
    console.log("Outside function ", promises[i].query);

    promises[i].then(function(data) {
            console.log("In function ", this.query);
            processSearchResults(data,this.query);
    });
}
Q.allSettled(promises).then(function(results) {
    endFunction();
});

Comment: if `performSearch` returns a promise, then `data` is also a promise.
Comment: @BenFortune: `data` is not a promise - it *must not* be a promise according to the spec?
Comment: @BenFortune data is not a promise. I have set the query property on the promise object . I want to access this property from within the then function
Answer:
This is what I have:
promises[i].then(function(data) {
        console.log("In function ", this.query);
        processSearchResults(data,this.query);
});

The code prints "In function undefined".

The spec mandates that the callback is called with nothing for the this value, so this will refer to the global (window) object in sloppy mode, which does not have a .query property. In strict mode you'd have gotten an exception when this was undefined.

How do I access the value of the promise object from within the "then"
  function ?

There is no special method. You usually will not need to access a promise as an object, it's only a transparent value representing the single result of an asynchronous computation. All you need to do with it is to call its .then() method - and inside the callback, there's no reason to access the promise object, because the information it holds is already accessible to you (data, and the fact that the fulfillment callback was invoked).
So if you want to access your .query property, you'd have to use promises[i] as usual. However, you will need a closure for i so you'd better use map anyway and hold the query string in the closure directly instead of making it a property on a promise object:
var queries = ["2091 OR 2092 OR 2093",
            "2061 OR 2062",
            "2139 OR 2140 OR 2141"
            ];

var promises = queries.map(function(query) {
    var promise = performSearch(query);
    console.log("Outside function ", query);
    var processedPromise = promise.then(function(data) {
        console.log("In function ", query);
        return processSearchResults(data, query);
    });
    return processedPromise; // I assume you don't want the unprocessed results
});
Q.allSettled(promises).then(function(processedResults) {
    endFunction(processedResults);
});

Comment: Thanks . Works as expected .


Why more features are better than one

Question: We have an input composed of several features. Why is it better to use many of them in a Machine Learning algorithm, instead of using only the better discriminant one?
And in which way many features are combined in order to produce a good model?
Comment: Presumably you have taken exams before. Should the results (degree etc) be based on a single exam or multiple exams.
Comment: As long as the feature set includes variables that make sense as potential predictors of the output, the best choice among models admitting more than one feature will (nearly always) outperform a model based on the best single feature. It's not a certainty; it's possible to identify real examples where it won't happen but they're not the kind of problem that such techniques tend to be applied to. You should probably separate your two questions, though I believe the second is already addressed to some extent in a number of posts on site.
Answer: Let's do a really extreme example where neither of the two variables give much predictive ability, but the combination does.
library(ggplot2)
set.seed(2021)
N <- 1000
x0_class0 <- c(rnorm(N, 3, 1), rnorm(N, -3, 1))
x1_class0 <- c(rnorm(N, -3, 1), rnorm(N, 3, 1))
x0_class1 <- c(rnorm(N, 3, 1), rnorm(N, -3, 1))
x1_class1 <- c(rnorm(N, 3, 1), rnorm(N, -3, 1))

d0 <- data.frame(x0 = x0_class0, x1 = x1_class0, y = "0")
d1 <- data.frame(x0 = x0_class1, x1 = x1_class1, y = "1")
d <- rbind(d0, d1)

Look at the plots of the two marginal predictor variables. Given an x0 or x1 value, can you predict the color?
ggplot(d, aes(x = x0, fill = y)) +
  geom_density(alpha = 0.3) +
  theme_bw()

ggplot(d, aes(x = x1, fill = y)) +
  geom_density(alpha = 0.3) +
  theme_bw()

By construction, each color has the same distribution for x0 and x1. If you know that x0 = 3, you have no idea what color the point is, and if you know that x1 = -3, you have no idea what color the point is.
However, let's look at both predictors simultaneously.
ggplot(d, aes(x = x0, y = x1, col = y)) +
  geom_point() +
  theme_bw()

It's easy to see how the colors are separated in two dimensions! If the features are (x0, x1) = (3, -3), you can be pretty much certain about the color (red, not blue).
Depending on the model you run, this particular example might require an interaction (e.g., a classical logistic regression would require the interaction to be specified explicitly, while a large neural network would be able to figure it out).
Answer: This is not true in general.
Imagine that there's a causal relationship between two events. In such a case, knowing that the cause has happened would be enough to predict the effect. A single feature would be enough.
Now imagine the opposite case, where you're trying to predict a completely random, independent of everything, event. No matter how many features do you have, you wouldn't be able to predict it. With more features you could only be more prone to overfit to the training data, gaining a false sense that you're able to predict something.
Let's consider one more scenario, where you're making weather forecasts. Having one data from a single weather station wouldn't let you build a precise model. On another hand, having data from multiple weather stations gives you much more precise information on the weather conditions, helping you to build a much better water model.
You need accurate data, not a lot of data.
Answer: In general, you should add features carefully and try to add features which are not correlated with each other. Without given data, no one can predict if the model will be really good on just one feature. We definitely don't want to overfit but that doesn't mean we underfit and don't use the features which provide us discriminatory information.
What do you mean by "And in which way many features are combined in order to produce a good model ?"
Are you asking a feature selection method?

Why more features are better than one


Find the indicial equation for $r_1$ and $r_2$

Question: The given expression is:
$$x^2y^{''}+xy^{'}+(x^2-\frac{1}{4})y=0$$
First we need to convert the given into its indicial equation:
$$x^2\sum^\infty_{n=0}(n+r)(n+r-1)C_nx^{n+r-2}+x\sum^\infty_{n=0}(n+r)C_nx^{n+r-1}+x^2\sum^\infty_{n=0}C_nx^{n+r}-\frac{1}{4}\sum^\infty_{n=0}C_nx^{n+r}=0$$
Now factoring through the $x$ coefficients
$$\sum^\infty_{n=0}(n+r)(n+r-1)C_nx^{n+r}+\sum^\infty_{n=0}(n+r)C_nx^{n+r}+\sum^\infty_{n=0}C_nx^{n+r+2}-\frac{1}{4}\sum^\infty_{n=0}C_nx^{n+r}=0$$
Now bringing first, second and fourth series into a single series
$$\sum^\infty_{n=0}\left[(n+r)(n+r-1)+(n+r)-\frac{1}{4}\right]C_nx^{n+r}+\sum^\infty_{n=0}C_nx^{n+r+2}=0$$
Now to evaluate the expression with $n=0$ and $n=1$; And just as a personal preference, I like to factor out the $x^r$ during this step:
$$x^r\left[C_0\left(r^2-r+r+x^2-\frac{1}{4} \right) x^0\right]+x^r\left[(1+r)(r)C_1x+(1+r)C_1x+C_1x^3-\frac{1}{4}C_1x \right]+\sum^\infty_{n=0}...=0$$
Now from here I calculated my $r$ values and this is where I got confused. For the first bracket group of the expression above I got $r=\frac{1}{2}$ but when I tried to calculate $r$ for the second bracket group I got $r=-\frac{1}{2}$ and $r=-\frac{3}{2}$. This is where I know I messed up somewhere as I am only supposed to get two values of $r$. I re-did the problem from the start and got the same answers, where did I go wrong?
Comment: Your indicial equation is $r^2-\frac 14 =0\implies r= \pm \frac 12$
Comment: Everything is correct and well done. You made a little mistake $-\frac{1}{y}=x^5-2x^2+C \implies  {y}=-\dfrac 1 {x^5-2x^2+C}$
Answer: $$\sum^\infty_{n=0}\left[(n+r)(n+r-1)+(n+r)-\frac{1}{4}\right]C_nx^{n+r}+\sum^\infty_{n=0}C_nx^{n+r+2}=0$$
$$\sum^\infty_{n=0}\left[(n+r)^2-\frac{1}{4}\right]C_nx^{n+r}+\sum^\infty_{n=2}C_{n-2}x^{n+r}=0$$
Changing the indices:
$$ \color {blue} {C_0x^r(r^2-\frac 14)}+C_1x^{r+1}\left(r^2+2r+\frac 34 \right)+\sum^\infty_{n=2}(\left[(n+r)^2-\frac{1}{4}\right]C_n+C_{n-2})x^{n+r}=0$$
Your indicial polynomial is  the coefficient of the lower power of $x$:
$$P(r)=r^2-\frac 14$$
The indicial equation is:
$$\left(r^2-\frac 14 \right)=0$$
$$\implies S_r=\left  \{ -\frac 12, \frac 12 \right \}$$
Comment: Here $\sum^\infty_{n=0}\left[(n+r)(n+r-1)+(n+r)-\frac{1}{4}\right]C_nx^{n+r}$ Factorize $n+r$ @EricBrown
Comment: How did you get $(n+r)^2$ on the second line?
Comment: @EricBrown factorize $n+r$


Java Singleton - IsEnabled?

Question: Any ideas on a good interface for a singleton with an isEnabled method?
For example, I have a UDPClient and only want to create the Socket once, so I'm setting it up as a singleton.  And I want the app to continue if the configuration says to enable it, but it cannot.
Can I do better than this client code and the resulting singleton implementation?  (and please correct me if I've screwed up the singleton).  This will be used in a web app if it makes any difference.
public class UDPConnectionManager {
    private static final UDPConnectionManager INSTANCE = new UDPConnectionManager();
    private UDPClient udp = null;

    private UDPConnectionManager() {
        try {
            InitialContext ic = new InitialContext();

            String udpHost = (String) ic.lookup("java:comp/env/udpHost");
            Integer udpPort = (Integer) ic.lookup("java:comp/env/udpPort");
            Boolean udpEnabled = (Boolean) ic.lookup("java:comp/env/udpEnabled");

            if (udpEnabled) {
                udp = new UDPClient(udpHost, udpPort);
            }
        } catch (Exception e) {
            log.error("UDP Connection Manager:  error while setting up UDP Manager.", e);
        }
    }

    public static UDPConnectionManager instance() {
        return INSTANCE;
    }

    public UDPClient getUDPClient() {
        return udp;
    }

    public Boolean isEnabled() {
        return (udp != null);
    }
}

Client:
UDPClient udpCM = UDPConnectionManager.instance();
if (udpCM.isEnabled()) {
    UDPClient udpClient = udpcCM.getUDPClient();
    udpClient.send("test");
}

Answer: If you expect it to be sort of a fire-and-forget-even-if-its-not-available sort of thing, then you might ease the burden on the client and just put the send() method on the singleton.
By doing this, you can have the singleton do the check, and not send it if it's null.
public class UDPConnectionManager {
    private UDPConnectionManager() { ... }
    public static UDPConnectionManager instance() { ... }

    public void send(String message) {
        if(udp != null) {
            udp.send(message);
        }
    }
}

Don't make the client do anything the module could do (PDF, page 27)
Comment: I like this, so I upvoted it.  The problem is that I didn't mention there were also 5 other methods, similar to send that I would need to do the if not null test to.  5 methods isn't too bad.  I'll have to think about this over night.  Thanks for the insight.
Answer: There's nothing wrong with it the way it is per-se, but if all your use cases look like the above then I'd just put a send() method on the singleton and have that decide whether it's enabled or not. If you want to know whether it went through ok, you could have it return a boolean value. Or if you don't want that method on the singleton connection manager, you could write another class that it works through and offload it to that instead.
Of course, if you're planning to use the isEnabled() method to decide on other actions then you may need it available on the singleton anyway and there's nothing wrong with that in my book.

Java Singleton - IsEnabled?


ERRO NO ANDROID STUDIO APP FECHANDO AO EXECUTAR

Question: recentemente (e do nada) surgiu um erro extremamente irritante e chato no Android Studio, na verdade a própria IDE nem erro aponta em nenhum código, mas quando vou executar um app que tenha imagens, como pelo menos um imageView ou Button com um background, ao executar o app ele fecha na hora no celular.
Eu estou até pegando projetos prontos de pequenos apps do curso que eu faço e só abrindo eles no Android Studio e executando, no caso não tem nenhum erro no código, mas mesmo assim fica fechando. Já troquei a versão da IDE, já instalei de novo do zero, já dei Rebuild e Clean, mas nada resolve.
Vou deixar os códigos abaixo de um app pequeno que possui uma activity com tres botoes, um play, um pause e um stop, o projeto está funcionando de boa, porém ao colocar um imagem de background nos botoes, o app já fecha ao executar. Deixarei também os erros que aparecem no Logcat.
Main Activity:
package com.example.joaovictor.mediaplayer;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaPlayer = MediaPlayer.create(getApplicationContext() , R.raw.musica);

    }

    public void executarSom(View view) {

        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    public void pausarMusica(View view) {

        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }

    }

    public void pararMusica(View view) {

        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();

            mediaPlayer = MediaPlayer.create(getApplicationContext() , R.raw.musica);

        }

    }

}

activity_main :
(Coloquei um background apenas no botão Pause, para vcs verem, mas quando eu tiro esse background e deixo so o botão igual os outros o app funciona normalmente, mas colocando a imagem de background, não vai)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.joaovictor.mediaplayer.MainActivity">

    <Button
        android:id="@+id/button11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/pause"
        android:onClick="pausarMusica"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button13"
        app:layout_constraintStart_toEndOf="@+id/button12"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:onClick="executarSom"
        android:text="Play"
        app:layout_constraintBaseline_toBaselineOf="@+id/button11"
        app:layout_constraintEnd_toStartOf="@+id/button11"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button13"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:onClick="pararMusica"
        android:text="Stop"
        app:layout_constraintBaseline_toBaselineOf="@+id/button11"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button11" />

</android.support.constraint.ConstraintLayout>

Aqui está o que aparece no Logcat no momento que o app fecha no celular e fica escrito nele "O MediaPlayer parou" :
12-15 00:03:42.280 20121-20121/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:03:42.280 20121-20121/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:03:43.594 20135-20135/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:03:43.594 20135-20135/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:03:44.148 20151-20151/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:03:44.148 20151-20151/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:03:44.342 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:03:44.803 20163-20163/com.example.joaovictor.mediaplayer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.joaovictor.mediaplayer, PID: 20163
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joaovictor.mediaplayer/com.example.joaovictor.mediaplayer.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class Button
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
     Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class Button
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.joaovictor.mediaplayer.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:5975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
     Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.joaovictor.mediaplayer:drawable/pause" (7f060062)  is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f060062 a=-1 r=0x7f060062}
        at android.content.res.Resources.loadDrawableForCookie(Resources.java:2420)
        at android.content.res.Resources.loadDrawable(Resources.java:2360)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:749)
        at android.view.View.<init>(View.java:3730)
        at android.widget.TextView.<init>(TextView.java:650)
        at android.widget.Button.<init>(Button.java:111)
        at android.widget.Button.<init>(Button.java:107)
        at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:71)
        at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:67)
        at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
        at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
        at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.joaovictor.mediaplayer.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:5975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
12-15 00:03:50.004 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=2,01 rxSuccessRate=8,38 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-57
12-15 00:04:20.014 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=0,00 rxSuccessRate=1,06 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-69
12-15 00:04:20.019 667-786/? E/WifiStateMachine: WifiStateMachine starting scan for "Medeiros"WPA_PSK with 2462
12-15 00:04:20.481 20199-20199/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:20.481 20199-20199/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:21.144 20212-20212/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:21.144 20212-20212/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:21.771 20230-20230/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:21.772 20230-20230/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:24.610 20242-20242/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:24.610 20242-20242/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:25.204 20255-20255/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:25.204 20255-20255/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:28.841 20269-20269/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:28.841 20269-20269/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:29.256 15251-15251/? E/Finsky: [1] com.google.android.finsky.verifier.impl.VerifyPerSourceInstallationConsentInstallTask.b(86): Package name null is not an installed package
12-15 00:04:29.258 15251-15251/? E/Finsky: [1] com.google.android.finsky.verifier.impl.gi.d(83): PSIC will not run.
    java.lang.IllegalArgumentException: Provided installer data is not valid (uid: -1, package name: null). Data could be missing, invalid, or just not match each other. PSIC will not run.
        at com.google.android.finsky.verifier.impl.gi.d(SourceFile:58)
        at com.google.android.finsky.verifier.impl.PackageVerificationService.a(SourceFile:14)
        at com.google.android.finsky.verifier.impl.b.h.onStartCommand(SourceFile:4)
        at com.google.android.finsky.verifier.impl.PackageVerificationService.onStartCommand(SourceFile:9)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2891)
        at android.app.ActivityThread.access$2100(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
12-15 00:04:30.009 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=1,38 rxSuccessRate=2,01 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-69
12-15 00:04:30.010 667-786/? E/WifiStateMachine: WifiStateMachine starting scan for "Medeiros"WPA_PSK with 2462
12-15 00:04:31.403 1283-1299/? E/DefContainer: OBB dir: /storage/MicroSD/.android_obb/com.example.joaovictor.mediaplayer not found
12-15 00:04:31.447 3678-3678/? E/PackageActionReceiver: ACTION_PACKAGE_REMOVED
12-15 00:04:31.616 3678-3701/? E/ExternalAccountType: Unsupported attribute readOnly
12-15 00:04:32.310 20376-20376/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:32.310 20376-20376/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:32.326 19212-19231/? E/Clock_animationIcon: android.intent.action.PACKAGE_REMOVED
12-15 00:04:32.661 1327-1327/? E/ActivityThread: Performing stop of activity that is not resumed: {com.asus.launcher/com.android.launcher3.Launcher}
    java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.asus.launcher/com.android.launcher3.Launcher}
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3336)
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3417)
        at android.app.ActivityThread.access$1100(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
12-15 00:04:32.854 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:04:33.218 20424-20424/com.example.joaovictor.mediaplayer E/MediaPlayer: Should have subtitle controller already set
12-15 00:04:33.251 20424-20424/com.example.joaovictor.mediaplayer E/MediaPlayer: Should have subtitle controller already set
12-15 00:04:34.807 3678-3678/? E/PackageActionReceiver: ACTION_PACKAGE_ADDED
12-15 00:04:35.596 20593-20593/? E/GoogleTagManager: Invalid macro: _gtm.loadEventEnabled
12-15 00:04:35.597 20593-20652/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:04:35.607 20593-20655/? E/GoogleTagManager: Invalid macro: _gtm.loadEventEnabled
12-15 00:04:35.725 19212-19231/? E/Clock_animationIcon: android.intent.action.PACKAGE_REPLACED
12-15 00:04:36.160 20663-20663/? E/ACRA: Initializing ANR detector for process: com.instagram.android
12-15 00:04:36.819 20752-20752/? E/ACRA: Skipping ANR Detector for process: com.instagram.android:videoplayer
12-15 00:04:50.004 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=3,74 rxSuccessRate=3,25 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-65
12-15 00:04:50.004 667-786/? E/WifiStateMachine: WifiStateMachine starting scan for "Medeiros"WPA_PSK with 2462
12-15 00:04:55.869 20779-20779/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:55.869 20779-20779/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:55.916 667-777/? E/InputDispatcher: channel '245c764a com.example.joaovictor.mediaplayer/com.example.joaovictor.mediaplayer.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
12-15 00:04:56.066 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:04:56.482 20793-20793/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:56.483 20793-20793/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:57.114 20813-20813/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:57.114 20813-20813/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:58.297 20826-20826/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:58.297 20826-20826/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:58.870 20842-20842/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:04:58.870 20842-20842/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:04:59.043 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:04:59.534 20854-20854/com.example.joaovictor.mediaplayer E/MediaPlayer: Should have subtitle controller already set
12-15 00:04:59.583 20854-20854/com.example.joaovictor.mediaplayer E/MediaPlayer: Should have subtitle controller already set
12-15 00:05:13.324 1327-1953/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:05:20.011 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=3,51 rxSuccessRate=4,98 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-69
12-15 00:05:29.283 20885-20885/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:29.283 20885-20885/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:29.453 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:05:29.867 20899-20899/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:29.867 20899-20899/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:30.004 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=2,97 rxSuccessRate=4,31 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-66
12-15 00:05:30.004 667-786/? E/WifiStateMachine: WifiStateMachine starting scan for "Medeiros"WPA_PSK with 2462
12-15 00:05:30.501 20919-20919/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:30.501 20919-20919/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:33.230 20934-20934/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:33.230 20934-20934/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:33.746 20947-20947/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:33.746 20947-20947/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:37.044 20961-20961/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:37.044 20961-20961/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:37.445 15251-15251/? E/Finsky: [1] com.google.android.finsky.verifier.impl.VerifyPerSourceInstallationConsentInstallTask.b(86): Package name null is not an installed package
12-15 00:05:37.447 15251-15251/? E/Finsky: [1] com.google.android.finsky.verifier.impl.gi.d(83): PSIC will not run.
    java.lang.IllegalArgumentException: Provided installer data is not valid (uid: -1, package name: null). Data could be missing, invalid, or just not match each other. PSIC will not run.
        at com.google.android.finsky.verifier.impl.gi.d(SourceFile:58)
        at com.google.android.finsky.verifier.impl.PackageVerificationService.a(SourceFile:14)
        at com.google.android.finsky.verifier.impl.b.h.onStartCommand(SourceFile:4)
        at com.google.android.finsky.verifier.impl.PackageVerificationService.onStartCommand(SourceFile:9)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2891)
        at android.app.ActivityThread.access$2100(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
12-15 00:05:40.244 1283-1299/? E/DefContainer: OBB dir: /storage/MicroSD/.android_obb/com.example.joaovictor.mediaplayer not found
12-15 00:05:40.343 3678-3678/? E/PackageActionReceiver: ACTION_PACKAGE_REMOVED
12-15 00:05:40.481 3678-3701/? E/ExternalAccountType: Unsupported attribute readOnly
12-15 00:05:40.967 19212-19231/? E/Clock_animationIcon: android.intent.action.PACKAGE_REMOVED
12-15 00:05:41.117 21027-21027/? E/memtrack: Couldn't load memtrack module (No such file or directory)
12-15 00:05:41.117 21027-21027/? E/android.os.Debug: failed to load memtrack module: -2
12-15 00:05:41.429 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
12-15 00:05:41.911 21056-21056/com.example.joaovictor.mediaplayer E/AndroidRuntime: FATAL EXCEPTION: main
   ...ompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.joaovictor.mediaplayer.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:5975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5264)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
     Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.joaovictor.mediaplayer:drawable/pause" (7f060062)  is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f060062 a=-1 r=0x7f060062}
        at android.content.res.Resources.loadDrawableForCookie(Resources.java:2420)
        at android.content.res.Resources.loadDrawable(Resources.java:2360)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:749)
        at android.view.View.<init>(View.java:3730)
        at android.widget.TextView.<init>(TextView.java:650)
        at android.widget.Button.<init>(Button.java:111)
        at android.widget.Button.<init>(Button.java:107)
        at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:71)
        at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:67)
        at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
        at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
        at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
...................

61/? E/ACRA: Initializing ANR detector for process: com.instagram.android
    12-15 00:05:50.005 667-786/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source -2 txSuccessRate=7,48 rxSuccessRate=7,36 targetRoamBSSID=30:99:35:a0:1b:ef RSSI=-65
    12-15 00:05:50.005 667-786/? E/WifiStateMachine: WifiStateMachine starting scan for "Medeiros"WPA_PSK with 2462
    12-15 00:06:01.147 1327-1882/? E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
    12-15 00:06:01.604 21448-21448/com.example.joaovictor.mediaplayer E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.joaovictor.mediaplayer, PID: 21448
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joaovictor.mediaplayer/com.example.joaovictor.mediaplayer.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class Button
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:147)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5264)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
         Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class Button
   ................. mais erros... (nao cabe mais aqui)

Comment: Boa mano se pretendes mostrar uma imagem em um botão convém usar um imagebutton e defineres o a imagem em atributo src.
Answer: Pelo que testei aqui o problema provavelmente pode ser na pasta "drawable/pause"
Já aconteceu comigo o mesmo erro.
Verifica se não tem nenhuma pasta em res do tipo "drawable-vXX". O que pode tá acontecendo é que esse seu drawable está em apenas em uma pasta referente a versão "vXX"
E ao utilizar uma versão menor acontece o erro.
Pegue essa imagem "pause" e cole em todas pastas que tiver drawable.
Espero ter ajudado.
Comment: Se ajudei marque essa resposta como útil, para ajudar outros desenvolvedores com o mesmo problema.
Comment: Deve ser isso mesmo o problema, obriagdo xD


Why can't I add a product?

Question: I need to add product via services, but I have strange issue with a price field.
The case is that all fields saved correctly except price field amount and it returns:

The requested URL returned error: 500 Internal Server Error : An error occurred (0): Unable to get the data property amount as the parent data structure is not set.

The url which is used: endpoint/product.
Here is the code:
fields `$node_data = array(
  'sku' => 'sku1',
  'title' => 'product title',
  'type' => 'product',
//  'commerce_price_amount' => array('amount' => 122.000, 'currency_code' => 'KWD'),
  'commerce_price_amount' => 12.000,
  'commerce_price_currency_code' => 'KWD'
); 12.000,
  'commerce_price_currency_code' => 'KWD'`

which successfully added all fields except price.
I think it relate to price field format.
Comment: Try using a GET call with Firefox Poster (or Chrome's Postman) to retrieve a product through Commerce Services. That will reveal to you the structure of the product, which should help you build the structure to POST.
Answer: It works with me after disable some modules related to commerce like payment, order, cart, tax and then clear cache products saved.
I still didn't know the reason for that error

Why can't I add a product?


Definition for supremum

Question: Is the below definition for supremum correct? If no, then how to define it in similar way?
$$\sup E = s \Longleftrightarrow(\forall t, \; \forall x, \; x \le t \Longrightarrow x \le s \le t) $$
We suppose that $E \subseteq \mathbb R$; $x\in E$; $s,t \in \mathbb R$.
Answer: No. $s$ is $\le$ any other upper bound of $E$. It is not $\le$ any number that happens to be above an element of $E$. For instance if $E = (0,1)$ and $x = 1/2$ then $s = 1$, and $1/2 < 3/4$, but $s \not \le 3/4$.
Comment: Oh, thanks! I've made a stupid mistake.
Comment: Stupid mistakes are the best mistakes - they are the easiest to correct!
Answer: If by "similar way" you mean the definition should be written as a single logical formula, then we can write $$\textrm{sup}\:E=s⟺\bigg(\big(∀x,\:x≤s\big)  ∧\big(\left(∃t\:∀x,\:x≤t\right)⟹s≤t\big)  \bigg),$$ where $E⊆\mathbb{R};\:x∈E;\: s,t∈\mathbb{R}$.
Answer: I believe you forgot an important part of the definition of the supremum, which is that it is the lowest upper-bound. For that, you need to have that there exists an element in E bigger or equal to sup E - k, for k>0.
Answer: Paul Sinclair already noted that your definition is faulty. I'll explain how the supremum is defined.
If there exists a number $s$ such that

$s$ is an upper bound for $E$, that is, $\forall x \in E \implies s \geq x$;
$s$ is the lowest upper bound, that is, $\forall \epsilon > 0, \exists x \in E\quad\text{s.t.}\quad s - \epsilon \lt x \leq s$;

we call it supremum of $E$ and write $\sup E = s$.
To understand the second point, think about it in these terms: what does it mean to be the lowest upper bound? It means that if we subtract a positive amount, however small, we instantly find ourselves inside $E$. This does not happen if we are considering $E = (0, 1)$ and the upper bound $2$, for example.
Comment: I don't think it's necessary to assume the existence of a minus operator to define supremum.
Comment: @JanStout You are right, but since OP seemed to be working over $\mathbb R$ I adapted the definition. This one is also very easy to understand.
Answer: To be a supremum of $E$ (i.e. $s = \sup E$),

s must be a upper bound (i.e. $s \ge e, \forall e \in E$).
s must be the smallest upper bound of $E$ (i.e. $s \le b, \forall b$ where $b$ is an upper bound of $E$).

Similarly, the infimum can be defined.

Definition for supremum


Prove that a integral tends to zero as $n$ tends to infinity

Question: Let $x\in(0,2\pi)$. I want to show
$$\int_{0}^{x}\left(\frac{1}{2\sin{\frac{t}{2}}}-\frac{1}{t}\right)\sin \frac{(2n+1)t}{2}\ \,dt$$
tends to zero as $n$ tends to infinity. I know that we can use Riemann-Lesbegue lemma. But I want to do it without Lesbegue lemma and argue elementarily.  I tried to integrate indefinitely and use fundamental theorem of calculus. But fail to do so.
Comment: @Reveillark Riemann-Lebesgue Lemma
Comment: What do you mean by the Lebesgue lemma? There are several results that go by that name
Answer: Let $I(x)$ be given by
$$I(x)=\int_{0}^{x}\left(\frac{1}{2\sin({\frac{t}{2}})}-\frac{1}{t}\right)\sin \left(\frac{(2n+1)t}{2}\right) \,dt$$
Note that $\displaystyle f(t)=\left(\frac{1}{2\sin({t/2})}-\frac{1}{t}\right)=\frac t{24}+O(t^3)$ as $\displaystyle t\to0$.
Now, integrate by parts with $\displaystyle u=f(t)$ and $\displaystyle v=\frac{\cos((2n+1)t)}{-(2n+1)}$.
Can you finish now?
Comment: Did you mean $t/2$ in your substitution?
Comment: I have edited since the first post and now don't enforce any substitution.
Comment: @Mark Viola. I tried integration by parts, there are huge complicated terms? In essence, the most important things is the degree 1 n polynomial  so that as n tends to infinity and the whole sum tends to zero?
Comment: @user72342343 $u=f(t)$, $dv=\sin((2n+1)t)$.  Then, $du=f'(t)\,dt$ and $v=-\cos((2n+1)t)/(2n+1)$.  The term $f'(t)=\frac1{24}+O(t^2)$ is a "nice" function.  Does this help?
Comment: @Mark Viola Could use explain more on $O(t^3)$? since I have no knowledge or have not seen $O(t^3)$
Comment: You can read about [Big O Notation Here](https://en.wikipedia.org/wiki/Big_O_notation#Formal_definition).  In heuristic terms, the order of the next term in the taylor expansion of $f(t)$ is $t^3$.  Suffice to say that $f(t)$ has a removeable discontinuity at $0$ that once removed renders it a smooth continuously differentiable function.
Comment: @ Mark Viola Would you mind doing it without the Big O notation? Would appreciate it  if you can elaborate more on your answer. Thanks a lot. I am a self-taught old man without much mathematical maturity, just self-studying elementary math
Comment: @user72342343 Just know that $f(t)$ is a nice smooth function.  To find the limit as $n\to\infty$, you don't have to know what it is.  Then, can you proceed?
Comment: @ Mark Viola What do you mean by nice smooth function? infinitely many times differentiable?
Comment: Yes, it is infinitely differentiable.
Comment: @Mark Viola How does infinitely differentiable link to the tendency to zero?
Comment: Well, when we integrate by parts, the term $\frac1{2n+1}$ appears in both the $uv$ part and the $\int v\,du$ part.  Both $uv$ and $\int v\,du$ approach $0$ because of the $\frac1{2n+1}$ term


Adding More Than One Javascript Declaration to Joomla Module On Same Page

Question: I'm building out a module that needs to initiate a slider. Something similar to this:
jQuery('#slider').anythingSlider();

I can do that as long as I only have one module on the page, but if I add more than one module to the page, it will only add the last script declaration. The reason I need to cal this more than once is to have more than one slider on the same page, each with their own options (there's a plethora of options).
I've tried scriptDeclaration and I've even tried echoing the script to see if it would allow it to be echoed.
I'm am building on Joomla 1.7.3. This is isn't the first time I've had this problem, but this is the first time it's absolutely necessary to get this working correctly.
Thanks!
Answer: There are a number of things you could do:
1) use a class declaration to initialise your slider
jQuery('.slider').anythingSlider();

Now, all containers with the "slider"-class will be processed by the plugin.
2) just use different id's for your html containers.
Im not sure, what the exact html markup is, that your plugin requires, but something like this should work.
In your default.php (template):
 <div id="module_<?php echo $module->id; ?>">
  // your html stuff

// now add the jquery

The second option would be better, since it would allow you to use different configurations for wach slider. Hope this helps.
Comment: I have it set up like that already. The problem is that Joomla only outputs 1 script declaration. So I could have 30 modules on 1 page with different IDs or classes, but Joomla would only initiate the last module to be loaded (or the one with the highest ID, I'm not sure which). So I can only set the options for 1 slider, not any of the rest. I'm trying to figure out how to tell Joomla to print a script declaration for each module of the same type (even if it has to access functions from a component).
Comment: Can you please elaborate on "Joomla only outputs 1 script declaration"?  I am not quite sure what you mean by that..
Comment: When building a module I have a php variable with the javascript output. I use the Joomla function `addScriptDeclaration($var)` to insert the javascript into the head of the document. That's how I initiate the slider. This should be done for each and every module, but Joomla will only output one of the `addScriptDeclaration($var)` even if I have 30 of the same modules on the page (I need it to produce that code for each and every module but it won't even though that code is created within the module itself). I hope that explains it clear enough :). Thanks for helping!
Comment: well, you could just get rid of the addScriptDeclaration stuff and just include the javascript in your template, as in my example...
Comment: I had a helper file that I was using to print the scripts (I tried what you were using in your second example within that helper file) but it wouldn't work. It wasn't until I placed the `addScriptDeclaration` in the default.php that it started working. I'm still not sure why it does that, but I'm glad it's fixed. Thank you so much!


An equivalent condition of $f^+ \in L^1 (\Omega)$ for $f \in L^1_{\text{loc}} (\Omega)$

Question: Let $\Omega$ be an open subset of $\mathbb R^d$ and $f \in L^1_{\text{loc}} (\Omega)$. I'm trying to do below exercise, i.e.,

Prove that $f^+ := \max\{f, 0\} \in L^1 (\Omega)$ IFF
$$
B := \sup \left \{\int f \varphi : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \text{ and } \varphi \ge 0 \right\} < \infty.
$$
If $f^+ \in L^1 (\Omega)$ then $B = \|f^+\|_1$.

Could you have a check on my below attempt?

Is there a shorter alternative approach?

Let
$$
A := \sup \left \{\int f^+ \varphi : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \right\}.
$$
Let's show that $A=B$. Let $f^- := \max\{-f, 0\}$. Then
$$
\begin{align}
B &= \sup \left \{\int f^+ \varphi - \int f^- \varphi  : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \text{ and } \varphi \ge 0 \right\} \\
&\le \sup \left \{\int f^+ \varphi  : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \text{ and } \varphi \ge 0 \right\} \\
&\le \sup \left \{\int f^+ \varphi  : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \right\} \\
&=A.
\end{align}
$$
Let's prove the reverse, i.e., $A \le B$. We need the following approximation result, i.e.,

Lemma 1 Let $\Omega$ be an open subset of $\mathbb R^d$. Let $u \in L^\infty (\Omega)$.

There is $(u_n) \subset \mathcal C_c^{\infty} (\Omega)$ such that

$\sup_n \|u_n\|_\infty \le \|u\|_\infty$,
$u_n \xrightarrow{n\to\infty} u$ a.e. on $\Omega$, and
$u_n \xrightarrow{n\to\infty} u$ in $L^\infty (\Omega)$ w.r.t. the weak$^*$ topology $\sigma(L^\infty, L^1)$.

If $u \ge 0$ a.e. on $\Omega$, we can further take $u_n \ge 0$ a.e. on $\Omega$.
Deduce that $\mathcal C_c^{\infty} (\Omega)$ is dense in $L^\infty (\Omega)$ w.r.t. $\sigma(L^\infty, L^1)$.

Fix $\varphi \in \mathcal C^\infty_c(\Omega)$ such that $\|\varphi\|_\infty \le 1$. Let $P := \{x \in \Omega : \varphi (x) >0\}$. Then $P$ is open in $\Omega$. Fix $\varepsilon >0$.  By Lemma 1, there is $\psi \in \mathcal C_c^{\infty} (P)$ such that $\psi \ge 0, \|\psi\|_\infty \le 1$ and $|\int_P f^+ \varphi - \int_P f \psi| < \varepsilon$. We define $\overline \psi:\Omega \to \mathbb R$ by $\overline \psi (x) := \psi (x)$ if $x \in P$ and $0$ otherwise. Then $\overline \psi \in \mathcal C_c^{\infty} (\Omega)$ such that $\overline \psi \ge 0, \|\overline \psi\|_\infty \le 1$ and
$$
\int f^+ \varphi \le \int_P f^+ \varphi \le \varepsilon +\int_P f^+ \psi   = \varepsilon +\int f^+ \overline \psi.
$$
Let $\varepsilon \downarrow 0$, we get
$$
A = \sup \left \{\int f^+ \varphi : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \text{ and } \varphi \ge 0 \right\}.
$$
Fix $\varphi \in \mathcal C^\infty_c(\Omega)$ such that $\|\varphi\|_\infty \le 1$ and $\varphi \ge 0$. Let $P := \{x \in \Omega : f (x) >0\}$. Then $\int f^+ \varphi = \int_P f \varphi$. Fix $\varepsilon >0$. Because Lebesgue measure is outer regular, there is an open subset $Q$ of $\Omega$ such that $P \subset Q$ and
$$
\bigg | \int_P f \varphi - \int_Q f \varphi \bigg |< \varepsilon.
$$
By Lemma 1, there is $\psi \in \mathcal C_c^{\infty} (Q)$ such that $\psi \ge 0, \|\psi\|_\infty \le 1$ and $|\int_Q f \varphi - \int_Q f \psi| < \varepsilon$. We define $\overline \psi:\Omega \to \mathbb R$ by $\overline \psi (x) := \psi (x)$ if $x \in Q$ and $0$ otherwise. Then $\overline \psi \in \mathcal C_c^{\infty} (\Omega)$ such that $\overline \psi \ge 0, \|\overline \psi\|_\infty \le 1$ and
$$
\int f^+ \varphi \le \varepsilon +\int_Q f \varphi \le 2 \varepsilon + \int_Q f \psi   = 2\varepsilon +\int f \overline \psi.
$$
Let $\varepsilon \downarrow 0$, we get
$$
\begin{align}
A &\le \sup \left \{\int f \varphi : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \text{ and } \varphi \ge 0 \right\} \\
&= B.
\end{align}
$$
The claim then follows from below result, i.e.,

Lemma 2 $f \in L^1 (\Omega)$ IFF
$$
A := \sup \left \{\int f \varphi : \varphi \in \mathcal C^\infty_c(\Omega) \text{ s.t. } \|\varphi\|_\infty \le 1 \right\} < \infty.
$$
If $f \in L^1 (\Omega)$ then $A = \|f\|_1$.
Comment: @FShrike the former thread is about when $f \in L^1 (\Omega)$ whereas the latter about when $f^+ \in L^1 (\Omega)$.
Comment: @Analyst: I have posted a related result from where you can prove the statement in your OP and of the posting referred by FShrike. It is not based in weak topology and just on density arguments.
Comment: https://math.stackexchange.com/q/4676501/815585

Not quite sure what is the difference
Answer: There is another interesting result along these lines:
Suppose $X$ is a locally compact Hausdorff space (l.c.H), and $\mu$ a Radon measure defined on the Borel sets $\mathscr{B}(X)$ in $X$. Denote by $C_{00}(X)$ the space of all real valued continuous functions on $X$ that have compact support, and by $C_{00}(X;\mathbb{C})$ the space of all complex-valued continuous functions of compact support.

Theorem: Let $f\in L^{loc}_1(\mu)$ and $g\in C^+_{00}(X)$. If $f$ is real valued, then
\begin{align}
\int f^+g\,d\mu&=\sup\left\{\int fh\,d\mu: h\in C_{00}(X),\, 0\leq h\leq g\right\} \tag{1}\label{one}\\
\int |f|g\,d\mu&=\sup\left\{\int fh\,d\mu: h\in C_{00}(X),\,  |h|\leq g\right\} \tag{2}\label{two}
\end{align}
If $f$ is complex, then
\begin{align}
\int |f|g\,d\mu&=\sup\left\{\Big|\int fh\,d\mu\big|: h\in C_{00}(X;\mathbb{C}),\,  |h|\leq g\right\}\tag{3}\label{three}
\end{align}
The space $C_{00}(X)$ can be replace by other space of bounded functions that is dense in $L_1(\mu)$; for example, if $X=[0,1]$, one my consider step functions.

Proof: Without loss of generality, we may assume that $f\in L_1(X)$. For $\varepsilon>0$, there is $f_1\in C_{00}(X)$ such that
$$\int|f-f_1|g\,d\mu<\frac{\varepsilon}{3}$$
Notice that if $f$ is real, then $f_1$ can be chosen to be real, which we will do if that case. Let $K=\operatorname{supp}(f_1)$ and let $U$ be an open set with compact closure such that $K\subset U$. Let $h\in C_{00}(X)$ such that $0\leq h\leq 1$, $h=1$ on $K$ and $h=0$ on $X\setminus U$.
For $\delta>0$, define the function
$$\phi_\delta=\frac{\overline{f_1}}{|f_1|+\delta h}$$
on the support of $h$ and $0$ otherwise;
and if $f$ is real,
$$\psi_\delta=\frac{f^+_1}{f^+_1 +\delta h}$$
on the support of $h$ and $0$ otherwise. Since $\phi_\delta=0=\psi_\delta$ on $U\setminus K$, $\phi_\delta$ and $\psi_\delta$ are continuous and of compact support;  by definition, $|\phi_\delta|\leq1$ and $0\leq \psi_\delta\leq 1$.  Notice that $\phi_\delta\xrightarrow{\delta\rightarrow0}\frac{\overline{f_1}}{|f_1|}$ and $\psi_\delta\xrightarrow{\delta\rightarrow0}\mathbb{1}_{\{f_1>0\}}=\frac{f^+_1}{f_1}$ pointwise on $X$.
If $f$ is real, then by dominated convergence, there is $\delta>0$ small enough so that
$$
\int|f^+_1g-f_1\psi_\delta g|<\varepsilon/3
$$
Then
\begin{align}
\int f^+g-f\psi_\delta g&\leq \int (f^+-f^+_1)g+\int f^+_1g-f_1\psi_\delta g+ \int f_1\psi_\delta g-f\psi_\delta g\\
&\leq2\int|f-f_1|g+\int|f^+_1g-f_1\psi_\delta g|<\varepsilon
\end{align}
Hence
$$\int f^+g\,d\mu<\int f\psi_\delta g\,d\mu+\varepsilon$$
This implies \eqref{one}.
Generally, for $f$ complex,  dominated convergence yields $\delta>0$ small enough so that
\begin{align}
\int \big||f_1|g -f_1 \phi_\delta  g\,d\mu\big|\,d\mu<\varepsilon/3
\end{align}
Then
\begin{align}
\Big|\int(|f|g- f\phi_\delta g)\Big| &=\left|\int(|f|-|f_1|)g + \int|f_1|g- f_1\phi_\delta g +\int f_1\phi_\delta g-f\phi_\delta g\right|\\
&\leq\int|f-f_1|g +\int\big||f_1|g -f_1 \phi_\delta  g\big|+\int|\phi_\delta||f-f_1|g\\
&\leq2\Big(\int|f-f_1|g\Big)+\frac{\varepsilon}{3}<\varepsilon
\end{align}
Hence
$$\int|f|g\,d\mu\leq \big|\int f\phi_\delta g\,d\mu\big|+\varepsilon$$
This implies that \eqref{three} (if $f$ is real, \eqref{two} follows in a similar fashion).
Comment: The problem in the OP can be derived from Theorem 1 above by first approximating  as follows. Choose $f_1\in C_{00}(X)$ such that $\|f-f\_1\|_1<\varepsilon/2$. Let $K=\operatorname{supp}(f_1)$, and $h\in C_{00}(X)$ with $0\leq h\leq 1$ such that $h=1$ on $K$ and $0$ outside a compact neighborhood $U$ of $K$, and  let $f_2=f_1h$. Notice that  $f_1=f_1=0$ and so
\begin{align}
\int|f-f_1h|<\varepsilon/2
\end{align}
Apply Theorem 1 to $f_1h$.