How can I swap rows in a matrix in python without using numpy?

Question: If i have the matrix:
[[1,1,1],[2,3,4],[4,5,6],[7,1,2]]

I want to swap rows 1 and 2 so that it returns:
[[1,1,1],[4,5,6],[2,3,4],[7,1,2]]

Comment: Please show the code that you have tried.
Comment: Check this too http://stackoverflow.com/questions/7923521/python-swap-list-elements-in-a-copied-list-without-affecting-the-original-list
Comment: I would do it exactly the same way as **with** numpy.
Answer: You can do this the same way you do any other swap in python:
i.e. a, b = b, a -- or in your case:
>>> matrix = [[1,1,1],[2,3,4],[4,5,6],[7,1,2]]
>>> matrix[1], matrix[2] = matrix[2], matrix[1]
>>> matrix
[[1, 1, 1], [4, 5, 6], [2, 3, 4], [7, 1, 2]]


Cron Tasks not running in background, causing pages to take forever to load

Question: We recently upgraded to D8 and I have been experiencing weird issues with Cron. Specifically, whenever the Cron is running, web pages are taking forever to load because cron is running some JS on the front end of any page you attempt to load. Specifically, it appears to be a timeout method that is holding up the page load.

NOTE: I will update this post and provide the exact JS file and function that is running on the front end the next time it happens to me. At the time of writing, cron wasn't running and therefore I couldn't inspect the web page to get the running method

