Is it consistent for $P(\mathbb{N})$ to be present in a low layer of the Constructible Universe?

Question: $ZF+V=L$ implies that $P(\mathbb{N})$, the power set of the set of natural numbers, is a subset of $L_{\omega_1}$.  But my question is, is it consistent with $ZF$ if $P(\mathbb{N})$ is a subset of $L_{\omega+1}$, i.e. the only subsets of $\mathbb{N}$ are arithmetical sets?  Most mathematicians would definitely think it's a false statement, but is it inconsistent with either $ZF$ or $ZFC$?
The reason I ask is that this is basically Bertrand Russell's Axiom of Reducibility.
Comment: Any subsets of $\Bbb N$ in $L$ are also subsets of $\Bbb N$ in the actual universe. If $L$ cannot capture all the subsets of $\Bbb N$ in the first transfinite step of the constructible hierarchy, what hope do larger class-models have?
Comment: If $L$ is the smallest inner model, how can that even be possible?
Comment: @KeshavSrinivasan Elaborating on Asaf's comment: if $M$ is a model of ZF, then $L^M$ is a model of ZF + V=L. So $L^M$ contains a real $r$ which $L^M$ thinks is not in $(L_{\omega+1})^M$. But clearly $r\in M$, and by absoluteness $M$ doesn't think $r\in (L_{\omega+1})^M$ either. So for any model $M$ of ZF, there is an $r\in \mathcal{P}(\mathbb{N})^M$ with $r\not\in (L_{\omega+1})^M$. (And the same argument works for any $\gamma<\omega_1^M$.)
Comment: @AsafKaragila What does $L$ being the smallest inner model have to do with anything?
Comment: For all "small" countable ordinals $\alpha$ (certainly for all $\alpha<\varepsilon_0$, for instance, in particular for $\alpha=\omega+1$) you can exhibit explicit sets of natural numbers that are in $L$ but first appear at $L_{\alpha+1}$, which gives you an explicit counterexample to the claim that $\mathcal P(\omega)\subset L_\alpha$.
Comment: Do the answers below clarify the issue? If not, what remaining questions do you have?
Comment: @NoahSchweber Your answer did clarify the issue, thanks.  I think the problem is that I didn't ask the question I really intended to ask.  Now I posted the question I should have asked in the first place: https://math.stackexchange.com/q/3247203/71829
Answer: No: $L_\alpha$ is countable for any countable $\alpha$, so it cannot contain all of $P(\mathbb{N})$.
Comment: Do you know what exact axioms are used to prove that $L_{\omega+1}$ is countable?
Comment: @KeshavSrinivasan Few enough that it doesn't seem a good question. In particular, note that there's an obvious surjection from $\omega\times L_\omega$ to $L_{\omega+1}$ which you can define as long as you can talk about theories of structures, and the Ackermann interpretation gives an as-concrete-as-imaginable bijection between $L_\omega$ and $\omega$. In particular, KP + infinity is already overkill.
Comment: The body of your question, though, rephrases things even more simply: you ask whether it's consistent that every set of naturals is arithmetic. Well, it's easy to show that if the theory of $(\mathbb{N};+,\times)$ exists, then it's not arithmetic, so again as soon as you can talk about the set of natural numbers and can talk about theories of structures that's already too much. So it's really impossible to escape this without killing so much of set theory that I'm not sure what's left.
Comment: @NoahSchweber What about Zermelo set theory, i.e. ZF without replacement?  Does that suffice that $P(\mathbb{N}$ contains things other than arithmetical subsets?  And what do you mean by "if the theory of $(ℕ;+,×)$ exists, then it's not arithmetic"?
Comment: @KeshavSrinivasan I'm not sure what your last question means. The theory of $(\mathbb{N}; +,\times)$ is the set of Godel numbers of sentences $\varphi$ such that $(\mathbb{N}; +,\times)\models\varphi$. This is definable in set theory (indeed, we can uniformly define truth of *set-sized* structures), and we can prove that, if it exists, it's not arithmetic.
Comment: And yes, Zermelo set theory is again *far more* than is necessary. It will help to first consider the example of $\omega$-models for simplicity (so we don't have to think about nonstandard sentences). The point is that for every sentence of arithmetic $\varphi$, there is an *arithmetic* witness (= appropriate family of Skolem functions, or similar) to the truth of $\varphi$ or the truth of $\neg\varphi$; so when we apply Separation to get the set of sentences true in $\mathbb{N}$, we in fact get a complete consistent theory. It's not hard now to run the usual argument that it's not arithmetic.
Comment: Here's a way to think about things which is actually more axiomatically complicated but perhaps less intuitively complicated: look at the set $\mathcal{W}$ of computable well-orderings without descending sequences. This exists by Z (separation), but it's not hard to show (in RCA$_0$, even) that this set isn't arithmetic. Now this is axiomatically harder - KP + Inf alone does *not* prove that $\mathcal{W}$ exists - but it doesn't involve any model-theoretic ideas.
Answer: Let me compile my comments into an answer. I'll first explain (elaborating on Asaf's comment) why every model of ZF contains (things it thinks are) sets of naturals which (it thinks) have $L$-rank arbitrarily high below $\omega_1$. Then I'll talk about the relevant axiomatic strength.

If $M$ is a model of ZF, then $L^M$ is a model of ZF + V=L. So $L^M$ contains a real $r$ which $L^M$ thinks is not in $(L_{\omega+1})^M$. But clearly $r\in M$, and by absoluteness $M$ doesn't think $r\in (L_{\omega+1})^M$ either. So for any model $M$ of ZF, there is an $r\in \mathcal{P}(\mathbb{N})^M$ with $r\not\in (L_{\omega+1})^M$.
And the same argument works for any $\gamma<\omega_1^M$: if $\gamma<(\omega_1)^{L^M}$ then $L^M$ has a real $r$ it thinks has $L$-rank $>\gamma$, and this lifts to $M$.

Alright, so now let's talk about better logical strength bounds.
First, let me give an argument which gives a non-optimal upper bound but is rather elementary. Let $\mathcal{W}$ be the set of (indices of) computable linear orders without descending sequences. Any reasonable set theory at all (by far less than Z or KP or similar) proves that if $\mathcal{W}$ exists then it is non-arithmetic (indeed, RCA$_0$ proves this, appropriately phrased!). In particular, by Separation Zermelo set theory proves that there is a non-arithmetic set.
Unfortunately, the existence of $\mathcal{W}$ has rather high axiomatic strength; KP + Inf, for example, doesn't prove it exists. To bring things down we need to do some model theory. Inside any model of a tiny fragment of set theory - both Z and KP are already more than enough - truth for set-sized structures is definable (uniformly in the structure, even). Roughly speaking, a sentence $\varphi$ is true in $\mathcal{M}$ if there exists a family $\mathbb{F}$ of functions from finite powers of $\mathcal{M}$ to $\mathcal{M}$ which serve as Skolem functions for $\varphi$. This definition takes place (essentially) in $(\mathcal{P}(\mathcal{M}))^{<\omega}$, not in $\mathcal{M}$ itself, so we don't run up against Tarski here.

This definition is just a piece of language; where the theory comes in is showing that $(i)$ for all $\mathcal{M}$ and $\varphi$ either $\mathcal{M}\models\varphi$ or $\mathcal{M}\models\neg\varphi$ and $(ii)$ $Th(\mathcal{M})$ (=$\{\varphi: \mathcal{M}\models\varphi\}$) exists.

Now the proof of Tarski's undefinability theorem goes through in a very very tiny fragment of ZFC, and so in particular we have that the theory of the natural numbers (as a semiring) is not arithmetic.


Books/online notes for analytic maps in Banach spaces

Question: Can anyone suggest some good books/online notes on (real) analytic maps between Banach spaces? I am looking for the basic definitions and the implicit function theorem in this setting. Thanks!
Answer: I found to be useful these books
Analytic Theory of Global Bifurcation: An Introduction
Boris Buffoni and John Toland
https://press.princeton.edu/books/hardcover/9780691112985/analytic-theory-of-global-bifurcation
Zeidler, Nonlinear Functional Analysis and its Applications
I: Fixed-Point Theorems
https://link.springer.com/book/9780387909141


Get Number and Name From Array PHP

Question: I've created an array that contains the elements of an order:
Array ( [0] => M8 [1] => M8 [2] => U- )
(it gets the first 2 chars from the title in the foreach loop - its all i need)
I need to know how many M8's come up in this array.
basically if they buy 2 or more M8's then they get a free item. But if they buy 1 M8 and a U- they get nothing.
There will also be other products too:
Array ( [0] => M8 [1] => M8 [2] => U- [3] => D8)
if they buy an M8 and a D8 they get a free item as well
so its not just based off quantity its based off how many items they buy and the product ID (m8,d8 ect..)
a free item with any d8 and m8 purchase, or free item with any 2 d8 or and 2 m8
thanks.
Answer: There's a function for that:
https://www.php.net/manual/en/function.array-count-values.php
Should return an array like array('M8' => 2, 'U-' => 1, etc. etc.)
Edit: For example.
<code><?php
$counts = array_count_values($input);
if(isset($counts['M8']) && $counts['M8'] >= 2)
{
   //Do special things when 2 M8's are present.
}
</code>

Get Number and Name From Array PHP


Generating a random number from date in a reproducive manner in PHP

Question: I have been struggling with a problem for a while now.
Namely I need to generate a number in range 1 - 50 using a date. What I mean is if I run a some piece of code withing a specific date, it should produce me the same number for that day. If the date changes it should produce me a different number in defined range and preferably that does not show pattern with numbers generated in previous dates (constantly rising for example). I believe it can't be done with some mathematical linear function since the graph of that function would always produce me a pattern how the numbers are changing in time. Perhaps there is some function that is used in cryptography that would help?
Answer: seed your random generator via srand
If the input number should does not change for the day then your random returns will be predictable for that day.
You can use the number of days since 1970, or the day of the month as a seed value
Answer: Just use a hashing algorithm on your date convert it to a number and define an upper bound using modulo e.g.:
<code>$yournumber = hexdec( sha1($date) ) % 50;
</code>


Can I plug a regular distortion pedal in front of a Zoom G5 multi-effects?

Question: I'm wondering if I'm risking some kind of electrical damage while plugging a regular disto pedal (or other kinds of gain pedals) on the guitar input of a multi effect expecting a passive/active guitar.
Thanks in advance
Comment: And failing the sense of adventure, what happened to reading the manual: https://zoomcorp.com/media/documents/G5_operationManual_english.pdf? (P5 might give you a clue...)
Comment: I thought "this is the switch to use if you want to use a pedal on the input" was pretty clear
Comment: What happened to the sense of adventure? I'm picturing Jimi Hendrix wondering whether putting a fuzz box in front of his Marshall might hurt it… deciding not to & depriving the world...
Comment: @Tom - 'fraid not ;) Closest I ever got to a Hendrix story is I once drove past the pub in Clonakilty that Noel Redding was playing at… not really one to write home about, in the overall scheme of things ;) https://www.thejournal.ie/de-barras-clonakilty-3915699-Mar2018/
Comment: @tetsujin Any interesting anecdotes on that :P?
Comment: @Tetsujin I would have tryied If I stayed unto in analogic path but ever since I burned 2 usb / jack Cable putting them on the output bypassed of the G5 so ...
Comment: Guess I haven't read it all, I expected that setting active was the way but I wasn't sure it was enough for a disto gain, thanks for pointing that out
Comment: @DavidW could you formulate it as an answer so I can validate it ?
Answer: Page 5 of the manual says that about the "active/passive" switch:

set  this  to  "ACTIVE"  (pushed  in)  if you  have  an  effect  pedal  connected between your instrument and the G5 or you are directly connecting a guitar with active pickups

Therefore I think it's fine to have an effects pedal in front of it.
In the troubleshooting section it mentions using this switch if "the sound distorts strangely" suggesting that the likely consequence for having it set wrong is a bit of unwanted distortion (i.e. it probably won't break the G5, but may sound a bit bad)
Answer: There is no issue with plugging in an effect pedal in front of such multi-effect pedal.
Note however that a digital effect might have a limited input range, so you may end up clipping the multi-effect input if you try to use overdrive pedal to boost the input signal, similarly to how people do in front of real amps. But again, it's unlikely to damage anything.


Nusoap retorno $HTTP_RAW_POST_DATA vazio

Question: Estou tentando criar um WebService utilizando o nusooap. Porém o meu retorno é sempre vazio. Online é criado o webService e eu consigo ver os métodos e o xml (WSDL). Mas ao tentar acessar via cliente.php o retorno é vázio.
teste-server.php
require_once "php/class/nusoap-0.9.5/lib/nusoap.php";

$soap = new soap_server;

  $soap->configureWSDL('WS-WebCodeFree', 'http://www.philipsvaloriza.com.br/teste-server.php');

  $soap->wsdl->schemaTargetNamespace = 'http://www.philipsvaloriza.com.br/teste-server.php';

    $soap->register(
        'info',
        array(),
        array('x' => 'xsd:string'),
        'http://soapinterop.org/'
    );

    $soap->register(
        'post_java',
        array(),
        array('x' => 'xsd:string'),
        'http://soapinterop.org/'
    );

    $soap->register(
        'post_php',
        array(),
        array('x' => 'xsd:string'),
        'http://soapinterop.org/'
    );

    $soap->register(
        'login_user',
        array('login' => 'xsd:string','pass' => 'xsd:int'),
        array('x' => 'xsd:string'),
        'http://soapinterop.org/'
    );

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : 'teste123';
$soap->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '');

function info(){
    return "WebCodeFree - Desenvolvimento Web.";
}

function post_java(){
    return "Em Breve Acesso a Postagens Java Via Serviço";
}

function post_php(){
    return "Em Breve Acesso a Postagens PHP Via Serviço";
}

function login_user($login, $senha){
    return "Seja Bem Vindo Usuário ". $login . " !!!";
}

cliente.php
include('lib/nusoap.php');

        $cliente = new nusoap_client('http://localhost/vinicius/thiengo/doc/projects/web-service-php-nusoap/servidor.php?wsdl');

    $result1 = $client->call('info');

    $result2 = $client->call('post_java');

    $result3 = $client->call('post_php');

    $result4 = $client->call('login_user', array('Paulo',12));

    echo $result1."
";
    echo $result2."
";
    echo $result3."
";
    echo $result4."
";

Referência: http://www.webcodefree.com.br/blog/?p=1480
Comment: Qual éa versão do php? 5.6?
Comment: Sim @rray o servidor está utilizando o PHP 5.6
Answer: O uso de $HTTP_RAW_POST_DATA é obsoleto desde o php5.6 e removido no php7. Em seu lugar use:
$info = file_get_contents('php://input');

Comment: Eu subistitui o "$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : 'teste123';
$soap->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '');" por "$postData = file_get_contents('php://input'); $soap->service(isset($postData));". Mas o retorno continua vázio. Sabe me dizer se a forma de utilizar a classe nusoap tb muda?
Comment: @alan tira esse `isset()` de `$soap->service(isset($postData))`
Comment: Eu retirei. E mesmo assim o retorno continua vázio. Também criei um arquivo no servidor: "$file = fopen('arquivo.txt', 'w');
fwrite($file, $postData);" e ele criou o arquivo em branco. Por algum motivo a variável $postData não está recebendo valor.
Comment: @alan tentou fazer a chamada com soup_client (nativo) do php?
Comment: Não. fiz os testes apenas com nusoop_client. Vou fazer um teste.


