Minibatch Weighted Sampling for estimating log(q_z) for disentangled representation based on ELBO loss in VAE

Question: I'm reading the paper "Isolating Sources of Disentanglement in VAEs" https://arxiv.org/pdf/1802.04942.pdf. Assuming $p(n)$ is a uniform distribution and that we have a model to get $q(z|n)$ for any input n. Also, $q(z|n)$ represents a normal distribution, so the model predicts the mean and covariance matrix for $q(z|n)$. Please consider the following minibatch-based estimation provided by the author.

Doubt 1. I'm not able to understand how to come from the second line to the third line, where $E_{p(B_M)}$ is introduced along with averaging over the values of $q(z|n_m)$. It is somewhat intuitive, but I'd like to know concretely.
Doubt 2. What happened to the $E_r(B_M|n)$ coming to S4.
I'm sorry, if these are too trivial. Thanks for any help.
Answer: I am also looking at this formula recently. Based on my understanding,
$$E_{p(B_M)}[\frac{1}{M}\Sigma_{m=1}^{M}q(z|n_m)]=E[\frac{1}{M}\Sigma_{i=1}^{N} 1(i\in B_M)q(z|n_i)]=E[1(i\in B_M)](\frac{1}{M}\Sigma_{i=1}^{N} q(z|n_i))=\frac{M}{N}(\frac{1}{M}\Sigma_{i=1}^{N} q(z|n_i))=E_{p(n)}[q(z|n)]$$
Assuming the sampling is uniformly at random.
Comment: Hi, thnx for answering. But, wouldn't $E[1(i \in B_M)] = \sum_{i \in B_M}P(B_M) = (N^M - (N-1)^M) / N^M$
Comment: Hi! Assuming sampling with replacement:
Denote M as batch size and B as the number of batches. It is trivial to know that $$B=\frac{N!}{M!(N-M)!}$$. Then:
$$E_{P(B_M)}[1(i\in B_M)]=\Sigma_{b=1}^{B} P_{B_{Mb}}i(i\in B_{Mb})(1)$$
We also know that $$P_{B_{Mb}}=\frac{1}{B}$$ regardless of b. Then the RHS of eq.1 is $$\Sigma_{b=1}^{B}\frac{1}{B}1(i\in B_{Mb})(2)$$
Given a specific i, the number of items  in which $$1(i\in B_{Mb})=1$$ is $$\frac{(N-1)!}{(N-M)!(M-1)!}$$. Thus the final result of LHS in eq.1 should be:
$$\frac{(N-M)!M!}{N!} \frac{(N-1)!}{(N-M)!(M-1)!}=\frac{M}{N}$$
Comment: Your Doubt2 also confused me and Let me try to think about it.
Comment: I am sorry I think there are some problems for mine which is "sampling without replacement" while this paper is talking about "sampling with replacement" and to some extent I think your answer is correct.
Comment: Well I have to say that the minibatch weighted sampling is not "directly" correct for a couple of reasons. First, it can not go from first line to second line. Second, in the second line it should be q(z) rather than q(z,n). Third, it does not make any sense that you need the inequality term. More, the real machine learning is "sampling with replacement" and the i.i.d (aka sampling without replacement) is correct. My thought.
Comment: Wait guy! Got it! It does matter "sampling with replacement or sampling without replacement." For you answer:
$$\frac{N^M-(N-1)^M}{N^M}=1-(1-\frac{1}{N})^M \approx 1-(1-\frac{M}{N})=\frac{M}{N}$$(By Taylor approximation)
Comment: "Typo, ''It does not matter"
Comment: Wow! Taylor expansion was great. However, there is still a difference, one is biased, other is not. In section C.2 in the paper they calculate a unbiased Estimation of q(z) , using the same. So, I believe we are looking for unbiased one.
Comment: Also, since we are allowing replacement, we should instead be looking at
\begin{equation}
E(\text{#} i \in B_M) \\
= \frac{1}{N^M}\sum_{i=0}^{M-1}(M-i)(N-1)^i \\
\text{let }r = N-1,\text{ then}  \\
= \frac{1}{N^M}\frac{M(1-r) + r(r^M - 1)}{(1-r)^2}  \\
= \frac{(N-1)^{M+1} - N(M+1) + 1}{N^{M+2}} \\
\end{equation}


Should AWS CloudFront *increase* load time for infrequently accessed files?

Question: I am new to CDNs and experimenting with CloudFront. I have set everything up and all appears to be working fine. I can create a static image on a page and access it though my CloudFront distribution. I am using a custom origin (i.e. not an s3 bucket).
I'm worried that I might be worse off from a performance point of view though. I have a test page that is loading up the same 20 or so images with and without the CDN. Looking at the net panel in Firebug, the first time I load this page the images that are loaded directly from the origin server come in much faster. On subsequent page loads the benefits of the CDN become obvious -- after 3-5 refreshes the CDN is doing better than the origin server.
So I can see that on a popular page on our site that is being hit all the time, this will be a benefit. And I should expect a benefit because I'm in Seattle (around the corner from Amazon) and my server is in CA.
The thing is that if I leave the page for a few minutes and then reload, things are back to square one, with CloudFront being worse than the origin server. Is this expected? Do things drop out of the CDN "cache" so quickly?
Is it possible that something in my setup is hurting performance? Or is the reality that the CDN will only be a net positive for content that is currently being accessed every few seconds on average?
(cross posted from the AWS forum because I've been spoiled forever by SO's turnaround times)
UPDATE:
There are two good answers below that are worth looking at if you have questions about CloudFront performance. I recently found one explanation for my specific problem wasn't mentioned though. I had left TTL at 5 minutes as an oversight. Since I'm also using a custom origin there is an additional round trip to the authoritative nameserver to resolve that to the actual Amazon CloudFront domain. Now that the TTL setting is back to 12 hours it seems that the long loads happen more seldom.
Comment: Yes, it's possible that CloudFront is slower than just going directly to a fast server, because CloudFront is one of the slowest CDNs out there, due to the way Amazon has implemented it with multiple layers of DNS resolution, etc. Run some benchmarks from differnet locations around the world, and decide whether it's a good fit for you or not -- use http://www.webpagetest.org/ for testing.
Answer: It is possible. However, one purpose of a CDN is scalability. You can expect the CDN to perform the same if you throw 100 visits at once or 1 million visits at once.
As far as your setup goes, there's nothing that I can know with the information you provided, but I think that the point above is what makes a CDN so valuable. If you're creating a site that doesn't get a lot of traffic, you might be better off without the CDN. However, the CDN will provide a lighter load on your web server if you get a lot of traffic because you're passing off the serving of your media to another server. One last point, a good CDN (and Amazon's is) will user their extensive network to serve your content from the location closest to the requestor. In many cases, they can serve the content from the requestor's ISP, meaning VERY fast load times.
Hope that helps.
Comment: Thanks Jesse - very helpful. The point regarding scaling is well taken. And we have sufficient traffic for it to make a big difference. I would still love to know the caching policy though. I have found an enormous amount of info about HOW to set up the CDN and very little about its characteristics. I'm wondering, for example, whether I should exclude (from the CDN) old content that is accessed very infrequently.
Comment: Greg - I don't see an argument for excluding the content, other than maybe for financial reasons. You can, however, control the cache headers of your object in Amazon. You might try looking into this: http://stackoverflow.com/questions/269840/is-it-possible-to-change-headers-on-an-s3-object-without-downloading-the-entire-o
Comment: That would allow you specify far-future expires headers as you would with any normal web site's media.
Comment: Thanks again. That cache-control link isn't relevant to my situation because I'm using a custom origin server, not s3. But the principal applies and I do have far future expires headers set. BTW, Amazon's docs do say that content lives in the cache for 24 hours, but my experiments indicate something different.
Answer: Cloudfront sets a header in replies like "X-Cache: Hit from cloudfront" in replies. Presumably, it will say "Miss" if your file wasn't in the cache of the node to which you were directed.
It is possible that your files just aren't popular enough, so they get ejected from CloudFront's cache by more popular content even though 24 hours haven't elapsed. Is also possible that IO overload or some other circumstance inside of a particular CloudFront node makes access slow. Cloudfront is very inexpensive compared with Akamai or LimeLight. Worst-case performance and guaranteed service levels are two of the reasons to use the more expensive players.
I would do a test, putting just one popular file into cloudfront in production, and then use periodic tests to see if CloudFront is indicating hits (also record total transaction time).
Comment: I have updated the question with another potential explanation for the perf issue I saw, which is that I had left the TTL setting at the low setting of 5 minutes, but when switching back to 12 hours I don't think I'm seeing these occasional perf issues as often.
Answer: Have I misunderstood? Doesn't the cache-control manage how long things live at the edge locations before the edge locations reload them from S3? So surely they are relevant to your situation whether you use S3 or your own origin? No?
The Amazon FAQ says: "Q. How long will Amazon CloudFront keep my files at the edge locations? By default, if no cache control header is set, each edge location checks for an updated version of your file whenever it receives a request more than 24 hours after the previous time it checked the origin for changes to that file. This is called the "expiration period." You can set this expiration period as short as 1 hour, or as long as you'd like, by setting the cache control headers on your files in your origin. Amazon CloudFront uses these cache control headers to determine how frequently it needs to check the origin for an updated version of that file. If your files don't change very often, it is best practice to set a long expiration period and implement a versioning system to manage updates to your files."
[I assume the last sentence means "tough luck if you set it to 50 years and then want to change the file".]
Isn't the main point of using a CDN that it hosts static content? If so, would it help to use considerably longer TTL than one day? For virtually everything (all images and CSS), I use Cache-Control = "max-age=604800, public, must-revalidate" (i.e. 1 week). In my experience, files definitely do then take up to a week to change if I upload new versions onto S3.
Hope this helps. [BTW: On your more general point, I too wonder if a CDN helps performance as much as you think it's going to. I am about to move my entire site (CDN included) onto a super-fast dedicated server and do some tests to find out.]
Comment: You are correct that the cache-control influences how long the content is kept at the edge. The TTL is a separate matter though. TTL controls the caching of the IP address assigned to the domain name. So regardless of whether the static file is cached at the edge or not, the first time a server sees the URL of the file it has to find the IP address of this domain. With 1-day TTL, it is likely that a nearby server has this info in its DNS cache. With a 5 minute TTL this is much less likely and a complete round trip to my origin server is required (not for the file, but to resolve the URL)..
Comment: Ah OK thanks. I was confusing DNS TTL and cache-control :)
Answer: The reasons to use CDN is if you are expecting

Static content - infrequently or controlled updates
Viewed over the world
Accessed frequently

Our website is accessed infrequently as your case but we have a monitoring service setup that requests our website all over the world. So it keeps CDN caches warm. I would also like to share our case which is a simple one and demonstrates CDN capability.
Further more we are expecting a monthly charge of 2.2$ as opposed to 7$ for godaddy server(which cant handle surges)


SOMATÓRIO EM UMA COLUNA EM UM INTERVALO DE LINHAS

Question:
Tenho o seguinte banco de dados:
Gostaria de somar a INTE_C1 para cada mês.
Ou seja, pra janeiro somar do 1/1/2000 até 1/31/2000...
Comment: Bem-vinda ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/6700/como-fazer-uma-pergunta-reproduz%C3%ADvel-em-r/6701#6701) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Answer: Você também pode usar o pacote dplyr
library(dplyr)
summary <-  dados %>%
                  mutate (Date = as.Date(Date, "%m/%d/%Y"),
                          Mes = as.Date(Date, "%Y%m")) %>%
                 group_by (Mes) %>%
                 summarise (Soma = sum (INTE_C1, na.rm=TRUE)) %>%
                 ungroup ()

Caso queria aplicar isso para todas colunas você pode fazer da seguinte forma
summary <-  dados %>%
                  mutate (Date = as.Date(Date, "%m/%d/%Y"),
                          Mes = as.Date(Date, "%Y%m")) %>%
                 group_by (Mes) %>%
                 summarise_at (vars(INTE_C1:SO2), sum, na.rm = TRUE) %>%
                 ungroup ()

Se previsar de mais funcoes pode utilizar o seguinte:
summary <-  dados %>%
                  mutate (Date = as.Date(Date, "%m/%d/%Y"),
                          Mes = as.Date(Date, "%Y%m")) %>%
                 group_by (Mes) %>%
                 summarise_at (vars(INTE_C1:SO2), list (sum, mean, sd), na.rm = TRUE) %>%
                 ungroup ()

Uma outra sugestão é utilizar trabalhar os dados no formato longo da seguinte forma:
library (tidyr)
summary <-  dados %>%
                  mutate (Date = as.Date(Date, "%m/%d/%Y"),
                          Mes = as.Date(Date, "%Y%m")) %>%
                 gather (key = "Parametro", value = "Resultado", INTE_C1:SO2) %>%
                 group_by (Mes, Parametro) %>%
                 summarise (Soma =  sum(Resultado, na.rm = TRUE),
                            Media =  mean(Resultado, na.rm = TRUE)) %>%
                 ungroup ()

Comment: no formato longo é mais fácil trabalhar os dados, criar loops etc
Answer: Aqui vão duas maneiras de agregar uma coluna por mês.
Primeiro tem que transformar a coluna Date em verdadeira data.
dados$Date <- as.Date(dados$Date, "%m/%d/%Y")

Agora, somar a coluna INTE_C1 com aggregate.
Só com R base, o format cria um vetor de classe "character" com ano e mês.
mes <- format(dados$Date, "%Y-%m")
aggregate(INTE_C1 ~ mes, dados, sum)

Com o pacote zoo, também se obtém um vetor com ano e mês, de classe "yearmon" (year month).
mes <- zoo::as.yearmon(dados$Date)
aggregate(INTE_C1 ~ mes, dados, sum)

Código para criar os dados de teste.
set.seed(1234)

Date <- seq(as.Date("2000-01-01"), Sys.Date(), by = "day")
Date <- format(Date, "%m/%d/%Y")
INTE_C1 <- sample(20, length(Date), TRUE)
dados <- data.frame(Date, INTE_C1)


500 internal server error on a single node

Question: This just happend randomly today. I tried to access a page, but it keeps giving me a 500 internal server error http://www.austravel.com/holiday-destinations/australia
All the other pages are working fine. Any ideas why this may be?
Comment: Is there any error_log file in the root of the site?
Answer: Display PHP errors for that page or examine your Apache log file with errors enabled. Nobody can tell you what's misconfigured, or whatever typo you've made in your PHP ... log files can tell you though.
EDIT:
For further explanation on "errors" and specifically 500 error from Apache see:
https://stackoverflow.com/questions/8564259/php-5-3-troubleshooting-500-errors-debugging-parse-errors

PHP will respond with a "500" when it encounters a Fatal error, such
  as E_PARSE, E_ERROR and uncaught exceptions. 500 is the HTTP response
  code for "Internal Server Error" - something unrecoverable happened
  while processing the request.
In your php.ini, on a development machine, you should set your
  error_reporting level to (at least) E_NOTICE - preferably E_ALL - and
  make sure display_errors is on. This will show you the error message
  in the browser, including for "500" errors.
You can also check your Apache error logs, the errors will be listed
  there, as long as log_errors is enabled in php.ini. By default, this
  will be at \logs\error.log.
You can also control all this at run time with ini_set() and
  error_reporting()
Comment: Thanks tenken. I've asked the IT team here to take a look into this but I'm also trying to find the php error logs, as I think this will be a key to what is happening. The server has been configured very differently so may take a while to figure out. If I find the issue, I'll post it here for anybody that may have the issue in the future.
Answer: Sorry for not posting this sooner.
Just to answer @AgA yes there is a error_log file, I checked it and found the problem.
For anyone wondering, it was just a large image file that was breaking the page. I deleted it from the page and it worked fine.


Selenium webdriver usage plan?

Question: Well I'm going to post some thoughts about a usage of Selenium NOT WAITING for response, but you're welcome if you want to give tips or tricks.
Need to start automation testing project to test: UI, functionality and performance (not sure but is very possible).
Want use Selenium as the base element of our testing BUT I'm a little bit confused about the Architecture that need to use, as this is my first time creating from scratch a bundle framework for automation testing need to know some stuff, for example...
What's the correct way to work with Selenium? I know about Page Object pattern but not sure on how to implement it, does it needs a real architecture like in a regular web app like MVC, or Data access layer or whatever?... I can't find any example of a complete framework testing ANY test-web-page..
What I mean?
Need to know how to implement correctly Selenium, any architecture, maybe using other tools like TestNg, Cucumber, or whatever...
other thing is to implement some kind of code repository (maybe git?) to work with members collaboration..
AND THEN...
what I need to know about WHO'S going to execute my automated test cases? is there a robot for it? need to investigate more about that and everything else :)
Comment: Hi! Welcome to the site. Your post is written more like a blog post, may I suggest editing it to sound like more of a question?
Comment: Reading the question I am not sure what exactly is your problem. Maybe you could do some reading and experimentation first, and then ask more specific questions? Good helpful questions (that also attracts good insightful answers) requires clear thinking from the original poster (it is not always easy, but writing down the problem in clear form  helps you to understand what are the important questions - you could just write first privately and then share the questions that take a shape, one by one in Stackoverflow). Stackoverflow is not a place for personal diary.
Comment: Often things seem uphill when you start..but things often fall into place "when you start".  Ok avoiding the philosophy.. To understand a bit of what systems fit where, here's something based on my understanding of things : http://niharikawhatsnext.wordpress.com/2012/02/15/test-automation-to-building-to-execution-to-scheduling-java/  And finally, get started
Answer: It sounds like you are new to the testing world...and so, I'll explain basic concepts concerning what you asked.
Selenium takes the browsers on your machine and runs them.  That's it, simply.
Performance testing is possible, but I believe there are better tools for doing that.  I won't go into them here.
In order to write selenium code, there are really two parts...the selector and the action.   The selector tells WebDriver which element to perform the action on.  Because webpages change (but the actions may not), and because you may use an element twice in different places in your code, we separate the selector and the actions in our code.
The result of this is Page Objects.  In Java they look like this:
@FindBy(id = "logoffBtn")
WebElement logOffButton;

This says "In the HTML, there's an element that has an id of logoffBtn.  Next time I use logOffButton, find that element, and perform that action on it".
Now for the rest of your questions:
TestNG/Cucumber are testing frameworks.  They allow you to organize your tests, and make them flexible/powerful.
I'm not going into Git/Subversion.  They make it so different people can code on the same project, and are beasts of their own.
Finally, you can get your tests to run on different machines, but somebody has to own them and keep them running.  The common (and best) way to do this is with Selenium Grid.

Selenium webdriver usage plan?


How can I get count of deleted rows

Question: How can I get count of deleted rows after db_delete?
db_delete('node')
  ->condition('uid', 1)
  ->execute();

something like
$count = db_delete('node')
  ->condition('uid', 1)
  ->execute()->columnCount();

doesn't work
Answer: The delete query will return a query object for all methods except ->execute(). Methods can be chained until the query has been assembled. Execute() completes the chain.
Try:
$count = db_delete('node')
  ->condition('uid', 1)
  ->execute();

Comment: thanks. yes. the task was simple. Looks I simply had some mistakes in conditions of my query.
Answer: You can get count of deleted rows as follow:
db_delete('node')
  ->condition('uid', 1)
  ->execute();

$count = db_query('SELECT ROW_COUNT()')->fetchField();

print($count);

Answer: Next expression works:
$count= db_delete('node')
  ->condition('uid', 1)
  ->execute();

dpm($count);

db_delete returns count of deleted rows after execution.

How can I get count of deleted rows


Problema ao instalar o Flutter

Question: ao digitar o comando flutter doctor no cmd é exibido o seguinte erro:

Error: The Flutter directory is not a clone of the GitHub project. The flutter tool requires Git in order to operate properly; to set up
Flutter, run the following command: git clone -b stable https://github.com/flutter/flutter.git

Eu já mudei as variáveis do path de instalação, já reinstalei o git e nada funcionou, já executei o comando de dentro da pasta e infelizmente nada aconteceu. Alguém poderia me ajudar?
Comment: Ele está reclamando que o Git não está buscando um clone e tal. Não utilizo o Git por isso não sei como resolver, mas recomendo que procure algo do tipo e veja se há alguma configuração automática ativa e tente um outro editor (MS Code ou Android Studio) e veja se o mesmo acontece. Veja também se no windows há uma configuração armazenada em disco com relação a algum editor ou extensão que utiliza o Git e tente excluir.
Comment: Uma boa dica é utilizar o FVM - Flutter Version Management, com ele fica bem mais fácil o processo de instalação do Git e de diversas versões do Flutter, bastante setar qual é a versão que deseja utilizar em determinado momento. Fica a dica, entre em www.fvm.app, um bom começo é assistir um vídeo do Jacob Moura em https://www.youtube.com/watch?v=GSamxnXIRhg.
Answer: O Flutter procura por uma pasta git que normalmente é pasta oculta. Se você usou o modo copiar/colar do arquivo zip pode ser que esta pasta tenha sido perdida.
Você pode resolver copiando a pasta externa do flutter para incluir todos os arquivos ocultos ou executar o comando que o erro passa, que é:
git clone -b stable https://github.com/flutter/flutter.git

E o caminho que segui para instalação foi:
1 - Download do sdk no site oficial
2 - Extrair o arquivo (renomeei a pasta apenas para flutter) e colocar em um local preferencialmente sem a necessidade de privilégios. - O meu fica em C:\flutter
3 - Adicionar nas váriaveis do ambiente o caminho C:\flutter\bin ou o caminho que você selecionar para manter o sdk
Answer: Como voce fez a instalação do flutter?
Verifica se tua versão tá atualizada.
Usa o comando flutter upgrade para pegar a última versão estável.
Caso necessário, remove a instalação já feita e executa uma nova instalação.
Baixa o SDK direto no site https://flutter.dev/docs/get-started/install/windows
, depois extrai o arquivo zip dentro de C:/src/flutter, como a Google recomenda e executa o arquivo flutter_console.
Se executar sem problemas, adiciona a pasta C:\src\flutter\bin ao PATH de variáveis de ambiente.
Lembrando que é preciso ter o git instalado na máquina.

Problema ao instalar o Flutter


How can I test command-line applications using maven?

Question: I work on a complex, multi-module maven project. One of the modules is an executable jar that implements a command-line application. I need to integration test this application. I need to run it several times, with several different command-lines and validate the exit status and stdout/err. However, I can't find a plugin for maven that claims to support this, and also can't track down a JUnit library that supports testing command-line applications.
Before you say 'don't test the main method - instead do bla', in this case I really do mean to test the main method, not some subsidiary functionality. The whole point is to run the application as a user would in its own VM and environment, and validate that it is behaving itself - parsing command-line options correctly, exiting with the write status and hot-loading the right classes from the right plugin jars.
Answer: My current hack is to use apache-exec from within a junit test method. It appears to be working, but is quite fiddly to set up.
public void testCommandlineApp()
        throws IOException
{
    CommandLine cl = new CommandLine(resolveScriptNameForOS("./runme")); // add .sh/.bat
    cl.addArgument("inputFile.xml");

    exec.setWorkingDirectory(workingDir);
    exec.setExitValues(new int[] { 0, 1, 2 });

    int exitCode = exec.execute(cl);

    assertEquals("Exit code should be zero", 0, exitCode);
}

Comment: You could also use the standard ProcessBuilder class, but yes, it's fiddly. (Factor out some of the more fiddly bits…)
Answer: Why not simply use a shell script, using the maven-exec-plugin to build your classpath?
STDOUT=$(mvn exec:java -DmainClass=yourMainClass --arg1 --arg2=value2)
RETURN_CODE=$?

# validate STDOUT
# validate RETURN_CODE

You can even use something like shunit2 if you prefer a more structured approach.
Comment: The problem with this is that it is platform-specific. I realise that anything to do with running command-line apps will have some stuff that only works on windows or linux or whatever, but scripting the test in sh is probably going a step too far.


Show that there exists a subspace $W \subset \mathcal{P}(4)$ such that $\mathcal{P}(4) = \mathcal{U}(4) \oplus W.$

Question: Let $\mathcal{U}(4)$ be a subspace of $\mathcal{P}(4)$ consisting of polynomials that are even functions. Show that there exists a subspace $W \subset \mathcal{P}(4)$ such that $$\mathcal{P}(4) = \mathcal{U}(4) \oplus W.$$
Additionally,
I know that a function $f:\mathbb{R} \mapsto \mathbb{R}$ is even if $f(x) = f(-x)$ for all $x$.
And that a function can also be expressed as the sum of an odd an even function $$f(x) = \frac{f(x)+f(-x)}{2} + \frac{f(x)-f(-x)}{2}.$$
Answer: $$\mathcal{U}(4)=Span(1,x^2, x^4), \mathcal{W}=Span(x,x^3)$$
Comment: My pleasure, happy to help.
Comment: Thanks! :) Clarified everything.


Intuition why the derivative of $e^x$ is itself

Question: Is there an intuitive reason why the constant $e$ to the power of $x$ has a derivative that equals the value of the function? I know that this is the result of differentiating, and I've seen several proofs of how you work out the derivative, I was just wondering why this is and why it is the case for a number estimated from constant growth?
Comment: If you compute the derivative of $b^x$, you find that the answer is $b^x$ multiplied by an annoying constant. So we then ask, is there a special value of $b$ that makes that annoying constant equal to $1$. The answer is $b = e$. In my mind this is how we discover the constant $e$.
Comment: https://www.youtube.com/watch?v=m2MIpDrF7Es for a very nice video about what @littleO was saying
Comment: @user1936752 This is exactly the video I would have recommended!
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: How do you define $e^x$? The answer is different depending on the definition. For example, if you define $\exp$ as "the function whose derivative is equal to itself, with value $1$ at $x=0$", then it's trivial.
Comment: I'm not sure I'm just not getting the obvious here, I was just wondering, is there a reason why b is equal to the constant we get when we estimate what value we get from constant growth? Is the fact that e makes the constant equal to 1 related to the fact that it is derived from estimating constant growth?
Answer: Maybe a nice way to see it is the power series expansion:
$$\forall x\in \mathbb{R} \colon e^x =1 + x + \frac {x^2} {2!} + \frac {x^3} {3!} + \cdots
$$
Answer: By definition,$$\frac{d}{dx}a^x=\lim_{h\to0}\frac{a^{x+h}-a^x}{h}.$$Each exponential function has the nice property $a^{x+h}=a^xa^h$, so we can take out an $h$-independent $e^x$ factor, making the above limit the original function $a^x$ times just a number, namely $\lim_{h\to0}\frac{a^h-1}{h}$. This limit is in turn, by definition, the derivative of $a^x$ at $x=0$. Now if we gradually increase $a$ from just above $0$ to not quite $\infty$, $a^x$ will get steeper and steeper at $x=0$. And $e$ is just the choice of $a$ for which the slope is $1$, so that $e^x$ is its own derivative.
Answer: Something that might lend some intuition, is that
$$
e^x=\lim_{n\to\infty}\left(1+\frac xn\right)^n=\lim_{n\to\infty}\left(1+\frac xn\right)^{n-1}
$$
and
$$
\frac{\mathrm{d}}{\mathrm{d}x}\left(1+\frac xn\right)^n=\left(1+\frac xn\right)^{n-1}
$$
It takes a little bit to make this rigorous, but intuition and rigor often follow different paths.
Comment: I really like this answer, but I wonder how one would _intuitively_ draw the connection between the statements $$e=\lim\limits_{n\to\infty}\left(1+\frac1n\right)^n\quad\text{and}\quad e^x=\lim\limits_{n\to\infty}\left(1+\frac{x}{n}\right)^n.$$
Comment: Perhaps $$ \begin{align} \lim_{n\to\infty}\left(1+\frac xn\right)^n &=\lim_{n\to\infty}\left(\left(1+\frac xn\right)^{n/x}\right)^x\\ &=\left(\lim_{n\to\infty}\left(1+\frac xn\right)^{n/x}\right)^x \end{align} $$
Comment: I understand this line of thinking, but this assumes $x\neq0$, does it not?
Comment: Why worry about $x=0$? That obviously gives $1$ on both sides.
Comment: The right side looks to be in the form $(1^\infty)^0=1^{\infty\cdot0}$.  Should this be a problem?
Comment: Never mind, this is a silly comment.  Need my morning coffee.
Comment: What I meant was $ \lim\limits_{n\to\infty}\left(1+\frac0n\right)^n=1$ and $e^0=1$.
Answer: If $x$ changes by $1$, then the function changes from $e^x$ to $e^{x+1} = e\cdot e^x.$
If $x$ changes by $2$, then the function changes from $e^x$ to $e^{x+2} = e^2 e^x.$
If $x$ changes by $h$, then the function changes from $e^x$ to $e^{x+2} = e^h e^x.$  In each case the change in the function is $e^x(e^h-1)$, which is $e^x$ times some number.  This is true for any base, but for $e$, the "some number" over $h$ happens to tend to $1$.
Answer: The slope of the tangent line at point $x$ is always equal to the value of $f(x) = e^x$. This may be the intuition you're looking for. And this is true for every point $x$. And it is true for every point $x$ only for functions of the form $e^x + const$. That makes $f(x) = e^x$ quite "special" if you think about it from geometrical perspective.
How to see this? Draw in one plane: 1) the graph of $e^x$, 2) the unit circle, 3) the line S with the equation $x=1$ (on which values of $\tan$ are measured).
Take any point $x_0$ and draw the tangent line $L_0$ to the graph (of $e^x$) at the point $(x_0, e^{x_0})$. Now draw a line $L_1$ passing through $(0,0)$ and parallel to the tangent line $L_0$. Note the height at which $L_1$ intersects the line $S$. The special ting here is that this height is always equal to $e^{x_0}$ i.e. to the value (at point $x_0$) of the function itself. In a way that property is quite remarkable especially since it holds for every value of $x$ ($x_0$ was taken arbitrary here).
Why remarkable? Because as we know no other function (apart from the functions $g(x) = e^x + const$) has this property (no other function has it for every $x$, I mean).
Comment: I don't think OP asked for intuition for the meaning of the statement, rather for why it is true.
Comment: @Wojowu Hm... I think the title and the question clearly designate the opposite. The title itself talks about $intuition$.
Comment: Yes. *Intuition why it's true*.
Comment: Let's see what the OP thinks... I think I understood their ask correctly.
Comment: @Wojowu Btw, that is exactly why it is true. Because the meaning of the derivative is just that and it happens to be equal to the value of the function... and that happens to be true for every $x$. That's exactly what intuition, insight, etc. is about.
Comment: Thank you for this explanation, I think I might've worded my question incorrectly. I was thinking more along the lines of, the intuition to why a constant defined in a way that estimates the value of constant growth would give us a number that when taken to the power x would give us a derivative that is equal to the value of the function. Sorry for any misunderstanding.


