Why is my answer wrong for this inequality $\frac{\left(1-x\right)}{x^2+x}<0$

Question: Good evening to everyone. So I have this inequality: $$\frac{\left(1-x\right)}{x^2+x} <0 $$ It becomes $$ \frac{\left(1-x\right)}{x^2+x} <0 \rightarrow \left(1-x\right)\left(x^2+x\right)<0 \rightarrow x^3-x>0 \rightarrow x\left(x^2-1\right)>0 $$ Therefore from the first $ x>0 $, from the second $ x_1 = 1 $ and $x_2=-1$ therefore $ x $ belongs to $(-\infty,-1)$ and $(1,\infty)$ therefore $x$ belongs to $(1,\infty)$. But on the answer sheet it shows that it's defined on $(-1,0)$ and $(1,\infty)$. Where I am wrong? Thanks for any response.
Comment: Since the comparison is with $0$, you should do a sign-change graph and see what happens to the numerator and denominator...
Comment: Multiplication with $(x^2+x)^2$ is fine.
Comment: @fleablood $\frac{a}{b}<0$ iff $ab<0$.
Comment: @abiessu thanks I think that I'll try that
Comment: You are wrong let me add a solution
Comment: You _cannot_ multiply by $x^2+x$ without assuming $x^2+x >0$ without changing the inequality.  You are approaching this in a most incorrect way!
Comment: I can only understand a *single* thing you did *anywhere* in this solution.  You start with $(1-x)/(x^2 - x) < 0 \implies (1-x)(x^2 - x) < 0$.  Why on earth would that be true?  Then you get $(1-x)(x^2 - x) < 0 \implies x^3 - x > 0$.  Why on earth would you assume that.  Then you concluded $x(x^2 - 1) > 0$.  This is the only thing I understand and agree with.  Then you conclude $x > 0$.  This is absolutely wrong but I understand why you said it.  Consider $(-5)(-4) > 0 \not \implies -5 > 0$.
Comment: @fleablood I started with $\frac{\left(1-x\right)}{x^2-x}<0$ if you multiply by $\left(x^2-x\right)^2 $ and then simplify you'll get $ \left(1-x\right)\left(x^2-x\right) $. So the first expression is good. Then the final result is $x-x^3<0$ if you change the sign it becomes the reverse(the exact expression you were asking for. With $ x>0 $ I know it's a mistake that I have to treat more carefully in the future.
Answer: Once you write this $\frac{1 - x}{x(1 + x)} < 0$ you will find that the critical point are at $x = \{-1, 0, 1\}$.  You can simply plug in $x = -2$ to find that:
$$
\frac{1 + 2}{4 - 2} = \frac{3}{2} > 0
$$
Therefore this expression is $> 0$ when $x < -1$, $< 0$ when $-1 < x < 0$,it's $>0$ when $0 < x < 1$ and it's $<0$ when $x > 1$.
Therefore this is true when:
$$
(-1, 0) \wedge (1, \infty)
$$
Comment:
Take a long hard look at my anser.  It's compact but it's concise if you take enough to look at it.  My answer relies on the fact that a sign change requires an "odd" factor (all of your factors are odd).  As soon as you establish the sign of any region you have established the sign of all regions!
A more "Rigorous" Way:
A more rigorous way is to show where each of the factors are positive or negative.  The following picture shows the three factors and their sign chart when $x = -1$, $x = 0$, and $x = 1$ (the three vertical lines).
\begin{align}
1-  x > 0 \rightarrow x < 1 \\
x > 0 \rightarrow x > 0\\
1 + x > 0 \rightarrow x > -1
\end{align}
This shows a sign chart where we have:
Answer: It seems to me that you are only considering two roots for the cubic polynomial. The polynomial has three roots, $-1,0,1$ and they are all simple root.
Hence the polynomials is positive on $(1,\infty)$. (it is positive as it goes to positive infinity).
The sign changes at the roots.
it is negative on $(0,1)$. positive on $(-1,0)$, negative on $(-\infty,-1)$.
Comment: What about when $x > 1$, clearly this inequality is negative???
Comment: I am working with $x(x^2-1)>0$ rather than the initial inequality (of which the opposite works)
Comment: I don't understand your comment of $x(x^2+2)^2$...it doesn't work because your inequality if wrong for the initial statement of $\frac{1-x}{x^2+x} < 0$ which is only true for $x\in (-1,0)\cup (1, \infty)$.
Comment: $$\frac{1-x}{x^2+x}<0$$
if and only if
$$\frac{1-x}{x^2+x}(x^2+x)^2<0$$
if and only if
$$(1-x)(x^2+x)<0$$
if and only if
$$x(x^2-1)>0$$
Comment: "Another" way to understand is $\frac{a}{b}<0$ iff $ab<0$.
Answer: $$f(x) = x(x^2-1)= x^3-x$$
$$f'(x)= 3x^2-1$$ then x get local extreme value at point x =  $\sqrt 3 /3   $or $-\sqrt 3 /3 $
And it is on the interval ($-\infty$,$-\sqrt 3 /3  $) or ($\sqrt 3 /3   $,$+\infty$) is increasing and the interval  ($-\sqrt 3 /3  $,$\sqrt 3 /3$) is decreasing.
$$f(-\sqrt 3 /3) \geq0$$
$$f(\sqrt 3 /3) \leq 0$$
So it can draw the $f(x)$'s diagram:

EDIT: your answer is wrong because x>0 is not necessary. For instance, x = -0.5, x<0, however $x^2-1 <0$ rather than bigger than 1. Therefore you can't assert x>0.
Answer: In inequality questions, first you need to make all the coefficients of $x$ positive.
We can write it as
$$\frac{x-1}{x(x+1)}>0$$
Now , multiply both sides by $(x(x+1))^2$ which is always greater than $0$.
Hence we are left with this
$$x(x-1)(x+1)>0$$
Solving this critical points are at $x=-1,0,1$
Plot a number line mark these points. Now on the extreme right hand side interval mark $+$ , and then going fro right to left.. mark alternating $-$ then $+$ .. and so on..
Now see the $+$ intervals on the number line which is marked in the interval
$$ x \in (-1,0) \cup (1,\infty)$$
Answer: Your attempt is ok up to $x(x^2-1)>0.$ The next sentence is unintelligible ("from the first $x>0$".  First what? And what are $x_1, x_2$?).
Observe that $x(x^2-1)>0\iff x^3>x $ $\iff [(x>0\land x^2>1)\lor (x<0\land x^2<1)\lor (x=0\land PigsCanFly)]$ $\iff (x>1\lor -1<x<0).$
And if you  wrote any 1-way implications, you now have to now check whether $(x>1\lor -1<x<0)\implies (1-x)/(x^2+x)<0.$ You can avoid the need for this check by writing  $$(1-x)/(x^2+x)<0\iff ((1-x)(x^2+x)<0 \iff x^3>x\iff x\in \{-1,0\}\cup \{1,\infty)$$ and with the additional steps, between " $x^3>x$" and the last formula, preceded and followed  by valid " $\iff$ ".


Colocar vídeo do Youtube como background de site

Question: Quero colocar um vídeo de background em uma tela de espera. Tem como fazer isso puxando um vídeo do youtube sem mostrar os botões padrões e que ele inicie automaticamente?
O Jquery que tenho para colocar o vídeo que está no meu host.
$('body').bg({
position:"fixed",
zIndex:-1,
mp4:'meuvideo.mp4',
ogv:'meuvideo.ogv',
webm:'meuvideo.webm',
poster:'meuvideo.jpg',
opacity:0.5
});

Aqui eu puxo o vídeo direto do meu servidor, e do youtube?
Comment: Mesmo com background não sei se dá, mas se não fizer diferença pode tentar assim: https://jsfiddle.net/ks8hu650/12/
Answer: Felipe, boa tarde.
É possível colocar um vídeo do youtube como background usando um link modificado do próprio youtube. Este link contém informações adicionais tanto em pathInfo quanto em parameters
Utilizando um iFrame, como o usuário @Miguel comentou, é possível deixar o vídeo como um background mesmo:

Note que é preciso alterar o IDdo link postado acima com o ID correspondente do vídeo.
Sendo que:

o parametro autoplay=1 significa que o vídeo iniciará automaticamente.
o parametro controls=0 significa que não haverá opções de controle, tais como play, volume, config, tela cheia, legendas etc.
o parametro showinfo=0 significa que o player não mostrará o nome do vídeo
o parametro autohide=1 significa que a barra de progresso do vídeo ficará invisível.

Você pode ler informações aqui


Room - Compare lists in Entity

Question: I have a problem with Room.
I have an Entity:
<code>@Entity(tableName = "Entity")
data class Entity(val recipients: List<ID>?) {
    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true) var id: Long = 0
}
</code>
As you can see it holds List of ID's (typealias ID = Long)
And so, I made TypeConverter:
<code>@TypeConverter
fun getListOfLongs(data: String?): List<ID> {
    if (data == null) {
        return Collections.emptyList()
    }
    val listType = object : TypeToken<List<Long>>() {}.type

    return gson.fromJson(data, listType)
}

@TypeConverter
fun convertListToString(ids: List<ID>): String = gson.toJson(ids)
</code>
But I have a problem, I can't make right Query for this list:
<code>@Query("select count(*) from Message where recipients in (:recipients)")
fun count(recipients: List<ID>?): Int
</code>
As you see, I need to compare two lists (list in entity and list from method) and get all entities which contains Id's from method's list, but this Query returns always 0. I read that with TypeConverter's lists may be problems, but I can't find any solution.
Answer: Solve it with @RawQuery:
<code>" WHERE recipients LIKE ${recipients.joinToString(",", "\"", "\"")}"
</code>
end editing TypeConvertor:
<code>@TypeConverter
fun getListOfLongs(data: String?): List<Long> {
    if (data == null) {
        return Collections.emptyList()
    }
    val listType = object : TypeToken<List<Long>>() {}.type

    return gson.fromJson("[$data]", listType)
}

@TypeConverter
fun convertListToString(ids: List<Long>?): String? {
    if (ids == null) return null
    var idsString = gson.toJson(ids)
    idsString = idsString.replace("]", "")
    idsString = idsString.replace("[", "")
    return idsString
}
</code>

Room - Compare lists in Entity


easy "show this is a subset" question

Question: I am having a hard time showing this simple relation. Here, all the letters below are in $\mathbb{N} \cup \{0\}$.
$$A = \{(a,b) : a + 2b \leq n+2\}$$
$$B = \{(a,c+1) : a + 2c \leq n\}$$
How to show that $B \subset A$?
This is something I got from a sum over the above indices. I wanted a lower bound on the sum (which is where $B$ came in). Obviously I set $b = c+1$ in $A$ to get $B$ but how to show that it's a subset?
Thanks
Answer: I take it you mean for $n$ to be some fixed positive integer.
To show $B \subset A$, you want to show that any ordered pair of $B$ can also be found in $A$. To that end, let $(a, c+1) \in B$. That is, $a + 2c \leq n$.
We want to know whether $(a,c+1) \in A$. In other words, is $a + 2(c+1) \leq n + 2$? Just follow your nose:
$$
\begin{align*}
a + 2(c+1) &= [a + 2c] + 2\\
&\leq [n] + 2,
\end{align*}
$$
where the last line comes from our assumption about $(a,c+1) \in B$ (the brackets are just for emphasis).
Answer: If $(a,c+1)$ is an element of $B$ and you set $b=c+1$, then $a+2b=a+2(c+1)=(a+2c)+2\leq n+2$.
Comment: Yeah that's what i did, but is it obvious from this that it's a subset? Am I just being stupid?
Comment: Then you have shown that $(a,c+1)$ is an element of $A$ since it satisfies the required condition. That's all you need to show $B$ is a subset.

easy "show this is a subset" question


Preencher modal do Bootstrap com valor de uma div