Probability distribution function of $Z=\frac{Y}{X+1}$

Question:
I have two random variable $X,Y$ in the same space $(\Omega,\mathcal{F},\mathcal{P)}$.
$X$ takes its values on $\Bbb{N}$, I denote $P(X=k):=p_k$ and $Y$ takes its values on $\Bbb{R}$? and denote $H$ his probability distribution function.

I would like to express $Z=\frac{Y}{X+1}$ in function of $H$ and $p_k$.
I know that $F_X(x)=\sum_{n\in \Bbb{N}}p_k$ but writing $F_Z(x)=P(Z\le x)=P(\frac{Y}{X+1}\le x)$ doesn't seems to 'simplify' is something about $p_k$ or $H$.
Any ideas?
Answer: Since no information about the joint distribution, only the marginals, of $X$ and $Y$ is given, how about the following (if $X$ and $Y$ are independent):
$$
\begin{eqnarray*}
F_{Z}(z)&{}:={}&P\left(\dfrac{Y}{X{}+{}1}{}\leq{} z\right)\newline
&{}={}&P\bigg(Y{}\leq{} z\left(X{}+{}1\right)\bigg)\newline
&{}={}&\sum\limits_{x=1}^{\infty}P\bigg(Y{}\leq{} z\left(x{}+{}1\right)\bigg|X{}={}x\bigg)P\left(X{}={}x\right)\newline
&{}={}&\sum\limits_{x=1}^{\infty}H\bigg(z(x+1)\bigg)p_x\,.
\end{eqnarray*}
$$
Comment: The problem is that $X,Y$ are not independent, but perhaps it's an oversight. +1 anyway.


Azure Data Factory Python SDK - Convert PipelineResource to JSON

Question: I am creating Azure Data Factory pipeline using Python SDK (azure.mgmt.datafactory.models.PipelineResource). I need to convert PipelineResource object to JSON file. Is it possible anyhow?
I tried json.loads(pipeline_object) , json.dumps(pipeline_object) but no luck.
Answer: you can use this.
# Create a copy activity
act_name = 'copyBlobtoBlob'
blob_source = BlobSource()
blob_sink = BlobSink()
dsin_ref = DatasetReference(reference_name=ds_name)
dsOut_ref = DatasetReference(reference_name=dsOut_name)
copy_activity = CopyActivity(name=act_name,inputs=[dsin_ref], outputs=[dsOut_ref], source=blob_source, sink=blob_sink)

#Create a pipeline with the copy activity

#Note1: To pass parameters to the pipeline, add them to the json string params_for_pipeline shown below in the format { "ParameterName1" : "ParameterValue1" } for each of the parameters needed in the pipeline.
#Note2: To pass parameters to a dataflow, create a pipeline parameter to hold the parameter name/value, and then consume the pipeline parameter in the dataflow parameter in the format @pipeline().parameters.parametername.

p_name = 'copyPipeline'
params_for_pipeline = {}

p_name = 'copyPipeline'
params_for_pipeline = {}
p_obj = PipelineResource(activities=[copy_activity], parameters=params_for_pipeline)
p = adf_client.pipelines.create_or_update(rg_name, df_name, p_name, p_obj)
print_item(p)

Answer:
I need to convert PipelineResource object to JSON file. Is it possible anyhow?

You can try the following code snippet as suggested by mccoyp:
You can add a default argument to json.dumps to make objects that are not JSON serializable into dict
import json
from azure.mgmt.datafactory.models import Activity, PipelineResource

activity = Activity(name="activity-name")
resource = PipelineResource(activities=[activity])

json_dict = json.dumps(resource, default=lambda obj: obj.__dict__)
print(json_dict)


Angular 2 - Receiving a POST Response Header with Content-Length > 0 but no content

Question: With Angular 2 I'm using Http.post() to retrieve some JSON data. When I use cURL or HttpRequestor everything works correctly. However, with Angular I'm getting a Response Header with Content-Length > 0 but the Response itself has no data.
public retrieveJsonData() {
    var url = 'https://somewhere.com/whatever/GetItem?token=XXXX&resource=YYYY&data=%7B%22id%22%3A2207%7D';
    let options = new RequestOptions({});

    return this.http
        .post(url, '', options)
        .map(result => result.json())
        .catch(this.handleError);
}

Request Headers:
POST /whatever/GetItem?token=XXXX&resource=YYYY&data=%7B%22id%22%3A2207%7D HTTP/1.1
Host: somewhere.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:8888/
Content-Length: 0
Content-Type: text/plain;charset=UTF-8
Origin: http://localhost:8888
Connection: keep-alive

Response Headers:
HTTP/1.1 200 OK
Date: Tue, 12 Apr 2016 22:49:23 GMT
Server: Apache/2.2.15 (CentOS) mod_ssl/2.2.15 OpenSSL/1.0.1e-fips
Set-Cookie: Foo=6djdhg7pnsqavk0nqa83u7rqt6; path=/; secure
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 1311
Keep-Alive: timeout=15, max=1000
Connection: Keep-Alive
Content-Type: text/json

So in this example the Content-Length = 1311 but the response is empty. If I use a tool like HttpRequester the POST works as expected and the response is 1311 characters. What is going on?
Comment: You can see response body in your browser developer tools like firebug, if response is correct, then it means you have error in your code. It looks like you want to use GET, but current method is POST.
Comment: The request and response headers above are copied directly from Firebug. A POST request is required for this call and works correctly in environments other than Angular 2.
Answer: Here is how I do post requests
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post(url, JSON.stringify({firstName:'Joe',lastName:'Smith'}),{headers:headers})
            .map((res: Response) => res.json())
            .subscribe((res:Person) => this.postResponse = res);

Try this after replacing with your values.


Continuity in argument of minimization

Question: Let
$$g(c) = \min_{Ax=c} f(x),$$
where $x$, $c$ are vector-valued, $A$ is a matrix and $f$ is a smooth convex function. Under what conditions can we say $g(c)$ is continuous in $c$?
Answer: If $A$ is a bijection, then this is trivial, because you only changed coordinates with an affine transformation.
Otherwise, the map $Ax=c$ defines a continuous sequence of "slices" (a linear foliation of space) parameterized by $c$: $X=\{x,Ax=c\}$ is the preimage of $A$ (returns a vector subspace of the dimensionality of the kernel of $A$, with the requirement that $c$ is in the image of $A$, which restricts the domain of $g(c)$).
If $c$ is a scalar ($A$ is of rank $1$, $X$ is a hyperplane of dimension $n-1$), you proceed as such:
When the path of the minimum $\vec{x}(c)$ (where $g(c)=f(\vec{x}(c))$) itself is continuous, there is no problem, because the value of a continuous function on a continuous subdomain is also continuous.
Another possibility would be that two local minima exchange in which is the global minimum. In this case, consider two "trajectories" of local minima:
$$g(c)=\min(f(\vec{x}_1(c)),f(\vec{x}_2(c)))$$
Because on both trajectories, the function is continuous, and they interchange, they must have an intersection (there is $c$ where the values are equal). So, $g(c)$ is also continuous in this case.
Moreover, this cannot happen if $f$ is convex: on a hyperplane $X$, which slices the entire space, $f$ is also convex. Therefore, it can only have one extremum, and there is always only one trajectory $\vec{x}(c)$ which is both local and global minimum for a given $c$. Moreover, convexity ensures that the function is bounded from below, so the minimum always exists.
In conclusion, $g(c)$ is continuous if $c$ is a scalar and f is a smooth convex function.
For ranks $r>1$, continuity can be checked line-wise: for every subdomain $\vec{c}=\vec{c}_0+\vec{s}t$ for $t\in \mathbb{R}$, $g(\vec{c}_0+\vec{s}t)$ is continuous for the reasons above. Therefore, it is continuous as a whole (if no "cut" has a jump, the entire thing has no jumps).

Continuity in argument of minimization


Histograma 3D usando ggplot2

Question: Tenho dados de uma distribuição bidimensional, por exemplo, uniforme. Desejo fazer um histograma com esses dados. Tentei o pacote plot3D, mas não ficou muito legal.
teste = matrix(runif(100), ncol = 10)

plot3D::hist3D(z = teste, bty = "g", phi = 15,  theta = -15,
                   xlab = "X1", ylab = "X2", zlab = "Relative frequency", main = "Teste",
                   col = NULL, border = "black", shade = 0.8, curtain = T, plot = T,
                   ticktype = "detailed", space = 0.15, d = 2, cex.axis = 1e-9, image = T, contour = T)