Shifting the total group by 1 step- MYSQL

Question: Here I have name and pay as columns of a database table.
Table has Name and Pay(sorted lowest to highest) as columns and "column I need" is the required column.

I need the rightmost column, it is displaying basically the next pay.
Gross, Stanford pay is 14, the next highest pay is 15. Likewise for others.
How can I do this?
Any help is appreciated.
Comment: Can you show an expected result?
Comment: Please only tag the relevant RDBMS, and see [Why should I provide an MCRE for what seems to me to be a very simple SQL query](http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query)
Comment: Please add information of calculating the rightmost column. I can't figure it out why Darson and Meads have got different values ?
Comment: Column sorted by pay.Here Darson next highest pay is 22, similarly, Meads Next highest pay is 20
Answer: I understand that you want the "next" value pay.
If you are running MySQL 8.0, you can use window functions and a range frame:
select t.*,
    min(pay) over(order by pay range between 1 following and unbounded following) next_pay
from mytable t

In earlier versions, an alternative is a correlated subquery:
select t.*,
    (select min(t1.pay) from mytable t1 where t1.pay > t.pay) next_pay
from mytable t

Comment: @RamyaM: your sample data did not show decimals. Say you have 2 decimal digits, you might want to use `over(order by pay * 100 range between 1 following and unbounded following)`. Or just use the subquery solution, that works regardless of the numeric type.
Comment: Thank you for the answer. This is working if the pay is integer but when there is a decimal to it. Its showing a different number.