Question: Tenho uma tabela na qual o valor carregador dentro dela através do PHP, precisa estar no value de alguns inputs que estão em uma janela modal do boostrap. Já tentei várias soluções, porém, naõ funciona.
Quando eu clico na linha da tabela, ela carrega o modal, mas o campo fica vazio. Pretendo fazer assim, utilizando a linha da tabela para carregar o modal, e não um button para carregar o modal.
segue o código:
Tabela HTML

   <?php echo $linha['PLACA'] ?>
    <?php echo $linha['NOME'] ?>
    <?php echo $linha['ANO'] ?>
    <?php echo $linha['CPF'] ?>

Janela modal:

Alterar dados do veículo

                    <form class="modal_novo_item">

                        <input type="text" placeholder="Nome" id="nome" name="nome">

                        <input type="text" placeholder="Ano" id="ano" name="ano">

                        <input type="text" placeholder="Placa" id="placa"  name="placa">

                        <select name="proprietario">
                        <?php listar_editar( $link ); ?>
                        </select>

              </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar janela</button>
                <button type="button" class="btn btn-primary">Alterar</button>
                <button type="button" class="btn btn-danger">Excluir</button>

A janela é aberta, porém não funciona. Em outro projeto já tinah feito isso, com outro código jQuery, porém, o que carregava o modal era um button. Tentei adequar ao meu código, mas nada.
Grato desde já.
Jquery que deveria estar funcionando:

Comment: Qual o html da tabela?
Comment: E versão do bootstrap?
Comment: O primeiro item é a linha tabela, na qual eu quero clicar, e abrir o modal. Quer ver a tabela inteira?
Comment: Bootstrap 4.0.0
Comment: seria bom porque aqui funcionou normal.
Comment: Deve ter outra coisa dando conflito
Comment: Com esses códigos que enviei? não creio
Comment: Rapaz, você pode editar a pergunta colocando as bibliotecas usadas?
Answer:

$(document).ready(function(){
  $("tr[data-toggle='modal']").click(function(){

    //valores das células da linha clicada
    var a = $(this).text();

    //split de a porque cada valor está separado por um \n (nova linha)
    var n = a.split('\n');

    //atribuindo os valores aos devidos inputs
    $("#placa").val(n[1]);
    $("#nome").val(n[2]);
    $("#ano").val(n[3]);
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.css">

    ASD 123
    Igor
    2018
    CPF

   QWE 456
    dvd
    19eAntigamente
    CPF 2

   AAA 001
    Leo
    2021
    CPF 3

Alterar dados do veículo

                    <form class="modal_novo_item">

                        <input type="text" placeholder="Nome" id="nome" name="nome">

                        <input type="text" placeholder="Ano" id="ano" name="ano">

                        <input type="text" placeholder="Placa" id="placa"  name="placa">

                        <select name="proprietario">
                        <?php listar_editar( $link ); ?>
                        </select>

              </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar janela</button>
                <button type="button" class="btn btn-primary">Alterar</button>
                <button type="button" class="btn btn-danger">Excluir</button>

Comment: Ainda não funciona aqui
Comment: to usando a versão 3.1 do jquery pra todas as outras funções, e a 4.0.0 pro bootstrap
Comment: @Igor Então, veja com versão 3.1 do jquery e boostrap 4.0.0 em http://kithomepage.com/sos/preencher-modal.html Inclusive a resposta foi editada para essas bibliotecas.
Comment: @Igor alguma coisa vc está fazendo errado ou alguma outra biblioteca está conflitando.
Comment: Funciona certim
Comment: Bom, com os arquivos no diretório funciona. Mas eu preciso usar apenas as CDN deles. Poderia por favor me enviar os links das CDN do BS e do Jquery usados aí? quero me certificar que peguei a mesma que tu vai usar e funcionar
Comment: são as que estão na resposta
Answer: Você pode pegar o texto da primeira td e jogar no campo da modal com o evento .click:
$(document).ready(function (){
   $("[data-toggle='modal']").click(function(){
      var valorDaDiv = $("td:first", this).text();
      $("#placa").val(valorDaDiv);
   });
});

Exemplo:

$(document).ready(function (){
   $("[data-toggle='modal']").click(function(){
      var valorDaDiv = $("td:first", this).text();
      $("#placa").val(valorDaDiv);
   });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

   123
    nome
    ano
    cpf

   456
    nome
    ano
    cpf

Alterar dados do veículo

                    <form class="modal_novo_item">

                        <input type="text" placeholder="Nome" id="nome" name="nome">

                        <input type="text" placeholder="Ano" id="ano" name="ano">

                        <input type="text" placeholder="Placa" id="placa"  name="placa">

                        <select name="proprietario">
                        <?php listar_editar( $link ); ?>
                        </select>

              </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar janela</button>
                <button type="button" class="btn btn-primary">Alterar</button>
                <button type="button" class="btn btn-danger">Excluir</button>

Se quiser colocar cada texto nos devidos campos da modal, use .eq(), onde .eq(0) é o texto da primeira td e assim sucessivamente:

$(document).ready(function (){
   $("tr[data-toggle='modal']").click(function(){
      var placa = $("td:eq(0)", this).text();
      var ano = $("td:eq(1)", this).text();
      var nome = $("td:eq(2)", this).text();
      $("#placa").val(placa);
      $("#nome").val(ano);
      $("#ano").val(nome);
   });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

   123
    fulano
    1997
    cpf

   456
    ciclano
    2000
    cpf

Alterar dados do veículo

                    <form class="modal_novo_item">

                        <input type="text" placeholder="Nome" id="nome" name="nome">

                        <input type="text" placeholder="Ano" id="ano" name="ano">

                        <input type="text" placeholder="Placa" id="placa"  name="placa">

                        <select name="proprietario">
                        <?php listar_editar( $link ); ?>
                        </select>

              </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar janela</button>
                <button type="button" class="btn btn-primary">Alterar</button>
                <button type="button" class="btn btn-danger">Excluir</button>

Comment: Continua não funcionando. Deve ser  por causa da listagem em Php, sobre o que tu falou de repetir o id. No caso o 'data-toggle="modal"' é repetido sempre, como se fosse o identificador
Comment: Veja que tirei os ids.... não precisa deles.
Comment: esse popper.min.js não é necessário!
Comment: Não é não... eh que o meu link pro bootstrap puro não tah mais funcionando.
Comment: @LeoCaracciolo Dá uma olhada nisso... acho que vc mata fácil: https://pt.stackoverflow.com/q/295309/8063
Comment: É vdd, com essa biblioteca da sua resposta tem que colocar ele. Fiz teste e comprovei
Comment: @LeoCaracciolo È, quando tem algumas funcionalidades tem que ter o popper
Comment: Mas na minha resposta não usei ele e funciona bem, outras bibliotecas
Comment: @LeoCaracciolo Eu tenho um link pro CDN mas a porcarria não ta´funcionando, aí boto essas aí mermo


issue with scaling EC2 Volume (Make it smaller) in EC2

Question: I'm trying to resize the size of one of my servers,
currently it's 850GB and i would like to scale it down to 100GB.
scaling them up isn't a problem, i just follow the basic scheme of

shutting down the server
detaching the volume
Creating snapshot
Creating new volume and attaching it to the same zone.

the problem is that i cannot create a smaller volume based on that snapshot, anyone has any idea on how to do it ?
the OS is ubuntu (if it matters)
Answer: Assuming this isn't a boot volume, your best bet is probably just to attach a new EBS volume, copy everything over, then detach the old larger volume.
Comment: Actually it is, that's the issue.


Categorical variable as predictor/regressor in ARIMA

Question: I apply ARIMA and I want to consider weekly seasonality as a dayOfWeek predictor (1, 2, ..., 7).
How do I deal with dayOfWeek as a categorical variable?
Answer: Weekly seasonality:
There are ~ 52,1429 weeks per year. This is not an integer number. ARIMA is only designed for seasonalities with integer numbers.

Daily seasonality:
Every year has 365,25 days. Every month has 28-31 days (or an other number cultural regions which depend on the moon calendar and not the Gregorian calender). Every weeks has 7 days. You will likely observe multiple seasonalities. Some pattern recur every monday, some pattern recur always at the beginning of the month and some pattern recur always at the beginning of the year. ARIMA is not designed for multiple seasonalities.

A general advice about categorical regressors:
Take on category, i.e. day as 0-level and the other ones as 1-6. You "save" on independent variable and avoid multicollinearity.

Solution:
ARIMA is not designed for multiple seasonalities and uneven seasonalities. You can try another model like tbats instead.

Bibliography:
The original tbats model.
De Livera, A., Hyndman, R., Snyder, R. (2012). Forecasting Time Series with Complex seasonality patterns using exponential smoothing.  Journal of the American Statistical Association. p. 1513-1527
You can also have a closer look at the question with the tags tbats or multipleseasonalities
Comment: Why are you downvoting me?
Answer: I'm interpreting this question as "how do I go about coding my variables" or "how do I make categorical predictors into quantitative ones?"
One way to do it is to make 6 predictors $X_{i,1}, X_{i,2}, \ldots, X_{i,6}$ where

$X_{i,1}$ is set to one if observation $i$ falls on a Monday
$X_{i,2}$ is set to one if observation $i$ falls on a Tuesday
$X_{i,3}$ is set to one if observation $i$ falls on a Wednesday
$X_{i,4}$ is set to one if observation $i$ falls on a Thursday
$X_{i,5}$ is set to one if observation $i$ falls on a Friday
$X_{i,6}$ is set to one if observation $i$ falls on a Saturday

For any row $i$, at most one of these new columns will have a $1$. And sometimes, on Sundays, you won't have any $1$s. If you have a categorical variable with $p$ levels, you generally need $p-1$ dummy variable predictors.
R has model.matrix() which is pretty cool:
yt <- rnorm(21)
x.cat <- as.factor(rep(c("sunday", "monday", "tuesday", "wednedsay", "thursday", "friday", "saturday"),3))
x.quant <- model.matrix(~x.cat)
x.quant <- x.quant[,-1] #remove intercept column
mod <- arima(yt, order=c(1,1,0), xreg=x.quant)

Eh, if you really want your baseline to be Sunday, like in my example, replace the second line with x.quant <- model.matrix(~., data = as.data.frame(x.cat)).
Answer: You can plug the weekly seasonality dummy and it'll work fine. The question is whether it's the best way to deal with seasonality. This may work for things like Web site load, where the loads may be spiking on weekends and the customer behavior is persistent.


Order of middle group in short exact sequence

Question: If we have a short exacts sequence of abelian group with $A$ and $C$ finite, $0\to A\to B\to C$, is it true that $|B|=|A|\cdot |C|$ even if it does not split?
Answer: Yes, it's simply Lagrange's theorem. By definition of short exact sequence, $C\cong B/\operatorname{im}(f)$, where $f\colon A\to B$ is the given map. Since $f$ is injective, $\lvert\operatorname{im}(f)\rvert=|A|$.


How to uncomment multiple lines in a file using Ansible playbook

Question: I want to uncomment multiple lines in a file using Ansible playbook.
Let's say this as a content which I need to comment out.

if [xxxx]; then
    echo xxxxxxxx
    exit;
fi
These 4 lines I need to comment out using Ansible playbook.
PLease help me how I can comment out.
Comment: Please show some efforts you've made so far...
Answer: An option would be to use blockinfile if you control the content of the file. Set the BEGIN and END markers in the file. Then replace the block as you wish.
If the content of the file is not under your control you might want to try and set the markers with lineinfile (use line, insertbefore, insertafter, firstmatch ...)
The best practice, however, is to use the module template.

Example of blockinfile
Given the file below for testing
shell> cat /tmp/test.txt
line1
line2

if [yyy]; then echo yyyyyyyyy exit;
  cmd
  cmd
fi

# if [xxxx]; then echo xxxxxxxx exit;
#   cmd
#   cmd
# fi

lineX

the goal is to uncomment the if statement. Create the markers first. Declare the variables
  marker: marker_1
  path: /tmp/test.txt
  regex1: '# if \[xxxx\]; then echo xxxxxxxx exit;'
  replace1: '# if [xxxx]; then echo xxxxxxxx exit;'
  regex2: '# fi'
  replace2: '# fi'

Test if the BEGIN marker exists. If it does not exist, create the markers in the block
    - name: "Check begin marker {{ marker }}"
      ansible.builtin.command:
        cmd: >
          grep -q '# BEGIN ANSIBLE MANAGED BLOCK {{ marker }}' {{ path }}
      register: checkmarker
      ignore_errors: true
      changed_when: false

    - block:
        - name: "Create begin marker {{ marker }}"
          ansible.builtin.replace:
            path: '{{ path }}'
            regexp: '{{ regex1 }}'
            replace: |-
              {{ '#' }} BEGIN ANSIBLE MANAGED BLOCK {{ marker }}
              {{ replace1 }}
        - name: "Create end marker {{ marker }}"
          ansible.builtin.replace:
            path: '{{ path }}'
            regexp: '({{ regex1 }}[\s\S]*?){{ regex2 }}'
            replace: |-
              \g<1>{{ replace2 }}
              {{ '#' }} END ANSIBLE MANAGED BLOCK {{ marker }}
      when: checkmarker.rc != 0

gives
shell> cat /tmp/test.txt
line1
line2

if [yyy]; then echo yyyyyyyyy exit;
  cmd
  cmd
fi

# BEGIN ANSIBLE MANAGED BLOCK marker_1
# if [xxxx]; then echo xxxxxxxx exit;
#   cmd
#   cmd
# fi
# END ANSIBLE MANAGED BLOCK marker_1

lineX

Declare the variables
  test_content: "{{ (test_out['content']|b64decode).splitlines() }}"

  marker_1_begin: "{{ test_content|select('regex', '^.*BEGIN.*marker_1.*$')|first }}"
  marker_1_end: "{{ test_content|select('regex', '^.*END.*marker_1.*$')|first }}"
  block_1_begin_index: "{{ test_content.index(marker_1_begin) + 1 }}"
  block_1_end_index: "{{ test_content.index(marker_1_end) }}"
  block_1: "{{ test_content[block_1_begin_index|int:block_1_end_index|int] }}"
  block_1_update: "{{ block_1|
                      map('regex_replace', block_1_regex, block_1_replace)|
                      join('\n') }}"
  block_1_regex: '^#\s(.*)$'
  block_1_replace: '\1'

Read and update the block
    - name: "Read file {{ path }}"
      slurp:
        src: "{{ path }}"
      register: test_out

gives
  marker_1_begin: '# BEGIN ANSIBLE MANAGED BLOCK marker_1'

  block_1_begin_index: '9'

  marker_1_end: '# END ANSIBLE MANAGED BLOCK marker_1'

  block_1_end_index: '13'

  block_1:
  - '# if [xxxx]; then echo xxxxxxxx exit;'
  - '#   cmd'
  - '#   cmd'
  - '# fi'

  block_1_update: |-
    if [xxxx]; then echo xxxxxxxx exit;
      cmd
      cmd
    fi

Update the block
    - name: "Update block {{ marker }} in {{ path }}"
      ansible.builtin.blockinfile:
        path: "{{ path }}"
        marker: '# {mark} ANSIBLE MANAGED BLOCK {{ marker }}'
        block: |
          {{ block_1_update }}

gives
shell> cat /tmp/test.txt
line1
line2

if [yyy]; then echo yyyyyyyyy exit;
  cmd
  cmd
fi

# BEGIN ANSIBLE MANAGED BLOCK marker_1
if [xxxx]; then echo xxxxxxxx exit;
  cmd
  cmd
fi
# END ANSIBLE MANAGED BLOCK marker_1

lineX

Example of a complete playbook for testing
- hosts: localhost

  vars:

    marker: marker_1
    path: /tmp/test.txt
    regex1: '# if \[xxxx\]; then echo xxxxxxxx exit;'
    replace1: '# if [xxxx]; then echo xxxxxxxx exit;'
    regex2: '# fi'
    replace2: '# fi'

    test_content: "{{ (test_out['content']|b64decode).splitlines() }}"

    marker_1_begin: "{{ test_content|select('regex', '^.*BEGIN.*marker_1.*$')|first }}"
    marker_1_end: "{{ test_content|select('regex', '^.*END.*marker_1.*$')|first }}"
    block_1_begin_index: "{{ test_content.index(marker_1_begin) + 1 }}"
    block_1_end_index: "{{ test_content.index(marker_1_end) }}"
    block_1: "{{ test_content[block_1_begin_index|int:block_1_end_index|int] }}"
    block_1_update: "{{ block_1|
                        map('regex_replace', block_1_regex, block_1_replace)|
                        join('\n') }}"
    block_1_regex: '^#\s(.*)$'
    block_1_replace: '\1'

  tasks:

    - name: "Check begin marker {{ marker }}"
      ansible.builtin.command:
        cmd: >
          grep -q '# BEGIN ANSIBLE MANAGED BLOCK {{ marker }}' {{ path }}
      register: checkmarker
      ignore_errors: true
      changed_when: false

    - block:
        - name: "Create begin marker {{ marker }}"
          ansible.builtin.replace:
            path: '{{ path }}'
            regexp: '{{ regex1 }}'
            replace: |-
              {{ '#' }} BEGIN ANSIBLE MANAGED BLOCK {{ marker }}
              {{ replace1 }}
        - name: "Create end marker {{ marker }}"
          ansible.builtin.replace:
            path: '{{ path }}'
            regexp: '({{ regex1 }}[\s\S]*?){{ regex2 }}'
            replace: |-
              \g<1>{{ replace2 }}
              {{ '#' }} END ANSIBLE MANAGED BLOCK {{ marker }}
      when: checkmarker.rc != 0

    - name: "Read file {{ path }}"
      slurp:
        src: "{{ path }}"
      register: test_out

    - debug:
        var: test_content
    - debug:
        var: marker_1_begin
    - debug:
        var: block_1_begin_index
    - debug:
        var: marker_1_end
    - debug:
        var: block_1_end_index
    - debug:
        var: block_1
    - debug:
        var: block_1_update

    - name: "Update block {{ marker }} in {{ path }}"
      ansible.builtin.blockinfile:
        path: "{{ path }}"
        marker: '# {mark} ANSIBLE MANAGED BLOCK {{ marker }}'
        block: |
          {{ block_1_update }}

See:

Example of blockinfile markers
files-markers.yml


Adding Labels or Edit boxes as actions of buttons in C#

Question: "I am using Visual Basic C# 2010 and I want to create a form for shape drawing with three shapes possible namely line,rectangle, ellipse. Initially I display only three buttons with text as 'Line' , 'Rectangle', 'Ellipse'. According to which button i click on, I want labels and edit boxes to appear asking for properties of the shape to draw. For example, if i click on line, I want the label asking for length to appear. And if i have clicked on rectangle, I want the label asking for length and breadth to appear only. So how can i implement these labels as actions of specific button?
"
I have written this code and my previous problem of how to ask for user input differently for different button clicks is resolved.Thanks to repliers!
Now in this code only thing remaining is to create an area where the shape would be drawn.I cant understand how to do it.Can anyone help?
Why the shape is not getting drawn? Please note that i want to draw the shape on original form and not the pop up form.
please help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShapeDrawing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public abstract class SHAPE
        {
            public Pen MyPen = new Pen(Color.Brown, 3.5F);
            public abstract void getparameters();
            public abstract void drawshape(Form1 e);
        }

        public class LINE : SHAPE
        {
            float x1,x2,y1,y2;
            public override void getparameters()
            {
                PopForLine Popup = new PopForLine();
                DialogResult dialogresult = Popup.ShowDialog();
                if (dialogresult==DialogResult.OK)
                {
                    try
                    {
                        this.x1 = (float)Convert.ToDouble(Popup.Point1XText.Text);
                        this.y1 = (float)Convert.ToDouble(Popup.Point1YText.Text);
                        this.x2 = (float)Convert.ToDouble(Popup.Point2XText.Text);
                        this.y2 = (float)Convert.ToDouble(Popup.Point2YText.Text);
                    }
                    catch(Exception e)
                    {
                        x1=x2=y1=y2=0;
                    }
                }
                Popup.Dispose();
            }
            public override void drawshape(Form1 e)
            {
                Graphics formGraphics=e.CreateGraphics();
                formGraphics.DrawLine(MyPen,x1,y1,x2,y2);
                formGraphics.Dispose();
            }
        }

        class RECTANGLE : SHAPE
        {
            float Length, Breadth;
            public override void getparameters()
            {
                PopForRect Popup = new PopForRect();
                DialogResult dialogresult = Popup.ShowDialog();
                if (dialogresult == DialogResult.OK)
                {
                    try
                    {
                        Length = (float)Convert.ToDouble(Popup.LengthText.Text);
                        Breadth =(float) Convert.ToDouble(Popup.BreadthText.Text);
                    }
                    catch (Exception e)
                    {
                        Length = 0;
                        Breadth = 0;
                    }
                }
                Popup.Dispose();
            }
             public override void drawshape(Form1 e)
             {
                Graphics formGraphics = e.CreateGraphics();
                formGraphics.DrawRectangle(MyPen, 0, 0, Length,Breadth);
                formGraphics.Dispose();
             }
        }

        class ELLIPSE : SHAPE
        {
            float radius1, radius2;
            public override void getparameters()
            {
            PopForEllipse Popup = new PopForEllipse();
            DialogResult dialogresult = Popup.ShowDialog();
            if (dialogresult == DialogResult.OK)
            {
                try
                {
                    this.radius1 = (float)Convert.ToDouble(Popup.SRadText.Text);
                    this.radius2 = (float)Convert.ToDouble(Popup.LRadText.Text);
                }
                catch (Exception e)
                {
                    radius1 = 0;
                    radius2 = 0;
                }
            }
            Popup.Dispose();
        }
        public override void drawshape(Form1 e)
        {
            Graphics formGraphics = e.CreateGraphics();
            formGraphics.DrawEllipse(MyPen, 0, 0, radius1, radius2);
            formGraphics.Dispose();
        }
    }

    private void LineButton_Click(object sender, EventArgs e)
    {
        LINE MyLine = new LINE();
        MyLine.getparameters();
        MyLine.drawshape(this);
        MyLine.MyPen.Dispose();
    }

    private void EllipseButton_Click(object sender, EventArgs e)
    {
        ELLIPSE MyEllipse = new ELLIPSE();
        MyEllipse.getparameters();
        MyEllipse.drawshape(this);
        MyEllipse.MyPen.Dispose();
    }

        private void RectButton_Click(object sender, EventArgs e)
        {
            RECTANGLE MyRectangle = new RECTANGLE();
            MyRectangle.getparameters();
            MyRectangle.drawshape(this);
            MyRectangle.MyPen.Dispose();
        }
    }

}

Comment: You can use popup windows (forms) to show the labels and textboxes for input when the buttons are clicked. Or you can use panels that you have hidden, and show them when the user clicks one of the buttons.
Comment: You can manage the label text as you click "those 3 buttons".
Comment: @Wolf5 Thanks! I found a related link: http://www.howtosolutions.net/2013/01/creating-a-new-popup-window-in-winform-using-csharp/#.VZD8N_mqqko
Answer: Add a label and on the ButtonClick Event of each button you can set Text property of the label
If circle is clicked
labelName.Text = "Enter the radius";
If Square is clicked
labelName.Text = "Enter the side lenght";
this would help your requirement
Comment: No but then for an ellipse or a rectangle? I need two lengths there.
Answer: If this is WPf application and you are using MVVM then on button click you can notify your text property with appropriate text.
Answer: I finally got this code working and got the job done exactly the way i wanted.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShapeDrawing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public abstract class SHAPE
        {
            public Pen MyPen = new Pen(Color.Brown, 3.5F);
            public abstract void getparameters();
            public abstract void drawshape(Form1 e);
            public abstract void description(Form1 e);
            public void enabling(Form1 e)
            {
                e.RetryButton.Enabled = true;
                e.ExitButton.Enabled = true;
            }
        }

        public class LINE : SHAPE
        {
            float x1,x2,y1,y2;
            public override void getparameters()
            {
                PopForLine Popup = new PopForLine();
                DialogResult dialogresult = Popup.ShowDialog();
                if (dialogresult==DialogResult.OK)
                {
                    try
                    {
                        this.x1 = (float)Convert.ToDouble(Popup.Point1XText.Text);
                        this.y1 = (float)Convert.ToDouble(Popup.Point1YText.Text);
                        this.x2 = (float)Convert.ToDouble(Popup.Point2XText.Text);
                        this.y2 = (float)Convert.ToDouble(Popup.Point2YText.Text);
                    }
                    catch(Exception e)
                    {
                        x1=x2=y1=y2=0;
                    }
                }
                Popup.Dispose();
            }
            public override void drawshape(Form1 e)
            {
                Graphics formGraphics = e.ShapeSpace.CreateGraphics();
                formGraphics.DrawLine(MyPen,x1,y1,x2,y2);
                formGraphics.Dispose();
            }

            public override void description(Form1 e)
            {
                double linelength;
                linelength = Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
                e.Description.Text = "This is a line of length " + Convert.ToString(linelength) + " starting from (" + Convert.ToString(x1) + "," + Convert.ToString(y1) + ") to (" + Convert.ToString(x2) + " , " + Convert.ToString(y2)+") .\n";
            }
        }

        class RECTANGLE : SHAPE
        {
            float Length, Breadth;
            public override void getparameters()
            {
                PopForRect Popup = new PopForRect();
                DialogResult dialogresult = Popup.ShowDialog();
                if (dialogresult == DialogResult.OK)
                {
                    try
                    {
                        Length = (float)Convert.ToDouble(Popup.LengthText.Text);
                        Breadth =(float) Convert.ToDouble(Popup.BreadthText.Text);
                    }
                    catch (Exception e)
                    {
                        Length = 0;
                        Breadth = 0;
                    }
                }
                Popup.Dispose();
            }
            public override void drawshape(Form1 e)
            {
                Graphics formGraphics = e.ShapeSpace.CreateGraphics();
                formGraphics.DrawRectangle(MyPen, 0, 0, Length,Breadth);
                formGraphics.Dispose();
            }

            public override void description(Form1 e)
            {
                e.Description.Text = "This is a rectangle of width= " + Convert.ToString(Length) + " and height= " + Convert.ToString(Breadth) + " .\n";
            }
        }

        class ELLIPSE : SHAPE
        {
            float radius1, radius2;
            public override void getparameters()
            {
                PopForEllipse Popup = new PopForEllipse();
                DialogResult dialogresult = Popup.ShowDialog();
                if (dialogresult == DialogResult.OK)
                {
                    try
                    {
                        this.radius1 = (float)Convert.ToDouble(Popup.SRadText.Text);
                        this.radius2 = (float)Convert.ToDouble(Popup.LRadText.Text);
                    }
                    catch (Exception e)
                    {
                        radius1 = 0;
                        radius2 = 0;
                    }
                }
                Popup.Dispose();
            }
            public override void drawshape(Form1 e)
            {
                Graphics formGraphics = e.ShapeSpace.CreateGraphics();
                formGraphics.DrawEllipse(MyPen, 0, 0, radius1, radius2);
                formGraphics.Dispose();
            }

            public override void description(Form1 e)
            {
                e.Description.Text = "This is an ellipse of width= " + Convert.ToString(radius2) + " and height= " + Convert.ToString(radius1) + " .\n";
            }
        }

        private void LineButton_Click(object sender, EventArgs e)
        {
            LINE MyLine = new LINE();
            MyLine.getparameters();
            MyLine.drawshape(this);
            MyLine.MyPen.Dispose();
            MyLine.description(this);
            MyLine.enabling(this);
        }

        private void EllipseButton_Click(object sender, EventArgs e)
        {
            ELLIPSE MyEllipse = new ELLIPSE();
            MyEllipse.getparameters();
            MyEllipse.drawshape(this);
            MyEllipse.MyPen.Dispose();
            MyEllipse.description(this);
            MyEllipse.enabling(this);
        }

        private void RectButton_Click(object sender, EventArgs e)
        {
            RECTANGLE MyRectangle = new RECTANGLE();
            MyRectangle.getparameters();
            MyRectangle.drawshape(this);
            MyRectangle.MyPen.Dispose();
            MyRectangle.description(this);
            MyRectangle.enabling(this);
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void RetryButton_Click(object sender, EventArgs e)
        {
            Description.Text = " ";
            ShapeSpace.Image = null;
        }
    }

}


Como posso mostrar o segundo/próximo valor de um vetor Int? Usando a linguagem Java

Question: Basicamente é um exercício que faz um cálculo pra saber qual charrete vai chegar primeiro dadas as informações que o usuário fornecer (de acordo com a premissa do exercício).
Estou começando agora com Java, estava usando a Linguagem C antes, e lá quando queria mostrar o próximo valor de um vetor eu fazia algo como: (vetor[contador]+1) para mostrar o vetor, na posição contador +1. Aqui no Java isso não está funcionando, e gostaria de saber como fazer isso.
Código abaixo:
package exercicio5;

import java.util.Scanner;

public class Exercicio5 {

    public static void main(String[] args) {
      Scanner ler = new Scanner(System.in);
     final int N = 2;
        int aux = 0, cont = 0, numCha[];
        double  distancia[], velocidade[], metros[], tempo[];
        numCha = new int[N];
        velocidade = new double[N];
        distancia = new double[N];
        metros = new double[N];
        tempo = new double[N];
      while (aux < N){

          for (int i = 0; i < N; i++){

        System.out.println("Digite o número da charrete [1-99]: ");
       numCha[cont] = ler.nextInt();
               while ((numCha[cont] < 1) || (numCha[cont] > 99)){
                   System.out.println("Valor Inválido!\nUtilize um valor entre [1 e 99]");
                   System.out.println("Digite novamente o número da charrete: ");
                   numCha[cont] = ler.nextInt();
               }
        System.out.println("Digite a distância da charrete até a chegada em metros: ");
      distancia[cont] = ler.nextDouble();
                while ((distancia[cont] < 0) || (distancia[cont] > 1000)){
                    System.out.println("Valor Inválido!\nUtilize um valor entre [0 e 1000]");
                    System.out.println("Digite novamente a distância: ");
                   distancia[cont] = ler.nextDouble();
                }
        System.out.println("Digite a velocidade da charrete em km/h: ");
     velocidade[cont] = ler.nextDouble();
                while ((velocidade[cont] < 0) || (velocidade[cont] > 50)){
                    System.out.println("Valor Inválido!\nUtilize um valor entre [0 e 50] km/h");
                    System.out.println("Digite novamente a velocidade: ");
                   velocidade[cont] = ler.nextDouble();
                }
            metros[cont] = velocidade[cont] * 0.27778;
            tempo[cont] = distancia[cont] / metros[cont];

                aux++; cont++;
       }
        //essa linha abaixo é onde está dando erro no código e é a fonte da minha duvida
          if (tempo[cont] < (tempo[cont]+1)){
             System.out.println("A charrete "+numCha[cont]+" vai chegar em primeiro lugar!");
         } else if (tempo[cont] > (tempo[cont]+1)){
             System.out.println("A charrete "+(numCha[cont]+1)+" vai chegar em primeiro lugar!");
      } else {System.out.println("Ambas as charretes irão chegar no fim ao mesmo tempo!");}
    }

}
}

Comment: *eu fazia algo como: (vetor[contador]+1) para mostrar o vetor, na posição contador +1* - não, pra isso vc tem que fazer `vetor[contador + 1]`. Se colocar o `+ 1` dentro dos colchetes, vc pega a posição `contador + 1`. Se fizer `vetor[contador] + 1` vc está somando 1 ao **valor que está na posição `contador`**
Answer: Você está tendo um problema na linha onde você compara tempo[cont] com (tempo[cont] + 1) e (numCha[cont] + 1) com relação à decisão de qual charrete chegará primeiro. O problema está na forma como você está usando a variável cont.
Quando você entra no loop for (int i = 0; i < N; i++), você já está iterando pelas posições 0 e 1 dos arrays. Portanto, dentro desse loop, você deve se referir às posições do array usando a variável i, não a variável cont.
Aqui está a parte corrigida do seu código com explicações:
for (int i = 0; i < N; i++) {
    System.out.println("Digite o número da charrete [1-99]: ");
    numCha[i] = ler.nextInt();
    // ... (as outras leituras e validações)

    metros[i] = velocidade[i] * 0.27778;
    tempo[i] = distancia[i] / metros[i];
}

// Agora você precisa comparar os tempos das duas charretes
if (tempo[0] < tempo[1]) {
    System.out.println("A charrete " + numCha[0] + " vai chegar em primeiro lugar!");
} else if (tempo[1] < tempo[0]) {
    System.out.println("A charrete " + numCha[1] + " vai chegar em primeiro lugar!");
} else {
    System.out.println("Ambas as charretes irão chegar no fim ao mesmo tempo!");
}

Dentro do loop for, usamos i para iterar pelas posições dos arrays, e fora do loop, comparamos os tempos diretamente usando tempo[0] e tempo[1].
Além disso, notei que você está incrementando aux dentro do loop while (aux < N). Isso fará com que seu loop nunca termine, pois aux nunca será maior ou igual a N. Você pode remover a variável aux e simplificar o loop para for (int i = 0; i < N; i++). Isso fará com que o código funcione corretamente.


Find an example of a set of points of the plane such that there exist at least $2^{n-2}$ good partitions.

Question: If a set of $n$ points of the plane can be divided into two subsets $\{ A_1, A_2, \dots,  A_k\}$ and $\{ B_1, B_2, \dots, B_{n-k}\}$  so that there is a point $M$ of the plane such that
$$ MA_1+ MA_2+ \dots+MA_k= MB_1+ MB_2+ \dots+MB_{n-k},$$
then we shall say that there exists a good partition of the set of these $n$  points of the plane.
Prove that for all $n \ge 2$ there is a set of $n$ points of the plane such that the number of good partition of this set is not less than $2^{n-2}$.
Partitions in which two sets $A$ and $B$ change between themselves are the same partitions.
My work. I tried to place points at the vertices of a regular polygon or on a line at the same distance from each other. But it is difficult to prove the problem for these cases.
Comment: Can we use linear algebra here?
Comment: Yes, of course! We can use linear algebra.
Answer: Put $n-1$ points in a ball of radius $\epsilon$ and one point that is at distance $R$ from the origin. Make $\epsilon = R/(1000n)$. Pick any point in the circle and the point that is far away. Call these points special points. Now partition the other $n-2$ points into two sets arbitrarily. Call these partitions set $A$ and $B$.
Now extend the partition by adding the special point that is inside the circle in way that the two sets have different sizes. We can assume that $|A| > |B|$ after adding in this one special point. Now assign the other special point that is far away to set $B$. This gives us $2^{n-2}$ possible partitions. We show that each partition is good.
Let $f(M) = \sum_{A_i \in A} MA_i - \sum_{B_i \in B} MB_i$. Note that $f$ is a continuous function in $M$. Now let $M_1$ be the origin of the circle. We can compute that
$$ f(M_1) \le \frac{Rn}{500n} -R < 0.$$
Let $M_2$ be the special point that is very far away from the circle. We have
\begin{align*}
f(M_2) &\ge (R-\epsilon)|A|-(R+\epsilon)(|B|-1)  \\
       &\ge R(|A|-(|B|-1)) - \epsilon n \\
       &\ge R-\epsilon n > 0
\end{align*}
where we have used the fact that $|A| > |B|-1$ due to the way we added the special points.
Then by the intermediate value theorem, there exists some point in the plane such that $f = 0$, as desired.
Comment: Ah ok, sorry for the error! Glad that it worked out
Comment: Very nice idea! But if $n$ is odd, then in your proof will be repeat the same partitions twice. We have $\binom{n-2}{\frac{n-3}{2}}$  partitions such that there are $\frac{n-3}{2}$ points in one set, and $\frac{n-1}{2}$  points in another set. Also we have $\binom{n-2}{\frac{n-1}{2}}$  partitions such that there are $\frac{n-1}{2}$ points in one set, and $\frac{n-3}{2}$  points in another set. In both cases we are obliged to add a special point that is inside the circle to a larger set. So in both cases we will have the same partitions.
Comment: Partitions in which two sets $A$ and $B$ change between themselves are the same partitions.
Comment: I accept your answer, because very valuable your idea. Based on your idea, I made another proof in which there is only one special point - the point that is far away. Thank you very much!


How do I integrate the Color module in my theme?

Question: I have installed drupal 8.4.2 and created a subtheme with base theme
   bootstrap. I want to customize settings adding the color module, but
   really I do not know what steps I am missing.

I have enabled color module (it's in core)
I have copied (from bartik) the color directory and files
I have edited color.inc to have  my custom color schemes
I  have edited THEME.theme adding this:
function MYTHEME_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
}
function MYTHEME_preprocess_page(&$variables, $hook) {
    // Hook into color.module
    if (module_exists('color')) {
        _color_page_alter($variables);
    }
}

As a result I have white page with no rendering. (It's not cache issue) and I guess my problem is with .theme file
I'd like to know where to find the instructions (drupal.org has not much). Thanks
Answer: There's actually a video on YouTube about how to do this in Bootstrap.  There's also a more general video for other themes by the same person.
You'll need to use a LESS or SASS subtheme; the most basic subtheme that just uses regular CSS will not work because the Color module will change the values of the variables.
You will also need a way to compile the LESS/SASS on the server that you use the Color module on, so if you plan to make adjustments on your production server, you will need something like the LESS module, which does not yet have an official release for Drupal 8 (might still work, needs testing).
You can also find a feature request on drupal.org for putting this directly into Bootstrap, but it hasn't made any progress in the past couple years.


Using $set and $setOnInsert during upsert

Question: I'm trying to update a collection in mongodb and if a field exists, will insert it. I'm not so sure how can I do that with the upsert option.
MongoCollection<Document> docs = mongoDb.getCollection("users");
Bson filterQuery = new Document("userId", userId).append("fileType", fileType);
Bson updateQuery = new Document("$set", new Document("fileType", fileType).append("fileName", fileName).append("fileSize", fileSize).append("userId", userId).append("lastModifiedTimestamp", new Timestamp(System.currentTimeMillis())));
updateQuery.append("$setOnInsert", new Document("creationTimestamp", new Timestamp(System.currentTimeMillis())));
docs.updateOne(filterQuery, updateQuery, (new UpdateOptions()).upsert(true));

This is not working. I'm not updating the same fields for $set and $setOnInsert but not sure why this isn't working. Any thoughts?
Comment: Are you trying to update the lastModifiedTimestamp every time you do an update, or what are you trying to achieve ? I think you if the record does not exist you are trying to insert the creationTimestamp, if record exist you only try to update the lastModifiedTimestamp, I am correct ?
Comment: Yes exactly. Trying to update the lastModifiedTimestamp every time I do an update.
Answer: Tried to use the following config, I have some compilation errors in your code that I fix below.
public class StackOverflowApp {

   public static void main (String[] args){

    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).build();
    MongoClient client = new MongoClient(new ServerAddress(), options);
    MongoDatabase db = client.getDatabase("test").withReadPreference(ReadPreference.secondary());

    String userId = "myUser2";
    String fileType = "fileType2";
    String fileName = "fileName";
    String fileSize = "fileSize";
    MongoCollection<Document> docs = db.getCollection("users");
    Bson filterQuery = new Document("userId", userId).append("fileType", fileType);
    Bson updateQuery = new Document("$set", new Document("fileType", fileType).append("fileName", fileName).append("fileSize", fileSize).append("userId", userId).append("lastModifiedTimestamp", new Date(System.currentTimeMillis())));
    ((Document)updateQuery).append("$setOnInsert", new Document("creationTimestamp", new Date(System.currentTimeMillis())));
    docs.updateOne(filterQuery, updateQuery, (new UpdateOptions()).upsert(true));
    }
}

If I run the first time I insert this one.
"_id" : ObjectId("570c6f2105c7937ac1c794cb"),
"fileType" : "fileType2",
"userId" : "myUser2",
"fileName" : "fileName",
"fileSize" : "fileSize",
"lastModifiedTimestamp" : ISODate("2016-04-12T03:44:33.454Z"),
"creationTimestamp" : ISODate("2016-04-12T03:44:33.454Z")

Second time only lastModifiedTimestamp is updated
"_id" : ObjectId("570c6f2105c7937ac1c794cb"),
"fileType" : "fileType2",
"userId" : "myUser2",
"fileName" : "fileName",
"fileSize" : "fileSize",
"lastModifiedTimestamp" : ISODate("2016-04-12T03:44:59.947Z"),
"creationTimestamp" : ISODate("2016-04-12T03:44:33.454Z")

I think that is what you were tried to achieve.
Comment: Did you use java.util.Date? I'm not able to save the timstamps for some reason.


Covariance of Student's t-distribution

Question: Another integral (this time it looks like a lot of work but maybe it can be simplified).
I have the Student's t-distribution
$$\int_{-\infty}^\infty \frac{\Gamma(D/2+\nu/2)}{\Gamma(\nu/2)}\frac{|\Lambda|^{1/2}}{(\pi \nu)^{D/2}}\left(1+\frac{(x-\mu)^{T}\Lambda(x-\mu)}{\nu}\right)^{-D/2-\nu/2}\mathrm dx$$
and I want to calculate its covariance, so I started using the definition $\text{cov}[x] = E[(x-E[x])(x-E[x])^{T}]$ which simplifies to $E[xx^{T}]-\mu\mu^{T}$
Trying to solve the expectation $E[xx^{T}]$, we get something like this
$$E[xx^{T}]=C \int \left(1+\frac{(x-\mu)^{T}\Lambda (x-\mu)}{\nu}\right)^{-\alpha} xx^{T}dx$$
with $\alpha=D/2+\nu/2$ and $C$ as a normalization constant.
Changing variables via $y=\Lambda^{1/2}(x-\mu)$, we obtain
$$E[xx^{T}]=C \int \frac{1}{\left(1+\displaystyle \frac{y^{T}y}{\nu}\right)^\alpha} (\Lambda^{-1/2}y+\mu) (\Lambda^{-1/2}y+\mu)^{T}|\Lambda|^{-1/2}dy$$
At this point, I know the cross terms of the product $(\Lambda^{-1/2}y+\mu) (\Lambda^{-1/2}y+\mu)^{T}$ vanish and the last term is going to produce $\mu\mu^{T}$ because the distribution is normalized, but I'm having a hard time getting the first term
$$C \int_{\infty}^{\infty} \frac{\Lambda^{-1/2}y y^{T}\Lambda^{-1/2}}{\left(1+\displaystyle \frac{y^{T}y}{\nu}\right)^\alpha}|\Lambda|^{-1/2}dy$$
I tried to use spherical coordinates but since $yy^{T}$ is a $D×D$ matrix I would need to integrate every term. There should be a better procedure.
By the way, the result I should get is $\text{cov}[x]=\displaystyle \frac{\nu}{\nu-2}\Lambda^{-1}$.
Any help is appreciated.
Answer: I haven't checked you algebra, but since you are interested in integration in polar coordinates, let us say that you want to compute that last integral
$$
\int_{\mathbb{R}^n} \frac{ \Lambda^{-1/2}  y y^T \Lambda^{-1/2}}{(1+\frac{y^T y}{\nu} )^{\alpha}}|\Lambda|^{-1/2} dy = |\Lambda|^{-1/2}  \Lambda^{-1/2}  \Big\{ \int_{\mathbb{R}^n} \frac{ y y^T }{(1+\frac{y^T y}{\nu} )^{\alpha}} dy \Big\} \Lambda^{-1/2}
$$
by the linearity of the integral and that $\Lambda$ is constant. Now, in general
$$
\int_{\mathbb{R}^n} f = n v_n \int_0^\infty \int_{S^{n-1}} f(r \theta) r^{n-1} d \sigma(\theta) dr
$$
where $\theta$ is general point on the sphere $S^{n-1}$ and $\sigma$ is uniform measure on that sphere. Here $v_n$, is the volume of the unit ball in $\mathbb{R}^n$. (See An Elementary Introduction to Modern Convex Geometry, by K. Ball, p. 5.)
Letting $y = r\theta$ and noting that $y^Ty = r^{2}$ since $\theta^T \theta = 1$, we get
$$
\int_{\mathbb{R}^n} \frac{ y y^T }{(1+\frac{y^T y}{\nu} )^{\alpha}} dy = n v_n
\int_0^\infty \frac{r^2}{(1+r^2/\nu)^\alpha} r^{n-1} dr \int_{S^{n-1}} \theta \theta^T d\sigma(\theta).
$$
Note that $\int_{S^{n-1}} \theta \theta^T d\sigma(\theta) $ is the covariance of a random variable uniformly distributed on the sphere $S^{n-1}$. By symmetry, it is equal to some constant, say $\alpha_n$, times the identity matrix $I_n$. To obtain that constant, you can verify that each coordinate of such a random variable is distributed as a Beta random variable. Thus,
$$
\int_{\mathbb{R}^n} \frac{ y y^T }{(1+\frac{y^T y}{\nu} )^{\alpha}} dy = n v_n \alpha_n I_n
\int_0^\infty \frac{r^2}{(1+r^2/\nu)^\alpha} r^{n-1} dr
$$
PS. The distribution of $\theta$ is the same as the distribution of $\frac{X}{\|X\|}$ where $X$ is a standard normal random variable.
EDIT: If you need a rigorous proof of that integration formula in polar coordinate, one that I know of is based on the heavy machinery of geometric measure theory. In particular, if you have heard of co-area formula, then this is a special case. For example, in "Sobolev mappings, co-area formula and related topics" by Piotr Hajlasz, the following is derived (p. 232)
$$
\int_{\mathbb{R}^n} g \,dx = \int_0^\infty \Big(
\int_{\partial B(0,r)} g \,d \mathcal{H}^{n-1} \Big) dr
$$
as an application of that general result. Here $\mathcal{H}^{n-1}$ is the $(n-1)$-dimensional Hausdorff measure and $\partial B(0,r)$ is the boundary of the ball of radius $r$ centered at origin. Note that $H^{n-1}$ restricted to $\partial B(0,r)$ is in essence the distribution of a random variable uniformly distributed on the sphere of radius $r$. I will leave it to you to show that this version and the one I mentioned earlier are the same.
Comment: This is a compact way of writing those sine-cosine relations, or rather a more abstract way of writing it. Every vector $y$ can be written as $ y = (y/\|y\|) \|y\|$. $\theta$ is the $y/\|y\|$ part and $r$ is $\|y\|$. (You can verify that this $\theta$ has unit norm $\theta^T \theta = \|\theta\|^2 = 1$.) This rather abstract and elegant way of writing the integration in polar coordinates is useful if you can use symmetry (in some sense) to effectively bypass detailed computations for that integral over the sphere. Otherwise, you have to go back to a lots of sines and cosines...
Comment: Wow, that's quite something. Can you describe why $y=r\theta$ and $\theta^{T}\theta=1$? The representation of spherical coordinates I have seen always involves a lot of sines and cosines for the $n-1$ coordinates.
Comment: By the way, I read the description of K. Ball where he's using that change of variables but I still don't know the reason.
Comment: ... which might not be even worth the effort.
Comment: +1. Interesting. I haven't found much information about that transformation. By the way, what is $v_{n}$?
Comment: $v_n$ is the volume of the n-dimensional Euclidean ball, it is explained in K. Ball's notes. His first lecture is trying to compute that exact quantity by integrating the n-dimensional Gaussian distribution in polar coordinates. Take a second look at the notes; it might make more sense on a second or third reading.

Covariance of Student's t-distribution


12 points circle associated with a cyclic hexagon

Question: When I research this problem A chain of six circles associated with a cyclic hexagon. I found the followings result.
Let $ABCDEF$ be a cyclic hexagon. Let $A_1$ be any point on $AD$, the circle $(A_1AB)$ meets $BE$ again at $B_1$. The circle $(B_1BC)$ meets $CF$ again at $C_1$. The circle $(C_1CD)$ meets $AD$ again at $D_1$. The circle $(D_1DE)$ meets $BE$ again at $E_1$. The circle $(E_1EF)$ meets $CF$ again at $F_1$. Then show that $F_1, F, A, A_1$ lie on a circle and six points $A_1, B_1, C_1, D_1, E_1, F_1$ lie on a circle.

My question: Let $A_2, D_2 \in AD; B_2, E_2 \in BE, C_2, F_2 \in CF$ such that such that the sidelines of the hexagon $A_2B_2C_2D_2E_2F_2$ parallel to the sidelines of $A_1B_1C_1D_1E_1F_1$ respectively. Let line $A_2B_2$ meets the circle $(ABB_1A_1)$ at two points $A_b, B_a$. Define $B_c$, $C_b$, $C_d, D_c$, $D_e, E_d$, $E_f, F_e$, $F_a, A_f$ cyclically (cyclically meen: define the same, define similarly). Then show that twelve points: $A_b, B_a$, $B_c$, $C_b$, $C_d, D_c$, $D_e, E_d$, $E_f, F_e$, $F_a, A_f$ lie on a circle.
Answer: From radical center theorem we get that $A_bB_aB_cC_b$ is cyclic and from other arguments that it's center coincides with the center of $(A_1B_1C_1)$. Same for other quadrangles. $\Box$


Unitary Operator on Hilberspace to show that Fourierbasis is a maximal Orthogonal Set

Question: I have looked at the proof Proving that the Fourier Basis is complete for C(R/$2*\pi$ , C) with $L^2$ norm
but am having trouble understanding the argumentation about the Hilberspace. I think the proof is quite nice and would like to understand it, and also need to refresh my Functional analysis. In particular:

This is probably not the most elegant way, but this method generalizes to showing the unitarity of the Fourier transform. The essential part of this proof is showing that the map L2(R/2πZ)→ℓ2(Z) given by taking the Fourier coefficients from the discrete Fourier transform is an isometry, since the discrete Fourier transform is essentially the orthogonal projection onto the closure of the span of the functions e^inx. Then, by basic Hilbert space theory, it would follow that {e^inx} is a maximal orthogonal set.

The "then by basic Hilber space theory" is not clear to me...
Is this because if you take the Span of $e^{inx}$ it has the same Image under an Unitary Operator  as L2(R/2πZ), and thus {e^inx} must be dense in L2(R/2πZ) - And if yes, whats the name of a theorem showing this/can you direct me to one?
thank you
Answer: To show that $\{ e^{int} \}$ is a complete orthogonal subset of $L^2[0,2\pi]$, suppose that $(f,e^{int})=0$ for all $n\in\mathbb{Z}$. It must be shown that $f=0$ a.e.. To prove this, define
$$
                   E(\lambda)=\frac{1}{e^{-2\pi i\lambda}-1}\int_{0}^{2\pi}ie^{-i\lambda t}f(t)dt,\;\;\;\lambda\in\mathbb{C}.
$$
Then $E$ extends to an entire function of $\lambda$ because it has only removable singularities at the integers. It is not too hard to show that $E(\lambda)$ is uniformly bounded on square contours $C_n$ formed by connecting these vertices in order
$$
              \frac{2n+1}{2}(-1-i),\;\frac{2n+1}{2}(1-i),\;\frac{2n+1}{2}(1+i),\;\frac{2n+1}{2}(-1+i).
$$
Using such boundedness, a simple modification of the proof of Liouville's Theorem shows that $E$ must be a constant function. Hence, there is a constant $C$ such that
$$
             \int_{0}^{2\pi}f(t)e^{-i\lambda t}dt = C(e^{-2\pi i\lambda}-1).
$$
Choosing $\lambda=-ir$ for $r > 0$, and letting $r\rightarrow\infty$ gives $0$ on the left and $-C$ on the right. Hence, $C=0$. Therefore the left side is identically $0$ in $\lambda$. All of the derivatives with respect to $\lambda$ must also be $0$. Therefore,
$$
                    \int_{0}^{2\pi}f(t)t^{n}dt=0,\;\;\; n=0,1,2,3,\cdots.
$$
Because the polynomials are dense in $L^2$, it follows that $f=0$ a.e.. Hence, $\{ e^{int} \}_{n=-\infty}^{\infty}$ is a complete orthogonal subset of $L^2[0,2\pi]$.
Comment: Very cool! I've never seen this proof before +1
Answer: I actually love Disinegrating's answer, but I do think it may have omitted the Hilbert space theory that OP asked about? For the sake of completeness, maybe it's good if I  describe the underlying theory for future viewers.

Definition: we say that a subset $A$ of an inner product space $H$ is an orthonormal set of vectors if we have $\langle x,y \rangle = 0$ for all distinct $x,y \in A$ as well as $\|x\|^2 = \langle x,x \rangle = 1$ for all $x \in A$.

Definition: in an inner product space $H$, we say that a set $A$ of orthonormal vectors is maximal if, given $x \in H \setminus A$, the set $\{x\} \cup A$ is not an orthonormal set of vectors.

Definition: we say that a countable, maximal, orthonormal set of vectors is an orthonormal basis.

Proposition: if $(e_n)$ is an orthonormal basis for a Hilbert space $H$ (i.e., $(e_n)$ are all distinct and $\{e_n : n\in\mathbb{N}\}$ is an orthornomal basis), then we have $v = \sum_{n\in\mathbb{N}} \langle v,e_n \rangle e_n$ for all $v \in H$.

Theorem: given a sequence $(e_n)$ of mutually orthonormal vectors in a Hilbert space $H$, we have that $(e_n)$ is an orthonormal basis if and only if, for all $v \in H$, $\|v\| = \sum_{n\in\mathbb{N}} |\langle v,e_n \rangle|^2$.

Remark: it is always true that $\|v\| \geq \sum_{n\in\mathbb{N}} |\langle v,e_n \rangle|^2$. The reverse inequality is non-trivial.
In conclusion: in the question cited by OP, the scalars $a_n$ are in fact of the form $\langle f,e_n \rangle$ for some sequence $(e_n)$ of orthonormal vectors. Thus, to be able to conclude that $(e_n)$ are maximal, the problem in the post which OP refers to is to show that $\sum_{|n| \leq N} |a_n|^2 \to \|f\|^2$. as $N\to\infty$.
For a proof of the theorem referenced above, see, perhaps, Real and Complex Analysis by Rudin, or Real Analysis: Measure Theory, Integration, and Hilbert Spaces by Stein and Shakarchi.


Number of frames in a video using PyAV

Question: I use the library PyAV because it's one of the fatest available with Python.
Here is a simple example of code I would like to use:
import av

video = av.open("My_Super_Video.mp4")

total_frames = # ????

for i, frame in enumerate(video.decode(video=0)):
    img = frame.to_image()  # PIL image

    print("Frame: %d/%d ..." % (i, total_frames))

I could obviously use other libraries to load the library, however I would prefer using PyAV if possible due to its processing speed.
Question 1: Is it possible to obtain the number of frames with PyAV ? If yes, how ?
Question 2: In the case, I would consider using another library to load and process the video frame by frame. Which library would allow me to do the above with the highest speed as possible. I know the followings, but don't know how they compare:

PIMS On top of PyAV, could add some interesting feature ?
MoviePy (limited to videos which fit in RAM), but what about perf ?
Imageio (probably same limitation as above), but what about perf ?
OpenCV (probably same limitation as above), but what about perf ?
Others ?
Answer: To get the frames of the first video stream do:
container = av.open("My_Super_Video.mp4")
total_frames = container.streams.video[0].frames

Comment: I tried this and got 0 frames returned, so it seems like this only works some of the time.
Comment: `frames` is a proxy to the `nb_frame` attribute of the AVStream struct, according to the [ffmpeg docs](https://ffmpeg.org/doxygen/trunk/structAVStream.html#a4382c3064df1c9eb232ac198dec067f9) it is 0 if it is unknown. Not sure when this happens though, maybe some codecs do not contain that information
Comment: `ffprobe` gives the number of frames but `pyav` still returns 0, so weird
Comment: I run into an edge case when it returned 0 - a (English) `.mkv` file. The workaround was to use:
`int(container.streams.video[0].metadata.get('NUMBER_OF_FRAMES-eng', '0'))` instead.
Answer: You can get the number of frames in stream with Stream.frames attribute.
Source: http://docs.mikeboers.com/pyav/develop/api/stream.html#av.stream.Stream
Comment: Doc for the attribute itself: https://pyav.org/docs/develop/api/stream.html#av.stream.Stream.frames
Answer: Old question, but only partly answered. Let me answer the second question as well.

Question 1: Is it possible to obtain the number of frames with PyAV ? If yes, how ?

import av

with av.open("My_Super_Video.mp4") as container:
    total_frames = container.streams.video[0].frames

Question 2: In the case, I would consider using another library to load and process the video frame by frame. Which library would allow me to do the above with the highest speed as possible. I know the followings, but don't know how they compare: [...]

ImageIO timings:  0.497
PyAV timings:     0.908
MoviePy timings:  0.766
OpenCV timings:   0.766
OpenCV timings:   0.569 (no conversion to RGB)

ImageIO is the fastest; hands down. OpenCV comes close (14% slower), but only if you can do your processing in BGR. If you have to work in RGB then the conversion costs you dearly (54% slower ).
That said, it is highly workload-dependent and you should always benchmark with your specific setup. In practice, the difference is often negligible compared to how much time you spend processing each frame.
Here is the benchmark code for those interested:
import cv2
import av
import imageio.v3 as iio
from moviepy.editor import VideoFileClip
from PIL import Image
from timeit import Timer

# create a test video (roughly 11 sec and sane encoding)
frames = iio.imread("imageio:cockatoo.mp4", plugin="pyav")
iio.imwrite("test_video.mp4", frames, plugin="pyav", codec="h264")

def iio_read():
    total_frames = iio.improps("test_video.mp4", plugin="pyav").shape[0]
    for idx, frame in enumerate(iio.imiter("test_video.mp4", plugin="pyav")):
        foo = Image.fromarray(frame)

        # Note: I will not print in the benchmark. This will skew the result
        # print("Frame: %d/%d ..." % (idx, total_frames))

def av_read():
    with av.open("test_video.mp4") as container:
        total_frames = container.streams.video[0].frames
        for frame in container.decode(video=0):
            foo = frame.to_image()

def moviepy_read():
    # Can not read frame_count
    for frame in VideoFileClip("test_video.mp4").iter_frames():
        foo = Image.fromarray(frame)

def cv2_read():
    cap = cv2.VideoCapture("test_video.mp4")

    total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    success, frame = cap.read()
    idx = 0
    while success:
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        foo = Image.fromarray(frame)
        success, frame = cap.read()
        idx += 1

def cv2_read2():
    cap = cv2.VideoCapture("test_video.mp4")

    total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    success, frame = cap.read()
    idx = 0
    while success:
        foo = Image.fromarray(frame)
        success, frame = cap.read()
        idx += 1

repeats = 10
time_moviepy = min(Timer("moviepy_read()", globals=globals()).repeat(repeats, number=1))
time_cv2 = min(Timer("cv2_read()", globals=globals()).repeat(repeats, number=1))
time_cv2_no_convert = min(Timer("cv2_read2()", globals=globals()).repeat(repeats, number=1))
time_iio = min(Timer("iio_read()", globals=globals()).repeat(repeats, number=1))
time_av = min(Timer("av_read()", globals=globals()).repeat(repeats, number=1))

print(
f"""
ImageIO timings:  {time_iio:.3f}
PyAV timings:     {time_av:.3f}
MoviePy timings:  {time_moviepy:.3f}
OpenCV timings:   {time_cv2:.3f}
OpenCV timings:   {time_cv2_no_convert:.3f} (no conversion to RGB)
"""
)

Package Versions:
av==10.0.0
moviepy==1.0.3
Pillow==9.4.0
opencv-python==126.96.36.199
imageio==2.25.0

Number of frames in a video using PyAV


Display a message "No internet" if internet connection is lost while using webview pages in flutter android

Question: <code>bool connectionStatus = true;
Future check() async {
  try {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      connectionStatus = true;
    }
  } on SocketException catch (_) {
    connectionStatus = false;
  }
}

class _BackButtonState extends State<BackButton> {
  DateTime backbuttonpressedTime;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size(double.infinity, 0),
        child: AppBar(
          title: Text(""),
          backgroundColor: Colors.deepPurple,
        ),
      ),
      body: FutureBuilder(
          future: check(), // a previously-obtained Future or null
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (connectionStatus == true) {
              return WillPopScope(
                onWillPop: onWillPop,
                child: WebviewScaffold(
                  url: 'https://www.theonlineindia.co.in',
                  hidden: true,
                  initialChild: Container(
                    child: const Center(
                      child: CircularProgressIndicator(
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.deepPurple)),
                    ),
                  ),
                ),
              );
            } else {
              return Center(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    child: Text('No internet connection !!!',
                        style: TextStyle(
                          // your text
                          fontFamily: 'Aleo',
                          fontStyle: FontStyle.normal,
                          fontWeight: FontWeight.bold,
                          fontSize: 25.0,
                        )),
                  ),
                  /* RaisedButton(
                    onPressed: () {
                      setState(() {});
                    },
                    color: Color(0xFF673AB7),
                    textColor: Colors.white,
                    child: Text('Refresh'),
                  ), */
                  // your button beneath text
                ],
              ));
            }
          }),
    );
  }

  Future<bool> onWillPop() async {
    DateTime currentTime = DateTime.now();

    //ifbackbuttonhasnotbeenpreedOrToasthasbeenclosed
    //Statement 1 Or statement2
    bool backButton = backbuttonpressedTime == null ||
        currentTime.difference(backbuttonpressedTime) > Duration(seconds: 2);
    if (backButton) {
      backbuttonpressedTime = currentTime;
      Fluttertoast.showToast(
          msg: "Double tap to exit the app",
          backgroundColor: Colors.deepPurple,
          textColor: Colors.white);
      return false;
    }
    exit(0);
    return true;
  }
}
</code>