Answer: No seu caso eu faria um gráfico assim:
library(ggplot2)
library(tidyr)
library(dplyr)
teste %>% data.frame() %>%
  mutate(x = 1:10) %>%
  gather(y, z, -x) %>%
  mutate(y = y %>% gsub("X", "", .) %>% as.numeric()) %>%
  ggplot(aes(x, y)) +
  geom_raster(aes(fill = z))

Nele você tem a mesma informação que no gráfico 3d (abaixo) porém (ao meu ver) é
muito mais fácil de enxergar. Na verdade, acho que nenhum gráfico em 3D ficaria bom.
Comment: Concordo que sua sugestão é melhor que o gráfico 3D. Por sinal, este tipo de gráfico se chama *heatmap*.

Histograma 3D usando ggplot2


A question about proving that there is no greatest cardinal

Question: I would like to know if it is possible to prove that there is no greatest cardinal without axiom of choice
Comment: Related: http://math.stackexchange.com/questions/304378/do-you-need-the-axiom-of-choice-to-accept-cantors-diagonal-proof ; http://math.stackexchange.com/questions/284812/a-reverse-diagonal-argument/284834#284834
Answer: This is just Hartogs theorem, stating that if $X$ is any set, then there is an ordinal which admits no injections into $X$.
If $\alpha$ is any ordinal, then $\alpha$ can be mapped into $\mathcal P(\alpha)$, which has a larger cardinality, so by Hartogs theorem there is an ordinal of cardinality larger than $\alpha$. Namely, if $\alpha$ was a cardinal, then there has to be a larger cardinal than $\alpha$.
It should also be noted that without the axiom of choice, the class of cardinals contains more than just ordinals. So appealing toe Cantor's theorem works just fine, as it ensures that there is no maximal cardinal.


rsyslog : logs in double in my file

Question: I've configured my firewall to send logs to rsyslog.
But all logs appears twice.
<code>cat fortigate100D | grep "sessionid=97294098"
Jun 27 11:24:16 date=2016-06-27 time=11:24:16 logid=0000000013 type=traffic subtype=forward level=notice vd=root poluuid=49990e52-2bfa-51e5-e6c1-523e6d971a8b sessionid=97294098 ...
Jun 27 11:24:16 date=2016-06-27 time=11:24:16 logid=0000000013 type=traffic subtype=forward level=notice vd=root poluuid=49990e52-2bfa-51e5-e6c1-523e6d971a8b sessionid=97294098 ...
</code>
I've configured my forti to send to local0.
Here's my rsyslog.conf
<code># rsyslog configuration file

# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html

#### MODULES ####

# The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal
#$ModLoad imklog # reads kernel messages (the same are read from journald)
#$ModLoad immark  # provides --MARK-- message capability

# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514

# Provides TCP syslog reception
ModLoad imtcp
$InputTCPServerRun 514

#### GLOBAL DIRECTIVES ####
#Default file permission
$umask 0000
$FileCreateMode 0600

# Where to place auxiliary files
$WorkDirectory /var/lib/rsyslog

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not required,
# not useful and an extreme performance hit
#$ActionFileEnableSync on

# Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf

# Turn off message reception via local log socket;
# local messages are retrieved through imjournal now.
$OmitLocalLogging on

# File to store the position in the journal
$IMJournalStateFile imjournal.state

# AccessRights
action(type="omfile" fileOwner="root" fileGroup="logstash" FileCreateMode="0640" File="/var/log/fortigate100D")

#### RULES ####

# Save Forti100D to fortigate100D
local0.*                                                /var/log/fortigate100D
&~

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                                                 /dev/console

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages
local0.none

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

# Log all the mail messages in one place.
mail.*                                                  -/var/log/maillog

# Log cron stuff
cron.*                                                  /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 :omusrmsg:*

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log

# ### begin forwarding rule ###
# The statement between the begin ... end define a SINGLE forwarding
# rule. They belong together, do NOT split them. If you create multiple
# forwarding rules, duplicate the whole block!
# Remote Logging (we use TCP for reliable delivery)
#
# An on-disk queue is created for this action. If the remote host is
# down, messages are spooled to disk and sent when it is up again.
#$ActionQueueFileName fwdRule1 # unique name prefix for spool files
#$ActionQueueMaxDiskSpace 1g   # 1gb space limit (use as much as possible)
#$ActionQueueSaveOnShutdown on # save messages to disk on shutdown
#$ActionQueueType LinkedList   # run asynchronously
#$ActionResumeRetryCount -1    # infinite retries if host is down
# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
#*.* @@remote-host:514
# ### end of the forwarding rule ###
</code>
Answer: i've made it via logstash.
https://discuss.elastic.co/t/logstash-duplicate-message/26096/3
thanks

rsyslog : logs in double in my file


Why do I get error C2440 when I try to compile XPCOM code?

Question: I need to create a Firefox addon that calls C++ code. I did some research and found this tutorial to get me started: http://briankrausz.com/building-a-c-xpcom-component-in-windows/
I followed all the steps but got stuck in the part where I need to compile the code using VS. I'm using VS 2005.
To be more specific, I have a project that contains 2 header files (IMyComponent.h & MyComponent.h) as well 2 cpp files (MyComponent.cpp & MyComponentModule.cpp).
Each cpp file is configured to compile with no CLR support and without precompiled headers.
However, when I attempt to compile, I get 3 C2440 error messages that correspond to the following lines of code:
//MyComponentModule.cpp

#include "nsIGenericFactory.h"
#include "MyComponent.h"

NS_GENERIC_FACTORY_CONSTRUCTOR(MyComponent)

static nsModuleComponentInfo components[] =
{
    {
      MY_COMPONENT_CLASSNAME,
      MY_COMPONENT_CID,          //'initializing': cannot convert from const char[37]    to PRUint32
      MY_COMPONENT_CONTRACTID, //'initializing': cannot convert from const char[39] to    PRUint16
      MyComponentConstructor, //'initializing': cannot convert from nsresult (__stdcall *)(nsISupports *, const nsIID &, void **) to PRUint16
   }
};

NS_IMPL_NSGETMODULE("MyComponentsModule", components)

In the correspond header file I have the following code:
//MyComponent.h

#ifndef _MY_COMPONENT_H_
#define _MY_COMPONENT_H_

#include "IMyComponent.h"

#define MY_COMPONENT_CONTRACTID "@example.com/XPCOMSample/MyComponent;1"
#define MY_COMPONENT_CLASSNAME "A Simple XPCOM Sample"
#define MY_COMPONENT_CID "4c6f45e0-6366-4c69-Ab68-bb3c75cdada3"

class MyComponent : public IMyComponent
{
public:
 NS_DECL_ISUPPORTS
 NS_DECL_IMYCOMPONENT

 MyComponent();

private:
  ~MyComponent();

protected:
  /* additional members */
};

#endif //_MY_COMPONENT_H_

All the other code was generated using the xpidl.exe tool included with the Gecko SDK.
Can someone please give some hints?
PS: Here is the nsModuleComponentInfo:
 struct nsModuleComponentInfo {
 const char*                                 mDescription;
 nsCID                                       mCID;
 const char*                                 mContractID;
 NSConstructorProcPtr                        mConstructor;
 NSRegisterSelfProcPtr                       mRegisterSelfProc;
 NSUnregisterSelfProcPtr                     mUnregisterSelfProc;
 NSFactoryDestructorProcPtr                  mFactoryDestructor;
 NSGetInterfacesProcPtr                      mGetInterfacesProc;
 NSGetLanguageHelperProcPtr                  mGetLanguageHelperProc;
 nsIClassInfo **                             mClassInfoGlobal;
 PRUint32                                    mFlags;
 };