IIFE and function hoisting - is not a function error

Question: var Mod=(function () { say('hello');
             var say =  function (m){ console.log(m); };
              return ({a: 'b'}); }
 )();

VM3488:1 Uncaught TypeError: say is not a function(…)(anonymous function) @ VM3488:1(anonymous function) @ VM3488:1
but this works
var Mod = (function () {
              say('hello');
              function say (m){ console.log(m); };
              return ({a: 'b'}); }
     )();

why is this happening ? If I need to use "say" as a public function in my Mod, how is that going to work ?
Comment: It has nothing to do with the IIFE but read this: http://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order/3887590#3887590
Answer: That's because function expressions are not hoisted. The first one is a a function expression and the second one is a function statement which is hoisted.
Also note that neither of your code snippets exports the say function so it remains as a private function.
Comment: thx for the quick reply. What pattern do I need to follow if I need to expose "say" as a public method ?
Comment: @KaPr It can be a method of the returned object: `return { say: say, a: 'b' }`. Or in ES2015: `return { say /* shorthand syntax */, a: 'b' }`
Answer: Function expressions are not hoisted, which is why you are getting an error. You can move the expression before invocation and return the variable as a response to your IFFE. Now you can call say() in other places.

var Mod=(function () {
             var say =  function (m){ console.log(m); };
              say('hello');
              return {say: say};
})();