In the above code I am able to display the message "No internet" only at the time of launching the app.
I want to display the same message after app is launched and if the internet connection is lost while visiting the web pages within the webview.
I would prefer to achieve the above via code itself not looking for any plugins. Plugins will be secondary option.
*
Answer: Option 1
Define a timer that periodically check the connection
<code>  const period= const Duration(seconds:5);
  new Timer.periodic(period, (Timer t) => check());
</code>
Option 2
Use the connectivity plugin and define a stream in your app main widget
<code>    StreamSubscription<ConnectivityResult> networkSubscription;
    @override
      void initState() {
        super.initState();
        networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
          check();
        });
        checkNetwork(); // Needed for the check on start
      }
</code>
Comment: @atifshaikh You're welcome, glad it helps ! Could you mark the answer as accepted ? if it completely answer you question of course
Comment: @atifshaikh https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: Thanks a lot it worked for me.    Timer.periodic(new Duration(seconds: 10), (time) async {
      final flutterWebViewPlugin = FlutterWebviewPlugin();
      if (connectionStatus == false) flutterWebViewPlugin.reload();
      try {
        final result = await InternetAddress.lookup('google.com');
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          connectionStatus = true;
        }
      } on SocketException catch (_) {
        connectionStatus = false;
        Fluttertoast.showToast(
            msg: "No internet connection",
          );
      }
    });