Comment: Can you also post the declaration of `nsModuleComponentInfo`?
Comment: You probably need someway to cast the data types. Sorry, I'm not more helpful for I don't know about the firefox technique but that is an error code that I'm sure you can see if self explanatory. It can't convert one datatype to the other. A `char[x]` is really an array of 1 byte(on most systems) `int`s. So it could possibly be that it's out of it's capability.?? [This](http://msdn.microsoft.com/en-us/library/sy5tsf8z(v=vs.80).aspx) is always helpful as well!
Comment: When you declare `components` it looks like you are missing a few pieces of data that should be at the beginning of the structure before `MY_COMPONENT_CLASSNAME`. In fact there are 3 member variables before  the Contract ID.
Comment: Chris, please see the original post. i have added the code you requested.
Comment: Just a note: you would be better off using [js-ctypes](https://developer.mozilla.org/en/js-ctypes) if possible (add your own library to the extension and call its exported functions). An XPCOM component needs to be recompiled for each Firefox release which is every 6 weeks.
Answer: The first error is because you are trying to pass in a char * instead of the required type.  This page:  https://developer.mozilla.org/en/Adding_XPCOM_components_to_Mozilla_build_system
at least mentions how to deal with the CID param:
{ "Friendly class description for people to read",
 YOUR_CLASS_CID,
 YOUR_CLASS_CONTRACTID,
 nsYourConcreteClassNameConstructor }

and
/* 2d96b3d0-c051-11d1-a827-0040959a28c9 */
#define NS_WINDOW_CID \
{ 0x2d96b3d0, 0xc051, 0x11d1, \
{0xa8, 0x27, 0x00, 0x40, 0x95, 0x9a, 0x28, 0xc9}}

Comment: I set MY_COMPONENT_CID to a value formatted like the one above and the code now compiles. Thanks


ReflectionException Class UsersTableSeeder does not exist , while i use composer dump-autoload still same error?

Question: <code>class UsersTableSeeder extends Seeder
{
    public function run()
    {
        User::create([
        'name'=> 'prakash',
        'username' => 'prakash',
        'number' => '*******',
        'active' => '1',
        'email'=> 'firstname.lastname@example.com',
        'password' => bcrypt('pokhrel215'),
        'remember_token'=> str_random(10),
        ]);
    }
}
</code>
I tried lots of time, but still same error what can I do?
I am a beginner at laravel.
Comment: What error you getting?
Comment: [ReflectionException] Class UsersTableSeeder does not exist
Comment: did you add this in the run() of the DatabaseSeeder class like this $this->call(UsersTableSeeder::class); i think that should solve your issue..although not a laravel expert
Comment: i tried but still same problem show , sir where i put "$this->call(UsersTableSeeder::class);" ,?? i am getting confuse
Answer: Make sure the database directory is included in the composer.json file:
<code>"autoload": {
        "classmap": [
            "database"
        ]
 }
</code>
All php files in that directory is scanned when "dumpautoload"-ing. Hope this helps!
Answer: I know this is coming in late, but it might help some future readers with similar problem.
Had this same issue and was able to solve it by doing composer dump-autoload in the root of my application
<code>$ composer dump-autoload
</code>
Comment: Thank you @Mena for that observation, I've corrected my answer.
Answer: Hey hi seeder should be like this
<code>```class UsersTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\User::class, 30)->create()->each(function($user) {
        $user->save();
       });
    }```
</code>
If you want to create a user that should be place in migration file not here. hope it will works for you


My Grails app issues http get requests for the same images (a js driven clock) repeatedly. What do I need to do so it doesn't do that?

Question: I have a Grails app (2.0 RC1) that uses a clock that is made up of images to display the time including seconds. The clock is a simple JavaScript function that gets the time and then updates the image source to show the correct image. The whole app and the clock in it are working just fine.
The problem I'm trying to solve is that each time the clock updates (i.e. once every second) the image source an http get request is sent to the server instead of using the cached images.
The images are precached when the page loads into Image() objects. The function then calculates the time and updates the image like this:
document.getElementById('hour1').src = eval('window.' + 'num' + hour1 + '.src')

where "num" + hour1 is the name of the Image() object to be displayed. The element in the gsp is an img tag.
I spent hours searching for an answer but to no avail... Do I have to use the "cached resources" plugin to get any caching? If so, could someone tell me how to use that in this case? I played around with that but haven't been able to get that to work yet...
Answer: First, don't use eval() like that.  Replace your eval() with this:
window["num" + hour1].src

Second, your browser will send the GET request and the server should respond with a 304 - Not Modified, which will then cause the browser to use the cached image.  Is your browser serving the image for each request, or is it sending a 304 status code?
Comment: Thanks for the quick response! From what I can see in Firebug the response is a 302 (sorry, not totally sure if I'm using that right). Funny thing is that the same javascript in a non-grails app doesn't send the constant requests. -- Actually, it does, just not as frequently. Sorry, I really don't know what I'm talking about here... is there any way to prevent all those requests going to the server? that's really what I'm trying to accomplish. (Thanks for the tip on the use of eval() btw.)
Comment: 302 is a redirect status. Perhaps if you change to use the url you are redirected to directly, that would solve your issue. I'm not very familiar with Grails... could it be modifying the URLs?
Comment: Watching for that some more, most responses actually are 200 OK responses and only some are 302 responses. So it seems it's actually serving the images each time. From what I found so far on Grails and caching it understand that it's not doing it out of the box. Looks like I need to do some more reading on this so I actually understand what's going on and check out the "cached resources" plugin some more.


How to process IEnumerable in batches?

Question: A lot of time my lists are too big tor process and i have to break them up into batches to process.
Is there a way to encapsulate this in a method or an extension. I seem to have to write this batching logic everywhere.
const int TAKE = 100;
int skip = 0;
while (skip < contacts.Count)
{
    var batch = contacts.Skip(skip).Take(TAKE).ToList();
    DoSomething(batch);
    skip += TAKE;
}

I would like to do something like -
Batch(contacts, DoSomething);

Or anything similar so i do not have to write this batching logic again and again.
Answer: Using the batch solution from this thread it seems trivial:
const int batchSize = 100;

foreach (var batch in contacts.Batch(batchSize))
{
    DoSomething(batch);
}

If you want to also wrap it up:
public static void ProcessInBatches<TSource>(
              this IEnumerable<TSource> source,
              int batchSize,
              Action<IEnumerable<TSource>> action)
{
    foreach (var batch in source.Batch(batchSize))
    {
        action(batch);
    }
}

So, your code can be transformed into:
const int batchSize = 100;

contacts.ProcessInBatches(batchSize, DoSomething);

How to process IEnumerable in batches?


Sample size for CI precision

Question: I am interested in calculating the required sample size to achieve some precision using a CI for the mean.
Let's say that I wish to build a 95% CI for the mean, so that the difference between the population mean and the sample mean won't be larger than 2 units (with 95% confidence), and I assume a S.D of 5 units. To do so, I play a bit with the formula, extract N, and being an exact calculation, I get what I want. In the case of t (rather than z), the computer will do it and give me N = 27. Now I tried to do it with SAS, and I found this source.
Apparently, SAS adds another dimension to the calculation, which is an equivalent to the power of hypothesis testing. I don't understand why is it necessary in the first place. Using the CI formula, if N = 27 give a precision of 2, isn't it enough ? For 80% "power" I get N = 32, and for 90% "power" I get N = 35, while all along I find N = 27 to be sufficient.
Can you please help me understand when should I use the simple direct method coming from the formula and when should I use this approach by SAS (and probably others)?
Comment: I think the SAS procedure and your CI formula are the same.
Comment: But they yield different N's, and in SAS I need to specify a "power", in my way I don't. It must take a role in the calculations. If we simplify and take Z for a second, then all I do is a bit of algebra. I do not have a power term in my formula.
Comment: Which formula did you use to calculate the power? probably I can show you they are the same.
Comment: I didn't calculate power. In SAS, you are required to add this term, I quote from their manual: "An analysis of confidence interval precision is analogous to a traditional power analysis, with CI Half-Width taking the place of effect size and Prob(Width) taking the place of power". Where in my way, the power doesn't exist, as all I do, is to play with the CI formula to extract N for the highest desired mu - Xbar value.
Comment: See here, this may explain: http://ncss.wpengine.netdna-cdn.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_One_Mean.pdf  and http://ncss.wpengine.netdna-cdn.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_One_Mean_with_Tolerance_Probability.pdf
Answer: (I don't have access to SAS, and don't get the same numbers as you in R or GPower.)
You and SAS are asking slightly different questions. You are asking what sample size you need when your mean is 2, to get p = 0.05.
SAS is telling you how likely it is that your result will be significant, given that the population mean is 2.
When you sample from a population where the mean is 2, you will sometimes get a higher value, and sometimes get a lower value, than 2. Both of these are equally likely. If the mean is exactly 2, then p will be 0.05, but the mean is less than 2, p will be greater than 0.05, and if the mean is greater than 2, then p will be smaller than 0.05. In other words, you have a 50% chance of getting a significant result.  What you have worked out is the sample size to get 50% power - a 50% chance of a significant result.
Most people want more than 50% power. With a larger sample size, a value smaller than 2 will still be significant. SAS is saying that if you want a significant result with 80% chance, you're going to need a bigger sample.
Answer: This is not an answer.
Did you try the following codes from the SAS manual? The SAS codes are for two sample t test. The first PASS manual you listed is for one sample test. The second PASS manual is for a tolerance interval which I think quite different from the ordinary confidence intervals.
<code>proc power;
twosamplemeans test=diff
meandiff = 5 6
stddev = 12 18
alpha = 0.05 0.1
ntotal = 100 200
power = .;
run;
</code>

Sample size for CI precision


How to find P(A and B and C) given all the marginal probabilities and two conditional probabilities w/r/t to same random variable A?

Question: Given marginal probabilities $P(A)$, $P(B)$, and $P(C)$ and conditional probabilities $P(A|B)$, $P(B|A)$, $P(A|C)$, and $P(C|A)$ is it possible to find $P(A\cap B \cap C)$ ?
Attempt:
$P(A \cap B \cap C) = P(A \cap B)\cap P(A \cap C)= P(B|A)\cdot P(A)\cap P(C|A)\cdot P(A)= P(A) [P(B|A) \cap P(C|A)] = P(A) \cdot [P(B|A | C|A)] \cdot P(C|A) = P(C) \cdot [P(B|A | C|A)] $
Can I distribute the conditioning variable? Are there useful properties I should know about? Any help is appreciated. My intuition tells me it should be possible to calculate $P(A\cap B \cap C)$. Any help appreciated.
Comment: Your notation does not make sense to me: after writing $P(A \cap B \cap C)$ you take the intersection of two real numbers: $P(A \cap B) \cap P(A \cap C)$. What exactly are you trying to do?
Answer: This is actually asking if we can find the joint with marginals and $P(A|C),P(A|B)$, i.e. knowing $P(C|A)$ and $P(B|A)$ doesn't provide additional information since they can be found via Bayes rule. First of all, we know nothing about the dependence relation between $B$ and $C$, and also we don't know what happens when we condition on two of the events, which should give you a heads up already. We can't do it.
Let's find an example. Assume event $A$ has nothing to do with the other events both jointly and mutually, i.e. $P(A|B)=P(A),P(A|C)=P(A),P(A|B,C)=P(A)$. (e.g. $A$ can represent the event of raining in Amazons today, where $B,C$ represents the probability of heads of the same (maybe biased) coin in different tosses). Then, $P(A,B,C)=P(A)P(B,C)$, and we can't calculate $P(B,C)$ with only $P(B)$ and $P(C)$.
Also, your solution attempt is not meaningful because of @MauritusM 's comment.
Answer: Let's say for simplicity that each variable $A$, $B$ and $C$ has only two states such that they jointly have $8$ states. As described in the answers to What is the number of parameters needed for a joint probability distribution? you will need $8-1=7$ independent parameters to describe this distribution.

You only have $5$ parameters $P(A)$, $P(B)$, $P(C)$, $P(B \vert A)$ and $P(C \vert A)$. Note that $$P(C \vert A) = P(A \vert C) P(C)/P(A)$$ and $$P(B \vert A) = P(A \vert B) P(B)/P(A)$$ are not independent from the other $5$ parameters.

Counter-example
Let the probabilities $P(A=a \cap B=b \cap C=c)$ be expressed by the numbers $n_{abc} $ with subscripts $a$, $b$, $c$ taking the values $0$ or $1$ depending on whether $A$, $B$, $C$ are true or not. Then we have $8$ numbers, but only $6$ equations to define them.
$$\begin{array}{rcl}
n_{000}+n_{001}+n_{010}+n_{011}+n_{100}+n_{101}+n_{110}+n_{111} &=&1 \\
n_{100}+n_{101}+n_{110}+n_{111} &=& P(A=1)\\
n_{010}+n_{011}+n_{110}+n_{111} &=& P(B=1)\\
n_{001}+n_{011}+n_{101}+n_{111} &=& P(C=1)\\
(n_{110}+n_{111})/(n_{100}+n_{101}+n_{110}+n_{111}) &=& P(B=1 \vert A=1) \\
(n_{101}+n_{111})/(n_{100}+n_{101}+n_{110}+n_{111})  &=& P(C=1 \vert A=1) \\
\end{array}$$
So this will have multiple solutions that can be expressed by two additional numbers. Let $p_a = 1-q_a = P(A=1)$ (and similar for $B$ and $C$)
$$\begin{array}{rcl}
n_{000}=q_a q_b q_c + r + s + t + u \\
n_{001}=q_a q_b p_c + r - s - t - u \\
n_{010}=q_a p_b q_c - r + s - t - u \\
n_{011}=q_a p_b p_c - r - s + t + u \\
n_{100}=p_a q_b q_c - r - s + t - u \\
n_{101}=p_a q_b p_c - r + s - t + u \\
n_{110}=p_a p_b q_c + r - s - t + u \\
n_{111}=p_a p_b p_c + r + s + t - u \\
\end{array}$$
In these equations you can see the expression of the numbers $n_{abc}$ as independent (the product of terms $q$ and $p$) plus extra terms that make the numbers deviate from independence. Those terms are $r$, $s$, $t$ and $u$ which will leave probabilities like $P(A=1)$ invariant (you can see it has the higher dimensional version of this case: https://stats.stackexchange.com/a/363777/164061 ).  When we put these $8$ solutions into the before mentioned 6 equations you get:
$$\begin{array}{rcl}
1 &=&1 \\
p_a &=& P(A=1)\\
p_b &=& P(B=1)\\
p_c &=& P(C=1)\\
(p_b p_a + 2 r)/(p_a) &=& P(B=1 \vert A=1) \\
(p_c p_a + 2 s )/(p_a)  &=& P(C=1 \vert A=1) \\
\end{array}$$
So you can find counter examples by using different values for the parameters $t$ and $u$ which will render different solutions that still satisfy your conditions $P(A)$, $P(B)$, $P(C)$, $P(B \vert A)$ and $P(C \vert A)$.
For example the two cases below:
$$n_{000}=n_{001}=n_{010}=n_{011}=n_{100}=n_{101}=n_{110}=n_{111} =0.125$$ or $$\begin{array}{rcl}
n_{000}=n_{011}=n_{101}=n_{110}&=&0.1 \\
n_{001}=n_{010}=n_{100}=n_{111} &=&0.15
\end{array}
$$
are an example of two different distributions with the same $P(A) = P(B) = P(C) = P(B \vert A) = P(C \vert A) = 0.5$ and in this particular case also $P(C \vert B) = 0.5$.

Graphical
The image below sketches a cube which is how I intuitively imagine these variables $r$, $s $, $t $, as a crossed pattern that changes the distribution while leaving the marginal distributions (including some conditional) invariant. And the variable $u $ will leave all marginal distributions invariant (when you take the sum of $n $ allong any rib then you get both a $+u $ and $-u $ term).


L-Integral of a series of functions

Question: Let $f_k\colon \mathbb{R}\longrightarrow \mathbb{R},\ k\in\mathbb{N}$ be given by
$f_k(x)=\frac{k}{\lfloor \sqrt{k^2x}\rfloor }\chi_{[4/k^2,1]}(x)$.
Note the floor function in the denominator, it is not displayed very clearly in the TeX code!
I want to compute $\lim_{k\to\infty}\int_{\mathbb{R}} f_k\mathrm{d}\lambda$.
Since $\{x\in\mathbb{R};\chi_{[4/k^2,1]}(x)>a\}=\begin{cases}[4/k^2,1]\text{ for }0\le a<1\\
\emptyset\text{ for } a\ge 1\\
\mathbb{R}\text{ for } a<0 \end{cases}$
i know that $f_k$ is measurable for every $k$.
I can't use monotone convergence theorem, since $(f_k)_{k\in\mathbb{N}}$ is not monotonically increasing. But for the integral
$\lim_{k\to\infty}\int_{\mathbb{R}}\frac{k}{\lfloor \sqrt{k^2x}\rfloor }\chi_{[4/k^2,1]}(x)\mathrm{d}\lambda(x)$ I am not entirely sure how to approach it best.
Comment: Is the square root at the denominator $\sqrt{k^2} = k$?
Comment: No, I corrected it. It should be $\sqrt{k^2x}$.
Answer: For $k>2$, you can write explicitly your function as
$$
f_k(x) = \frac{k}{j}
\quad
\text{if}\ \ \frac{j^2}{k^2} \leq x < \frac{(j+1)^2}{k^2},
\quad j\in\{2, \ldots, k-1\}.
$$
Indeed $f_k$ is different from $0$ only in the interval
$I_k :=[4/k^2,1]$. Since $2 \leq \sqrt{k^2 x} \leq k$ for $x\in I_k$,
you have that $[0,1) = \bigcup_{j=2}^{k-1} I_{k,j}$, with
$$
I_{k,j} := \left[\frac{j^2}{k^2} , \frac{(j+1)^2}{k^2}\right), \qquad
j \in \{2, \ldots, k-1\}
$$
and
$$
\lfloor \sqrt{k^2x}\rfloor = j
\quad \forall x \in I_{k, j},
\quad \text{i.e.}\quad
f_k(x) = \frac{k}{j}
\quad \forall x \in I_{k, j}.
$$
Hence
$$
\int f_k =
\sum_{j=2}^{k-1} \int_{I_{k,j}} f_k
= \sum_{j=2}^{k-1} \frac{k}{j} \cdot \frac{(j+1)^2 - j^2}{k^2}
= 2 \frac{k-2}{k} + \frac{1}{k} \sum_{j=2}^{k-1} \frac{1}{j} \to 2.
$$
Comment: I have added more details to my answer.
Comment: Could you elaborate how to write the function explicitly like this?

L-Integral of a series of functions


Terminal Services License Server Install Failed on Server 2008 SP2 DC

Question: I am trying to install Terminal Services License Server on a 2008 Server Standard DC. The only roles installed on this machine are Active Directory and DNS.
I went thru the Wizard and selected to install TS License Server ONLY (no need to install Terminal Services on this DC) and it did the whole install process only to fail at the end.
This thread here http://social.technet.microsoft.com/Forums/en-US/winserverTS/thread/1cf16372-79b8-436c-acc0-1bd0b11ea37c indicates demoting, installing Term Svc LS worked, but I'd rather not do that.
The last bits of the log state:
1148: 2009-09-25 15:57:34.082 [CbsUIHandler]              Error: -2147021879 :
1148: 2009-09-25 15:57:34.097 [CbsUIHandler]              Terminate:
1148: 2009-09-25 15:57:34.097 [CBS] Error (Id=0) Function: 'NativeMethods.GetPackageStatus(out status)' failed: 80070bc9 (-2147021879)
1148: 2009-09-25 15:57:34.097 [CBS]                       ...done installing 'Licensing-UI Licensing '. Status: -2147021879 (80070bc9)
1148: 2009-09-25 15:57:34.253 [TS]                        Skipped configuration of 'TerminalServicesLicenseServer' because install operation failed.
1148: 2009-09-25 15:57:34.253 [Provider]
[STAT] ---- CBS Session Consolidation -----
[STAT] For
          'TerminalServicesLicenseServer'[STAT] installation(s) took '202.8734434' second(s) total.
[STAT] Configuration(s) took '0.0004573' second(s) total.
[STAT] Total time: '202.8739007' second(s).

1148: 2009-09-25 15:57:34.269 [Provider] Error (Id=0) Sync Result - Success: False, RebootRequired: True, Id: /RMTInstances/http___schemas.microsoft.com_sdm_Windows_ServerManager_TerminalServer_2005_09_TerminalServicesLicenseServerType_d367e9aa-72be-45b9-84fb-ed3516900e93.xml
1148: 2009-09-25 15:57:34.269 [Provider] Error (Id=0) Sync Message - OperationKind: Install, MessageType: Error, MessageCode: -2147021879, Message: <null>, AdditionalMessage: The requested operation failed. A system reboot is required to roll back changes made
1148: 2009-09-25 15:57:35.738 [InstallationProgressPage]  Sync operation completed
1148: 2009-09-25 15:57:35.785 [InstallationProgressPage]  Performing post install/uninstall discovery...
1148: 2009-09-25 15:57:36.613 [CBS]                       LastModified CBS Time (UTC): 09/25/2009 19:57:25
1148: 2009-09-25 15:57:36.613 [Provider]                  C:\Windows\system32\ServerManager\Cache\CbsUpdateState.bin does not exist.
1148: 2009-09-25 15:57:36.613 [CBS]                       IsCacheStillGood: False.
1148: 2009-09-25 15:57:36.628 [CBS]                       CreateSessionAndPackage: begin
1148: 2009-09-25 15:57:44.129 [CBS]                       CreateSessionAndPackage: done
1148: 2009-09-25 15:57:44.129 [CBS]                       >>>GetUpdateInfo--------------------------------------------------
1148: 2009-09-25 15:58:00.879 [CBS] Error (Id=0) Function: 'ReadUpdateInfo()->Package_EnumerateUpdates' failed: 80070bc9 (-2147021879)
1148: 2009-09-25 15:58:00.879 [CBS]                       <<<GetUpdateInfo--------------------------------------------------
1148: 2009-09-25 15:58:00.988 [DISCOVERY]                 hr: -2147021879 -> reboot required.
1148: 2009-09-25 15:58:01.160 [InstallationProgressPage]  About to load finish page...
1148: 2009-09-25 15:58:01.223 [InstallationFinishPage]    Loading finish page
1148: 2009-09-25 15:58:01.504 [InstallationFinishPage]    Finish page loaded

edit:
Per FarSeeker added the event log failures. There are a bunch, literally thousands of errors in the System log. Nothing looks particularly illuminating to me other than clearly something is incredibly broken. :D
First it starts with Event ID 4371 "Info" level events:
Windows Servicing started a process of changing package Windows Foundation(Foundation) state from Installed(Installed) to Installed(Installed) - Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~6.0.6001.18000
Windows Servicing started a process of changing package Server-Features(Feature Pack) state from Installed(Installed) to Installed(Installed) - Microsoft-Windows-Server-Features-Package~31bf3856ad364e35~amd64~~6.0.6001.18000
Windows Servicing started a process of changing package BitLocker(Feature Pack) state from Installed(Installed) to Installed(Installed)
Windows Servicing started a process of changing package KB948465(Service Pack) state from Installed(Installed) to Installed(Installed) - Package_221_for_KB948465~31bf3856ad364e35~amd64~~188.8.131.520
-- process continues for basically every service pack / update on the system, several hundred --
Then:
The start type of the Windows Modules Installer service was changed from demand start to auto start. 7040
Then a few dozen of these:
Windows Servicing is setting package KB955302(Update) state to Installed(Installed) 4372
Finally the magic:
The Terminal Services Licensing service entered the running state. 7036
The description for Event ID 18 from source Microsoft-Windows-TerminalServices-Licensing cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
XXXXXX (name of the server)
The description for Event ID 0 from source Microsoft-Windows-TerminalServices-Licensing cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
(blank)
Then all the Servicing items from before fail:
Windows Servicing failed to complete the process of setting package Windows Foundation (Foundation) into Installed(Installed) Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~6.0.6001.18000 Operation: Installed OpCompleted: True ErrorCode: 0x80070bc9 state 4375
Windows Servicing failed to complete the process of setting package Server-Features (Feature Pack) into Installed(Installed) state
Finally, looking in the application log I have only a few (maybe 10 or so) failures, instead of the several thousand in the setup log:
Fault bucket 552641751, type 5
Event Name: CbsPackageServicingFailure
Response: None
Cab Id: 0

Problem signature:
P1: 6.0.6002.18005
P2: Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~6.0.6001.18000
P3: 80070bc9
P4: Execute
P5: Installed
P6: Installed
P7:
P8:
P9:
P10:

Attached files:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\CBS.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\cbs.persist.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\poqexec.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\pending.xml
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\setupapi.dev.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report5438a66c\windowsupdate.log

These files may be available here:
C:\ProgramData\Microsoft\Windows\WER\ReportArchive\Report5fc87216

Fault bucket 582891150, type 5
Event Name: WindowsWcpAIFailure3
Response: None
Cab Id: 0

Problem signature:
P1: 6.0.6002
P2: Group Trustee
P3: 38
P4: Install (first install)
P5: d0000065
P6: amd64_microsoft-windows-t..vices-licenseserver_31bf3856ad364e35_none_9f63f02ef67d0811
P7: Servicing
P8: unknown
P9: NormalBoot
P10:

Attached files:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\pending.xml
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\poqexec.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\CBS.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\Cbs.persist.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\SCM.EVM
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\FilterList.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\WER2768.tmp.hdmp
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report558c4a90\WER490A.tmp.mdmp

These files may be available here:

Fault bucket 616121109, type 5
Event Name: WindowsWcpOtherFailure3
Response: None
Cab Id: 0

Problem signature:
P1: 6.0.6002
P2: base\wcp\cmiadapter\installers.cpp
P3: Windows::WCP::CmiAdapter::CMIWrapperBasicInstaller::Install
P4: 123
P5: d0000065
P6: 0x3b37514a
P7:
P8:
P9:
P10:

Attached files:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\pending.xml
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\poqexec.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\CBS.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\Cbs.persist.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\SCM.EVM
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\FilterList.log
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\WERC032.tmp.hdmp
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\Report588fe0ca\WERDC37.tmp.mdmp

These files may be available here:

Answer: This is a very generic MS Error Code. The relevant part of your log file is the first two lines.
Most of the time it would appear that this is caused by a service that the role relies on not being detected correctly, and requires a lot more information than what you've got there.
If you check in the Event Log, do you see a related failure in there? If you can find it, can you update your post with the failure(s) so that we can have a look?
Update:
Hmm, sorry, I'm all out of ideas. Those event codes are no help (Event 0 = started, Event 18 = TS Licensing Server Not Activated - both pretty normal).
ErrorCode: 0x80070bc9 doesn't have a specific generic meaning, although it commonly seems to mean "Restart Required from Previous Update". I'm guessing that's not its meaning in this situation though (I assume you've already restarted).
Comment: Thanks for the reply. Unfortunately, there's an awful lot of failures in the event log related to this
Comment: Thanks for posting them. I've had a skim and I'll go through in more detail soon.
Comment: I've updated my answer. Sorry I couldn't be more help :(
Comment: Looks like I may have to contact MS Support. Thanks anyway!! :)
Answer: I resolved the issue by adding the folder named "appPools" folder at location C:\inetpub\temp. I also have "Everyone" the permission to write during installation.


Utilizar if() dentro de .catch() - erro: unexpected token if

Question: É o seguinte
Sou novato em javascript e não estou sabendo lidar com esse erro. Estou tentando chamar uma função e colocando um .catch() para evitar o erro UnhandledPromiseRejectionWarning logo após ela, porém gostaria de fazer uma verificação de 'caso ocorra um erro, faça isso'.
Tentei fazer essa verificação utilizando um if(), porém meu  console para devido à SyntaxError: unexpected token if. Já tentei utilizar try...catch, mas ocorreu o erro UnhandledPromiseRejectionWarning que eu falei... Meu código se assemelha a este:
    //um pouco de código aqui

    function(args).catch(error => console.log(error),
    if(error){
         //Código que deve ser executado caso ocorra erro
    });

    //um pouco mais de código aqui

Resumindo, é possível colocar um if() dentro de um .catch()? Existe uma forma melhor de fazer essa verificação?
Answer: A sintaxe de função flecha (arrow function)  está errada. Podes fazer isso assim (assumindo que essa função retorna uma Promise):
minhaFn('foo').catch(error => {
    if(error){
         console.log(error);
         // Outro código que deve ser executado caso ocorra erro
    }
});

Exemplo: https://jsfiddle.net/zkodkf7b/

function minhaFn(nr) {
    return new Promise((resolve, reject) => {
        // isto vai dar asneira pois a variavel "naodeclarado" não está declarada
        resolve(nr / naodeclarado);
    });
}

minhaFn(20).catch(err => {
    if (err) {
        console.log(err);
        if (err.message.includes('is not defined')) {
            alert('Há variáveis não defenidas!');
        }
    }
}).then(res => console.log(res))
Comment: Muito obrigado, Sergio! você me tirou de um aperto =D


Product of Ideals in Ring that is not UFD

Question: can someone tell me if I calculated the following products of Ideals correctly?
$I=(2,1+\sqrt{-5}),\ J=(3,1+\sqrt{-5}), K=(3,1-\sqrt{-5})$ in $\mathbb{Z}[\sqrt{-5}]$.
then
$I\cdot J=(1+\sqrt{-5})\\ I\cdot K=(1-\sqrt{-5})\\I^2=(2)\\J\cdot K=(3) $
Answer: You ought to know that for finitely generated ideals, for example $I = (a,b)$ and $J=(c,d)$, the ideal $IJ = (ac,ad,bc,bd)$ is the ideal generated by all products of generators. That said, you only need to check that you computed those products correctly.
For example, $$IJ=(2,1+\sqrt{-5})(3,1+\sqrt{-5}) = (6,2+2\sqrt{-5},3+3\sqrt{-5},-4+2\sqrt{-5}) \\= (2+2\sqrt{-5},3+3\sqrt{-5})=(1+\sqrt{-5}),$$ since $$3+3\sqrt{-5}-(2+2\sqrt{-5}) = 1+\sqrt{-5}.$$ The others are checked similarly.
Comment: But in your case it's $IJ=I$ and since $IJ\subset I\cap J\subset J$ it follows that $I\subset J$ which is not correct ($2\notin J$).
Comment: As user424862 notes, your computation of $IJ$ is not quite correct, since $(1+\sqrt{-5})^{2} = -4+2\sqrt{-5}$.
Comment: I'm fairly sure I know how to compute those products. My question was just about whether they're correct. So if one could verify that I'd be glad.
Comment: Have you tried learning how to use Sage? or Magma? It would be much faster and more convenient for checking calculations
Answer: As reference, this website is NOT for checking calculations. You should really learn how to use a calculator for that. I would like to direct you to Sage or Magma.
<code>sage: K.<r> = NumberField(x^2 + 5)
sage: Ok = K.ring_of_integers()
sage: r*r
-5
sage: I = Ideal(2, 1 + r)
sage: J = Ideal(3, 1 + r)
sage: K = Ideal(3, 1 - r)
sage: I*J
Fractional ideal (r + 1)
sage: I*K
Fractional ideal (-r + 1)
sage: I*I
Fractional ideal (2)
sage: J*K
Fractional ideal (3)
sage:
</code>
So they are all correct.
Comment: No, it's semester break over here and I'm reading a book I'm interested in, so I was interested in whether I understood everything.
I didn't know about sage and I'm quite surprised about this. Maybe I will get a hand on it!
Comment: Introduction to commutative algebra by Atiyah-Macdonald. I guess I will give sage a try if I have enough time. Thanks for introducing me to it:)
Comment: Less annoying than the students who post assignments, but I still don't think that asking essentially computational questions is relevant.
Comment: I'm sorry for sounding angrier in the answer. In my head, you were just a lazy person who couldn't be bothered checking multiplication. -- within  Algebraic Number Theory computation is very important, I think Sage will serve you well.
Comment: Which book are you reading btw?, also if you edit your question a bit, I can change my downvote, unless you're fine with me downvoting it.
Comment: You may also enjoy Ideals, Varieties and Algorithms by Cox, Little and O'Shea. It's more computational and can give a better insight, especially at ground level. If you're more interested in the Algebraic Number Theory side, you may enjoy a book of the same name by Jarvis.


How should I deduce the variance and expectation of the log of a variable?

Question: I read this paper "voom: precision weights unlock linear model analysis tools for RNA-seq read counts", in the methods, the "Delta rule for log-cpm" section:
The RNA-seq data consist of a matrix of read counts $r_{gi}$, for RNA samples $i=1$ to $n$, and genes $g=1$ to $G$. Write $R_i$ for the total number of mapped reads for sample $i$:
$$R_i=\sum_{g=1}^{G}r_{gi}$$ They define the log-counts per million (log-cpm) value for each count as: $$y_{gi}=\log_2\left(\frac{r_{gi}+0.5}{R_i+1}\times 10^6\right)$$
Write $\lambda=E(r)$ for the expected value of a read count given the experimental conditions, and suppose that: $$\text{Var}(r)=\lambda+\phi\lambda^2$$ If $r$ is large, then the log-cpm value of the observation is: $$y\approx\log_2(r)-\log_2(R)+6\log_2(10)$$ where $R$ is the library size. The analysis is conditional on $R$, so $R$ is treated as a constant. It follows that $\text{Var}(y)\approx \text{Var}(\log_2 r)$. If $\lambda$ also is large, then:
$$(\log_2 r)(\ln 2)\approx \ln r \approx \ln\lambda+\frac{r-\lambda}{\lambda}$$ so $$\text{Var}(y)(\ln 2)^2\approx\frac{\text{Var}(r)}{\lambda^2}=\frac{1}{\lambda}+\phi$$
How should I deduce the last 2 equations?
Comment: There are a couple of "log 2" factors in the last 2 displays (one with subscripted 2) that I think you meant to represent the natural log of 2. It might be easier to read this if you explicitly wrote `ln` for the natural log where that's intended.
Comment: I suspect this is a case where someone did some math and didn't pay attention to the numerical implications of the result.   Let's look at the first of your equations; assume $\lambda = 100$ ("large") and $r \approx \lambda$.  Then $\lambda + (r-\lambda)/\lambda \approx \lambda$ and $\log_2(r) \approx \log_2(\lambda)$, so we have $\log_2(100) \approx 100$.  Making $\lambda$ larger won't help.  Even if we make $r =$, say, $2\lambda$ or $\lambda/2$, we don't get anything like "approximately equal to".
Comment: Yes you are right, it seems the author changed the online version recently. I updated these equations. Thanks
Comment: There is an updated version and these equations had been corrected. http://www.statsci.org/smyth/pubs/VoomPreprint.pdf  I updated my question to the updated equations.
Answer: With the corrected version of the equations, this follows from a standard approximation to the variance of a natural log of a random variable, given the variance of the random variable. See this page, along with its warnings about when this approximation might get you into trouble.
Work first with the natural log of $r$. The Taylor expansion of $\ln r$ about the mean value $\lambda$ for $r$ is:
$$ \ln r \approx \ln \lambda + \frac{(r-\lambda)}{\lambda} - \frac{(r-\lambda)^2}{2\lambda^2}+\dots,$$
based on the first and second derivatives of the natural log function at $r=\lambda$. The terms after the first two are assumed to become small with large $\lambda$.
Then continue by taking the expectations of both sides. As $\lambda$ is the mean of $r$, the expectation of the second term is 0, leaving:
$$E[\ln r] \approx \ln E[r].$$
Now, working with the first two terms of the Taylor expansion, take the variance of both sides, the expected value of squared deviations from the mean:
$$\text{Var}(\ln r) \approx E\left[\left(\ln \lambda + \frac{(r-\lambda)}{\lambda} -  \ln E[r]\right)^2\right]$$
$E[r]$ is $\lambda$, so the first and third terms within the parentheses on the right cancel, leaving:
$$\text{Var}(\ln r)\approx E\left[ \left(\frac{(r-\lambda)}{\lambda} \right)^2\right]=\frac{\text{Var }r}{\lambda^2}.$$
Given the assumed form for the variance of $r$, the rightmost part of the last display immediately follows. The $\ln 2$ factors translate between the natural log and the $\log_2$ scales.
Answer: Based on Taylor expansions for the moments of functions of random variables
$$
\begin{align}
\log X & = \log (\mu_X+X-\mu_X) \\
&\approx \log (\mu_X)+ \log' (\mu_X)(X-\mu_X)+\frac{1}{2}\log''(\mu_X)(X-\mu_X)^2 \\
&\approx\log (E(X))+\frac{X-E(X)}{E(X)}
\end{align}
$$ so take expectations and variances on both sides,
$$E(\log X)\approx\log (E(X))$$
$$\text{Var}(\log X)\approx E\left[\frac{X-E(X)}{E(X)}\right]^2=\frac{\text{Var}(X)}{(E(X))^2}$$
So
$$E[\log r]\approx\log (\lambda)+\frac{r-\lambda}{\lambda}
$$
$$\text{Var}[\log r]\approx\frac{\text{Var}(r)}{\lambda^2}
$$


Como utilizar SUM em um código de vários retornos?

Question: Fiz em um código onde faz uma somatória de dados inseridos nos meses,
porém não sei como fazer com que o AS transforme-se em um array.
O Código que fiz:
DECLARE @I INT = 1;
WHILE @I < 12
BEGIN
  SELECT SUM(valueEarn) AS monthValue1
    FROM earnAccount
   INNER JOIN bankAccount ON bankAccount.idBankAccount = 1
   WHERE MONTH(dateEarnCreate) = @I

  SET @I += 1
END

como ficou:

Como pode ver ele me retorna o mesmo nome de coluna monthValue1, queria que gera-se de monthValue1 a monthValue12,pq depois vou pegar esses dados para colocar em um gráfico.
queria algo nesse estilo:
Comment: Posta a estrutura das tabelas utilizada no select. e explique com mais detalhes a regra do que você precisa.
Comment: Isto responde à sua pergunta? [Ajuda com um PIVOT ( Sql Server )](https://pt.stackoverflow.com/questions/362219/ajuda-com-um-pivot-sql-server)
Answer: Para mostrá-los linha a linha basta remover o while e adicionar um CASE verificando qual o mês em questão:
SELECT SUM(CASE MONTH(dateEarnCreate) WHEN 1 THEN valueEarn ELSE 0 END) AS monthValue1,
       SUM(CASE MONTH(dateEarnCreate) WHEN 2 THEN valueEarn ELSE 0 END) AS monthValue2,
       SUM(CASE MONTH(dateEarnCreate) WHEN 3 THEN valueEarn ELSE 0 END) AS monthValue3,
       SUM(CASE MONTH(dateEarnCreate) WHEN 4 THEN valueEarn ELSE 0 END) AS monthValue4
       SUM(CASE MONTH(dateEarnCreate) WHEN 5 THEN valueEarn ELSE 0 END) AS monthValue5,
       SUM(CASE MONTH(dateEarnCreate) WHEN 6 THEN valueEarn ELSE 0 END) AS monthValue6,
       SUM(CASE MONTH(dateEarnCreate) WHEN 7 THEN valueEarn ELSE 0 END) AS monthValue7,
       SUM(CASE MONTH(dateEarnCreate) WHEN 8 THEN valueEarn ELSE 0 END) AS monthValue8,
       SUM(CASE MONTH(dateEarnCreate) WHEN 9 THEN valueEarn ELSE 0 END) AS monthValue9,
       SUM(CASE MONTH(dateEarnCreate) WHEN 10 THEN valueEarn ELSE 0 END) AS monthValue10,
       SUM(CASE MONTH(dateEarnCreate) WHEN 11 THEN valueEarn ELSE 0 END) AS monthValue11,
       SUM(CASE MONTH(dateEarnCreate) WHEN 12 THEN valueEarn ELSE 0 END) AS monthValue12
  FROM earnAccount
 INNER JOIN bankAccount
    ON bankAccount.idBankAccount = 1

Comment: obrigado ajudou sim, porém no caso ali está errado em vez de THEM é THEN


How to troubleshoot deployment of Inception serving running in kubernetes

Question: I'm following the Serving Inception Model with TensorFlow Serving and Kubernetes workflow and everything work well up to the point of the final serving of the inception model via k8s when I am trying to do inference from a local host.
I'm getting the pods running and the output of $kubectl describe service inception-service is consistent with what is suggested by the workflow in the Serving Inception Model with TensorFlow Serving and Kubernetes.
However, when running inference things don't work. Here is the trace:
$bazel-bin/tensorflow_serving/example/inception_client --server=184.108.40.206:9000 --image=cat.jpg

Traceback (most recent call last):
File "/home/dimlyus/serving/bazel-
bin/tensorflow_serving/example/inception_client.runfi
les/tf_serving/tensorflow_serving/example/inception_client.py", line 56, in
tf.app.run()

File "/home/dimlyus/serving/bazel-
bin/tensorflow_serving/example/inception_client.runfi
les/org_tensorflow/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))

File "/home/dimlyus/serving/bazel-
bin/tensorflow_serving/example/inception_client.runfi
les/tf_serving/tensorflow_serving/example/inception_client.py", line 51, in
main
result = stub.Predict(request, 60.0) # 10 secs timeout

File "/usr/local/lib/python2.7/dist-
packages/grpc/beta/_client_adaptations.py", line 32
4, in call
self._request_serializer, self._response_deserializer)