I know it's not the CPU on the server because when cron was running it never got above 20% CPU utilization.
Isn't cron suppose to run in the background? Why would cron have a JS file being executed on every page, causing any page not to load until cron finishes?
Comment: Yes, interesting is the name before it was a core module: [Add a poormanscron-like feature to core](https://www.drupal.org/node/331611)
Comment: You should never use the built-in "Run cron every x hour" under heavy load in production. Run cron from outside using the link from the config page.
Comment: Why would they provide a feature that "you should never use"? That seems ridiculous... How would you go about running cron from "outside" using the link and have it do so every hour?
Comment: `crontab -e` from the command line or if you have a webserver admin panel something like this https://blog.cpanel.com/how-to-configure-a-cron-job
Comment: Yes, @4k4 is correct: It should not be used in a production site with much traffic. The module implementing that functionality, which isn't necessary to run Drupal cron tasks, was thought for small sites. It also help users who cannot set Drupal cron tasks from cPanel, or similar software. The module is part of Drupal core, but that doesn't mean that every site should use it. I personally don't use it, even for small size sites.
Comment: From the issue linked by @4k4, it's clear that adding that feature didn't find the consensus of all the users, but it was added because, without cron tasks executed, for example, the search feature doesn't work as it should. The content is indexed only during cron tasks, and without that, searching on the site would not find anything.
Answer: Part of the settings on /admin/config/system/cron are for the Automated Cron module, which adds them via automated_cron_form_system_cron_settings_alter(). The form field it adds has the following description.

More information about setting up scheduled tasks can be found by reading the cron tutorial on drupal.org.

If you follow that link, you will read the following sentences. (Emphasis is mine.)

The automated cron module has the disadvantage that it is triggered by a request, and the unlucky user who sends the request may experience a fairly long delay. For this reason, the automated cron is typically used by smaller sites that are unable to create a cron job manually, e.g. using the Linux crontab. If crontab is desired, Drupal console command may be used to simplify the configuration (rather than curling the long URL show in /admin/config/system/cron. Here is an example crontab entry:
30 * * * * web_user /var/www/html/vendor/bin/drupal --root=/var/www/html/docroot cron:execute > /dev/null 2>&1

Essentially, what you are experiencing is how the Automated Cron module work, but that isn't the only way to run cron tasks for Drupal.
You could also pass the URL shown on on /admin/config/system/cron after To run cron from outside the site, go to to wget or curl. This requires that you have access to, for example, cPanel for the site, which allows to set cron tasks.
Comment: @BlondeSwan, do you have a better idea what Drupal can do from inside of the PHP application if the site admin is not willing to invest the money or time to setup a proper cron?
Comment: Sounds like a good plan. The button to run cron manually is by the way not the link, this triggers cron once by submitting the admin form. For the *real* cron task `wget` or `curl` the long link containing the secret authentication key. This will run all Cron Jobs you've wrote and is not a workaround but the final solution according to the docs.
Comment: So basically, Drupal cron isn't an actual cron.. Awesome. What a classic Drupal implementation
Comment: Yes, _Automated cron_ isn't cron in the sense used by Linux and other OSes. It's a way for running some code without depending from settings Drupal doesn't directly control.
Comment: They should really not call it cron then. What a joke.
Comment: Nope, not really. We wrote a bunch of Cron Jobs and are suppose to go live in a week, but now since Drupal irresponsibly named/advertised this module incorrectly we have to go back to the drawing board and rethink this particular aspect of the website.

Will likely just write up a real cron task that makes a request to the url from the "run cron manually from here" as a workaround for now.
Comment: Awesome, will do. Thank you for your clarification and generous help on this! Much appreciated


Dashboards for Development Metrics

Question: I need a private, host my own, behind-a-firewall dashboard like Geckoboard or Ducksboard.
Widgets for Atlassian products, Git, Junit based results and Splunk would be ideal.
More context-
Geckoboard and Ducksboard look great to me, but my Atlassian products, Git, etc. are all behind a firewall.  Opening up the firewall for Geckoboard, Ducksboard, etc. is not an option.
I know they both have APIs where I could push data to, but I don't really want to write custom REST calls for aforementioned products.
Know of any similar dashboards where I can install locally?
Answer: You can check out Dashing http://shopify.github.io/dashing/
It's a dashboard written by the guys from Shopify, written in Ruby.
You can see the list of widgets it supports in the link below, though I know it doesn't really cover what you are after. But you should be able to write your own widgets.
https://github.com/Shopify/dashing/wiki/Additional-Widgets
I've only played around it for a little bit, but seems quite easy to get started.

Dashboards for Development Metrics


Input string was not in a correct format, List to Dictionary

Question: I am trying to create a program that reads user inputted integers from the console, then creates a Dictionary<int, int>, and finally prints all inputs with the number of times they have been entered.
My idea was to collect each entry until an empty line in a List. Then I would parse it and create the dictionary with input for Key and times typed as Value.
I get "Unhandled Exception: System.FormatException: Input string was not in a correct format" at int integer = int.Parse(number); and nothing gets printed.
Would you please help me understand where the code falls apart. I am a beginner and not sure how to correct it.
static void Main(string[] args)
    {
        string input = "0";
        List<string> listNumbers = new List<string>();
        Console.WriteLine("Type several numbers and press Enter after each one:");
        while (input != string.Empty)
        {
            input = Console.ReadLine();
            listNumbers.Add(input);
        }

        IDictionary<int, int> intOccurences = new Dictionary<int, int>();
        foreach (string number in listNumbers)
        {
            int integer = int.Parse(number);
            int count;
            if (!intOccurences.TryGetValue(integer, out count))
            {
                count = 0;
            }
                intOccurences[integer] = count + 1;
        }
        PrintNumbers(intOccurences);
    }
        private static void PrintNumbers(IDictionary<int, int> intOccurences)
    {
        foreach (KeyValuePair<int, int> entry in intOccurences)
        {
            Console.WriteLine(
                "Number '{0}' occurs {1} time (s) in the input.", entry.Key, entry.Value);
        }
    }

Comment: It means while the string wasn't null, it was something that couldn't be converted to int. For example, `int.parse` cannot convert "hello" to an integer. OR You are including the newline in your list of strings, since you are using `ReadLine()`
Comment: As @KeyurPATEL said, the string you want to parse is not convertable to integer. You could use `int.TryParse()` which returns true if the conversion succeeded.
Comment: @Keyur PATEL, I can add that the format exception is throw when I input the last Console.ReadLine, which is empty (just pressing Enter) and is supposed to stop the while loop.
Comment: Then simply add a `if (!String.IsNullOrWhiteSpace(number)) { int integer = int.Parse(number); }` to filter out the unwanted empty or null strings.
Answer: Consider using TryParse:
        string possibleInteger ="12";
        int resultInteger;
        bool isCorrectInteger = int.TryParse(possibleInteger, out resultInteger);
        if (isCorrectInteger)
        {
            // add to dictionary
        }
        else
        {
            Console.WriteLine("Not a correct integer number");
        }

Also, remember to consider your Culture settings while parsing numbers and dates. For example if the current language uses/doesn't use some decimal separator or thausand separator, you may end up with format exceptions. If it is a factor in your case, consider using the version of TryParse that takes it into account.
Answer: Possible solution
Replace
int integer = int.Parse(number);

With
int integer;

var isInteger = int.TryParse(number, out integer);

if(!isInteger) continue; // Not a number skip

if (!intOccurences.TryGetValue(integer, out count))
{
                count = 0;
}

Idea remains, skip the non integers, else devise a mechanism to handle them. You cannot int.parse(<Non Integer>)
Answer: You could try directly converting to integers immediately after reading a line from the console, adding them to a list of integers. This makes everything easier to understand as well. For example:
IDictionary<int, int> intOccurences = new Dictionary<int, int>();
List<int> allInputs = new List<int>();
while (input != string.Empty)
{
    input = Console.ReadLine();
    allInputs.Add(Convert.ToInt32(input));
}
foreach (int i in allInputs)
{
    int currentCount; //defaults to 0
    intOccurences.TryGetValue(i, out currentCount);
    frequencies[i] = currentCount + 1;
}


Coefficients in binomial expansions of $(x+y)^n$

Question: Is it true that if we expand $(x+y)^n$ where $n$ is a prime number, then all the coefficients are divisible (except the first and last term) by $n$?
Note. There are many examples of when $n$ isn't prime, and the coefficients are not divisible by $n$.
Comment: Write out the definition of the general term pCr where p is the prime, and notice that it is an integer, but the p in the numerator has not cancelled out
Comment: this is known as [Freshman's dream](https://en.wikipedia.org/wiki/Freshman%27s_dream) and was already asked quite often, just check out the link or use the search - you'll find what you're looking for for sure, like [here](http://math.stackexchange.com/questions/1238531/proving-the-freshmans-dream)
Answer: Hint:
$$(x+y)^n = \sum_{i=0}^n{n\choose i} x^iy^{n-i}$$
So all you need to prove is that ${p\choose i}$ is divisible by $p$ if $p$ is prime.


How do I make microtonal music less jarring?

Question: I'm a beginner at composing with microtones. I understand that microtonal music is going to be jarring for most people because it is so different compared to 12-tet music. My current strategy is to kind of sneak the microtones in in the inner voices of chords. I also use "shimmer" effects similar to those in this piece by using downminor 2nd intervals (I am currently using 24-tet). Essentially, my strategy of making microtonal music less jarring is to write as if I am in 12-tet and use microtones as "color".
What other ideas and strategies can be used to accomplish this goal?
Edit: An example of a "non-jarring" use of microtones (for me at least) is the transition into G half sharp minor in Little Blue by Jacob Collier.
Comment: If you don't want your music to sound like you're using microtones, why are you using microtones?
Comment: I think the "jarring" idea needs to be examined a bit. What about Arabic music. I understand some of that music used scales with microtones. Do you rate that as jarring? Some do. Personally, I don't.
Comment: "I understand that microtonal music is going to be jarring for most people because it is so different compared to 12-tet music": not necessarily.  It might just sound like a period instrument group playing baroque music, or like a barbershop quartet.  @AlexanderWoo lol!  "My current strategy is to kind of sneak the microtones in in the inner voices of chords": this may give unsophisticated listeners the impression that the performance is out of tune.  It may be better to be up front about the tone pallette than to try to be sneaky.
Comment: An example of a "non-jarring" use of microtones (for me at least) is the transition into G half sharp minor in Little Blue by Jacob Collier. https://www.youtube.com/watch?v=HUGoUHKAGAE I'll add this to the question.
Comment: I think you'll get better answers to this question in [The Auditorium](https://chat.stackexchange.com/rooms/126233/the-auditorium). You can post a recording of one of your pieces and ask for feedback, which is the main purpose of that chat room.
Comment: BTW, there are a number of microtonal compositions already posted there by another user. Those might provide some insights into the kind of effects you're going for.
Comment: ... I'd also think that microtones in diminished chords could seem very reasonable... And, even in very classical jazz-ish stuff, like "close 4" and so on, those diminished chords do not seem wildly out-of-key, to begin with.
Comment: Aren't blue notes a type of microtone? That could be another approach. Not necessarily blues, but perhaps a select palette, very limited, of certain microtonal chords.
Comment: Too bad your question was closed. It was interesting, and answerable. Consider looking in Stockhausen and pointillism and how factors other than vertical harmony can make music "jarring" and disjunct. Then assess microtonal works through that framework asking whether the composer is using elements beside vertical microtonal chords to create jarring effects.
Comment: https://www.youtube.com/watch?v=y_nQgNKSl5Y has moments of kooky, disjunct effect, but others somewhat serene. https://www.youtube.com/watch?v=Lq9-6NnXPVg while it surely has a strange, other-worldly sound, and is sometimes jarring, notice the many passages with slow, even rhythms, and the smooth lines, and how that contributes to the overall effect. Don't necessarily equate dissonance with "unpleasant" and use your other musical resources to create less jarring effects... whatever exactly that means to you.
Comment: You might also draw inspiration from Debussy. While he didn't use microtones, he did use "traditional" dissonances - tritones, cluster-like seconds, whole tone scales, etc. - but used those harmonic materials to make lush, beautiful music.
Answer: One suggestion is working with either of:

A tuning that is not an equal temperament;
An equal temperament other than 24-TET (a.k.a. 24EDO).  24-TET just sticks a set of 12 "out-of-tune" pitches between the familiar 12, so of course it seems jarring.

Maybe choose an EDO where some of the intervals align well with the just versions of some diatonic intervals from common-practice music.  In some cases they will align better with just intervals than 12-EDO, while allowing some modulation that you wouldn't get with just intonation, or well temperaments.
I would also say that once you choose an EDO, start with the melody.  Choose a subset of the EDO for most of your melody notes just as common practice music selects mostly from 7 of the 12 tones, with some extras added for modulation, color, etc.
Try selecting a subset whose size is coprime with the size of the EDO.  (Consider that 5 and 7 are both coprime with 12, and that scales of size 5 and 7 are common).  It's no coincidence that the fifth interval in 12EDO corresponds to 7/12 of an octave and it can be used to generate a diatonic scale. (As can 5/12, which corresponds to the fourth.)
Then experiment with harmonies to suit your own idea of what is and is not "jarring" in the setting.  (I personally find those "shimmer" effects to be jarring so obviously it's a matter of taste and cultural conditioning.)
The Xenharmonic wiki page on EDOs also gives some ideas of how to choose.


Como plotar apenas uma parte de uma variável Posixct?

Question: Eu tenho um df com 2 variáveis. A primeira é um contador de tempo que chega à 9min em uma taxa de aquisição de 1000Hz (Portanto, é enorme 540 mil linhas). A segunda variável é uma medida eletrofisiológica em uS (micro siemens). Seguem as 20 primeiras linhas abaixo:
> dput(head(SC,20))

structure(list(time = c(0, 0.001, 0.002, 0.003, 0.004, 0.005,
0.006, 0.007, 0.008, 0.009, 0.01, 0.011, 0.012, 0.013, 0.014,
0.015, 0.016, 0.017, 0.018, 0.019), Conductance = c(0, 0, 0,
0.01, 0.01, 0.02, 0.03, 0.04, 0.05, 0.07, 0.07, 0.08, 0.09, 0.09,
0.09, 0.09, 0.1, 0.09, 0.09, 0.09)), row.names = c(NA, 20L), class = "data.frame")

Converti a variável "time" para um Posixct e preciso plotar num gráfico. Contudo, não quero plotar toda a variável Time. Somente parte dela. Não tenho habilidade com Posixct e não sei como editar o "xlim" do gráfico.
require(lubridate)
SC$time <- as_datetime(SC$time)

> head(SC$time)
[1] "1970-01-01 00:00:00 UTC" "1970-01-01 00:00:00 UTC"
[3] "1970-01-01 00:00:00 UTC" "1970-01-01 00:00:00 UTC"
[5] "1970-01-01 00:00:00 UTC" "1970-01-01 00:00:00 UTC"

> tail(SC$time,10)
 [1] "1970-01-01 00:09:13 UTC" "1970-01-01 00:09:13 UTC"
 [3] "1970-01-01 00:09:13 UTC" "1970-01-01 00:09:13 UTC"
 [5] "1970-01-01 00:09:13 UTC" "1970-01-01 00:09:13 UTC"
 [7] "1970-01-01 00:09:13 UTC" "1970-01-01 00:09:13 UTC"
 [9] "1970-01-01 00:09:13 UTC" "1970-01-01 00:09:13 UTC"

Usei o seguinte código mas ele leva toda a informação, inclusive o formato do eixo x não fica bom pq inclui HORA (que não é relevante):
pl <- ggplot(SC, aes(x = time, Conductance)) + geom_line()

Como fazer o ajuste do eixo x para qualquer unidade de tempo (janela) desejada? Por Exemplo: somente do 2,5 minutos até 6,5 minutos (janela de 5min portanto).
Comment: Compartilhe seus dados utilizando o resultado de `dput(head(SC, 20))` que isso irá facilitar muito a vida de quem for tentar te ajudar.
Comment: Pode postar com os valores depois de colocar em Posixct? E o resultado esperado é só com os minutos no xlim?
Answer: Olha, o gráfico que tu mandou a imagem tá em minutos não? Se vai de 0 a 9 minutos o gráfico mostra de 00:00 a 09:00, sendo minutos:segundos.
Mas enfim, se quiser ter certeza que é pra manter os segundos ou minutos é só usar minute() do pacote dplyr. Aqui tô usando second() porque os primeiros 20 dados são todos no primeiro minuto.
Mas o que eu faria pra conseguir o que você quer seria usar o filter() do pacote dplyr pra selecionar os dados, fazer o gráfico e no final mudar a escala se eu não achasse a automática boa.
library(ggplot2)
library(dplyr)
library(lubridate)

SC %>%
  mutate(second = second(time)) %>%
  filter(between(second,.005,.012)) %>%
  ggplot(aes(second(time), Conductance)) +
  geom_line() +
  scale_x_continuous(breaks = seq(.005, .012, by = .002))

Outra opção seria fazer a operação no gráfico. Você pode usar xlim pra escolher a região do x do gráfico.
ggplot(SC, aes(second(time), Conductance)) +
  geom_line() +
  xlim(c(.005,.012))

Ou utilizar coord_cartesian pra dar um zoom na região que você quer e depois, se precisar, mudar a escala.
ggplot(SC, aes(second(time), Conductance)) +
  geom_line() +
  coord_cartesian(xlim=c(.005,.012)) +
  scale_x_continuous(breaks = seq(.005, .012, by = .002))

Comment: Veja a documentação do pacote `scales`. Este pacote funciona muito bem para fazer este tipo de formatação que tu deseja.
Comment: De fato o gráfico que mandei já estava em minutos, contudo, como não estava conseguindo usar o "xlim" com a variável Posixct. Eu preciso cortar os 9min em pedaços menores. Pude observar na sua resposta que em ambas as possibilidades: "xlim"; "coord_cartesian" e "scale_x_continuous" as operações foram com a variável em sua forma numérica (.005, .012) portanto, vou encontrar os valores que representam os minutos os quais devo trabalhar. Minha esperança era que se podia chamar um intervalo de um objeto Poisxct diretamente usando algo parecido com %M%S.


INSTALL_FAILED_UPDATE_INCOMPATIBLE ao tentar instalar apk

Question: Estou tendo este problema ao instalar no meu celular uma nova versão de uma aplicação Android que estou construindo e, pelo que já pesquisei, pode ser facilmente resolvido desinstalando a aplicação antiga e instalando a nova. Porém, se eu fizer isso irei perder os dados do app antigo, coisa que eu não queria. Teria alguma maneira de resolver este problema sem perder os dados existentes?
Comment: Pode haver mais de uma razão para isso acontecer. Indique o que de relevante alterou entre as duas versões.
Comment: Não foi alterado nada estrutural (nome de packages, adição de novas bibliotecas, absolutamente nada disso), apenas algumas funcionalidades básicas.
Comment: Esses dados do seu app antigo, estão em banco de dados(tipo sqlite))? Tem como exportar esses dados?
Comment: Dados em arquivos de texto e no banco de dados. Não teria como exportar pois existem várias pessoas usando a aplicação, sendo que cada um deles tem seus próprios dados em seus telefones
Comment: Isso não pode ser assinaturas diferentes? Tipo duas chaves distintas.
Answer: Conforme a série de respostas em INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device
Esta mensagem quer dizer que o aplicativo já esta instalado:

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]

Isto pode ocorrer por talvez ter instalado o aplicativo de outra maneira, ou instalou via root ou via playstore, você pode tentar desinstalar via adb:
<code>adb uninstall <nome do pacote>
</code>
Ou então você pode desinstalar pelo próprio celular, vá até Settings > Apps e selecione seu App e clique em Uninstall

Versões mais recentes do Android basta arrastar o App e no topo da tela aparece o Uninstall (ou Desinstalar):

Nota: Se aparecer apenas o Remove significa que não é possível desinstalar

Teria alguma maneira de resolver este problema sem perder os dados existentes?
Existem algumas, ainda sim se o problema ocorre a todos momento você deveria checar o que esta ocorrendo, provavelmente estava tentando instalar o app por meios diferentes, ou o teu ADT esta desatualizado.

Nota: Se aparecer apenas o Remove significa que não é possível desinstalar

Clique em Setting
Vá até Back up & sync:

Ligue o backup clicando em ON (se estiver off):

Clique em Backup All

Ou então pode usar um aplicativo como:

Backup Your Mobile
Helium - App Sync and Backup
Comment: @flpn pode instalar um APP para fazer backups, ou um para navegar nas pastas e copiar os dados ou simplesmente sincronizar os dados com sua conta da PlayStore.
Comment: Infelizmente não respondeu a minha pergunta, mas obrigado mesmo assim


$\lim_{y \rightarrow b} \lim_{x \rightarrow a} f \neq \lim_{(x,y)\rightarrow (a,b)} f \neq \lim_{x \rightarrow a} \lim_{y \rightarrow b} f$

Question: Can someone give me an example to show that in general
$\lim_{y \rightarrow b} \lim_{x \rightarrow a} f(x,y) \neq \lim_{(x,y)\rightarrow (a,b)} f(x,y) \neq \lim_{x \rightarrow a} \lim_{y \rightarrow b} f(x,y) $
I have been able to construct examples when the first and last limit exist but the middle one does not, but I can't find one where the middle limit exists but is not equal to the other two (both of which exist).
Does the existence of the middle limit as well as the other two imply that they must be equal to the middle one?
Comment: Use '\lim' instead of 'lim' to get $\lim_{x \to \infty}$ instead of $lim_{x \to \infty}$
Answer: The limit
$$\lim_{x\to 0}\biggl(\lim_{y\to 0} x\sin\frac{1}{xy}\biggl)$$
does not exists. But
$$\lim_{y\to 0}\biggl(\lim_{x\to 0} x\sin\frac{1}{xy}\biggl)=0$$
Comment: Thank you. But my question was if the non equality is true when all three limits exist. I modified it now for clarity.
Comment: Oh, ok. Excuse me.
Comment: Oh but I see that here $\lim_{(x,y)\rightarrow(0,0)} f = 0$ and is not equal to one of the other limits so this is the closest thing to the answer I need. Thank you!
Answer: Now since $\lim_{x\rightarrow a} \lim_{y\rightarrow b} f(x,y)$ and $\lim_{y\rightarrow b} \lim_{x\rightarrow a} f(x,y)$ both exist it is obvious that $\lim_{x\rightarrow a} f(x,y)$ and $\lim_{y\rightarrow b} f(x,y)$ have to exist. For if not then the former two limits cannot be be calculated.
Lemma - If $\lim_{(x,y)\rightarrow (a,b)} f(x,y) = l$ and if both $\lim_{x\rightarrow a} f(x,y)$ and $\lim_{y\rightarrow b} f(x,y)$ exist then $\lim_{x\rightarrow a} \lim_{y\rightarrow b} f(x,y) = l = \lim_{y\rightarrow b} \lim_{x\rightarrow a} f(x,y)$.
Proof -
Define the functions $g_1(x) = \lim_{y\rightarrow b} f(x,y)$ and $g_2(y) = \lim_{x\rightarrow a} f(x,y)$.
Given an, $\epsilon > 0$

There exists a $\delta_1 >0$ such that $|f(x,y) -l| < \epsilon /2$ whenever $0 < \sqrt{(x-a)^2 + (y-b)^2} < \delta_1$
There exists a $\delta_2 > 0$ such that $|f(x,y) - g_1(x)| < \epsilon /2$ whenever $0 < |y - b| < \delta_2$

Let $\delta = \min\{\delta_1,\delta_2\}$
When both $0<|y-b|<\delta /\sqrt{2}$ and $0<|x-a|<\delta /\sqrt {2}$ we have $0 < \sqrt{(x-a)^2 + (y-b)^2} < \delta$. So,
$$|g_1(x) - l| = |g_1(x) - f(x,y) + f(x,y) - l| \leq  |f(x,y) - g_1(x)| + |f(x,y) - l| < \epsilon /2 + \epsilon /2 = \epsilon$$
Thus $\lim_{x\rightarrow a} g_1(x) = l$.
Similarly for $g_2(y)$. $\square$

Thus if all three limits in the question exist then they have to be equal.
Answer: This is an example of a function that is discontinuous at $x=0=y$ and has different limits when  that point is approached from different directions.
Comment: Doesn't the definition say that whichever way you approach $(a,b)$ the limit exists and is the same?
Comment: Yes. But for that you have to approach $(a,b)$ through a well defined path. If one of the inner limits doesn't exist then this path from which you want to approach $(a,b)$ is not defined at all.
Comment: @Rise As I read the [definition](https://en.wikipedia.org/wiki/Limit_of_a_function#Functions_of_more_than_one_variable)  the (two variable) limit does not exist **by definition** unless $f(x,y)$ becomes close to L for all $x,y$ close to $a,b$ .


php PDO query with several parameters to bind

Question: I am currently learning PHP concepts and just can not figure out how to properly bind a query. According to PDO manual, queries are bound only if they are of type string, int, float, etc. My first question is: "Do I need to bind date?" If yes, which parameters use. Otherwise, I need to bind some attributes of a relation to insert and what to do with remaining which are not of these types mentioned above?
Here is my code:
public function addCustomer($fname, $lname, $email, $dob, $hashedPwd, $hash)
{
    $customer = new Customer($fname, $lname, $email, $dob, $hashedPwd);

    $sql = $this->pdo->prepare("INSERT INTO customer(fname, lname, email, date_of_birth, password, hash, active)"
        . " VALUES(:fname, :lname, :date_of_birth, :email, :password, :hash, :active)");

    $sql->bindValue(':fname', $customer->getFname(), PDO::PARAM_STR);
    $sql->bindValue(':lname', $customer->getLname(), PDO::PARAM_STR);
    $sql->bindValue(':email', $customer->getEmail(), PDO::PARAM_STR);
    $sql->bindValue(':password', $customer->getPassword(), PDO::PARAM_STR);
    $sql->bindValue(':hash', $hash, PDO::PARAM_STR);
    $sql->bindValue(':active', 0, PDO::PARAM_INT);

    try {
        $sql->execute(['date_of_birth' => $dob]);
        echo "SUCCESS" . "
";
    }catch (PDOException $e) {
        $e->getMessage();
    }

}

Comment: just treat it as a string, and just stick with one way, either load them all up inside the `->execute()` or use `->bindValue`, don't combine both
Comment: @SergeyKim Where did you see that dates should not be bound? They should not be bound as integers but binding them should be fine. Maybe this thread would be useful https://stackoverflow.com/questions/2374631/pdoparam-for-dates
Comment: @Ghost just changed to this:  '$sql->bindValue(':date_of_birth', $customer->getDob());$sql->execute();' and it worked. However, according to manual, data types like date should not be bound. So, what's the proper way?
Answer: I do it by passing an array, and using question marks as my place holders
I also recommend working up a set of generic functions or a db handler class that you can simply pass a query and array (or maybe a 2nd array with db connection info) and get back an array with a true or false at element 0 and either an error message at element 1 or data from element 1 on (in the case ofa select).
Here's a snippet of mine, modified to take out all the other handling, but it shows how I paramaterize and prepare the query.
    <?php
    $query="insert into tablename(first_name,last_name) values(?,?)";
    $array=array("John","Doe");

    $dbconn = new PDO('mysql:host=' . $hostname . ';port=' . $dbPort . ';dbname=' . $dbName . ';charset=utf8', $username, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
    $dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $result = $dbconn->prepare($query);
    $result->execute($arr);
    if (!$result) {
        $retVal[] = false;
        $retVal[] = "some sort of error on execute";
        $retVal[] = $dbconn->errorInfo();
        return;
    }
    $retVal[] = true;
    $retVal[] = $dbconn->lastInsertId();

    return;

    ?>


$L^2$ bound on polynomial

Question: I want to show the following theorem:
Let $\frac{1}{1+|p|} \in L^2(\mathbb{R}^d)$ where $p$ is some polynomial. Then $\forall z \in \mathbb{R} \backslash A$ for $A:=\overline{\{p(x);x \in \mathbb{R}^d\}}$, we have $\frac{1}{p-z}\in L^2(\mathbb{R}^d).$
My ideas so far did not really lead to anything: Of course somehow we have to use the fact that the first function is in $L^2$ to conclude it for the other function. Probably we have to split the domain of integration somehow and use different estimates, i.e. on any compact set $M$ we have $\frac{1}{d(z,A)}$ is an upper bound to $\frac{1}{p-z}$ and square-integrable on $M$. But for the non-compact part $M^C$ we probably have to use $\frac{1}{1+|p|}$ somehow.
Comment: In case you had't noticed, there's a big gap in my solution. A correct solution has appeared - you should unaccept mine...
Answer: Let $E_k=\{x\in \mathbb R^d: k\le |p(x)| < k+1\}, k = 0,1,\dots $ Note that because $1/(1+|p|)^2$ is bounded below by $1/(k+2)^2$ on $E_k,$ we have $m(E_k) < \infty$ for each $k.$
Consider the set $\cup_{k<|z|}E_k.$ This is a set of finite measure, hence $1/|p-z|^2,$ being bounded above, is integrable there.
For $k>|z|,$ we have
$$\tag 1\int_{E_k} 1/|p-z|^2 \le 1/(k-|z|)^2m(E_k).$$
On the other hand
$$(1/(k+2)^2)m(E_k) \le \int_{E_k} 1/(1+|p|)^2.$$
Therefore $ \sum_{k>|z|}(1/(k+2)^2)m(E_k) < \infty.$ Now the ratio of  $1/(k-|z|)^2$ to $1/(k+2)^2$ tends to $1$ as $k\to \infty.$ Hence
$$\sum_{k>|z|} 1/(k-|z|)^2m(E_k) <\infty.$$
This and $(1)$ show $\sum_{k>|z|} \int_{E_k} 1/|p-z|^2 < \infty,$ hence $1/|p-z|\in L^2$ as desired.
Comment: Btw, I was not notified of your last comment- you forgot to put @..
Answer: It's clear that $p$ has positive degree, hence $p$ tends to infinity at infinity. Choose $R$ so that $$|p(x)|>1+2|z|\quad(|x|>R).$$
The integral of $1/|p-z|^2$ over $|x|\le R$ is finite, simply because you're integrating a continuous function over a compact set. On the other hand, if $|x|>R$ then $$|p(x)-z|\ge|p(x)|-|z|=\frac{|p(x)|+1}2+\frac{|p(x)|-(1+2|z|)}2\ge\frac{|p(x)|+1}2.$$
Comment: By positive degree maybe you mean even degree ? Otherwise the image of $p$ is the whole $\mathbb R$, right ? Ops, actually in $\mathbb R^n,\,n>1$ it is not enough that the degree is even.
Comment: Your first sentence: Surely you mean $|p|\to \infty?$ If so, why is this true? That seems to be the crux of the matter.
Comment: @zhw. Oops. Wasn't thinking...
Comment: @Svetoslav This is not nearly as clear as I thought. Sorry. Thanks.
Comment: I think your solution is OK: if there is no $z\in\mathbb R\setminus A$ then nothing to prove, i.e it is assumed there is such $z$. In either ways, $|p|\to\infty$, no matter what is the polynomial, so this is enough.
Comment: @Svetoslav Consider the polynomial $p(x,y) = (x^2-y^2)^2.$
Comment: @zhw Aha, you are right.
Comment: @zhw. But from the condition that $\int\limits_{\mathbb R^d}{\frac{1}{(|p|+1)^2}}<\infty$ I think it follows that $|p|\to\infty$
Comment: That may be true, but it seems difficult to show. Fortunately we can avoid that; see my answer below.

$L^2$ bound on polynomial


For continuous function $ f:\mathbb S^1 \to \mathbb R$ there exists uncountably many distinct points $x,y$ such that $f(x)=f(y)$

Question: Let $\mathbb S^1$ denote the unit circle in $\mathbb R^2$.

Then prove that for every  continuous function $f:\mathbb S^1 \to \mathbb R$, there exist uncountably many pairs of distinct points $x, y$ in $S^1$, such that $f(x)=f(y)$.
Comment: Where did you get this question from? What are your thoughts?
Answer: Assume $f$ is non constant. Take a point $y_0$ between the minimum and maximum of $f$.
Assume the $f^{-1} (y_0)= \{x_0 \}$ i.e. it consists of only one point of $\mathbb{S}^1$.
Then $ f(\mathbb{S}^1/{x_0} )$ must be connected which leads to a contradictions.
So the preimage of $y_0$ has at least two points.
Comment: With $\mathbb{S}^1/{x_0}$ do you mean set subtraction?
Answer: $S^1$ is compact and connected; the continuous image of a compact and connected set is also compact and connected, and hence a bounded interval $[a, b]$ in $\mathbb R$. Let $(\cos \theta, \sin \theta)$ be a point of $S^1$ such that $f(\theta) = a$. Define
$$
g: [0, 2 \pi ] \to S^1: t \mapsto (\cos (\theta + t), \sin(\theta + t))\\
h = f \circ g.
$$
Then $h(0)) = h(2\pi) = a$, and the image of $h$ is $[a, b]$.
For some point $0 < u < 2 \pi$, we must have $h(u) = b$.
Now consider the intervals $[0, u]$ and $[u, 2\pi]$. $h$ maps each of these intervals continuously to the whole interval $[a, b]$. For any $c$ between $a$ and $b$ there are points $x_L$ and $x_R$ in the two intervals, respectively, with $h(x_L) = h(x_R) = c$, by the intermediate value theorem. Each value $c$ provides and instance of a point-pair that maps to the same value in $[a, b]$ under $f$.
Comment: By the way, @clark's comment below makes essentially the same argument, but in short form. I wanted to make it really explicit and use only basic theorems like IVT, but his use of "continuous image of connected set is connected" is far more pithy.
Answer: A useful way to look at this is topologically. If you take the space $S^1\times S^1$ and remove the diagonal, the space is still path-connected. Define $h(x,y)=f(x)-f(y)$. Then any path between $(x_0,y_0)$ and $(y_0,x_0)$ inside this set will contain a zero of $h$. (Why?)
Then, show there is an uncountable collection of curves between $(x_0,y_0)$ and $(y_0,x_0)$ that are 100% distinct - no pair of paths intersect (except at the end points.)

Verbose details
If $f(e^{ix_0})\neq f(e^{iy_0})$ for $0<x_0\leq y_0< 2\pi$, then for each $u\in(0,1)$ define the define a path $\phi_u$ which goes linearly from $(x_0,y_0)$ to $(0,t)$ and then from there to $(y_0-2\pi,x_0)$.
You need to show that:

This path says inside the region: $\{(x,y):-2\pi<x-y<0\}$, and so if $x,y$ is on the path, then $e^{ix}\neq e^{iy}$.
$\phi_u(t)\neq \phi_{u'}(t)$ unless $t=0,1$ or $u=u'$.

Then defining $h(x,y)=f(e^{ix})-f(e^{iy})$ you get that $h(\phi_u(0))=-h(\phi_u(1))$ and thus, there must be a $\phi_u(t)$ for some $t\in(0,1)$ with $h(\phi_u(t))=0$. Since $(x,y)=\phi_u(t)$ has the property that $e^{ix}\neq e^{iy}$, this means that $f(e^{ix}=e^{iy}$ for some $(x,y)$ inside this curve.
But there are uncountably many $u$, and since the curves are disjoint except on the endpoints, there are thus uncountably many such pairs $(x,y)$.


How do I append new line break and retain the previous line break after an event is fired?

Question: Im making a chat app and need to append messages. The issue is that the new messages are all inline, I need a way to create a new line after a message is sent and not delete the previous message.
I have used '\n' but it only provides spaces. I tried using innerHTML but it replaces everything so the previous messages are lost.
I want to use vanilla js to solve this problem.
Essentially I want to convert this line of Jquery into js:
socket.on('chat message', function(msg){
  $('#messages').append($('
').text(msg));
});

Answer: Have you tried wrapping the message in a new tag, such as
 or
? You could also give these tags a class which has display: block; which in most circumstances will display them on a new line.
Answer: Wrap your new lines in a block-level element (I've used section in this example). To avoid clearing the whole log whenever you add a line you could use insertAdjacentHTML which allows you to direct where your HTML ends up.

const area = document.querySelector('textarea');
const save = document.querySelector('button');
const log = document.querySelector('#log');

save.addEventListener('click', handleClick, false);

function handleClick() {
  const { value } = area;
  const html = `<section>${value}</section>`;
  log.insertAdjacentHTML('beforeend', html);
  area.value = '';
}
<textarea></textarea>
<button>Save</button>

Log


Pass Interference Behind Scrimmage

Question: What if a receiver or a running back is behind the line of scrimmage can a defensive player step across the line of scrimmage to attack the player? Does the defensive player need to allow him to touch the ball before he makes contact or can he immediately collide with him regardless of whether the ball has been thrown or not?
Answer: NFL - No foul for contact behind the line of scrimmage.  Contact which is otherwise legal is allowed up to 1 yard past the line of scrimmage. I think (but am not 100% certain) that this is true in NFHS and NCAA as well.
Comment: Welcome to Sports SE - to make this a stronger answer, are you able to reference the specific rule in the NFL Rulebook which supports this?

Pass Interference Behind Scrimmage


Form redirect (?)

Question: I' trying to build this kind of pages:

one page for each taxonomy term with taxonomy info and all commerce products related to term

plus

one 'products' page where users can click on a taxonomy image to view all the products in a box (loaded via ajax).

I have built taxonomy/term/* pages and the products page and they work fine but when I tried to add a product to cart (from taxonomy/term AND products pages.. ) drupal add the product to cart but always redirect me in the taxonomy/term page.
So I tried to setup a different form #redirect in hook_form_alter() but it work in a strange way: when I call taxonomy/term page via ajax to include it in products page now drupal serve me the product page itself like there is a all times redirect from taxonomy/term page to products page.
<code>$form['#redirect'] = drupal_goto('products');
</code>
If I write
<code>$form['#redirect'] = 'products';
</code>
just do not redirect.
How can I achieve a right redirect?
I'm working in D7 with drupal commerce to manage e-commerce
Comment: You know [Working with #redirect](https://api.drupal.org/comment/18139#comment-18139)?
Comment: I missed comment https://api.drupal.org/comment/40338#comment-40338!! Thank you ^^
Comment: So if it works now, why not to post an answer? ;)
Comment: I needed to wait 2 days before answer my own question ^^
Answer: I solved this problem with this code:
<code>function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if( startsWith($form_id, 'commerce_cart_add_to_cart_form_') ){
    array_push($form['#submit'], '_mymodule_redirect_to_products_page');
  }
}

function  _mymodule_redirect_to_products_page(&$form, &$form_state){
  global $language ;
  $lang_name = $language->language ;

  $form_state['redirect'] = url('prodotti', array('language' => $language));
}
</code>

Form redirect (?)


implement one abstract method in two child classes

Question: I have two child classes and one parent class.
Parent class have abstract method and it has a class as a parameter. Child class implement the abstract method of parent and it has a another class as a parameter. But the child class method gives an error:

"does not implement inherited abstract member".

Here is the code:
abstract class StudentBizz
{
    public abstract Boolean enrollNewStudent(Student stuObj);
}

class MScStudentBizz:StudentBizz
{
    public override Boolean enrollNewStudent(MScStudent stuObj)
    {
        //code
    }
}

Comment: What do you want to happen when someone does `StudentBizz foo = new MScStudentBizz(); foo.enrollNewStudent(new OtherStudent())`? (  `OtherStudent` is a class that inherits from `Student` but not from `MScStudent`)
Answer: Depending on the rest of your code, another approach could be to use generics with type constraints (here I'm assuming MScStudent inherits from Student):
abstract class StudentBizz<TStudent> where TStudent : Student
{
    public abstract Boolean enrollNewStudent(TStudent stuObj);
}

class MScStudentBizz:StudentBizz<MScStudent>
{
    public override Boolean enrollNewStudent(MScStudent stuObj)
    {
        //code
    }
}

Comment: this is the thing that i had expected. It works really well. thank you
Answer: The overriding method should have the same signature as the base class method.
So your, overriding method should look like:
class MScStudentBizz: StudentBizz
{
  public override Boolean enrollNewStudent(Student student)
  {
     //code
  }
}

Comment: Yes. Declaring an abstract member means you need to have the exact same signature to override. There are two ways to work around it: the best is, as others have suggested, making the base generic on the student type. Another would be to use an interface for the Student method, using an explicit implementation in the derived class that calls through to the more specific overload; that way, code using the interface uses basic students (or even IStudent), while code specifically using the derived class uses the corresponding specialised student.
Comment: @Nuwan: If you want to change the type of your `student` parameter, you'll need to use a generic type parameter in `StudentBizz`.
Comment: if there is no any solution??  only solution is to use same method signature?


Angular 2/4 redux framework

Question: Can you tell me what is the difference between ng-redux vs ngrx-store library in angular? I want to implement redux in my application but not sure which library to use and what are the benefits?
Comment: ng-redux is a library / ngrx is a profile containing multiple github repos
Comment: can you elaborate on that. i thought ngrx-store is angular implementation of redux pattern using rxjs. If yes, i want to know how is it different from ng-redux? Is it better or worst?
Comment: check this https://reduxsimplified.blogspot.com/2018/08/redux-introduction.html
Answer: They both implement centralized state for your front-end, but I'd use ngrx/store for an Angular 2 app, because:

ngrx is built on RxJS, which is also the basis for Angular 2's http module; This allows for various possibilities for interacting with your components like store && dispatcher through RxJS methods like filter, transform data... I also thought it was nice having the Observable pattern implemented uniformly for all my data logic. RxJS observables provide a more robust manner to interact with data related actions
One method I thought was particularly cool was select(key) on the store module, which selects the specified state key and returns an observable that can be shared from a centralized service to multiple components; This minimized store subscription from components themselves and allowed for easy state updates from container(stateful) to component(stateless) leveraging Angular 2's change detection and async pipe.

Angular 2/4 redux framework


Como travar um pivot quando o evento de Holding for disparado?

Question: Estou querendo que quando o evento de Holding for disparado, eu consiga bloquear a movimentação do meu pivot.
Já tentei utilizar as propriedades IsEnable e IsHitTestVisible, no entanto eu ainda consigo realizar o swipe durante o holding. A única propriedade que funcionou foi a IsLocked, entretanto, ela "apaga" o cabeçalho, comportamento que não é desejado para a aplicação.
Alguém já passou e conseguiu resolver esse problema?
Answer: Dá uma olhada aqui e aqui
Nos dois casos é mostrado como desabilitar o "swipe" para o Pivot.
Veja:
public MainPage()
{
    InitializeComponent();
    Touch.FrameReported += (s, e) =>
    {
        if (e.GetPrimaryTouchPoint(slider1).Action == TouchAction.Up)
        {
            pivot1.IsHitTestVisible = true;
        }
    };
}

private void slider1_ManipulationStarted(object sender
    , ManipulationStartedEventArgs e)
{
    pivot1.IsHitTestVisible = false;
}

Outra possibilidade é setar a propriedade UseOptimizedManipulationRouting="False".
Comment: eu agradeço a resposta. No caso, eu quero evitar para o Runtime do Windows Phone e a propriedade  `UseOptimizedManipulationRouting` como pode ser visto [aqui](http://pt.stackoverflow.com/q/62805/1333), outro ponto é que isso não resolve para o _ holding_, já que ele desabilita as manipulações, evitando que o `ManipulationStarted` seja "despachado".
Comment: Então, o segundo link (de onde o código acima foi tirado) é para Windows Phone. De qualquer forma, veja outro exemplo de como desabilita os eventos Tap e Holding no WindowsPhone: http://blog.mjfnet.com/2010/07/16/windows-phone-7-detecting-tap-and-hold/


Hide block on 404 (not found) page

Question: SITUATION:

A View page displays all "items" that have a certain "code".

The code is passed via a contextual filter, e.g. /items/17, where 17 is the code.

A user might try to guess a code by typing it in, e.g. /items/345.

When the View is empty (i.e. the code is bogus), a not-found exception is raised as follows:
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if ($view->current_display == 'page_machine_name' && empty($view->result)) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  }
}

There is a menu included as a block that's displayed at the top of the View page.

The menu block configuration restricts the block to pages with paths /items/*.

PROBLEM:
The menu also appears on the 404 page, since that page retains the bogus path /items/345. How can I exclude the menu block from the 404 page?
NOTES:

I want to display the default 404 page rather than the view with a "not found" message as its body.
I don't want to display the view as a block instead of as a page unless it's the only way. I already know how to solve the problem if I have to do that.
If there were a way to say, "Include this block only on View pages" (like you can for content types), that would be ideal.
There are actually three blocks that need to be excluded from the 404 page; I mention only one to make it simpler. The other blocks are a text block and a banner block.
I see that a solution to this problem has been proposed for Drupal 9, but not available yet.
Answer: Yes, the solution is not available yet in core, see https://www.drupal.org/node/2245767.
But you can use this contrib module https://www.drupal.org/project/block_in_page_not_found and negate the condition to not show the block on a 404 page:
Comment: This works perfectly! I wondered how I missed this in the posts I read, but redoing the search I found that my search terms just didn't include it. I hope this post will be easier to find for others who need the same direction.
Answer: programmatically:
 $route_name = \Drupal::request()->attributes->get('_route');
  if ('system.404' === $route_name) {
    $region_name = 'content';
    $block_names = ['oneBlockID', 'andAnother'];
    foreach ($block_names as $block_name)
    if (isset($variables['page'][$region_name][$block_name])) {
      $variables['page'][$region_name][$block_name]['#access'] = FALSE;
    }
  }

Hide block on 404 (not found) page


How can I use multiple substring functions in an update statement?

Question: I have a table with a column called candidate_name in which the names are formatted as lastname, firstname. I'd like to update the column so that the names are in firstname lastname format.
I wrote this query to see if the string functions were working correctly:
SELECT
    SUBSTRING(candidate_name, 1, LOCATE(',', candidate_name) - 1) AS last,
    SUBSTRING(candidate_name, LOCATE(',', candidate_name) + 2, LENGTH(candidate_name) - LOCATE(',', candidate_name) - 1) AS first
FROM
    colorado_project.candidates
WHERE
    candidate_name = 'AHREND, JARED';

This returns the strings into new columns as expected:

But I don't know how to use these in an update statement. I've tried many statements similar to this:
UPDATE candidates
SET candidate_name = SUBSTRING(candidate_name, 1, LOCATE(',', candidate_name) - 1),
                     SUBSTRING(candidate_name, LOCATE(',', candidate_name) + 2,
        LENGTH(candidate_name) - LOCATE(',', candidate_name) - 1)
WHERE candidate_name = 'AHREND, JARRED';

Pretty sure I've gotten every error known to mankind at this point, but the main error I get is

'1292 Truncated incorrect DOUBLE value 'AHREND'.

I've searched around and it seems like this error is often associated with comparing a string value to a number value, but I don't understand by the substring functions would be returning a number value now, when they were returning strings before? Or maybe that's not whats going on here. Any help would be appreciated. Thanks!
Comment: [Why should I "tag my RDBMS"?](https://meta.stackoverflow.com/questions/388759/why-should-i-tag-my-rdbms) - please add a tag to specify whether you're using `mysql`, `postgresql`, `sql-server`, `oracle` or `db2` - or something else entirely.
Comment: I'm not sure how to find the table definition, I'm still new to this. But the 'candidates' table is made up of text columns, with the exception of the 'candidate_name' column that I'm working with here. I changed it to a VARCHAR column in an effort to get this to work, but it didn't help.

I've also tagged MySQL and will remember to do that in the future.
Answer: You must concatenate the 2 parts of the name:
UPDATE candidates
SET candidate_name = CONCAT(
  SUBSTRING(candidate_name, LOCATE(',', candidate_name) + 2, LENGTH(candidate_name) - LOCATE(',', candidate_name) - 1),
  ' ',
  SUBSTRING(candidate_name, 1, LOCATE(',', candidate_name) - 1)
)
WHERE candidate_name = 'AHREND, JARED';

See the demo.
or, simpler with SUBSTRING_INDEX():
UPDATE candidates
SET candidate_name = CONCAT(
  TRIM(SUBSTRING_INDEX(candidate_name, ',', -1)),
  ' ',
  SUBSTRING_INDEX(candidate_name, ',', 1)
)
WHERE candidate_name = 'AHREND, JARED';

See the demo.
Comment: This worked, thank you! I thought about using CONCAT, but convinced myself that wouldn't work for some reason. Now, looking at it, it makes total sense!


IE Automation - Click does not work

Question: I am trying to automate clicking a button in IE without any success. Any help would be appreciated. The web page is a public search site: https://eams.dwc.ca.gov/WebEnhancement/
There are a fews required input text boxes and three buttons on that page. The buttons are: Cancel, Reset and Next.
My code to populate the fields and clicking the Next button:
oIE = CREATEOBJECT([InternetExplorer.Application])
oIE.Navigate([https://eams.dwc.ca.gov/WebEnhancement/])
oie.visible = .t.

oie.document.forms[0].elements[0].value='somebodys first name'
oie.document.forms[0].elements[1].value='somebodys last name'
oie.document.forms[0].elements[3].value='some email'
oie.document.forms[0].elements[4].selectedindex = 2

?oie.document.forms[0].elements[7].value && displays Next
oie.document.forms[0].elements[7].click  && does not work
oie.document.forms[0].submit && does not work

inputCollection = oie.document.getElementsByTagName("input")
?inputcollection.item[6].value  && displays Next
inputcollection.item[6].click() && does not work.

View Source contains this:

Requestor information capture

<form id="requestor" action="InformationCapture" method="post">

...
...

        <input type="submit" name="action" value="Cancel" >
        <input type="submit" name="action" value="Reset" >
        <input type="submit" name="action" value="Next" >

</form>

Thanks!
Answer: I finally figured it out. The following code is equivalent to clicking the Next button:
    oIE.Document.forms[0].submit(3)
The solution was passing 3 as a parameter to the Submit method.

IE Automation - Click does not work


How to find this limit given only a derivative in a point?

Question: Given that
$f(x)$ is differentiable and $f'(0)=1$,
I'm trying to find $$
\lim_{x\to0}\frac {f(x^2)-f(0)}{\sin^2(x)}
$$
I feel like I should try and use Tailor to make the denominator more usable but that's no good because $f(x)$ is only differentiable once.
How best to approach this problem?
Comment: Rewrite as $\frac{x^2}{sin^2 x}\frac{f(x^2)-f(0)}{x^2}$ and it's almost over.
Answer: HINT:
$$\lim_{x\to0}\frac {f(x^2)-f(0)}{\sin^2(x)}$$
$$=\lim_{x\to0}\frac {f(x^2)-f(0)}{x^2-0}\cdot\dfrac1{\left(\lim_{x\to0}\dfrac{\sin x}x\right)^2}$$
Now $g'(x)=\lim_{h\to0}\dfrac{g(x+h)-f(x)}h$


Simpana CommVault logs and Splunk

Question: What is the best way to get CommVault log data into Splunk? I don't see a Splunk app developed for CommVault, and CommVault generates a lot of log data. It would be extremely beneficial to collect and manage it with Splunk.
Has anyone successfully done this?
Any ideas would be helpful!
Comment: If you have sample data from the log files, it would greatly aide being able to help :)
Answer: Wow - just up my street! We use both and do exactly what you state - we simply use Splunk to grab the logs and then have some searches written that only show us the errors rather than the successes - works a treat, but you're right there's nothing specific for it.

Simpana CommVault logs and Splunk


Hypothesis testing - Paired sample t test or two sample t test

Question: I'm trying to test the hypothesis that there is a significant difference between the data below. I'm having trouble deciding whether I should use a paired sample t test or a 2 sample t test. Can't decide whether they're 2 independent groups or paired. The sentence "In the 1990's a group of researchers reported the results of a study that controlled for genetic and socioeconomic differences by examining 15 pairs of monozygotic twins..." is making me lean towards using a paired t test. Although I'm still quite unsure.
Answer: I personally would use a paired $t$-test here: there is an obvious pairing here (twins: one unaffected, the other affected), and the samples are obviously very dependent (twins).
Remember that the two-sample $t$-test assumes that your two samples are independent.
Demonstration in R, in case you would like the code for $H_1$ with $\mu_{\text{unaffected}}-\mu_{\text{affected}}  \neq 0$:
<code>unaffected <- c(1.94, 1.44, 1.56, 1.58, 2.06, 1.66, 1.75, 1.77, 1.78, 1.92, 1.25, 1.93,
2.04, 1.62, 2.08)
affected <- c(1.27, 1.63, 1.47, 1.39, 1.93, 1.26, 1.71, 1.67, 1.28, 1.85, 1.02, 1.34,
2.02, 1.59, 1.97)

difference <- unaffected - affected

t.test(difference)

    One Sample t-test

data:  difference
t = 3.2289, df = 14, p-value = 0.006062
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 0.0667041 0.3306292
sample estimates:
mean of x
0.1986667
</code>


Doubt in Ivan Niven's proof of irrationality of pi.

Question: In the proof, how do we get the upper limit for $f(x) \sin{x}$ as $\pi^n \cdot \frac{a^n}{n!}$ ?
I thought $f(x) \sin{x}$ would be maximum at $x=\pi/2$ when its value would be: $$\pi^n \cdot \frac{a^n}{2^{2n}n!}$$
Where am I going wrong?
Comment: Is a *strict upper bound*. The maximum isn't required. And your supposed maximum us highly suspicious.
Comment: @Martín-BlasPérezPinilla : The maximum evaluated by Moibus is correct. As $f(x)$ is a symmetric function on $[0,\pi]$ attaining maximum at $x = \frac{\pi}{2}$, and $\sin{x}$ also attains maximum at $x = \pi/2$, hence their product attains maximum also at $x = \pi/2$. So now we can just put $x = \pi/2 = a/2b$. But your observation is indeed correct. One upvote from me.
Comment: @DiffeoR, true. I overlooked the symmetry of $f$.
Comment: Thanks to naslundx, Git Gud and Sabyasachi for editing the question and making it more readable. I was not familiar with LaTeX. Now I have used it in the answer below.
Comment: DiffeoR and Martín-BlasPérezPinilla, please check out the answer below. As Martín-Blas Pérez Pinilla said, it is a strict upper bound.
Answer: The upper limit of $f(x) \sin{x}$ mentioned in the proof is not the least upper bound.
The least upper bound is $$\pi^n \cdot \frac{a^n}{2^{2n}n!}$$ as mentioned in the question.
Given $f(x) = \frac{x^n.(a-bx)^n}{n!}$
a general argument for getting the upper bound mentioned in the proof would be that the maximum value of $x$ is $\pi$ and the maximum value of $(a-bx)$ is $a$.
After posting this question here, I found an explanation of the limits of the proof in Presh Talwalkar's blog
I posted my doubts in the comments section and Presh was kind enough to respond and clarify my doubt.


Connection between grey scale and intensity in image matrices

Question: Let A be a image matrix where each element in the matrix displays the integer value of the pixel intensity for a specific pixel. We also have a greyscale between two values.
For example let A be a image matrix symbolizing a 4x4 pixel image. The greyscale of the picture is [0,3] where 0 is black and 3 white.
$$
A =
\begin{pmatrix}
1 & 1 & 0 & 3\\
0 & 2 & 0 & 2\\
2 & 3 & 0 & 3\\
1 & 0 & 3 & 1
\end{pmatrix}
$$
Here is where I am confused, mainly in terminology. What element are of intensity 0 and 1 in the image matrix? Does intensity 1 here mean just simply each matrix element containing a 1? Or does intensity 1 mean white and therefore the elements containing a 3 in the matrix are considered of intensity 1?
Answer:
For example let A be a image matrix symbolizing a 4x4 pixel image. The
greyscale of the picture is [0,3] where 0 is black and 3 white.

This quote would indicate that, as you suspected, an intensity of 1 means white. Normally, I have seen "intensity" referred to as "brightness" or "value" in programs like Photoshop, Blender, etc. So, in your matrix you would divide everything by 3 to get the "intensity".
You can visualize this with the following code in Python:
import seaborn as sns
import matplotlib.pyplot as plt

image_matrix = [[1, 1, 0, 3],
                [0, 2, 0, 2],
                [2, 3, 0, 3],
                [1, 0, 3, 1]]

ax = sns.heatmap(image_matrix, annot=True, cmap="gist_gray")
plt.show()

This is a fairly common way of representing grayscale images. An 8-bit grayscale image, for example, will have a range from 0 to 2^8 - 1, or 0 to 255 for each pixel. An RGB image will have a third dimension for the "intensity" of the red, green, and blue values.
Comment: Perfect, just was I was looking for! Many thanks!
Answer: You could get similar results with the following code too. The original array:
A = np.array([[1,1,0,3],[0,2,0,2],[2,3,0,3],[1,0,3,1]])

After scaling the gray-scales to have intensity values in [0,1]:
A_scaled = A / A.max()

We could it in a more generic way with scikit-learn preprocessing module's MinMaxScaler (we shall get the same scaled intensity matrix as above):
from sklearn.preprocessing import MinMaxScaler
MinMaxScaler().fit_transform(A)
# array([[0.5       , 0.33333333, 0.        , 1.        ],
#        [0.        , 0.66666667, 0.        , 0.5       ],
#        [1.        , 1.        , 0.        , 1.        ],
#        [0.5       , 0.        , 1.        , 0.        ]])

Now, use matplotlib.pylab.imshow() to display the scaled intensities:
plt.imshow(A_scaled, cmap='gray')
plt.colorbar()
plt.axis('off')
plt.show()


What to set "intercept factor" and "slope factor" as in model?

Question: I was struggling a bit with understanding what exactly the intercept factor and slope factor is in a model. I need to estimate these in an a priori power analysis I am trying to do.
My understanding is that a "high" intercept would be 1, with the slope being the rate of change (either positive or negative). I noticed you can set the intercept above 1, and wondered when this would be the case. What is the difference between an intercept factor of 1 and 2? Is an intercept factor of 1 with a slope of -0.1 the same as an intercept factor of 2 with a slope of -0.2, for example.
How does the intercept change depending on the observed measure, if at all?
Added R code below. Latent variable is depression, with observed measure of PHQ-9 scores collected at 7 timepoints. I plan to analyse this with a latent growth curve model.
<code>
library(semPower)
powerLGCM <- semPower.powerLGCM(
  # define type of power analysis
  type = 'a-priori', alpha = .05, power = .80,
  # define hypothesis
  nWaves = 7,
  means = c(1, -0.15),     # i, s
  variances = c(.8, .7),  # i, s
  covariances = .5,
  nullEffect = 'sMean = 0',
  # define measurement model
  nIndicator = rep(1, 7), loadM = .7
)
</code>
Comment: This rather depends on the model you are planning to estimate. Can you provide more details? (But essentially it's the same as the slope and intercept in regression. You just have each person measured mutiple times, instead of once, as you do in regression).
Comment: You don't need power to plot a slope. You need power to test a null hypothesis. I'm not familiar with semPower but from reading the help file, it appears that you need to use the betaST or betaIT options.  I'm not a huge fan of this sort of wrapper function, I prefer to code a simulation myself so that I know that I understand what it is doing.
Comment: I am planning to estimate a latent growth model to analyse changes in depression, as indicated by PHQ-9 scores collected at 7 intervals.
I also plan to use predictors to analyse whether curves are different for different populations within the sample (e.g male vs female, high scores on adhd questionnaire vs low scores), although I have not included this in the power analysis as I am initially just trying to calculate the sample required to plot a slope.
I added my current R code to the main body.
Comment: I think the `simsem` package provides the flexibility Jeremy prefers.  You can find vignettes on the web site about power analysis for model fit/comparison: https://github.com/simsem/simsem/wiki/Vignette However, if you are interested in power for testing specific parameters, the `summaryParam()` function provides that for `sim()` output (see the `?summaryParam` help-page example).
Answer: I would strongly suggest that you read a bit more about latent growth curve (LGC) models before you run your power analysis. This will help you understand what the parameters of an LGC model are, how they relate to your observed variables, and how to set the parameters appropriately for your power analysis. There is a lot of good introductory literature available on this topic, for example:
Bollen, K. A., & Curran, P. J. (2006). Latent curve models: A structural equation perspective. New York: Wiley.
Duncan, T. E., Duncan, S. C., & Strycker, L. A. (2013). An introduction to latent variable growth curve modeling: Concepts, issues, and application. Routledge.
Little, T. D. (2013). Longitudinal structural equation modeling. New York: Guilford.
Newsom, J. T. (2015). Longitudinal structural equation modeling: A comprehensive introduction. Routledge.
Preacher, K. J. (2008). Latent growth curve modeling (No. 157). Sage.
https://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=1ACF96E33449B682E740E025BEAF408E?doi=10.1.1.138.4268&rep=rep1&type=pdf
https://www.youtube.com/watch?v=f4_FE9Q5LCo
In a nutshell, an LGC model, in the simple linear growth case consists of an intercept factor (initial or Time-1 latent variable) that represents the depression true (error-free) scores at Time 1, a linear slope factor (latent variable) that represents true inter-individual differences in linear change across time, and time-specific error variables that represent random measurement error and situation-specific variance.
The intercept and slope factors each have a mean and a variance as free parameters as indicated in your syntax. The intercept factor mean represents the average depression true (error-free) scores at Time 1. The variance of the intercept factor represents true (error-free) individual differences in depression at Time 1. The slope factor can be interpreted as a latent difference or latent change score variable that represents linear change in true scores across time. The mean of the slope factor represents the average rate of linear change in true scores across time. The variance of the slope factor represents the extent of inter-individual differences in linear change across time.
There is also a covariance parameter between intercept and slope that represents the linear association between the true initial status and linear change over time. Lastly, there are error variance parameters to be set for the observed variables. The error variances reflect the degree of unreliability and/or situation-specificity in the observed variables.
It may be difficult for you to guess the "right" (or at least plausible) parameter values for your simulation. (This is probably the hardest part of any kind of power analysis!) You might want to check out whether there is any prior literature that has reported an LGC model application to the same depression scale. Perhaps you can derive approximate parameter values from such an application. In any case, I would try out multiple different sets of parameter values to see how that affects estimated power, especially if you are not sure about what the actual parameters might look like in the population.
Comment: The means of the intercept and slope refer to the means of the latent factors. They are not identical to the observed variable means. However, the observed means can serve as a guide for finding plausible/realistic values for the intercept and slope factor means. It is plausible that the intercept factor mean is not too far away from the Time 1 observed variable mean. Regarding the slope factor mean, you have to ask yourself whether it is plausible that the average rate of linear decline between two time points is -1. In any case, I would not estimate an LGCM with only N = 10 cases.
Comment: Also, you have to make sure your simulated values for the latent factor variances and the error variances are plausible/realistic. This can be more tricky, especially with regard to the slope factor variance.
Comment: So regarding the estimated parameter of the mean intercept and mean slope, does this relate to the observed variable? For example, I expect the average PHQ-9 score in this study to be around 20 at first interval with a moderate variance. However if I change the mean intercept to 20, with an expected slope of -1. The power analysis using the code estimated 10 participants provides 0.88 Power, which just doesn't sound right to me and made me figure my understanding was wrong. Is this actually correct?
Comment: Thanks Christian, this is really helpful.


Why aren't notes and intervals plain numbers?

Question: Beginner question:
If we were to leave the historical context aside and redesign the system of musical notation: would we base this around the 12 steps we've divided octaves in?
What strikes me as very confusing and weird is that the notes and intervals (and even the layout of some instruments like the piano) is based around the major scale.
Am I correct in assuming this is just born from the historical context, where perhaps this 7 notes array is all there was, or is there any other reason?
Could we simply call the notes by numbers and their intervals maybe in flat ordinals (or the other way around)? What would we lose by doing that?
It would be awesome if answers can cite technical advantages of the current system vs flat numbers (I already assume a great deal of what we have nowadays is historical, but it's still a struggle for every beginner, I wonder if there are other reasons)
Edit: I'm interested in finding motivation to study theory, but I'm having trouble getting over the feeling that it's way more complex than it should be, so any argument helps
Comment: Does it make a lot of sense to cite technical advantages when the field is primarily artistic? What's the advantage in using numbers to distinguish notes? I have a degree in mathematics and even I don't like numbers *that* much.
Comment: @Ambluj thanks for your input! I could argue though, that the frequencies increase logaritmically, so this would even generate a direct relationship between the note and it's frequency
Think about this: what if we name them in base 12: "0123456789AB"
We could name the octave directly in a compound number eg: 7A is the A note in the 7th octave. This notation would also be directly linked to the log of the frequency, would it not? Sorry for the random thought :)
Comment: @ToddWilcox ha! valid point. I think the distances are inherently and intuitively mathematic: if you named the notes from 1 to 12, the distance between note 3-7 will be (7-3) or (3+12-7) in inversion
I'm just a bit sad that this is so easy to figure out mentally but I'm probably months away from doing that mentally and quickly with the standard notation.
So I want to convince myself it has a reason other than "it's the way it is" to motivate me to learn
I'm an engineer btw, weirdly enough I do like numbers when they seem to make sense to use
Comment: numbers are used heavily in modern atonality (pitch set classes), rhythmic analysis ("The Geometry of Musical Rhythm", Toussaint), and the somewhat older art of the construction of canon ("Technique of Canon", Norden)
Comment: There are also significant mathematical relationships between the frequencies of notes when the 12 note octave is used (going up an octave doubles the frequency). Numbering the notes might be quite confusing given the instrument-specific roles of numbers. Music has a lot of sets of information, and in many cases has to use different numeral systems to express different cardinal values (Roman numerals are used for positions on guitar whereas Arabic numerals are used for fingerings). There is an argument to be made that using numbers might actually make music more confusing.
Answer: Western music makes harmonic sense in relation to diatonic scales.  A simple-minded accompaniment to nuersery school kind tunes is singing a third or sixth above or below.  That's conceptually simple but it doesn't map to a simple concept in chromatic intervals: you get a haphazard sequence alternating between minor and major thirds (3 or 4 semitones).  Trying to play this kind of thing on an inherently chromatically organized instrument (like a chromatic button accordion) takes quite a bit of practice.
And if you want to analyze that kind of stuff (as well as the harmonic frame a melody moves in), there just is no way around relating it to the diatonic scale it is based on.  There are a few instruments with uniform keyboard layouts: apart from the mentioned chromatic button accordion, there is the Jankó keyboard for pianos.  Their principal advantage is that they make transposition easy and thinking in semitones.  This advantage was not enough to let the Jankó keyboard survive/thrive compared to the disadvantage of not being related to any diatonic scale (which our notation is based on as well as our harmonies).  The chromatic button accordion is basically the only thriving member of uniform keyboard layouts and that's mainly because it's so much more compact than a piano keyboard, making a better fit for the instrument class.
So in short: it has been tried.  There were lots of treatises particularly around the musical theoretical advantages of the Jankó keyboard and predictions that everybody would be using it.  This hasn't happened.
For better or worse, Western music (several developments outside of the classic frameworks aside) is rooted in diatonic scales and trying to ignore this is a hindrance rather than a help to understanding.
Comment: Thanks for your insight! I'd like to note that from my POV most string instruments are also equally distributed in semitones
Actually I think fewer ones have the diatonic scale so baked in like the piano
If you have other examples I'd be really interested in knowing them
Comment: Thanks for your participation and contribution "user52307" ;-)  Plus 1 (but who's counting numbers?).
Answer: You are correct- the reason standard notation is not orthogonal (i.e. a step can be a half tone or a whole tone (or more or less, with accidentals) depending on where it is on the staff, clef, and key signature) is historical.  In some sort of orthogonal notation it would certainly be easier to learn the intervals.
But that's not all there is to reading music. As Todd mentioned in the comments above, reading music has more to do with art than technical advantages.  And the art of Western music is still, even today, mostly based around scales that have the same pattern of whole and half steps they did when notation was being developed.  This pattern is built into the standard staff notation, so you can depict music from Bach to the Beatles in a way that's easy to read.
Sure, there is the drawback you mentioned: there's a fair amount to learn. And an orthogonal system would be simpler for twelve-tone music.  But for the bulk of the music most people do, standard notation is pretty hard to beat for readability.  And that's what notation is intended for: not for easy frequency analysis, but for musicians.
Comment: So, when you say "readability", you mean that the current system is compact in notation? I can't disagree with that, getting a system where we give all notes the same importance to work with notation would definitely be a challenge, so here's a valid point in favor of it, thanks!
Comment: @Alvaro - If I understand correctly what you mean by "compact", I agree. Standard notation is biased towards heptatonic scales, of the pattern WWHWWWH, starting at any point, and these scales make up the bulk of Western music.


Monit - issue configuring "check program"

Question: I'm trying to configure Monit to run my script but it's not working.
I'm running Monit 5.3.2 from a Ubuntu 11.2 environment (it's a virtual machine, my machine actually is Windows 7), and for some reason I cannot make the "check program" to work. It always gives the error:
Warning: Program is not executable: 'scriptPath'.
Just in case, I tested by copying the example Monit has on the manual (http://mmonit.com/monit/documentation/monit.html) and created the script as the manual, as described below:
An example:
  check program myscript with path "/usr/local/bin/myscript.sh"
  if status != 0 then alert

Sample script for the above example (/usr/local/bin/myscript.sh):
 #!/bin/bash
 echo test
 exit $?

Anyway, even with those instructions, I still receive the same error message:
 Warning: Program is not executable: /usr/local/bin/myscript.sh
I have no idea what can be happening. Any suggestion is very welcome.
Answer: As the error message says, your script file is not executable. You need to add the x permissions using chmod:
chmod +x /usr/local/bin/myscript.sh

Comment: Hi Mihael, thank you so much! It worked!
As you see, I'm not only new to Monit but also to Linux!


Python - Pandas - Create columns from row entries

Question: I am trying to create a useable Pandas dataframe from a particular .csv file. The file has one column to identify the type of test that the datain the row is for, two columns that identify the device that is being measured, and the rest of the columns contain the data.
The input .csv file follows this format:
testtype1, device1name, device1info, meas_1, meas_2, meas_3, ... ... , meas_n
testtype2, device1name, device1info, meas_1, meas_2, meas_3, ... ... , meas_n
testtype3, device1name, device1info, meas_1, meas_2, meas_3, ... ... , meas_n
testtype1, device2name, device2info, meas_1, meas_2, meas_3, ... ... , meas_n
testtype2, device2name, device2info, meas_1, meas_2, meas_3, ... ... , meas_n
testtype2, device2name, device2info, meas_1, meas_2, meas_3, ... ... , meas_n
...        ...          ...          ...     ...     ...               ...

And so on. I am trying to get this data into this format:
devicename    deviceinfo    testtype1   testtype2   testtype3
device1name   device1info   meas_1      meas_1      meas_1
device1name   device1info   meas_2      meas_2      meas_2
device1name   device1info   meas_3      meas_3      meas_3
...           ...           ...         ...         ...
device1name   device1info   meas_n      meas_n      meas_n
device2name   device2info   meas_1      meas_1      meas_1
device2name   device2info   meas_2      meas_2      meas_2
...           ...           ...         ...         ...

I read the file using pd.read_csv(filename), but once I have the data I get stuck. I have looked at using df.pivot, and also transposing the dataframe slice with the measurements, however I have no idea where to go from here. I am very new to Python so any help would be much appreciated!
Answer: A pivot table would be the correct way to do this - start off slowly - and then add complexity.
From the look of your data
 new_df = pd.pivot_table(orig_dataframe,index=['device1name','device1info'],values=['Col1','Col2'])

If you then wanted to do some numpy maths calls you would add a
,aggfunc=[np.sum,len]

To the pivot_table call
Comment: I am trying to use the `pd.pivot_table()` function, but it is taking the mean of each `meas_n` of the different tests. What I want to do is create a new row for each `meas_n`, with columns for `'devicename'` and `'deviceinfo'` filled in accordingly, similar to an SQL database format. It doesn't seem that there is anything built in for this?
Comment: I ended up solving this by looping through each line, using string.split() for the data and writing this to a StringIO object in the format I wanted. I then passed this to read_csv() and obtained the data in the format I wanted.


How to preload WKWebviews from the WKWebviews in swift5

Question: I have two independent WKWebViewController. I load the first WKWebView and then another WKWebView when the button is pressed.
So I want to load another WKWebView in advance. How can I do this?
Each of the two ViewControllers has WKWebView.

First WKWebView
    func openSecondScreen(){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let openSecondScreen = storyboard.instantiateViewController(withIdentifier: "SecondWebViewController") as! SecondWebViewController
        openSecondScreen.modalPresentationStyle = .overCurrentContext
        openSecondScreen.modalTransitionStyle = .crossDissolve
        openSecondScreen.delegate = self
        self.navigationController?.pushViewController(openSecondScreen, animated: true)
    }

Second WKWebView
    @IBOutlet var secondWKWebView: WKWebView!
    override func loadView() {
        super.loadView()

        let images = global.getIndicatorImage()
        let animatedImage = UIImage.animatedImage(with: images, duration: 1.0)
        self.indicatorImage.image = animatedImage

        contentController.add(self, name: "SecondWeb")

        config.userContentController = contentController

        secondWKWebView = WKWebView(frame: secondWKWebView.frame, configuration: config)

        secondWKWebView.uiDelegate = self
        secondWKWebView.navigationDelegate = self

        view.addSubview(secondWKWebView)
        view.addSubview(indicator)

        if contentController.userScripts.count > 0 {
            contentController.removeAllUserScripts()
        }
        let  localFilePath = Bundle.main.url(forResource: webUrl, withExtension: "html")
        let  myRequest = URLRequest(url: localFilePath)
        secondWKWebView.load(myRequest)
    }

How can I solve this problem?
Comment: you can make SecondWebViewController to UIView and load  WKWebView on this view and you can show and hide this UIView
Comment: @Lalitkumar Are you saying that we should use two WKWebViews for one view controller? I need animation to move from left to right when I'm showing another WKWebVIew, so it seems impossible.
Comment: yes On view you can animation according your requirement
Comment: @Lalitkumar My screen is moved from left to right as the edited questions screens to be. Is this possible?
Comment: you can take idea this url https://medium.com/@adeelkothiwala/menu-slide-out-with-xcode-swift-945c3b100e29

https://www.youtube.com/watch?v=ej5laXv2dzQ both url help you can make your view according your requirment
Comment: @Lalitkumar My logic is already geared to two independent controllers. Can't I preload with two controllers?
Answer: I think I found a solution. But there's a problem. I can still see the animate image of the indicator. I don't think the search is complete.
First WKWebView
    var openSecondScreen : SecondWebViewController!
    var preloadCheck = false
   ...
    func openSecondScreen(){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        openSecondScreen = storyboard.instantiateViewController(withIdentifier: "SecondWebViewController") as! SecondWebViewController
        openSecondScreen.delegate = self
        openSecondScreen.loadViewIfNeeded()
        openSecondScreen.secondWKWebView.uiDelegate = self
        openSecondScreen.secondWKWebView.navigationDelegate = self
        preloadCheck = true
    }
....
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if preloadCheck {
            self.navigationController?.pushViewController(openSecondScreen, animated: true)
            preloadCheck = false
        }
    }

Second WKWebView
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        indicatorImage.isHidden = true
        indicatorImage.stopAnimating()
    }

So I solved the problem by concealing an indicator image when the screen was shown.
Second WKWebView
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        indicatorImage.isHidden = true
        indicatorImage.stopAnimating()
}

When you press the button to open the secondWebview screen, indicator images are displayed on the firstWebview screen, indicator images disappear when navigation is complete, and the secondWebview screen appears preloaded.


LRT for PRT both unknown

Question: I have a random sample of ${X_1,...,X_n}$ from the following pdf:
$${\theta \beta^ \theta \over {x^{\theta+1}}}$$ where $\theta>0$,  $\beta>0$,  $x\ge\beta$
I want to find the LRT to test $H_o:\beta=1$ vs $H_a:\beta\neq1$, using $\alpha$=0.05 to find the critical values of the test.
I know the MLEs are $$\hat\beta = x_{(1)}=min_{(i)}\{X_i\}'s$$
$$\hat\theta = {n \over \sum_{i=1}^n ln(x_i)-nln(x_{(1)})}$$
which should give the LRT under the null of
$$\Lambda (\mathbf x)= {\hat\theta^n\prod_{I=1}^n {1 \over x_i^{\hat\theta+1}} \over \hat\theta^n x_{(1)} ^{\hat\theta(n)} \prod_{I=1}^n {1 \over x_i^{\hat\theta+1}} }$$
But I am stuck on simplifying and am not sure what distribution this statistic would follow...a guess would be to transform it with Wilks' Theorem for a chi-sq approximation.
Comment: Work in terms of the logarithms.
Comment: https://stats.stackexchange.com/q/345895/119261
Answer: Yes, without the restriction of assuming the null hypothesis, the MLEs are $\hat{\beta} = x_{(1)}$ and $ \hat{\theta} = \frac{n}{\sum_i(\log x_i - \log x_{(1)})}. $
However, when you are assuming the null, there is a different estimate for $\theta$:
$$
\hat{\theta}_0 =  \frac{n}{\sum_i\log x_i }.
$$
This means your expression for the LR test statistic is actually supposed to be
$$
\Lambda (\mathbf x) = \frac{\hat{\theta}_0^n (\prod_i x_i)^{-(\hat{\theta}_0 + 1)} }{\hat{\theta}^n\hat{\beta}^{n\hat{\theta}} (\prod_i x_i)^{-(\hat{\theta} + 1)}}.
$$
Then you can use Wilks' theorem to find the distribution of this under the null.
Comment: Hi thank you. Yes the test is of the form:

$nln[1-T(X)]$ where T(X)=$\frac{nln(x_{(1)})}{\sum_i=1^nln(x_{i})}$

Which could be easily approximated for a critical value~ $\chi_2^2$.

However what if expressing the fraction in terms of the exponential normalized spacings yields... $\frac{U}{U+V}$~$\beta$(1,n-1) where U~Gamma(1,$\theta$)  independent of  V~Gamma(n-1,$\theta$)?

What is preferred?

LRT for PRT both unknown


Select all non null fields

Question: I'm new to SQL. I have table with four columns containing values.
Example:
Id, country, adresse, dt
C1, LA, null, 2022-09-10
Null, Null,Null, 2022-09-11
Null, Null, Null, 2022-09-12
C2, null, null, 2022-10-01

I want to take all rows where id, country and adresse are not null in the same row. It means, I want to take row1, row4.
Query:
Select *
from tb1
where Id is not null and country is not null and adresse is not null

C1, LA, null, 2022-09-10
C2, null, null, 2022-10-01

It seems that my query doesn't return a row when value of id or country or adresse is null, which is not what I want to do.
Comment: Your query seems to do exactly what you want it to do. Please explain why this result is wrong.
Answer: As you explained in the description , you should be using or condition and not and condition.
select * from tb1
    where Id is not null or country is not null or adresse is not null

Assuming that you want to filter the rows that does not have all three values as null.

Select all non null fields


Swift method that is called after autolayout is finalized

Question: I have a method that draws pins by adding an ImageView on top of a slider when a button is pressed. Here is the code:
    var loopStartImageView : UIImageView = UIImageView()

    func addLoopDrawing(at time: CMTime, for loop: Int) {

        let imgHeight : CGFloat = 30
        let imgWidth: CGFloat = 30

        var pinImg : UIImage = UIImage(named: "pin2x")!

        let inset = slider.frame.origin.x
        let width = slider.bounds.width

        let xPos : CGFloat = CGFloat((Float(time.seconds) / slider.maximumValue)) * width + inset - (imgWidth / 2)
        var yPos : CGFloat = slider.frame.origin.y - (slider.frame.height / 2) - 3

        let imgV = UIImageView(frame: CGRect(x: xPos, y: yPos, width: imgWidth, height: imgHeight))
        imgV.image = pinImg

        loopStartImageView = imgV
        view.addSubview(loopStartImageView)
        view.sendSubviewToBack(loopStartImageView)
    }

The drawing is correct when I don't use autolayout to set the position of the slider, but once I do it shows up below the actual positioning.
This method is called in viewDidLoad. My guess is that for some reason the auto layout positioning is not set when viewDidLoad is called.
I was wondering if there is a method that is called once auto layout is fully adjusted?
//
This is what it should look like:

But this is how the view loads (even when calling the addLoopDrawing function inside the viewDidLayoutSubviews)
Comment: I think it would be easier to help if we could see what was your intended result. Could you include more details about this slider and/or what is being done with autolayout?
Comment: The images added in your edit are helpful here, thanks. Is there any reason that you can't do all of this with autolayout? Your results would probably be much more consistent that way. For example, you might create constraints in autolayout, connect them to the view controller with outlets, and then modify those constraints to reflect your desired pin position.
Comment: @MichaelFourre How would I go about adding the ImageViews  with the pins with auto layout constraints programmatically?
Comment: It seems as though the y-values of the slider incorrect when called in the viewDidLoad -- when I printed them, it said 558 in the viewDidLoad and 470 in the correct position
Answer:
I was wondering if there is a method that is called once auto layout is fully adjusted?

That would be viewDidLayoutSubviews. That is a very good time to do things that depend upon things having their correct frame, but beware: it can be called many times. The usual thing, therefore, is to implement it along with a Bool property to check that this is the first time.
On the other hand, it might be better not to ask an x-y question like this. The idea of an image view on top of a slider seems wrong. It might be better to describe what you are really trying to do.
Comment: I would like to echo that the premise here seems wrong. It sounds like OP may be going about this in a way that could cause more problems down the road.
Comment: Hey @matt - thanks for the answer. I edited my question with pictures to better describe what I'm trying to do


The difference between unbiased/biased estimator variance.

Question: The biased MLE of Normal distribution is:
$\hat{\sigma }_{MLE} = \frac{1}{N}\sum_{N}^{i=1}\left({x}_{i} - \hat{\mu }\right)^{2}$
And unbiased is:
$\hat{\sigma }_{unbiased} = \frac{1}{N-1}\sum_{N}^{i=1}\left({x}_{i} - \hat{\mu }\right)^{2}$
So Why the former is N and later is N-1?
Comment: Previously: • [Sample Standard Deviation vs. Population Standard Deviation](http://math.stackexchange.com/q/15098/856) • [Denominator to calculate standard deviation](http://math.stackexchange.com/q/28633/856) • [Intuitive Explanation of Bessel's Correction](http://math.stackexchange.com/q/61251/856) • [Calculating variance, how to determine when to use 1/n or 1/(n-1)?](http://math.stackexchange.com/q/243715/856)
Answer: If the elements of the sample are statistically independent, then ($\mu$ denotes the population mean and $\sigma^2$ the population variance):
\begin{align}
\mathbb{E}[\widehat{\sigma}_{\text{unbiased}}^2]
& = \mathbb E\left[ \frac 1{N-1} \sum_{i=1}^N \left(x_i - \frac 1N \sum_{j=1}^N x_j \right)^2 \right] \\
& = \frac 1{N-1} \sum_{i=1}^N \mathbb E\left[ x_i^2 - \frac 2N x_i \sum_{j=1}^N x_j + \frac{1}{N^2} \sum_{j=1}^N x_j \sum_{k=1}^N x_k \right] \\
& = \frac 1{N-1} \sum_{i=1}^N \left[ \frac{N-2}{N} \mathbb E[x_i^2] - \frac 2N \sum_{j \neq i}  \mathbb E[x_i x_j] + \frac{1}{N^2} \sum_{j=1}^N \sum_{k \neq j} \mathbb E[x_j x_k] +\frac{1}{N^2} \sum_{j=1}^N \mathbb E[x_j^2] \right] \\
& = \frac 1{N-1} \sum_{i=1}^N \left[ \frac{N-2}{N} (\sigma^2+\mu^2) - \frac 2N (N-1) \mu^2 + \frac{1}{N^2} N (N-1) \mu^2 + \frac {1}{N} (\sigma^2+\mu^2) \right] \\
& = \sigma^2.
\end{align}
Correspondingly,
\begin{align}
\mathbb{E}[\widehat{\sigma}_{\text{MLE}}^2]=\mathbb{E}\left[\frac{N-1}{N}\widehat{\sigma}_{\text{unbiased}}^2\right]=\frac{N-1}{N}\sigma^2<\sigma^2.
\end{align}
Therefore, the maximum likelihood estimator of the variance is biased downward. Source and more info: Wikipedia.
Comment: FYI Your answer is being used as reference in a Coursera course https://www.coursera.org/learn/competitive-data-science Cheers :)
Comment: @Hack-R Thanks for the heads-up, good to know. I took the opportunity to fix a small typo. :-)


Beginner. Having trouble getting NGINX to work.

Question: I'm diving into web development but I'm having troubles getting Nginx to work on my Ubuntu-OS computer. Firstly, localhost in my browser brings up an "Unable to Connect" page. I tried restarting Nginx and here's what I got:
Restarting nginx: nginx: [emerg] unknown directive "pass" in /etc/nginx/sites-enabled/default:62
nginx: configuration file /etc/nginx/nginx.conf test failed

I actually had it working yesterday where the page said "Welcome to Nginx" except the only problem then was that I couldn't get the phpinfo page to show up. I probably dwindled too much with the installation and configuration process. Any help would be appreciated.
Comment: You should post the relevant part of your nginx configuration.
Answer: unknown directive "pass" in /etc/nginx/sites-enabled/default:62

Your configuration is invalid, with the problem being on line 62 of that file. There is no pass directive -- you probably want proxy_pass or fastcgi_pass.


How to dynamically specify screens in React Navigation based on contents of redux store?

Question: My navigator is:
import { connect } from 'react-redux';
import { createDrawerNavigator } from 'react-navigation';

const screens = {
  Home: Homecreen,
};
if (this.props.userStatus !== 'active') {
  screens.Upgrade = UpgradeScreen;
}

const MainDrawer = createDrawerNavigator(screens);

const mapStateToProps = (state) => {
  return { userStatus: state.user.status };
};

export default connect(mapStateToProps)(MainDrawer);

I want to show the UpgradeScreen only if the user status is not active. In the code above, I get the error:
undefined is not an object (evaluating 'this.props.userStatus')

How do I fix this?
Comment: in the line `if (this.props.userStatus !== 'active')` what `this` are you referring to? that block doesn't seem to be a part of any method...
Comment: @IshitaSinha That's the problem. `this` just refers to the app. I don't how to to refer to a compponent in navigation.
Comment: You should wrap it in a component. Can you please check my answer and if you have further questions, please write me a comment. Thanks.
Answer: In order to have access to this.props.userStatus, you should have a component. Here's how you can do it:
import { connect } from 'react-redux';
import { createDrawerNavigator } from 'react-navigation';

const screens = {
  Home: Homecreen,
};

const MainDrawer = ({ userStatus }) => {
  if (userStatus !== 'active') {
    screens.Upgrade = UpgradeScreen;
  }

  const Navigator = createDrawerNavigator(screens);

  return <Navigator />
}

const mapStateToProps = (state) => {
  return { userStatus: state.user.status };
};

export default connect(mapStateToProps)(MainDrawer);

Comment: I am getting this error: `Warning: Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.
    in MainDrawer (created by Connect(MainDrawer))`
Comment: Oops. Fixed it.
Comment: My `HomeScreen` is actually is a stack of screens. This has caused navigation within the stacks to stop working.
Answer: As jordan pointed out, that solution works out. Here is my snippet.
const MyDrawerNavigator = createDrawerNavigator({
  Home: {
    screen: HomeScreen
  },
  Second: {
    screen: SecondScreen
  }
});

const MyApp = createAppContainer(MyDrawerNavigator);

const myCustomComp = props => {
  const username = useSelector(state => state.AuthReducer.username);
  const FirstCase = createAppContainer(MyDrawerNavigator);
  const SecondCase = createAppContainer(
    createDrawerNavigator({
      Home: {
        screen: HomeScreen
      }
    })
  );
  return username === "berkelmass" ? <FirstCase /> : <SecondCase />;
};

const mapStateToProps = state => ({
  username: state.AuthReducer.username
});

export default connect(mapStateToProps)(myCustomComp);


python dataframe, how do I perform % change given specific condition

Question: I have dataframe of time series and I want to take the % change between a value 3days prior and 1day prior to the current date. I have shown an example below
the dataframe is shown before
import pandas as pd
df = pd.DataFrame({'Date' : ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09'],
                   'income': [1849.04, 1857.62, 1872.34, 1885.52, 1890.9, 1888.77, 1865.09, 1845.04, 1851.96, 1872.18],

})

the expected answer, in this case, is as shown below in the table
value for 27/3/2014 is 0.015019 = 1885.52/1857.62-1
for 28/3/2020 is 0.009913 = 1890.9/1872.34-1
and so on. How do I get that?
Answer: Simple. Use .shift
df['%Change'] = df.income.shift(-3)/df.income.shift(-1)-1