Comment: I cant find the option to do that.


Where did my memory go on linux (no cache/slab/shm/ipcs)

Question: This is a headless server with 8GB RAM (kernel 3.12)... even after only a few days, i get low on memory. in fact, this server has OOMed a few days ago... something is losing memory, but i don't know where...
see the output below:
in short:

64bit system & OS
not a hypervisor nor a virtual machine
low free mem
swap in use
low cache
low buffer
inactive+active == 1GB ???
low ipcs
low shm
low slab
~500MB tmpfs usage
in fact total RSS of all processes is 262MB
and HWM of all processes is less than 600MB
i lost more than 6GB somewhere...?

[root@localhost ~]# cat /proc/meminfo
MemTotal:        8186440 kB
MemFree:          251188 kB
Buffers:             144 kB
Cached:           853548 kB
SwapCached:         9988 kB
Active:           480036 kB
Inactive:         529456 kB
Active(anon):     256196 kB
Inactive(anon):   333072 kB
Active(file):     223840 kB
Inactive(file):   196384 kB
Unevictable:       13656 kB
Mlocked:               0 kB
SwapTotal:       4194300 kB
SwapFree:        4092540 kB
Dirty:               356 kB
Writeback:             0 kB
AnonPages:        161576 kB
Mapped:            50116 kB
Shmem:            419812 kB
Slab:              72680 kB
SReclaimable:      50648 kB
SUnreclaim:        22032 kB
KernelStack:        1824 kB
PageTables:        10260 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     8287520 kB
Committed_AS:    1883404 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       91804 kB
VmallocChunk:   34359637332 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       83180 kB
DirectMap2M:     8296448 kB