File "/usr/local/lib/python2.7/dist-
packages/grpc/beta/_client_adaptations.py", line 21
0, in _blocking_unary_unary
raise _abortion_error(rpc_error_call)
grpc.framework.interfaces.face.face.AbortionError:
AbortionError(code=StatusCode.UNAVAILABLE, details="Connect Failed")

I am running everything on Google Cloud. The setup is done from a GCE instance and the k8s is run inside of Google Container Engine. The setup of the k8s follows the instructions from the workflow linked above and uses the inception_k8s.yaml file.
The service is set as follows:
apiVersion: v1
kind: Service
metadata:
  labels:
    run: inception-service
  name: inception-service
spec:
  ports:
  - port: 9000
    targetPort: 9000
  selector:
    run: inception-service
  type: LoadBalancer

Any advice on how to troubleshoot this would be greatly appreciated!
Answer: The error message seems to indicate that your client cannot connect to the server. Without some additional information it is hard to trouble shoot. If you post your deployment and service configuration as well as give some information about the environement (is it running on a cloud? which one? what are your security rules? load balancers?) we may be able to help better.
But here some things that you can check right away:

If you are running in some kind of cloud environment (Amazon, Google, Azure, etc.), they all have security rules where you need to explicitly open the ports on the nodes running your kubernetes cluster. So every port that your Tensorflow deployment/service is using should be opened on the Controller and Worker nodes.
Did you deploy only a Deployment for the app or also a Service? If you run a Service how does it expose? Did you forget to enable a NodePort?