Mod.say("say what you want to say.");


Long Range Wifi Equipment & Software

Question: I am looking to set up a somewhat logn range WiFi "hot spot" that will cover a radius of about 100 - 200 metres.  This network is meant to serve people in my building and adjacent buildings.
It is a "mini ISP" in that I would like to charge people in this region for Internet access.
Could you please point me towards the kind of equipment and software that I should be looking at?  Any tips?
Answer: I'd start by getting to know WiFi equipment, like really well, including the more structured deployment techniques and equipment (look at corporate gear, not SOHO). With an area that big (assuming it's got lots of walls and solid stuff in there) you'll need several APs. You could use pretty cheap equipment, but you often get what you pay for. I hate to direct you to Google (we have a policy against shopping questions, which this partly is...) but there are manufactures that really specialize in small WISPs like what you want to start.
Answer: For an integrated solution at reasonable cost, look at Open Mesh. If you have questions about it, this forum is helpful. There is lots of hardware from different manufacturers for sale at Streakwave.
Answer: One thing that certainly won't work would be trying to set up one powerful indoor Wi-Fi AP in your apartment with a signal that reaches into the rest of the apartments in your building and nearby buildings so well that people can just associate their laptops and smartphones to your one mega-AP.
Outdoor Wi-Fi gear can use higher power, but doesn't necessarily have good in-building penetration. The stuff sold for longer ranges is generally for point-to-point links with directional antennas.
There are systems for rooftop "point to multipoint" wireless broadband, but those require you to install rooftop receivers for each subscriber, and I'm not sure that's the way you're trying to go. Trango is a brand that springs to mind.
The best way to set up Wi-Fi access to all the rooms/apartments of a series of buildings is with a fleet of "enterprise" or "public access" class Wi-Fi APs, positioned strategically throughout the buildings for appropriate coverage. There are many players in this market, including Cisco, Aruba, Trapeze, Enterasys, HP Procurve, Ruckus, Xirrus, Meru, Meraki, Aerohive, and many others. There are also many VARs that will help you do a site survey to plan your network to make sure it meets your coverage and speed goals.
Answer: Try looking at smallnetbuilder - there will be reviews of the sort of prosumer gear that might be viable for these sorts of uses.
Answer: I am a fan of Aruba Networks, they have great gear. It takes a bit to setup, and the price may not be what you're looking for, however the network once set up is rock solid.
If you are looking for a cheaper solution you can look at Ruckus Networks, we use them at my office and have a great setup and easy install.

Long Range Wifi Equipment & Software


How to get the the most recent queries in Oracle DB

Question: I have a web application and I doubt some others have deleted some records manually. Upon enquiry nobody is admitting the mistakes. How to find out at what time those records were deleted ??  Is it possible to get the history of delete queries ?
Comment: You would want to use Log Miner to go through the archived logs to find the delete statements that you are interested in.  That can be quite time consuming if you aren't sure when the deletes happened.  It is possible that they would still be cached in v$sql but that is not certain.  And unless the queries used literals, you would not know the bind values used when the queries were executed.
Answer: If you have access to v$ view then you can use the following query to get it. It contains the time as FIRST_LOAD_TIME column.
select *
from  v$sql v
where upper(sql_text) like '%DELETE%';

Answer: If flashback query is enabled for your database (try it with select * from table as of timestamp sysdate - 1) then it may be possible to determine the exact time the records were deleted. Use the as of timestamp clause and adjust the timestamp as necessary to narrow down to a window where the records still existed and did not exist anymore.
For example
select *
from table
as of timestamp to_date('21102016 09:00:00', 'DDMMYYYY HH24:MI:SS')
where id = XXX; -- indicates record still exists

select *
from table
as of timestamp to_date('21102016 09:00:10', 'DDMMYYYY HH24:MI:SS')
where id = XXX; -- indicates record does not exist

-- conclusion: record was deleted in this 10 second window


What are the conditions of applicability of linear regression?

Question: I am looking for a list of "Conditions of applicability of linear regression" to finish a work, but I cannot find any reference of this in any book.
I founded something in several links, but in one of this the conditions are 5, in another 4, in another 10, so I am not sure what are the correct list of "Conditions of applicability of linear regression"
Thanks.
Answer: Basically the below are the assumptions of linear regression-
- Error should be normally distributed with mean zero and constant variance
Which means the residual should be randomly distributed without any particular pattern.
If there is any pattern in the error , that might be because of non linear data.
-Error should be independent.
Comment: Thank you for your contribution, Manisha.  You might enjoy reading the duplicate thread because it discusses the assumptions you haven't listed.


Problem with the template of a view

Question: I created a template to customize labels views. But the fields are not displayed between labels.
Here are the views-view-field--sitemap--views-data-export--field-image.tpl.php :
<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

echo $fields["field_image"]->content;

and here are the views-data-export-xml-header--sitemap.tpl.php :
<?php print '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
?>

and the result :
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">  <url>
    <loc>http://www.s1biose.com/boutique/produit/savon-d-alep-artisanal-bio-pure-olive</loc>
    <image:image><image:loc>http://www.s1biose.com/sites/default/files/image/boutique/savon-d-alep-artisanal-bio-pure-olive-photo-1.jpg</image:loc></image:image>
  </url>
  <url>
    <loc>http://www.s1biose.com/boutique/produit/savon-d-alep-artisanal-bio-5-de-laurier</loc>
</urlset>

The result should be :
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <url>
    <loc>http://example-1.com/sample.html</loc>
    <image:image>
      <image:loc>http://example-1.com/image_1.jpg</image:loc>
      <image:title>title image 1</image:title>
    </image:image>
    <image:image>
      <image:loc>http://example-1.com/image_2.jpg</image:loc>
      <image:title>title image 2</image:title>
    </image:image>
  </url>
  <url>
    <loc>http://example-2.com/sample.html</loc>
    <image:image>
      <image:loc>http://example-2.com/image_1.jpg</image:loc>
      <image:title>title image 1</image:title>
    </image:image>
    <image:image>
      <image:loc>http://example-2.com/image_2.jpg</image:loc>
      <image:title>title image 2</image:title>
    </image:image>
  </url>
</urlset>

Comment: Is the template even used? Tried flushing caches?
Comment: try changing your first line to `$fields["field_image"]->content = '' . $row->field_field_image[0]['rendered']['#item']["uri"] . '' . '' . $row->field_field_image[0]['rendered']['#item']["alt"] . '';`
Comment: @No Sssweat :-) thank you it works but it displays 1 image instead of 3. There is also a problem with the url because it starts with "public: //" instead of "http: //"
Comment: `instead of three` **[three ???](https://www.google.ca/search?q=three&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiB9MX3q_LMAhUOPlIKHXZvBw4Q_AUIBygB&biw=1280&bih=637)**
Comment: @No Sssweat yes
Comment: @Mathieu are you using unlimited values for your image field? or do the other 2 images belong to another node?
Comment: @No Sssweat all images belong to the same node, multiple parameter fields values is set to 4. I've updated the question
Comment: @No Sssweat you know how I can view the full URL of the image? I've updated the question with the results that it should give.
Comment: @Mathieu updated my answer.
Answer:
you know how I can view the full URL of the image?

I found it, replace your 1st line with:
$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

thank you it works but it displays 1 image instead of 3

In views click on your image field, click on MULTIPLE FIELD SETTINGS uncheck display all values in the same row.
Comment: I found this https://www.drupal.org/node/2061697
Comment: super thank you to the url complête it works. But for the image, you need the image belonging to the same node are grouped together. As in the last catch of the question.
Comment: Google Search Console does not recognize the tags
 image:loc and image:title :(
Comment: this is what it shows, just with the tag
 http://www.s1biose.com/sitemap-produit.xml

Problem with the template of a view


How do I use the keydown function on a winform through other windows?

Question: I have this piece of code
<code>private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode== Keys.Z)
        {
            BarTimer.Value = 0;
            timer1.Start();
            timer1.Interval = 500;
            BarTimer.Minimum = 0;
            BarTimer.Maximum = 80;
        }
    }
</code>
And it works just fine, but I want to be able to press it when in a fullscreen application, so I can see the progress bar on my second monitor. Is there a property or something i can change to make it work like that?
Comment: Do you mean to respond to the key, when the typing focus isn't in your form, but is in another screen?
Comment: Is the other screen within your application, or can it be in any other application?
Comment: It's a different application
Answer: If it's a single key you can use RegisterHotKey.  There is sample code in this answer: how to use RegisterHotKey and the one linked in it.   The Microsoft C++ documentation is here.
If you want to intercept all keyboard input you would need a keyhook.  I suggest you google WH_KEYBOARD_LL and SetWindowsHookEx.  But I don't think you can do this in c#; I've only ever seen key hooks written in C/C++.  They will also cause some firewalls to take an interest - intercepting all keyboard input can be considered potentially hostile.
Answer: Hi I know of a nice tutorial I found On code project.
It worked for me when i needed something like this.
http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
Regards,


google API - gcalcli - erro ao executar em um script