[root@localhost ~]# ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x01123bac 0          root       600        1000       8

[root@localhost ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           4.0G  393M  3.6G  10% /run

[root@localhost ~]# for i in /proc/*/status ; do grep VmRSS $i; done | awk '{ s = s + $2 } END { print s / 1024 }'
262.375

[root@localhost ~]# for i in /proc/*/status ; do grep VmHWM $i; done | awk '{ s = s + $2 } END { print s / 1024 }'
526.77

Edit: i've set overcommit=2 (disabled) just in case (i rebooted 2 days ago)

[root@localhost linux]# cat /proc/sys/vm/overcommit_memory
2
[root@localhost linux]# df -h | grep tmpfs
devtmpfs        3.9G     0  3.9G   0% /dev
tmpfs           4.0G     0  4.0G   0% /dev/shm
tmpfs           4.0G  532K  4.0G   1% /run
tmpfs           4.0G     0  4.0G   0% /sys/fs/cgroup
tmpfs           4.0G     0  4.0G   0% /tmp
tmpfs           4.0G  532K  4.0G   1% /var/spool/postfix/run/saslauthd
[root@localhost linux]# for i in /proc/*/status ; do grep VmRSS $i; done | awk '{ s = s + $2 } END { print s / 1024 }'
434.188
[root@localhost linux]# for i in /proc/*/status ; do grep VmHWM $i; done | awk '{ s = s + $2 } END { print s / 1024 }'
545.551
[root@localhost linux]# cat /proc/meminfo
MemTotal:        8186440 kB
MemFree:          146576 kB
Buffers:            1728 kB
Cached:          5212588 kB
SwapCached:            0 kB
Active:          2560112 kB
Inactive:        2874464 kB
Active(anon):      94464 kB
Inactive(anon):   136528 kB
Active(file):    2465648 kB
Inactive(file):  2737936 kB
Unevictable:        9772 kB
Mlocked:               0 kB
SwapTotal:       4194300 kB
SwapFree:        4194300 kB
Dirty:              1436 kB
Writeback:             0 kB
AnonPages:        230032 kB
Mapped:            50540 kB
Shmem:               960 kB
Slab:             316804 kB
SReclaimable:     291712 kB
SUnreclaim:        25092 kB
KernelStack:        1880 kB
PageTables:        11184 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     8287520 kB
Committed_AS:    1160812 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       91676 kB
VmallocChunk:   34359582672 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       91372 kB
DirectMap2M:     8288256 kB

so, i'm using 8GB:

5GB is cached
0.5MB tmpfs
450MB RSS
~1GB slab+pages+whatever (in meminfo)

i'm still short 1.5GB ... is this a kernel leak? or what is going on here???
Edit2: i have the same issue on another atom board
I also checked if kmemleak saw something, but nothing... i'm out of ideas...
Edit3: updating to kernel 3.17.2 seems to have resolved this issue, but i still don't know how to trace these memory leaks...
Comment: Did you do something silly like install 32-bit Linux?
Comment: of course not... and even then still 2GB would be lost... besides... the /proc/meminfo clearly shows the 8GB...
Answer: lkml thinks that it might have been https://lkml.org/lkml/2014/10/15/447 , but that patch wasn't in 3.17.2 and the thp allocation don't point that way
however, /proc kpageflags might show what part allocated what pages, so that might help. in tools/vm/page-types.c in kernel sources, that might hold some info on the structure of the kpageflags binary output.


How to prove that $\lim_{x\rightarrow\infty}x-\sqrt{x(x+1)}=-\frac12$

Question: How do I prove that $$\lim_{x\rightarrow\infty}x-\sqrt{x(x+1)}=-\frac12$$? I first got this question when I was graphing $\sqrt{x(x+1)}$ and I noticed that it approached a linear function as $x$ increases. We couldn't use L'hopital's rule since these functions aren't in fraction form. Also, we couldn't simply substitute $x=\infty$. And Taylor series approximation seems very complicated.
Comment: Hint: consider this as a (trivial) ratio and rationalize the numerator.
Answer: \begin{align*}
&\lim\limits_{x\rightarrow \infty} x-\sqrt{x(x+1)} \\
=& \lim\limits_{x\rightarrow \infty} \frac{x^2-x(x+1)}{x+\sqrt{x(x+1)}} \\
=& \lim\limits_{x\rightarrow \infty} - \frac{x}{x+\sqrt{x(x+1)}} \\
=& \lim\limits_{x\rightarrow \infty} - \frac{1}{1+\sqrt{1+\frac1x}} = -\frac12
\end{align*}
Usually, limits of the form $\infty-\infty$ can be calculated by multiplying the numerator and denominator by something of the form $\infty+\infty$ and then simplifying.
Hope this helps you.
Comment: What do you mean? The answerer just divided by $x$ on the top and bottom. There is no L'Hôpital's Rule there. @KamalSaleh
Comment: Thanks, very simple answer! But I don't think you could divide by $x$ without using L'hopital's rule...
Answer: $x - \sqrt{x(x+1)}$
$ = x(1 - \sqrt{ {x(x+1) \over x^2} })$
$ = x(1 - \sqrt{ 1 + {1 \over x}})$
$ = x(1 - \left[ 1 + {1 \over 2x} - {1 \over 8x^2} + \ldots \right])$
$ = x(-{1 \over 2x} + {1 \over 8x^2} + \ldots )$
$ = -{1 \over 2} + {1 \over 8x} + ...$
When you take $\lim_{x \rightarrow \infty}$, the first term $-{1 \over 2}$ survives and other terms $\rightarrow 0$.
Comment: I really like this answer since it uses asymptotics. Will accept it when the time limit ends
Answer: Let $y=\sqrt{x^2+x}$, then replace $y\to\dfrac1y$ to recover a derivative. $$\begin{align*}
\lim_{x\to\infty} \left(x-\sqrt{x^2+x}\right) &= \lim_{y\to\infty}\left(\frac{\sqrt{4y^2+1}-1}2-y\right) \\
&= -\frac12 + \lim_{y\to\infty} y \left(\sqrt{1+\frac1{4y^2}} - 1\right) \\
&= -\frac12 + \lim_{y\to0^+} \frac{\sqrt{1+\frac{y^2}4}-1}{y} \\
&= -\frac12 + \frac{d\sqrt{1+\frac{y^2}4}}{dy}\bigg|_{y=0} = \boxed{-\frac12}
\end{align*}$$
Answer: You can multiply and divide that difference by its conjugate to get a difference of squares in the numerator, end up with a fraction with numerator $x$, and then divide by $x$ every term to end up with a limit you know how to operate.
Answer: For the term $ \ \sqrt{x(x+1)} \ \ , \ $ one can also "complete the square" under the radical to obtain $ \ \sqrt{x^2 + x } $ $ = \ \sqrt{\left( x + \frac12 \right)^2  \ - \ \frac14} \ \ . \ $  The curve for this function is then the "upper half" of the hyperbola $ \ \left(x + \frac12 \right)^2 \ - \ y^2 \ = \ \frac14 \  \ , \ $ for which the asymptotes are $ \  y \ = \ | \ x + \frac12 \  | \ \ . \  $   The "limits at infinity" for our function are then
$$ \lim_{x \ \rightarrow \ +\infty} \ x \ - \ \sqrt{x(x+1)} \ \ \rightarrow \ \ \lim_{x \ \rightarrow \ +\infty} \ x \ - \ \left| \ x + \frac12 \  \right| \ \ = \ \ \lim_{x \ \rightarrow \ +\infty} \ x \ - \ \left( \ x + \frac12 \  \right) \ \ = \ \ -\frac12 \ \ , $$
$$ \lim_{x \ \rightarrow \ -\infty} \ x \ - \ \sqrt{x(x+1)} \ \  \rightarrow \ \ \lim_{x \ \rightarrow \ -\infty} \ x \ + \ \left( \ x + \frac12 \  \right) \ \  = \ \ \lim_{x \ \rightarrow \ -\infty} \ 2x \ + \  \frac12 \   \ \ = \ \ -\infty \ \ . $$


trying to stabilize a Type 2 system

Question: I got the system:
$$
P_2(s) = \frac{s+12}{s(s-3)}
$$
Sketching the root locus plot of this system I see that I can stabilize it with
$$ k > 3.1 $$

Now, I want the closed loop system's response to have a steady state error of 5% with a ramp signal as an input.
I used (Which I'm guessing I did wrong)
$$ ess = 0.05 = \frac{1}{K_v} \quad K_v = 20 = \lim_{s \Rightarrow 0 } s\cdot k \cdot \frac{s+12}{s(s-3)} $$
Which yields $ k = -5 $ But I need $ k > 3.1 $ for the system to be stable. Should I take k=5 ? If so, then why Can I justify taking the absolute value ?
It's been a while since I've done these calculations so help would be appreciated!
Comment: What is the transfer function from setpoint to tracking error?
Answer: Given a reference signal $R(s)$ and the reference to error transfer function $G(s)$ then the error signal is,
$$E(s) = G(s)\,R(s)$$
The steady-state error is the final value of this signal which can be found using final value theorem as you did already. The right hand side of your last equation computes
$$\lim_{t\to\infty} e(t).$$
The mistake is that the first equation should be asking that,
$$\|e_{ss}\| \leq 0.05$$
since you can of course have negative steady-state error just as much as you can have positive steady-state error. You want to have the steady-state error be bounded above and below by $0.05$. If you propagate that absolute value, you should have a bound on $\|k\|$ which then yields the desired result.

trying to stabilize a Type 2 system


Contador de cliques únicos em php com time de 12 horas

Question: Olá, estou tentando criar um contador de cliques que grave um log no banco de dados para gravar o IP do visitante para que ao ele clicar no link o contador de cliques só grave se ele clicou após 12 horas do último clique e ele deu no mesmo link.
no banco de dados já tenho a tabela log_clicks

Meu código PHP esta desta forma, ele já esta gravando o uid que seria o id do link, ip e o time() + 60*60*12 que seria 12 horas a frente para depois fazer o if(time() > $row_rsClicks['**time']) que tbm já esta funcionando certinho.
O que preciso agora é saber como fazer para que verifique na tabela log_clicks se o IP já clicou no link com o uid X se sim ele então verifica se quando ele clicou já passou de 12 horas se já passou então grave outro log.
Minha ideia é fazer este contador de cliques como deste site https://www.gamestop200.com/ a onde seu clique é somado apenas a pós 12 horas.
$colname_rsClicks = "-1";
if (isset($_GET['uid'])) {
  $colname_rsClicks = $_GET['uid'];
}
mysql_select_db($database_connectDB, $connectDB);
$query_rsClicks = sprintf("SELECT * FROM log_clicks WHERE site_uid = %s", GetSQLValueString($colname_rsClicks, "int"));
$rsClicks = mysql_query($query_rsClicks, $connectDB) or die(mysql_error());
$row_rsClicks = mysql_fetch_assoc($rsClicks);
$totalRows_rsClicks = mysql_num_rows($rsClicks);

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if (isset($_GET["uid"])) {
    if(time() > $row_rsClicks['time']){
  $insertSQL = sprintf("INSERT INTO log_clicks (site_uid, time, ip) VALUES (%s, %s, %s)",
                       GetSQLValueString($_GET['uid'], "text"),
                       GetSQLValueString(time() + 60*60*12, "int"),
                       GetSQLValueString($_SERVER['REMOTE_ADDR'], "text"));

  mysql_select_db($database_connectDB, $connectDB);
  $Result1 = mysql_query($insertSQL, $connectDB) or die(mysql_error());

  $insertGoTo = "/";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
}

echo $totalRows_rsClicks;
mysql_free_result($rsClicks);

Answer: Você tem o ID do link, IP do usuário.
Então no primeiro clique do usuário em um link, você aumenta o click para 1, e seta um campo proximo_clique = hora atual + 12.
Quando o usuário clicar no link você verifica, já existe esse IP registrado para esse ID de link? Caso afirmativo, você verifica, a hora atual é maior ou igual ao campo proximo_clique ? Caso afirmativo, você aumenta em um o clique, caso negativo você não aumenta.
Você pode ter uma tabela, com os campos, ID_LINK, IP, CLICKS, NEXT_CLICK...
SELECT * WHERE ID_LINK="link_clicado" AND IP="current_user_ip".....
Comment: já consegui fazer funcionar vlw


Sort an array with the sort method in javascript

Question: I have written this code but it isn't working . It's displaying the unsorted array as well as the button but when I click on the button nothing happens.
I am new to javascript. What I know so far is that we can call functions using the onclick method by javascript. We can write functions as we write in c or c++ . That's what I think I have done here but it isn't showing the sorted array .

var myarray = [4, 6, 2, 1, 9, ];
document.getElementById("demo").innerHTML = myarray;

function sort(myarray) {
  var count = array.length - 1,
    swap,
    j,
    i;

  for (j = 0; j < count; j++) {
    for (i = 0; i < count; i++) {
      if (array[i] > myarray[i + 1]) {
        swap = myarray[i + 1];
        myarray[i + 1] = myarray[i];
        myarray[i] = swap;
      }
    }
    document.write(myarray);
  }
}

Click the button to sort the array.

<button onclick="sort()">Try it</button>

Comment: @mmm its attached to button click.  Also @Nancy, you should check your console. there is an error `array is not defined`
Comment: Check you function, then check console, there are obvious errors in your code (hint: array vs myarray). And stop using document.write.
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Answer: The main problem is, to decide if a parameter should be set or not. If not, then use myarray for all operations. If you decide to use a parameter, then use only the parameter variable.

var myarray = [4, 6, 2, 1, 9, ];
document.getElementById("demo").innerHTML = myarray;

function sort() {                                        // no need for a parameter
    var count = myarray.length - 1,                      // change it to myarray
        swap,
        j, i;

    for (j = 0; j < count; j++) {
        for (i = 0; i < count; i++) {
            if (myarray[i] > myarray[i + 1]) {           // access only myarray
                swap = myarray[i + 1];
                myarray[i + 1] = myarray[i];
                myarray[i] = swap;
            }
        }
    }
    document.getElementById("demo").innerHTML = myarray; // return the sorted array
}

Click the button to sort the array.

<button onclick="sort()">Try it</button>

Answer:

var myarray = [4, 6, 2, 1, 9];
document.getElementById("demo").innerHTML = myarray;

function sort(myarray) {
  var count = myarray.length - 1,
    swap,
    j,
    i;

  for (j = 0; j < count; j++) {
    for (i = 0; i < count; i++) {
      if (myarray[i] > myarray[i + 1]) {
        swap = myarray[i + 1];
        myarray[i + 1] = myarray[i];
        myarray[i] = swap;
      }
    }
  }
 document.getElementById("result").innerHTML = myarray;
}

Click the button to sort the array.

<button onclick="sort(myarray)">Try it</button>

Answer: I found 2 problems with your code. The first is that you wrote array instead of myarray in 2 lines:
var count = array.length - 1,

and
if (array[i] > myarray[i + 1]) {

The second problem is that you didn't pass your array as argument, when calling the function, so:
<button onclick="sort()">Try it</button>

should be:
<button onclick="sort(myarray)">Try it</button>

Answer: Firstly you array definition has an extra , at the end.
Next, you have made use of array and not myarray in the if statement.
Once you sort, you need to have a statement:
document.getElementById("demo").innerHTML = myarray;
Comment: Its fine to use arrays with extra `,`. this does not gives any errors.
Answer: You are using a variable 'array' which is not defined or known to the function. Moreover on buttonclick you are not passing any parameter to sort function. That's the reason you're getting an error.
var myarray = [4, 6, 2, 1, 9, ];

function sort(myarray) {
  var count = myarray.length - 1,
    swap,
    j,
    i;

  for (j = 0; j < count; j++) {
    for (i = 0; i < count; i++) {
      if (myarray[i] > myarray[i + 1]) {
        swap = myarray[i + 1];
        myarray[i + 1] = myarray[i];
        myarray[i] = swap;
      }
    }
    document.write(myarray);
  }
}

Click the button to sort the array.

<button onclick="sort(myarray)">Try it</button>


Baire one extension of continuous functions

Question: I struggle with the following comment in Sierpinski's Hypothèse du continu, p. 49.
For every continuous function $f(x):X \rightarrow \mathbb{R}$, where $X \subseteq \mathbb{R}$, there exist a Baire one function $g(x): \mathbb{R} \rightarrow \mathbb{R}$ such that $g(x) = f(x)$ for all $x \in X$.
What if both $X$ and $\mathbb{R}\backslash X$ are dense and uncountable ?
Answer: I think it can be proved by the following:
For arbitrary $X\subset\mathbb{R}$, continuous $f:X\longrightarrow\mathbb{R}$ can be extended to a function $F:\mathbb{R}\longrightarrow\mathbb{R}$ such that $F^{-1}(A)$ is a $G_\delta$ set in $\mathbb{R}$ for every closed $A\subset\mathbb{R}$ (a Lebesgue-one function such that $F|_X=f$).
Then the Lebesgue-Hausdorff theorem implies that the Lebesgue-one function $F$ is also Baire-one.
Comment: How do you get such $F$? Sorry for being slow, but I'm unfamiliar with this area and would like to know a little more. If you could point to a good source, that would be extra helpful.
Comment: I was able to recall the reference: Kuratowski, Topology, Volume 1, p445.


Different users coming through VPN to my service

Question: I have a web service (php, sql etc) running on an AWS account. I have openVPN setup, so users must establish the VPN connection, then the IP address will work.
I currently have this set as example123.noip.com which goes to 172.xxx.xxx.123
And this works.
My service is taking off, and I want to be able to offer it to other firms, BUT i want to be able to keep multiple firms hosted on the same AWS instance, but I would like to give each company a seamless experience, so for example I am thinking i can setup more noip addresses:
clientcompany1.noip.com -> 172.xxx.xxx.123
clientcompany2.noip.com -> 172.xxx.xxx.123
clientcompany3.noip.com -> 172.xxx.xxx.123
So Mr X from Company3 goes to clientcompany3.noip.com and it will show his my service pages branded as Company 3... (they will not be aware other companies are hosted on that aws account)
(and some point I might need to add a separate AWS instance, and then I can just flip
clientcompany3.noip.com -> 172.xxx.xxx.new address 456)
BUT - what is the best way to detect or route this within AWS?
Do I just do some redirection detection from the HTTP headers using PHP?
Is there a clever way to have traffic routed in with openVPN?
Comment: My current thinking is that i use $SERVER['HTTP_HOST'] in a header on my PHP.
Answer: Ok, so I think the best way is to route my domain via Cloudflare.
I can then have subdomains defined as A records, routing to the private IP or public IP addresses for each service (so some users might have a static IP address which I can allow through the AWS firewall rules, so these are routed to the public IP address), whereas the rest have to activate the VPN and then that routes to the VPN private address.
My PHP header checks the SERVER['HTTP_HOST'] and will detect e.g. "clinicABC.example.com" and present the branding for ABC Clinic.