Update: Your service type is load balancer. So there should be a separate load balancer be created in GCE. you need to get the IP of the load balancer and access the service through the load balancer's ip. Please see the section 'Finding Your IP' in this link https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/
Comment: Thanks for looking into this. I updated the question with more information. I do run both `Deployment` and `Service`. The service is setup via the yaml file. Please take a look at code snippet in the updated question.
Comment: Your service type is load balancer. So there should be a separate load balance be created in GCE. you need to get the IP of the load balancer and access the service through the load balancer's ip. Please see the section 'Finding Your IP' in this link https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/
Comment: The server IP I'm using above comes from `kubectl describe service inception-service` which specifies the LoadBalancer Ingress IP. Any other things I could check?
Comment: It may still be the security rules not allowing the ports on the Master/Worker Nodes. Can you check what NodePort is listed when you run kubectl describe service inception-service? It should be a port in the range of 30000-33000 and you'll need to allow that port in security rules for Master/Worker Nodes.
Comment: The `kubectl describe service inception-service` returns NodePort:  32760/TCP. This seems consistent with what the workflow from the  Serving Inception Model with TensorFlow Serving and Kubernetes suggests. How do I check that the NodePort is allowed in security rules for Master/Worker Nodes?
Comment: This answer http://stackoverflow.com/questions/21065922/how-to-open-a-specific-port-such-as-9090-in-google-compute-engine
Comment: Checked that the NodePort is indeed allowed.
Comment: Did you check the POD logs? `kubectl logs pod-name`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/141301/discussion-between-drstarson-and-oswin-noetzelmann).
Answer: I figured it out with the help of several tensorflow experts. Things started to work after I introduced the following changes:
First, I changed inception_k8s.yaml file in the following way:
Source:
args:
    - /serving/bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server
      --port=9000 --model_name=inception --model_base_path=/serving/inception-export