Question: Dando continuidade ao meu problema relatado aqui agora eu consigo enviar eventos do shell-script diretamente para o google calendário, fiz um script para executar conforme programado, segue arquivo sms.sh abaixo
<code>#!/bin/bash
let oneminf=`date +%s`+600
dateonemin=`date -d @$oneminf +%R`
gcalcli --calendar 'zabbix' --title "$3" --when $dateonemin --reminder '1m sms' --where '' --descr '' --duration 1 add > /dev/null 2>&1 >> /tmp/zabbix_server.log
</code>

Este script foi foi elaborado com base nesse link

Quando executo ele diretamento do shell ele faz a inserção na agenda
<code>$/etc/zabbix/scripts/sms.sh "[parametroZabbix]:PROBLEM"
</code>
Porém quando o programa zabbix dispara a trigger que chama esse arquivo sms.sh ele me da uma mensagem de saída assim:
<code>    Sign in with your Google Account

[avatar_2x]

Email [                    ] Password [                    ] [Sign in] Need
help?
Create an account

One Google Account for everything Google

[logo_strip_2x]

  ⢠Google
  ⢠Privacy
  ⢠Terms
</code>
Já fiz o comando $gcalcli agenda --noauth_local_webserver com o usuário zabbix que é o usuário que executa a aplicação, e mesmo assim ele continua dando esse erro.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54269/discussion-on-question-by-sneeps-ninja-google-api-gcalcli-erro-ao-executar-e)
Answer: Para quem estiver ainda interessado eu reiniciei a maquina ( linux ) e voltou a funcionar normalmente, muito estranho...


Rendered do primefaces dando erro ao recuperar boolean de entidade

Question: Alguém sabe dizer por que o rendered do graphic image está dando erro???

                            <h:commandLink>
                                <f:ajax render=":formProjetista:projetistaSelecionado" event="click" listener="#{projetistaBean.selecionarProjetistaAtual()}" />
                                <h:panelGrid columns="1" style="border: none; width: 160px; text-align: center; "  >

                                    <h:panelGroup>
                                        <h:graphicImage value="resources/imagens/membroR3ePequeno.png" rendered="#{projetista.pertenceMembroR3e}"  />
                                        <h:graphicImage value="resources/imagens/membroOIAPequeno.png" rendered="#{projetista.pertenceMembroOIA}" style="margin-left: 4px;"/>
                                        <h:graphicImage value="resources/imagens/membroAntacPequeno.png" rendered="#{projetista.pertenceMembroAntac}" style="margin-left: 4px;"/>
                                        <h:graphicImage value="resources/imagens/ServicoConsultoriaPequeno.png" rendered="#{projetista.pertenceConsultor}" style="margin-left: 4px;"/>
                                        <h:graphicImage value="resources/imagens/possuiEtiquetaAPequeno.png" rendered="#{projetista.pertenceEtiquetaA}" style="margin-left: 4px;"/>
                                        <h:graphicImage value="resources/imagens/possuiEtiquetaBPequeno.pmg"  style="margin-left: 4px;" rendered="#{projetista.mostrarEtiquetaB}" />
                                    </h:panelGroup>
                                    <h:outputText value="#{projetista.nome}"/>
                                </h:panelGrid>
                            </h:commandLink>

Aqui está o código da entidade que utilizo para buscar o boolean para a renderização:
@javax.persistence.Entity
@Table(name = "projetista")
public class Projetista extends com.labcon.r3e.entity.Entity{

    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "nome", nullable = false)
    private String nome;

    @Column(name = "cidade", nullable = false)
    private String cidade;

    @Column(name = "email", nullable = false)
    private String email;

    @Column(name = "instituicao" , nullable = false)
    private String instituicao;

    @Column(name = "membro_r3e" , nullable = false)
    private Integer membro_r3e;

    @Column(name = "membro_antac" , nullable = false)
    private Integer membro_antac;

    @Column(name = "membro_oia" , nullable = false)
    private Integer membro_oia;

    @Column(name = "consultor" , nullable = false)
    private Integer consultor;

    @Column(name = "possui_projeto_a", nullable = false)
    private Integer possui_projeto_a;

    @Column(name = "possui_projeto_b" , nullable = false)
    private Integer possui_projeto_b;

    @Lob
    @Basic(fetch= FetchType.LAZY)
    private byte[] imagem;

    public Projetista() {

    }

    public boolean getPertenceMembroR3e(){
        return this.membro_r3e == 1;
    }

    public boolean getPertenceMembroAntac(){
        return this.membro_antac == 1;
    }

    public boolean getPertenceMembroOIA(){
        return this.membro_oia == 1;
    }

    public boolean getPertenceConsultor(){
        return this.consultor == 1;
    }

    public boolean getPertenceEtiquetaA(){
        return this.possui_projeto_a == 1;
    }

    public boolean getPertecenteEtiquetaB(){
        return this.possui_projeto_b == 1;
    }

    public boolean getMostrarEtiquetaB(){
        if(this.possui_projeto_a == 1){
            return false;
        }else return this.possui_projeto_b == 1;
    }

Aqui está o stack trace:
java.lang.NullPointerException
at com.labcon.r3e.entity.Projetista.getPertenceMembroR3e(Projetista.java:77)
at sun.reflect.GeneratedMethodAccessor511.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:182)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:297)
at com.sun.faces.renderkit.html_basic.GroupRenderer.encodeChildren(GroupRenderer.java:105)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:304)
at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:55)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:43)
at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:51)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:424)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

Comment: Acredito que a melhor forma de atacar a raiz do problema seria mudar a propriedade Not Null da coluna respectiva para false, e de seguida sincronizar com as entidades.
Comment: O problema é que o seu `Integer` está nulo. O fato de usar o atributo `nullable=false`, só te impede de salvar o campo com o valor nulo, mas não impede de buscar uma entidade em estado inconsistente. Aconselho a fazer uma carga na sua base, setando como 0 esses registros/colunas inválidas.
Comment: mas todos os conteúdos da base de dados estão ou com valor 0 ou com valor 1 nestas colunas
Comment: mas fiz o teste a nível de aplicação para verificar se as colunas estavam setadas como nulas. Caso estivessem retornaria false e deu certo
Answer: A solução do problema, como sugerido pelo usuário Wakin ontem, era setar os valores de Integers que estivessem como nulos


Theorem 1.8(viii) Proof of Mathematical Statistics - Jun Shao

Question: I have some questions about the proof of Theorem 1.8(viii) of Jun Shao's Mathematical Statistics.
The theorem is stating that If $X_n$ converges to $X$ in distribution, then for any $r > 0$, $lim_{n \rightarrow \infty} E\|X_n\|^r_r = E\|X\|^r_r < \infty$ if and only if ${\|X_n\|^r_r}$ is uniformly integrable.
My first question (highlighted in blue) is, why may we assume $X_n \rightarrow X$ almost surely by (iv)? The theorem guarantees only another set of random vectors $Y, Y_1, \cdots$ such that $Y_n \rightarrow Y$ almost surely.
My second question (highlighted in green) is, why is it that $\lim \sup_n E(\|X_n\|^r_r I_{B_n}) \leq \lim \sup_n E(\|X\|^r_r I_{B_n})$? There doesn't seem to be a statement that $X_n$ is monotone or ascending?
Thanks much in advance.
Here is the theorem and its corresponding proof:
Answer: For the blue question - this is a little subtle. Skorokhod's representation theorem indeed only gives a sequence $Y_n$ that converges a.s. to $Y$, and this may indeed be distinct from $X_n$ (roughly the point is that this representation doesn't need to preserve joint distributions, only the marginal for each $X_n$, so you may well have an $X_n$ that doesn't converge a.s. and only does in distro). However, in this case, all you care about are functionals on these marginal distributions, namely the $r$th moments of each of the $X_n$. So you might as well make the argument for this $Y_n$ and $Y$ - the $X_n$ will inherit the same since $P_{X_n} = P_{Y_n}$ for each $n$ and $P_X = P_Y$. This allows you to assume that $X_n \to X$ a.s. without loss of generality.
For the green question - no this doesn't imply monotonicity, and is just a property of sequences. Suppose for two sequences $a_n, b_n$ it holds that $a_n - b_n \to 0.$ Then for any $\varepsilon > 0,$ taking large enough $n$, $a_n \le b_n + \varepsilon$, and so $\limsup a_n \le \limsup b_n + \varepsilon$. But $\varepsilon$ is arbitrary, so this tells you that $\limsup a_n \le \limsup b_n$. In this case $a_n = \mathbb{E}[ \|X_n\|_r^r I_{B_n}], b_n = \mathbb{E}[\|X\|_r^r I_{B_n}].$
Comment: Thanks! They are all very clear to me now.


Are all classical guitar pieces composed based on chord progressions?

Question: For the last few days I enjoyed playing Fernando Sor's "Study in B Minor" mostly because chords that I had learned could be found throughout the piece and I deemed it more "organized".
I moved on to the next piece which was "Minuet in C" by the same composer, I could not identify chords as I could with "Study in B Minor".
So my question is, are some pieces written more randomly (without chord progressions) than other pieces OR is it just that I am incapable of finding the chords that fit?
Comment: I allowed myself to edit the title of the question, but now I wonder, do you mean chords as shapes on guitar (e.g. the popular form of C major: x32010), or chords as in harmony (e.g. C major as any inversion and form of C major that could be played in any place on the fretboard, or any instrument).
Comment: The question isn't quite clear. The title mentions "chord sheets"; to my mind this means printed "lead sheet" notation, i.e. a piece of paper that says, like, "C ... Am ... D7" etc. But the question seems to be more about compositional content. I suspect that "chord sheets" in the title is misleading and you're actually reading from traditional staff notation, and your question is "are all pieces composed 'chordally,'" but there's an outside chance that you're actually learning these pieces by ear or from some other notation. Please clarify.
Comment: yes you are right. The question should have been "are all pieces composed 'chordally;?" I am reading traditional staff notation. But "Study in B Minor" was composed so chordally that I thought it could have been written in a chord sheet.
Comment: Do you have a link to the "Minuet in C" you're talking about? I checked this on youtube, and if it's Sor's opus 25, then that sounded very chordal to me, something that could work as a fake book version, a melody with chord symbols and some improvisation.
Comment: I meant chords as in harmony. And yes, it is Sor's opus 25 and sounds chordal, too. But on the score I can only sparsely find chords that fit.
Comment: If it sounds chordal, it is chordal. Whenever you hear a chord, look at what notes are sounding, that's your chord, even if the shape looks unfamiliar. If you want to find a name for it, find the root note, third, possible seventh, lowest note to see what inversion it is. After that you know both a fingering pattern and a name for it, so you can add it to your chord pattern table. Keep doing this and your musical vocabulary gets larger and your ears get better. Try to play by ear without reading as well.
Answer:
are some pieces written more randomly (without chord progressions) … ?