Modification:
args:
    - serving/bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server
      --port=9000 --model_name=inception --model_base_path=serving/inception-export

Second, I exposed the deployment:
kubectl expose deployments inception-deployment --type="LoadBalancer"

and I used the IP generated from exposing the deployment, not the inception-service IP.
From this point I am able to run the inference from an external host where the client is installed using the command from the Serving Inception Model with TensorFlow Serving and Kubernetes.


Why variable_get() returns all values of checkboxes list, even if checkbox is not selected?

Question: I have checkboxes list in system settings form:
$form['mymodule_menu_perm_menus'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Menus'),
    '#options' => menu_get_menus(TRUE),
    '#default_value' => variable_get('mymodule_menu_perm_menus', array()),
);

return system_settings_form($form);

I submit this form with two checkboxes selected.
But on other page variable_get('mymodule_menu_perm_menus') return all values :/
Clearing cache doesn't help
Answer: Because Drupal doesn't actually filter out empty checkboxes values, it sets them to zero. I think this is so you get an accurate representation of what options were available when the form was submitted, and what was actually chosen by the user.
It's easy to get the filtered array though, using array_filter():
$values = array_filter(variable_get('mymodule_menu_perm_menus', array()));


Any good Haxe IDE for linux / ubuntu?

Question: I have find and tried different Haxe IDE in ubuntu and all have their own issues and dependencies even some have lost their support. Which is causing the IDE difficult to get ready for coding or development.
Currently using HIDE which is fair enough :s and get install in one command.
Is there any good working IDE for linux system ?
[update]

Haxe studio has no autocomplete feature
Sublime 2 bundle also do not support autocomplete or has one but don't show right properties
Gedit2 plugin has bugs which says python not found
Flashdevelope using wine opens a window which show list of flashdevelope extentions and do not go further then this screen.
Comment: While IDE's have their place, there is no replacement for simply coding with a good text-editor with a multi-document interface and good syntax-highlighting with an open terminal nearby. KDE's kate was/is one very capable editor which provides the ability to save collections of documents as a 'project'. gedit in gnome is OK as well. Don't forget 'vim' which is one of the most flexible editors on the planet that provides all the hooks needed to code, compile and test from within the editor (note it takes time to learn). Any terminal will do. I prefer KDE's konsole.
Answer: I think you might want to look at this page:
https://haxe.org/documentation/introduction/editors-and-ides.html
The options for Linux are:

Visual Studio Code (With Haxe extension)
IntelliJ IDEA (With Haxe plugin)
Sublime Text (With Haxe Bundle)
VIM (With Vaxe Plugin)
HaxeDevelop using Wine
Comment: You might want to add [Haxe Studio](http://www.haxestudio.com/) to the list. Also, there is some work on getting [FlashDevelop](http://www.flashdevelop.org/) functioning in Wine.
Comment: The IntelliJ haxe plugin now works on all JetBrains IDEs, that means their  limited but cheaper IDEs like WebStorm/PhpStorm can be used for Haxe development, too.
Comment: The IDEA community edition is free.
Comment: As i'm using my IDE for other stuff too, I use inteliJ idea community with the haxe plugin. setting up dependencies and changing targets is harder than FlashDevelop, and following tutorials is not that easy, but other than that it's a better IDE

Any good Haxe IDE for linux / ubuntu?


CloudBees app deploy Platform error - {{invalid_local_plugin_dir,"/etc/genapp/plugi

Question: I'm new to Cloudbees and having some difficulties getting my app deployed.
My app works in my local when using bees run. It also works when I placed it in another tomcat as Tomcat\webapps\ROOT.
In case it matters, I've added a lib:
C:\Java\cloudbees-sdk-1.3.1\biblenav\webapp\WEB-INF\lib\urlrewritefilter-4.0.3.jar
My war file is 635 KB and I'm using the free account.
I've tried to deploy using bees deploy from C:\Java\cloudbees-sdk-1.3.1\biblenav\
and I've tried to deploy the war file from the bees root dir. Both times I get the error below. I've no idea what to do about it. Can anyone help? Thanks!
C:\Java\cloudbees-sdk-1.3.1>bees app:deploy -a angelwarrior/biblenav ./biblenav/webapp/biblenav.war
Deploying application angelwarrior/biblenav (environment: ): .\biblenav\webapp\biblenav.war
........................uploaded 25%
........................uploaded 50%
........................uploaded 75%
........................upload completed
deploying application to server(s)...
Apr 25, 2013 11:25:23 PM com.cloudbees.api.BeesClient applicationDeployArchive
SEVERE: Invalid application deployment response: angelwarrior/biblenav
com.cloudbees.api.BeesClientException: Server.InternalError - java.lang.IllegalArgumentException: Platform error - {{invalid_local_plugin_dir,"/etc/genapp/plugins.d/jar"},
[{genapp_plugin,validate_plugin_dir,1},
{genapp_plugin,new,1},
{genapp_deploy,resolve_plugin,2},
{genapp_deploy,apply_stages,2},
{genapp_deploy,handle_task,1},
{e2_task,dispatch_handle_task,1},
{e2_service,dispatch_info,2},
{gen_server,handle_msg,5}]}
at com.cloudbees.api.BeesClient.readResponse(BeesClient.java:1121)
at com.cloudbees.api.BeesClient.applicationDeployArchive(BeesClient.java:638)
at com.cloudbees.sdk.commands.app.ApplicationDeploy.execute(ApplicationDeploy.java:322)
at com.cloudbees.sdk.commands.Command.run(Command.java:167)
at com.cloudbees.sdk.commands.Command.run(Command.java:80)
at com.cloudbees.sdk.Bees.run(Bees.java:117)
at com.cloudbees.sdk.Bees.main(Bees.java:308)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.cloudbees.sdk.boot.Launcher.main(Launcher.java:35)

Answer: That's an unfortunately obfuscated error message, but based on on the details, it looks like you attempted to deploy the app at some point using a "-t jar" flag.  This sets your runtime stack to "jar", which isn't a known stack...which led to this downstream error.
You can see a list of valid stack names to use with that -t STACK flag in the CloudBees ClickStack docs.
In your case, it sounds like you'd like to run the deployed app package with Tomcat, so you probably want one of the following commands:
For Tomcat 6:
bees app:deploy -t tomcat -a APPID WAR_FILE

For Tomcat 7:
bees app:deploy -t tomcat7 -a APPID WAR_FILE

For JBoss 7:
bees app:deploy -t jboss -a APPID WAR_FILE

Note:  once you set the stack with -t, it is sticky, so you don't need to specify on subsequent deployments.
This was a confusing error for you to see, so we'll also look at cleaning up that error to be more clear.
Comment: Thank you! I tried the tomcat 6 version and it worked perfectly!I wouldn't be surprised if I'd tried the -t jar at some point


Is it possible to show contents in a specific sites for multilingual site?

Question:
Is it possible to show contents in a specific sites for multilingual
  site?

I have a site of multilingual support with english and bangla language.
There is a content type blog. so Now I want to publish english content in a en.demo.com site and bangla content at bn.demo.com site and the different content will be visible at different site and it will generate different url. Is it possible and how ?
Answer: Go to en/admin/config/regional/language/configure and make sure URL is at the top. Press configure and select Domain. There you go.
Comment: You might want to read Gábor Hojtsy's post on [Node translations](http://hojtsy.hu/blog/2011-jan-31/drupal-7039s-new-multilingual-systems-part-4-node-translation).
Comment: It's solved. Thanks @Win Mostery for trying to help


Verificar se o valor já existe no arquivo txt

Question: estou desenvolvendo um aplicativo de inventário que em sua versão freeware irá trabalhar com os dados inseridos em um arquivo txt linha a linha, a estrutura dos dados será a seguinte
Código de barras + Descrição + Localização "E após localização quero colocar uma soma, em que cada vez que o mesmo código for lido ele irá somando +1 no arquivo texto"
Código de escrita;
 String dados;

                        //   lstrNomeArq = (txtScanResult.getText()  + ".txt");
                     File arquivo = new File(Environment.getExternalStorageDirectory(), "/MatheusArrudaDev/InventarioFree/" + timeStamp + "/geral.txt");

                     String unidademetalicascan = (String) txtScanResult.getText();
                     Editable localizacao =  identestoque.getText();
                     Editable descricao =  txtdescricao.getText();
                     dados = unidademetalicascan + localizacao;

                     try {

                     if (!arquivo.exists()) {
                     //cria um arquivo (vazio)
                     arquivo.createNewFile();
                     }

                     //caso seja um diretório, é possível listar seus arquivos e diretórios
                     File[] arquivos = arquivo.listFiles();

                     //escreve no arquivo
                     FileWriter fw = new FileWriter(arquivo, true);

                     BufferedWriter bw = new BufferedWriter(fw);

                     bw.write(unidademetalicascan + " " + descricao +"  "+ localizacao);

                     bw.newLine();

                     bw.close();
                     fw.close();

                     //faz a leitura do arquivo
                     FileReader fr = new FileReader(arquivo);

                     BufferedReader br = new BufferedReader(fr);

                     //equanto houver mais linhas
                     while (br.ready()) {
                     //lê a proxima linha
                     String linha = br.readLine();

                     //faz algo com a linha
                     System.out.println(linha);
                     }

                     br.close();
                     fr.close();

                     } catch (IOException ex) {
                     ex.printStackTrace();

                     }

Por exemplo:
O aplicativo leu "123" e a descrição do produto é "Creme", eu quero que ele escreva
123 Creme 1
Se ele ler 123 de novo, quero que ele Edite a linha acima e escreva
123 Creme 2.
Answer: Olá! Uma solução seria utilizar o SQLite, facilitaria um pouco sua vida!
Documentação SQLite
Artigo da TutorialsPoint sobre SQLite com Java
Uma outra solução seria carregar o conteúdo do arquivo em memória e utilizar um background worker para salvar o arquivo a cada x segundos por exemplo!
Espero que ajude!
Abraço
Comment: Entendo vou tentar trabalhar com o SQLite então, obrigado.


A property of potential function ($\lim_{z\rightarrow\infty}(p_{\mu}(z)-\mu(\mathbb{C})\log|z|)=O(1/|z|)$)

Question: I am studying the potential theory from Ransford book.
Let $\mu$ be a finite Borel measure on $\mathbb{C}$ with compact support and let $p_{\mu}:\mathbb{C}\rightarrow [-\infty,\infty)$.
The result is Theorem 3.1.2 says that
$$p_{\mu}(z)=\int\log|z-w|d\mu(w)=\mu(\mathbb{C})\log|z|+O(1/|z|)\qquad \text{as}\,\,\,z\rightarrow\infty$$
I think I see why the first term of the sum is $\mu(\mathbb{C})\log|z|$. This is because
$$p_{\mu}(z)=\int\log\left|z\cdot\frac{z-w}{z}\right|d\mu(w)=\int\log|z|d\mu(w)+\int\log|1-w/z|d\mu(w)=\mu(\mathbb{C})\log|z|+\color{red}{O(1/|z|)}$$ as $z\rightarrow \infty$
The punch line in the book says that "as $\mu$ has compact support, the final term is $O(1/|z|) as |z|\rightarrow \infty$."
I don't get why the second term in the sum asymptomatically to the Big-Oh of $1/|z|$. It seems easy, but I'm struggling to verify it. Could someone point me out, please?
Comment: it is $\int \log|1-w/z|d\mu(w)$ not $\int|1-w/z|d\mu(w)$ in your equation; then since $|w|$ lives in a compact set (support of $\mu$), $|\log |1-w/z|| \le C/|z|$ for $|z|$ large
Comment: @Conrad I edited it, it's a typo. Thanks.
Answer: Let $R>0$ be such that $\text{supp}(\mu)\subset B_R(0)$. Let $|z|>R$. Note that by the triangle inequality
$$
1-R/|z|\leq 1-|w/z|\leq |1-w/z|\leq 1+|w/z|\leq 1+R/|z|
$$
Now use the Taylor series for $\log(1\pm x)$ and that our bounds are uniform and the measure is finite.
Comment: Thanks for your concern. Just small point to clarify that the $\text{supp}(\mu)$ belongs to $B_R(0)$ because the support of measure is compact and hence covering by finitely many open balls and then you can say so, do I understand it correctly?
Comment: @Nothingone No, it's compact so it's closed and bounded. Since it's bounded, it's within some finite ball centered at the origin.
Comment: That's clear. Appreciate it.
Comment: @Nothingone no problem


UILabel sizeToFit break constraints only on ios 7

Question: I have an iOS app almos finished, but i found a bug. I have an UITableView with an prototype cell and an UILabel on the cell. In runtime i put text in the label and use the method sizeToFit() to resize the label. This works fine on iOS8 but on iOS7 a get an error of breaking constrains and the UILabel simply not resize.
I need your help, its the only thing that i have to do to publish the app.
The constrains :
UILabel to top of cell content - 10

UILabel to bottom of cell content - 10

UILabel to left of cell content - 5

UILabel to right of cell content - 5

P.S - I don't have an cell height defined and i don't use the method estimatedCellSize.
Comment: Nothing to do with Swing.  Please **read** the helpful tag pop-ups before slapping them on a question.
Comment: why do you need to call sizeToFit?
Comment: Because te text its added on run time and i dont know the text length, i use it to resize the label to fit the text.
Comment: I wanted to set "Swift", sorry was my fault.
Answer: use label.numberoflines=0;
labe.sizeToFit=YES;

Answer: You should be changing your constraints or your approach.
Either use the compression and hugging constraint values to make the label size to fit, and remove the constraints to the right and bottom (in this case to pin the label to the top left and resize).
Or, keep the current constraints and change the label to scale its contents to fit.
Comment: The cell will not adjust height unless you implement the appropriate delegate method
Comment: You can give me an example of how i do the second option?
Comment: Set `minimumFontScale` (in IB or code) - this deals with too much text, but it doesn't fit to small text - you don't actually state exactly why you size to fit
Comment: I want to UILabel adjust her size to the text content and the cell adjust her size to the new size of UILabel.


Tricky populate fields of excel sheet based on mapping using Pandas

Question: I have a df, df1, that, based on the bound, year, and state, I would like to populate another df, df3, with values from df2 if the year, qtr, state bound, and type match. I am thinking of using a combination of Pandas and OpenPyXL, but still researching this.
Data
df1
year    state   bound
2027    CA      low_stat
2027    CA      low_re
2027    NY      med_stat
2027    NY      med_re

df2
year    qtr    state type   low_stat low_re med_stat med_re high_stat   high_re
2027    2027Q1  NY   AA     5        6      0        1      3           4
2027    2027Q1  CA   AA     1        4      5        4      1           4
2027    2027Q2  NY   AA     3        6      4        16     56          1
2027    2027Q2  CA   AA     11       2      3        2      3           2
2027    2027Q1  NY   BB     1        2      3        4      3           2
2027    2027Q1  CA   BB     9        3      2        2      3           2
2027    2027Q2  NY   BB     3        1      4        1      5           6
2027    2027Q2  CA   BB     9        5      2        5      3           2

df3
year    state    qtr      low_stat_AA low_re_AA low_stat_BB low_re_BB med_stat_AA med_re_AA med_stat_BB med_re_BB
2027    CA       2027Q1
2027    CA       2027Q2
2027    NY       2027Q1
2027    NY       2027Q2

Desired
year    state   qtr     low_stat_AA low_re_AA low_stat_BB low_re_BB med_stat_AA med_re_AA   med_stat_BB med_re_BB
2027    CA      2027Q1  1           4         9           3
2027    CA      2027Q2  11          2         9           5
2027    NY      2027Q1                                              0           1            3          4
2027    NY      2027Q2                                              4           16           4          1

Doing
 merged = pd.merge(df2,df3, on = 'year','state','type')

I may be able to use a merge. However, I am still researching as this is not specific.
Any suggestion is appreciated.
Answer: Step1
melt df2 & merge with df1
df_merge = df1.merge(df2.melt(['year', 'qtr', 'state', 'type'], var_name='bound'))

df_merge.head(5)
    year    state   bound       qtr     type    value
0   2027    CA      low_stat    2027Q1  AA      1
1   2027    CA      low_stat    2027Q2  AA      11
2   2027    CA      low_stat    2027Q1  BB      9
3   2027    CA      low_stat    2027Q2  BB      9
4   2027    CA      low_re      2027Q1  AA      4

Step2
make pivot_table using df_merge.
Strings in the bound column and the type column must be connected with '_', so let's create grouper using the str.cat function.
grouper = df_merge['bound'].str.cat(df_merge['type'], sep='_')
out = (df_merge
       .pivot_table('value', index=['year', 'state', 'qtr'], columns=grouper)
       .reset_index())

out
bound   year    state   qtr     low_re_AA   low_re_BB   low_stat_AA low_stat_BB med_re_AA   med_re_BB   med_stat_AA med_stat_BB
0       2027    CA      2027Q1  4.0         3.0         1.0         9.0         NaN         NaN         NaN         NaN
1       2027    CA      2027Q2  2.0         5.0         11.0        9.0         NaN         NaN         NaN         NaN
2       2027    NY      2027Q1  NaN         NaN         NaN         NaN         1.0         4.0         0.0         3.0
3       2027    NY      2027Q2  NaN         NaN         NaN         NaN         16.0        1.0         4.0         4.0

If you want the same sorting as df3, you can reindex it using df3.columns.
out.reindex(columns=df3.columns)


Notificações Push no Android com PWA

Question: Tenho uma PWA(Progressive Web Application) que foi criado utilizando o VueJS em conjunto com um sistema web.
E para as notificações push foi utilizado o Firebase Cloud Messaging, porém estou com um problema na hora de receber as notificações push com o PWA instalado no smartphone, as notificações não aparecem.
Utilizando o sistema no computador as notificações são entregues dentro do normal, porém no smartphone, tanto no chrome quanto com o PWA instalado as notificações não chegam.
As notificações push funcionam somente para app's nativos Android??
Comment: Funcionam sim, mas precisa da autorização do usuário também, da uma olhada aqui: https://ada.is/progressive-web-apps-talk/
Comment: Vou fazer alguns testes aqui e se eu não der a resposta se funcionou ainda hoje eu respondo amanhã... Agradeço a ajuda @DavidDias
Comment: Estou seguindo o exemplo que é feito no artigo, porém estou tendo problemas na hora de registrar o `service-worker`...
Comment: @LeonardoEbert conseguiu resolver o problema?
Answer: As notificações via push funcionam sim via PWA, com exceção para o iOS (até o momento sem suporte).
Este link mostra um tutorial de como testar (em inglês):
https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
Aqui você pode acompanhar os navegadores e sistemas que suportam a notificação via push:
https://whatwebcando.today/push-notifications.html

Notificações Push no Android com PWA