Yes, but it's not random. A chordal approach to music is only one way to write music, and I believe if we examined all music written down in notation that we can understand, we would find that music written from a chordal perspective is less than 50% of the history of music.
It is definitely helpful as a classical guitarist to examine pieces for note groups that can be played with a familiar chord shape. I write these chord shapes into the music when I see them.
At the same time, there is plenty of literature where some or all of the piece does not lend itself to any chord shapes. Sometimes it can help to think about partial shapes and other times we just have to learn the music without the mnemonic device of chords.
I highly recommend you invest in a copy of Estudios Sencillos (simple studies) by Leo Brouwer. This collection of 20 short pieces is both a powerful tool for learning classical guitar as well as excellent music on its own. It came to mind because these studies have a mix of chordal and not chordal ideas, and even some of the chordal pieces use unusual shapes that are probably not familiar to you.
Expanding your ability to read guitar music without needing to see chord shapes (while still seeing them when it's helpful) will unlock a bigger, exciting world of music for you. I think you will enjoy the journey.
Comment: It's helpful to recognize familiar chord shapes, but it's even more helpful to recognize the harmony (if there is any).
Comment: This answer probably contains true statements about music. But the OP's example tune seems to be quite chordal https://www.youtube.com/watch?v=jA85pZPOrKI   To me that sounds like a melody line with comping chords. Can't be much more chordal than that?
Comment: @piiperiReinstateMonica I interpret the question as being about music in general, not about any particular pieces. Also, even if any number of particular pieces can be made easier using chord shapes, many classical guitar pieces have sections or are entirely not helped with chord shapes. I stand by my recommendation that the asker learn to play both with and without chord shapes.
Comment: Yes, I meant that this answer addresses the question as it was presented. The OP even claims he means chords as in "harmony", which I understand as in "sound". But if we consider the example piece that was supposedly non-chordal... It's actually completely chordal. The OP has a _problem_ which differs from the question, so even if the question is correctly answered, how can the OP accept the (correct) answer if it doesn't solve his actual problem. Which is something like thinking, if a fingering pattern isn't listed in a guitar chord table, then it's not a chord. Or something.
Comment: @piiperiReinstateMonica My interpretation is different, but I'm not convinced my interpretation is any more correct than yours or anyone else's.
Answer: Most pieces, especially a lot of studies, can be translated into chords per bar, etc. That's how a lot of music is. It also helps with guitar, since holding down a specified chord shape will make playing that bar easier.
So, maybe you just need a lot more experience finding which chords and their shapes/voicings are contained within. But, you're right, there's no compunction to write in the chords themselves for any piece like this. If they're there, it's a nice bonus.


Formatar data com DatePipe Angular

Question: Eu tenho uma data no formato timestamp e queria formatar para texto em português, por exemplo: "Quarta-feira, 18 de Outubro, 2017", mas eu ponho o pipe "| date:'fullDate'" e não funciona. Quando eu tiro o toLocaleString("pt-BR") e retorno um Date na função ele me retorna "Wednesday, October 18, 2017". Obrigado de antemão!
typescript
public dt: Date = new Date();
public getDate(): string {
  return this.dt.toLocaleString("pt-BR");
}

html

{{getDate() | date:'fullDate'}}

Answer: Existe um projeto que já possui um conjunto de funções destinadas a trabalhar com Data, pode dar uma conferida em:
http://momentjs.com/
Mas, segue também uma alternativa:
$scope.getDate = function() {
    let dt = new Date();

    let month = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
    let week  = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];

    let semana = week[dt.getDay()];
    let mes = month[dt.getMonth()];

    return semana + ', ' + dt.getDate() + ' de ' + mes + ', ' + dt.getFullYear();
}

Comment: Resolveu! Muito obrigado!

Formatar data com DatePipe Angular


How much RAM is there in an an iOS (Iphone/iPad/iPod Touch) Device?

Question: Different iPhones have different published memory 4GB, 8GB and 16GB. The touch can have 32GB. My understanding is this is the off-line memory (disk alike).
How much actual fast ram is there in the device available for my Cocoa Application?
Is there a preconfigured virtual amount?
Comment: Make sure your app doesn't request for more than 40M bytes of memory or some of the early device users will suffer crash quite easily
Answer: iPhone

iPhone (June 2007): 128MB
iPhone 3G (July 2008): 128MB
iPhone 3GS (June 2009): 256MB
iPhone 4 (June 2010): 512MB
iPhone 4S (October 2011): 512MB
iPhone 5 (September 2012): 1GB
iPhone 5S (September 2013): 1GB
iPhone 6 (September 2014): 1GB
iPhone 6 Plus (September 2014): 1GB
iPhone 6S (September 2015): 2GB
iPhone 6S Plus (September 2015): 2GB
iPhone 7 (September 2016): 2GB
iPhone 7 Plus (September 2016): 3GB

iPod touch

1st generation (September 2007): 128MB
2nd generation (September 2008): 128MB
3rd generation (September 2009): 256MB
4th generation (September 2010): 256MB
5th generation (October 2012): 512MB
6th generation (July 2015): 1GB

iPad

1st generation (April 2010): 256MB
iPad 2 (2011): 512MB
3rd generation (March 2012): 1GB
4th generation (November 2012): 1GB
iPad Air (November 2013): 1GB
iPad Air 2 (October 2014): 2GB
iPad Pro 12.9" (November 2015): 4GB
iPad Pro 9.7" (April 2016): 2GB

iPad mini

1st generation (November 2012): 512MB
iPad mini 2 (November 2013): 1GB
iPad mini 3 (October 2014): 1GB
iPad mini 4 (September 2015): 2GB

Apple Watch

1st generation (April 2015): 512MB

Apple TV

2nd generation (2010): 256MB
3rd generation (2012): 512MB
4th generation (2015): 2GB

iOS doesn't use swap space, therefore, only RAM will be available to processes. (That said, iOS does support paging executables.)
Comment: This is probably because unlike a harddrive flash memory can only be written to a limited number of times... before it fails. So this scheme vastly improves memory life.
Comment: Think of it as an OS X kernel without any swap files, it'll still page executables.
Comment: There's no paging of data, but readonly pages (ie instruction data) will be freed and reloaded as needed.
Comment: iPod touch 4th generation: 256MB
Comment: You mean it doesn't support paging memory (to flash in this case). I'm sure that it supports virtual memory.
Comment: By virtual memory, I didn't mean virtual address space. In fact it does support paging too, but not paging to flash (i.e. no swap files).
Comment: This answer ignores a key part of the question "available for my Cocoa Application?". There is no fixed amount, and you cant reliably ask the device how much you're allowed to have. You need to use as little as possible, don't ask for more too quickly, and be prepared to handle low memory warnings.
Comment: @AnthonyLambert really nice analyse here
Answer: Currently released Apple iOS devices have the following amounts of working memory:
<code>iPhone        =  128 MB
iPhone 3G     =  128 MB
iPhone 3GS    =  256 MB
iPhone 4      =  512 MB
iPhone 4S     =  512 MB
iPhone 5      = 1024 MB
iPhone 5S     = 1024 MB

iPod Touch 1G  =  128 MB
iPod Touch 2G  =  128 MB
iPod Touch 3G  =  256 MB
iPod Touch 4G  =  256 MB
iPod Touch 5G  =  512 MB

iPad           =  256 MB
iPad 2         =  512 MB
iPad (3)       = 1024 MB
iPad (4)       = 1024 MB
iPad Air       = 1024 MB

iPad mini (1G) =  512 MB
iPad mini (2G) = 1024 MB
</code>
Comment: Tony - there are multiple versions of the iPod Touch also - you should include those variations as well. Good summary!
Answer: iPhone and iPod touch has 128 megs of ram, but 3rd party applications should only count on having about 20 megs available.
Answer: As Mehrdad Afshari says, it's 128Mb (except for the 3GS which has twice that), but why do you need to know? Not all of it is accessible to programs and the exact amount varies. Presumably activities like running iPod in the background saps some memory and OS2.1, for instance, seemed to leave less free memory than 2.0.
The key, application wise, is to cache stuff rather than require everything in memory and to heed the memory warning notifications. Your app will be forced to quit if you don't. (If it quits with status 101, you were using too much memory.)
Comment: because I am writing an application with an in memory database. I will write it in a different way depending on how much memory is available.
Answer: Go to ios app maximum memory budget to  see more devices and RAM amount that can be really allocated.


List could not be mapped

Question: I have models in my .Net Core project where I want to have a List of Enum.
public class CartOptional
    {
        [Required]
        public Guid Id { get; private set; }
        public int Price { get; set; }
        public string CartId { get; set; }
        public string Type { get; set; }
        public List<FieldValidator> Validators { get; set; }
        public string Label { get; set; }
        public string Value { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
    }

FieldValidator is indeed an Enum
EF return me this error :

The property 'CartOptional.Validators' could not be mapped, because it is of type 'List' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

I tried different solution like adding [Serializable]. But nothing seems to work. I don't understand why the system cannot take the underliying int
EDIT:
I tried the solution with [Flags] annotation like so
[Flags]
public enum FieldValidator
{
    REQUIRED = 1,
    ALPHABETIC = 2,
    NUMERIC = 4,
    EMAIL = 8,
    PHONE = 16,
    DATE = 32
}

And in the parent class I have public FieldValidator Validators { get; set; }
But now I try to POST a new element and I got this error when I try to validate the ModelState:

"tierList[0].fieldList[0].validators": [
          "Unexpected token StartArray when parsing enum. Path 'tierList[0].fieldList[0].validators', line 24, position 25."
      ]

What is a token StartArray ?
Comment: @Ragnar if the enum is a *Flag*, the property shouldn't be a `List`, it should be `public FieldValidator Validators { get; set; }`.
Comment: Possible duplicate of [Asp.net Core List in model](https://stackoverflow.com/questions/45789635/asp-net-core-listenum-in-model)
Comment: Why use the `Serializable` attribute? The error says the problem is with the type itself. What is `FieldValidator`? Unless it's an *entity* mapped to another table, EF won't know what to do with it. Does it represent 5 columns in the table? A single `int` that's used as a bitfield? Something else?
Comment: why you are try to List? explain?
Comment: See also https://stackoverflow.com/questions/28429945/ef-property-of-type-listenum-not-created-in-db
Comment: @ershoaib Because this attribute can have one or N attribute in that list.
Comment: @RuiJarimba first solution tested. Doesn't seems to work.
Comment: @Ragnar then it's not an attribute at all. Multiple values means multiple *rows*. What does the *table* for that entity look like? Where would you expect to store the FieldValidator values?
Comment: @PanagiotisKanavos I'm thinkig to much in a NoSQL like. I cannot have a list of something in a row int the SQL world. I have to rethink my model.
Comment: you can use Enum[]
Answer: The problem is not enum at all. It is the List. You would get the same error even if you tried
public List<int> Validators { get; set; }

or
public List<string> Validators { get; set; }

or any other type.
This is not even a restriction of EF, but rather the database itself. You are trying to add a list of values in a table column. The databases I know don't have a configuration for such a thing.
If you want to attach a list of values in a database table, the way is to create a new table (possible a new Look Up Table in your case) that holds a foreign key to CartOptional. Something like this:
public class FieldValidatorEntity
{
    public int Id { get; set; }

    public int CartOptionalId { get; set; }
    public CartOptional CartOptional { get; set; }

    public FieldValidator Value { get; set; }
    // other columns
}

And use this property in your CartOptional entity:
public List<FieldValidatorEntity> Validators { get; set; }

A workaround would be to make Validators a string property and hold something like comma separated values, or even try a byte array if it suits you. Databases can store byte arrays in a column.
Hope I could help,
merry coding!
Comment: For the Enum I use the `[Flag]` attribute but this is the approach I did for my other list. Like I said I come from a NoSQL (Mongo mainly) world. I have to remember this difference.
Comment: Postgres has been able to define array columns since the year 2000 or so.
Most other major database engines can store arrays via JSON columns.
Answer: One Enum value shouldn't be an issue, but since the Enum is just an integer value, you cannot use it as (a list of) entities. You should either explicitly make the Enum an entity, or use a Flags Enum instead (which I would recommend).
Have a look at Working with Enumerated Values in Entity Framework, for instance.
Comment: Storing bitfields in table is a problem in itself as they *can't* be indexed or queried.
Comment: That's why I also suggested to _either explicitly make the Enum an entity, or use a Flags Enum instead_ ;)

List could not be mapped


Is any set a proper subset of the null set?

Question: Is there any $X$, such that $X \subset \emptyset = T$?
I suppose this is related to asking whether $\emptyset \subset \emptyset$, but not exactly the same.
Comment: Can a set have less than no elements?
Comment: There would have to be a point in $\varnothing$ that is not in $\varnothing$. This is a contradictory pair of conditions, so -- no.
Answer: $A \subset B$ means two things are true:

if $x \in A$, then $x \in B$
there exists $x \in B$ such that $x \notin A$

Now if there is some set $X$ such that $X \subset \emptyset$, it must be the case that

if $x \in X$, then $x \in \emptyset$
there exists $x \in \emptyset$ such that $x \notin X$

The second bullet point cannot ever hold because there cannot exist $x \in \emptyset$. So there cannot be such a set $X$.
Answer: To have
$$X\subset\emptyset$$
we need that every element in $X$ is also in $\emptyset$ and that there exists an element in $\emptyset$ that is not in $X$. As $\emptyset$ contains no elements, the second condition cannot hold, and hence the statement is not true.


max and min $x y - \ln(x^2 + y^2)$

Question: Find max and min
$$x y - \ln(x^2 + y^2) , 1/4 \le x^2 + y^2 \le 4$$
Problem: With this hairy expression as my partial derivatives, I do not know what to do.
Attempt:
Comment: just to make this much beautiful you could have removed the portion of that first and second questions... I do not see any reason for you to stop here.... what was the problem?
Comment: How do I continue? Getting started with partial derivatives after some time not doing them.
Answer: HINT:
Transform the expression:
$$xy - \ln(x^2 + y^2) \iff \ln(e^{xy}) - \ln(x^2 + y^2) \iff \ln\left(\frac{e^{xy}}{x^2 + y^2}\right)$$
Now just try to maximize/minimize the $\frac{e^{xy}}{x^2 + y^2}$ using Lagrange Multipler with KKT conditions.
Comment: KKT conditions?
Comment: @jacob [Read More](http://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions). Also you can find more on the internet.
Answer: \begin{align}
x-\frac{2y}{x^2+y^2}=0\\
y-\frac{2x}{x^2+y^2}=0
\end{align}
can be combined to, as you have done, to
\begin{align}
(x+y)\left(1-\frac2{x^2+y^2}\right)=0\\
(x-y)\left(1+\frac2{x^2+y^2}\right)=0
\end{align}
and also, since $(x,y)\ne(0,0)$, to
\begin{align}
2xy-2=0
\end{align}
Comment: I thought I was decent in algebra, but I really can't see the hidden algebraic steps here between the first and second expression.
Comment: the answrerer is respectively adding and subtracting your two equations, then factoring.
Comment: There is none. The first expression is the sum of both partial derivatives, the second one the difference. The third one is obtained by multiplying the x-derivative by x and the y-derivative by y and adding both, canceling the normsquare in the fraction.
Comment: Oh you mean the last step, sorry. Now I am confused. The second equation implies $y = x$ (since the second factor on the LHS is never zero). We deduce that the second factor of the first equation is zero. This gives me $x^2 = 1$ or $x = \pm 1$.
Comment: Yes, and since those two points are interior points of the annulus, they qualify for further study. Since the function has a pole towards $+\infty$ at the origin, and no other points with zero gradient exist, they must be minima or saddle points. But better check that with the Hessian.
Comment: What about

$$x-\frac{2y}{x^2+y^2}=0 \Rightarrow \frac{2y}{x}=x^2+y^2 $$

$$y-\frac{2x}{x^2+y^2}=0 \Rightarrow \frac{2x}{y}=x^2+y^2 $$
And so
$y^2=x^2$.
Answer: $$y-\frac{x}{x^2+y^2}=0,x-\frac{y}{x^2+y^2}=0\Rightarrow x^2=y^2\Rightarrow x=\pm y$$
You have to minimize $$xy-\log (x^2+y^2)$$
with given conditions
$$1/4 \le x^2 + y^2 \le 4$$
If $1/4 \le x^2 + y^2 \le 4$ can you find what are the bounds for $x^2$??
If you know what are bounds for $x^2$,
take its minimum value and substitute that in: $xy-\log(x^2+y^2)$
Can you do that now?

max and min $x y - \ln(x^2 + y^2)$


Laravel 5.6 post login redirect to login page

Question: SOLVED
SOLUTION
the problem is a primary key using on table of database i only pass the name of the primary key to attribute $primarykey in the model
I develop a login system for my laravel application with a table different of a users table aparently the login works fine, but if i use the redirect and the middleware auth to protect my routes i have a problem to enter on the route because on post login the app redirect to protected route and on enter in the protected route the app return to login, but the users credentials are correct.
My Model Users
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $table = 'pessoas';

    protected $fillable = [
        'nome_completo', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Login method
public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        //$email = $request->input('email');
        //$password = $request->input('password'));

        if (Auth::attempt($credentials)) {
            //return Auth::user()->nome_completo;
            return redirect()->intended('/usuario/home');
        }
    }

Routes with middleware and login
Route::group(['middleware' => ['auth']], function () {
    Route::get('/usuario/home', 'Usuarios\UsuarioController@renderHome')->name('home');

    Route::get('/usuario/perfil', function () {
        return view('usuario.meuperfil');
    })->name('perfil');

    Route::get('/usuario/estoque', function () {
        return view('usuario.estoque');
    })->name('estoque');

    Route::get('/usuario/fotos', function () {
        return view('usuario.fotos');
    })->name('fotos');

    Route::get('/usuario/carrinho', function () {
        return view('usuario.carrinho');
    })->name('carrinho');

    Route::get('/usuario/orcamentos', function () {
        return view('usuario.orcamentos');
    })->name('orcamentos');

    Route::get('/usuario/enviados', function () {
        return view('usuario.enviados');
    })->name('enviados');

    Route::get('/usuario/tickets', function () {
        return view('usuario.tickets');
    })->name('tickets');

    Route::get('/usuario/calculadora', function () {
        return view('usuario.calculadora');
    })->name('calculadora');

    Route::get('/usuario/tutorial', function () {
        return view('usuario.tutorial');
    })->name('tutorial');
});

Route::get('/login', function () {
    return view('usuario.login');
})->name('login');

Route::post('/login', 'Usuarios\UsuarioController@login');
Route::get('/logout', 'Usuarios\UsuarioController@logout')->name('logout');

what is the solution of the problem?
thanks for help
Answer: What's your "login" middleware? Isn't it should be "Auth" middleware? I think the reason is your middleware.Because you jump to protect routes means your "attempt" function has been successful.
Comment: the login middleware is a custom middleware is a custom middleware that i create to test, but the result is the same of the euth middleware redirect back to login route after post login


Integrate a two form on the sphere

Question: $$
\int_S x\,dy\,dz+y\,dz\,dx+z\,dx\,dy,
$$ where $S=\{(x,y,z)\in \mathbb{R}^{3}: x^2+y^2+z^2=1\}.$
Please, I don't know how to proceed. I will be thankful if you give me any hint, at first I thought it was an application of the Stokes' Theorem, but the differentials confuse me D:
Thanks!
Comment: The complete symmetry between $x$, $y$, and $z$ in both the integral and the definition of $S$ tells you the integrals of the three terms are equal. $\qquad$
Comment: Please show us your work and where you got stuck so that we can help you.
Comment: It seems that this question is approaching closure. This is sad. Two of the closure votes given so far claim that it is not clear what the question asks. Wrong! The question is very clear, and it is not the OP's fault that two MSE users have absolutely no clue about surface integrals.
Comment: I've made a mistake.... should say: I don't know how to proceed.....
Answer: The quickest way to do this is by using the Gauss-Ostrogradski theorem (which is just another name for Stokes' theorem in $\Bbb R^3$ - you have correctly guessed that this would lead to the solution): if $V$ is a 3-dimensional region, then
$$\int \limits _{\partial V} P \ \Bbb dy \Bbb dz + Q \ \Bbb dz \Bbb dx + R \ \Bbb dx \Bbb dy = \int \limits _V \left( \frac {\partial P} {\partial x} + \frac {\partial Q} {\partial y} + \frac {\partial R} {\partial z} \right) \Bbb d x \Bbb d y \Bbb d z .$$
Concretely, if $B = \{ (x,y,z) \in \Bbb R^3 \mid x^2 + y^2 + z^2 \le 1\}$, then $S = \partial B$ and
$$\int \limits _S x \ \Bbb dy \Bbb dz + y \ \Bbb dz\Bbb dx + z \ \Bbb dx \Bbb dy = \int \limits _B \left( \frac {\partial x} {\partial x} + \frac {\partial y} {\partial y} + \frac {\partial z} {\partial z} \right) \Bbb d x \Bbb d y \Bbb d z = 3 \text{vol } (B) = 4 \pi .$$
Of course, you can also do it using the definition of surface integrals of the second type, but this would require you to use a parametrization, to compute the coefficients of the metric and the formula of the outer unit normal in this parametrization and finally to perform an integral, which is way too long and tedious.
Comment: Alex, I wasn't certain what the OP intended.  As written as "raw integrals," my interpretation was that these were the "first kind" integrals.  Then, as I was getting ready to sleep last night, I thought that maybe the OP meant these to be the two form, as you interpreted.  So, I believe that both interpretations are viable.
Comment: @BrunoMarceloGoicocheaVilela: Your question received two different interpretations (and also caused a series of comments that is now deleted) and also caused an answer that is now deleted. There is some ambiguity in your notation, due to the fact that you haven't used the "wedge" to denote 2-forms. More clearly, the integrand almost surely is supposed to be $x \ \Bbb d y \wedge \Bbb d z + y \ \Bbb d z \wedge \Bbb d x + z \ \Bbb d x \wedge \Bbb d y$. I suspect that this is why you claimed to be "confused by the differentials".
Comment: 1.-Maybe I'm wrong but I think that it can't be interpret as an ordinary surface integral since the surface where we are integrating is in $R^{3}$ and each term is a function in $R^{2}$  is that approach correct?
Comment: No, it's not. Had it been an ordinary surface integral, the volume form of $S$ should have been present  - which is clearly not the case here. For your reassuring, could you tell us where you took the problem from?
Comment: @BrunoMarceloGoicocheaVilela As Alex has described, there is a bit of "built-in" ambiguity in the question.  It is likely, in my opinion, that Alex's interpretation is the one intended.  However, it is easy to see by symmetry that the value of the integral would be zero if interpreted as an "ordinary" surface integral. -Mark
Comment: It's a final exam question. There's no much I can do sincerely thanks for the help...both of you. But I don't understand in which way the problem could be considering as an "ordinary" surface integral since in every term we could consider a function from $\mathbb{R}^{2}\rightarrow \mathbb{R}$ but the surface where we are integrating is in $\mathbb{R}^{3}$
Comment: Consider the problem as a two-form integral is a good solution, but as @AlexM. said there's no wedge  :c
Comment: @BrunoMarceloGoicocheaVilela: There are professors who do not use the wedge sign, because they introduce second type surface integrals without discussing exterior differential forms (in order not to complicate things and scare students). The approach they take is to define $\int _{S_N} P \ \Bbb d y \Bbb d z + Q \ \Bbb d z \Bbb d x + R \ \Bbb d x \Bbb d y$ as $\int _S \langle (P, Q, R), N \rangle \ \Bbb d S$, where $N$ is a normal unit field to $S$, $S_N$ is $S$ with the orientation given by $N$ and the second integral is a first type surface integral. This is perfectly correct.
Comment: With that on mind there's no more doubts. Thanks!
Answer: If we interpret the integral in the OP as an ordinary surface integral, then
$$\begin{align}
3 \int_S z\,dx\,dy &=3\int_{-1}^1\int_{-\sqrt{1-y^2}}^{\sqrt{1-y^2}}\sqrt{1-x^2-y^2}\,dx\,dy+3\int_{-1}^1\int_{-\sqrt{1-y^2}}^{\sqrt{1-y^2}}\left(-\sqrt{1-x^2-y^2}\right)\,dx\,dy\\\\
&=0
\end{align}$$
where we exploited the symmetry noting that $\int_S x\,dy\,dz=\int_S y\,dz\,dx=\int_S z\,dx\,dy$.
And we are done!

However, if we interpret the integral in the OP to be equivalent to the closed surface integral expressed as
$$\int_S x\,dy\wedge dz+y\,dz \wedge dx+z\,dx \wedge dy=\oint_S \vec r\cdot \hat n\,dS \tag 1$$
then we can apply the Divergence Theorem to the right-hand side of $(1)$ to reveal
$$\begin{align}
\oint_S \vec r\cdot \hat n\,dS &=\int_V \nabla \cdot \vec r\,dV\\\\
&=\int_V 3\,dV\\\\
&=3\frac{4\pi}{3}\\\\
&=4\pi
\end{align}$$
Alternatively, one can evaluate the surface integral directly as
$$\begin{align}
3\oint_S z\,n_z\,dS&=3\int_{-1}^1\int_{-\sqrt{1-y^2}}^{\sqrt{1-y^2}} \sqrt{1-x^2-y^2}\,dx\,dy\\\\
&+3\int_{-1}^1\int_{-\sqrt{1-y^2}}^{\sqrt{1-y^2}}\left(- \sqrt{1-x^2-y^2}\right)\,(-1)\,dx\,dy\\\\
&=6 \int_0^{2\pi}\int_0^1 \sqrt{1-\rho^2}\,d\rho\,d\phi\\\\
&=4\pi
\end{align}$$
as expected!
Comment: Hmmm... this is a bit cheating: the previous (and previously deleted) version of this answer was *drastically* different (and wrong, too, since you had obtained the result to be $0$). After having significantly changed and undeleted it, it seems now that it had already been posted when I wrote mine, and that I have just copied it - clearly not true. I'm fine with you posting it, leave it here, I just want readers to know that I haven't copied it, as it may seem at a first view!
Comment: @AlexM. I decided to resurrect this answer with some edits to try and clarify the ongoing issue of interpretation.  I hope that you won't mind my doing so. -Mark
Answer: $\newcommand{\Vec}[1]{\mathbf{n}}$To complement the existing good answer: In classical notation, with $dS$ denoting the area element of the unit sphere and $\Vec{n}$ the outward unit normal field, your integral represents the flux through the unit sphere of the vector field
$$
F(x, y, z) = (x, y, z).
$$
This can be calculated directly by noting that on the unit sphere,
$$
F \cdot \Vec{n} = (x, y, z) \cdot (x, y, z) = x^{2} + y^{2} + z^{2} = 1,
$$
so the flux of $F$ is
$$
\iint_{S} F \cdot \Vec{n}\, dS = \iint_{S} dS = \text{area of $S$} = 4\pi.
$$

Integrate a two form on the sphere


What to mark on sheet music?

Question: Is there anything in general to mark down?

So far I don't mark notes
I do mark breath marks and phrases
I don't know whether to mark chords: C G7 D C, for example.

I just want a comprehensive list, if you can provide one.
Comment: Somewhat instrument dependent! Most of what you need should be already there. Don't name notes, just play them.
Comment: If you are writing marks on sheet music you have been given, it's usually called "marking up",  not "marking down". Could you confirm this is what you mean, or edit your question?
Comment: Can you explain what you mean by "mark down"? If sheet music doesn't have any notes written on it, it's not music, is it?
Answer: As Tim said, this is definitely instrument dependent, but I'll try to give you some specifics.
In general, though, here are some things that I really advise against marking down:

What the key signature means
Similarly, going through a piece to write in every accidental that is already given in the key signature
Note names
Instrument-specific guidance on the "fingering" mechanics of a given pitch (like a brass player writing "13" under a note); note that this does not apply to pianists, who very often should feel free to write in fingerings!

The above concepts are, in my opinion, far too basic to write down. Someone may need to write these things down in their first month of playing an instrument, but anyone caught doing so afterwards is just shouting to the world their amateur status.
Now, there are some things that are good to write down (again, this is just my opinion):

Breathing marks. This is especially helpful for ensemble players. Imagine you're a tuba player in an orchestra, and you have 16 bars of a held pitch in unison with the bass trombone. In most cases you'll want to make sure you don't breathe at the same time as the bass trombone, so the two of you will determine who breathes when, and you'll mark it in the music to remind you. But this doesn't only help brass players! Percussionists, string players, etc. all benefit from breath markings.
Expressive markings you (or your group) have decided to add in that are not already in the score. A simple rit. to remind you that your ensemble has decided to pull back the tempo at a certain spot, for instance.
Similarly, physical cues are really helpful. Oftentimes orchestral musicians will draw a little eyeball to remind themselves to look at the conductor. They may also draw a little ear followed by the words "4th horn" to remind themselves to listen to and match someone several players down the aisle.
Musical cues are also helpful. If you're an oboe player that's been counting rests for 79 measures, a quick reminder that the flute comes in in measure 78 is a real life saver, especially when the conductor decides to begin in some unknown spot in the middle of your 79 measures of rest.

These are just some examples. Again it depends on your instrument and your playing environment, but ultimately it just comes down to what works for you. Everyone has their own little idiosyncratic system. Personally, the first thing I ever did when I got a new orchestra part was to erase the previous user's markings, so just do what works for you and be happy with it.
You asked specifically about chords: in (for example) an orchestra setting, this could be useful. Due to just intonation, for instance, a trumpet player playing an E in a CM chord might want to write down "CM" on their sheet to remind themselves to keep that major third low. But (in my opinion), a musician working on that amount of detail should already be able to tell what chord tone they're playing.
Edit: I should note that this is for music which is used in performance, as suggested in your original question. If we're talking about analyzing scores (which I know you aren't), then that's something completely different!
Comment: I'd emphasize the "...what works for you."   A beginner will need different helper-markings than a more experienced player.
Comment: Definitely. Meanwhile, the beginner must remember not to develop a habit of relying on markings to tell them basic information. But then (in my opinion) we have to make sure not to create an environment where a beginner fears that marking their music is a weakness. It's a tight rope walk, to be sure!

What to mark on sheet music?


How to change value in input (textbox) by changing select

Question: I'm trying to change the value in an input when a different option gets selected from a select:
View image here.
The idea is that for each ad package you can have a different number of images (free gets 0 images, $20 for 4 images etc.). With this number I then want to display the correct amount of upload fields for images.
I'm already retrieving the values from the database for the number of images for each package as you can see in the code below:
<select name="ad_pack_id" class="dropdownlist required">

<?php foreach ( $results as $result ) { ?>

<option value="<?php esc_attr_e($result->pack_id); ?>" class="<?php esc_attr_e($result->pack_images); ?>"><?php esc_attr_e($result->pack_name); ?></option>

<?php } ?>

</select>

<input type="hidden" value="" name="packimages" id="packimages" />

I've tried getting the value from the select directly by doing:
mainform.ad_pack_id.options[selectedIndex].class.innerHTML

but this isn't getting the number of images.
How can I get the number of images for the selected ad package without submitting the form first?
Answer: you could also try jquery:
$("#ad_pack_id option:selected").val()

this should get you the value. to show/hide upload fields you can use for example the CSS display attribute:
$("#uploadfield_1").css("display", "none")
$("#uploadfield_1").css("display", "block")

Answer: try this:
document.mainform.ad_pack_id.options[Selected].className;

Answer: This code will set the input's value to the selected option's value.
I just added "id" attribute to select menu
<select id="ad_pack_id" name="ad_pack_id" class="dropdownlist required">

<?php foreach ( $results as $result ) { ?>

<option value="<?php esc_attr_e($result->pack_id); ?>" class="<?php esc_attr_e($result->pack_images); ?>"><?php esc_attr_e($result->pack_name); ?></option>
<?php } ?>

</select>

<input type="hidden" value="" name="packimages" id="packimages" />