Como chamar e exibir um Janela WPF que está em uma dll

Question: Tenho uma DLL contendo uma janela WPF, criada através de um projeto do tipo WPF User Control Library.
Como faço para exibir essa janela a partir de um outro projeto?
XAML da janela (projeto DLL):
<Window x:Class="UmaJanelaComUmBotao.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:UmaJanelaComUmBotao"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="112,55,0,0" VerticalAlignment="Top" Width="75"/>

    </Grid>
</Window>

Código C# da janela (projeto DLL):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace UmaJanelaComUmBotao
{
    ///
    /// Lógica interna para Window1.xaml
    ///
    public partial class Window1 : Window
    {
        public Window1 ( )
        {
            InitializeComponent ( );
        }
    }
}

Se for necessário o codebehind posso está postando também.
Método main (projeto .exe)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UmaJanelaComUmBotao;

namespace OExcutavel
{
    class Program
    {
        static void Main ( string[ ] args )
        {
            //Como chamar Window1 a partir daqui
        }
    }
}

codebehind:
namespace UmaJanelaComUmBotao {

    ///
    /// Window1
    ///
    public partial class Window1 : System.Windows.Window, System.Windows.Markup.IComponentConnector {

        #line 10 "..\..\Window1.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button button;

        #line default
        #line hidden

        private bool _contentLoaded;

        ///
        /// InitializeComponent
        ///
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "184.108.40.206")]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/UmaJanelaComUmBotao;component/window1.xaml", System.UriKind.Relative);

            #line 1 "..\..\Window1.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "184.108.40.206")]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:
            this.button = ((System.Windows.Controls.Button)(target));
            return;
            }
            this._contentLoaded = true;
        }
    }
}

Comment: Tentou um `new App().Run();`? Tem um `App.Xaml` configurado? O `StartupUri` está com o `Window1`?
Comment: Pior que não, não tentei nada disso, não sei nem por onde começar, toda a literatura não aborda em como fazer isso assim. Geralmente sempre deixam que a IDE gere tudo.
Eu não tenho um App.xaml pq o projeto do executável é do tipo `Console Application`.
Tenho uma linha referente a URI no codebehind, vou editar e postar o mesmo.
Comment: WPF e Console não combinam.
Comment: @MatheusSaraiva, você já gerou a DLL ?
Answer: Para isso funcionar você deve fazer os seguintes passos:
1º - Adicione as seguintes referencias no projeto console: PresentationFramework, WindowBase e PresentationCore.
2º - Deve adicionar a referencia a DLL que você criou, caso você já tenha criado a DLL.
Fiz um teste básico com este código e está funcionando:
using System;
using WpfApplication4;

namespace ConsoleApplication7
{
  class Program
  {
    [STAThread]
    static void Main(string[] args)
    {
        MainWindow main = new MainWindow();
        main.ShowDialog();
    }
  }
}

Segue imagem:

Fonte: Aqui, aqui e aqui.
Comment: Vou testar e dou o feedback.
Comment: Sim, marquei como respondido pois realmente funcionou. Mas não era bem esse resultado que eu tinha em mente.
Ao executar, uma janela de console é aberta junto com a janela, e eu não queria isso. Provavelmente é devido ao projeto do tipo console como o @bigown citou.
Minha ideia é deixar todo o front-end da aplicação fora do executável, ou seja, dentro de uma `dll`.
O executável deve ser "burro", servindo apenas para startar a aplicação. bac-kend e front-end ficariam em `dlls`.
Por isso pensei em um projeto console, pois é o executável mais básico que existe.
Comment: Entendi, da uma pesquisas sobre projeto em camadas, aí você vai conseguir fazer o que querendo. Resumindo grosseiramente, você cria uma projeto "exe" com wpf, e outro projeto do tipo biblioteca de classes com suas regras de negócios.
Comment: Entendi, eu já conheço o modelo de camadas, mas nesse caso que você cita o front-end ou ao menos parte dele (Janela Principal, ou um splash) ficaria no executável assim fugiria da minha ideia que é ter 0 GUI no executável. GUI e regras de negócios ficariam em `DLLs` distintas. A maioria das pessoas usa o trivial que é a GUI empacotada com o executável.
Mas estou começando a achar que é impossível fugir disso.
Comment: Acho que talvez o caminho seja [esse](http://stackoverflow.com/a/25381844/5913854), ou seja, realmente o tal arquivo App.xaml como citou o **bigown** citou.
Comment: Encontrei um material que pode ajudar: http://www.wpf-tutorial.com/wpf-application/working-with-app-xaml/


How to optimally configure memcache running on 16 cores 144G ram server?

Question:
Memcache is the only important app running on the server
Server has 16 cores and 144G RAM
Memcache is given 135G
Memcache runs at 32 threads
Gigabit network, test shows at least 300Mbit/s availability on network port
600 connections
3000 requests per second
Say that memcache (memory) usage is at 50% - it's definitely not full

As we increase number of requests towards server, requests slow down (from 8ms to 100ms per request) but server load remains 0.00. We suspect this can be solved by adjusting configuration but we don't understand many of the configuration parameters (besides, maybe, the number of threads).
Any ideas?
Comment: Have you looked into using Redis instead of Memcached?
Comment: Have you considered profiling the application (my assumption that you have one) that uses `memcached`? Maybe tracing a slow `memcached` process?
Answer: How many concurrent connections are open on this single machine?  Have you increased the file descriptor limit in limits.conf for the user running memcached?
It's possible that you're reaching a file descriptor limit, which will cause new TCP connections to be dropped.  And depending on your memcache client, this may result in a perceived slower response time.
Comment: good idea, however, that's seems fine... $ulimit -a -> open files (-n) 30000 .... and $ lsof | wc -l -> 1097


Python's sh module - Running Command wrapper in background

Question: When using python's sh module (not a part of stdlib), I can call a program in my path as a function and run it in the background:
from sh import sleep

# doesn't block
p = sleep(3, _bg=True)
print("prints immediately!")
p.wait()
print("...and 3 seconds later")

And I can use sh's Command wrapper and pass in the absolute path of an executable (helpful if the executable isn't in my path or has characters such as .):
import sh
run = sh.Command("/home/amoffat/run.sh")
run()

But trying to run the wrapped executable in the background, as follows:
import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True)
run()

Fails with a traceback error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument '_bg'

How can I run an executable wrapped by sh.Command in the background? Looking for an elegant solution.
EDIT:
I used the python interpreter for testing passing _bg to the command (not the wrapper), which I now realize is a bad way to test for blocking and non-blocking processes:
>>> import sh
>>> hello = sh.Command("./hello.py")
>>> hello(_bg=True) # 5 second delay before the following prints and prompt is returned
HI
HI
HI
HI
HI

With hello.py being as follows:
#!/usr/bin/python

import time

for i in xrange(5):
    time.sleep(1)
    print "HI"

Comment: You could use popen / subprocess.
Answer: import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True) # this isn't your command,
                                                   # so _bg does not apply
run()

Instead, do
import sh
run = sh.Command("/home/amoffat/run.sh")
run(_bg=True)

(BTW, the subprocess module provides a much less magical way to do such things.)
Comment: It looks like `_bg` doesn't apply to the command either. This is what I originally attempted before trying to pass `_bg` into the `sh.Command` wrapper. I should have mentioned that.
Comment: @billyw, Post a complete, runnable file and your full traceback for the case where you do this.
Comment: "It turns out I needed to assign the running command to a variable" <-- You're still misunderstanding what's going on. You should post your complete, real, preferably runnable code and something the corresponding output that shows what's happening.
Comment: Your solution wasn't causing a traceback, it was that the process was still blocking. It turns out I needed to assign the running command to a variable, i.e. `p = run(_bg=True)`. Running `run(_bg=True)` alone caused the process to block. You solved the problem that I originally posted, though, so I will accept this as the correct answer.
Comment: You'll need to give `run(...)` a name if you want to call a method on it later, of course, but it doesn't alter the behavior you're mentioning.
Comment: I edited my post with more information. I was testing `sh` in the python interpreter, not by running it in a file (whoops). Thanks for following up on my misunderstandings.
Comment: Can I keep on running this background process in the background even after the python script exits?


Finding all functions $f: [0, +\infty)\to \mathbb{R}$ with the properties $f^2(x)=k^2+x\cdot f(x+k)$ and $\frac{x+k}{2}\le f(x) \le 2\cdot (x+k)$

Question:
Let $f: [0, +\infty)\to \mathbb{R}$ be a function such that for one $k\in [0, +\infty)$:
$$f^2(x)=k^2+x\cdot f(x+k) \quad \forall x\in [k, +\infty) \tag 1 \label 1$$
and
$$\frac{x+k}{2}\le f(x) \le 2\cdot (x+k) \quad \forall x\in [k, +\infty) \tag 2 \label 2$$
Find all such functions $f$.

I have tried the following:
From \eqref{2}, with substitution $x=-k$ we get $0\le f(-k) \le 0$, so $f(-k)=0$. Then, from \eqref{1} with substitution $x=-k$ we get $0=k^2-k\cdot f(0)$, so $f(0)=k$, which is easily verifiable even when $k=0$.
I also see that $f(x)=x+k$ is a valid function. Any hint how to find ALL such functions? (I believe the above is the only function.)
Edit: As Hagen Von Eitzen noted, I cannot use the substitution $x=-k$, because both $x$ and $k$ are non-negative numbers...
Comment: You can't use $x=-k$ because $x$ and $k$ must both be $\ge 0$. Also, it seems that $f$ can be arbitrary on $[0,k)$
Answer: If we require that $(1)$ and $(2)$ hold for all $x\ge 0$, then $f(x)=x+k$ is the only solution. (It is a solution in the first place because clearly $(x+k)^2=k^2+x(x+2k)$ and $\frac{x+k}{2}\le x+k\le 2(x+k)$).
First consider the case $k=0$. Then $(1)$ translates to $f(x)^2=xf(x)$, so $f(x)=x$ or $f(x)=0$; and $(2)$ becomes $\frac x2\le f(x)\le 2x$ so that indeed $f(x)=x$ for all $x\ge 0$.
Assume $k>0$.
For $x\ge 0$ let $c(x)=\frac{f(x)-(x+k)}{k}$.
Then
$$\tag3-\frac{x+k}{2k}\le c(x)\le \frac{x+k}{k}$$
For $x>0$ we have $$\begin{align}f(x+k)&=\frac{f(x)^2-k^2}{x}\\&=\frac{(x+(c(x)+1)k)^2-k^2}{x}\\&=\frac{x^2+2(c(x)+1)kx_0+((c(x)+1)^2-1)k^2}{x}\\
&=x+2k\,+\,2c(x)k+\frac{c(x)(c(x)+2)k^2}{x}\end{align}$$
i.e.,
$$c(x+k)=2c(x)+\frac{c(x)(c(x)+2)k}{x} $$
If for some $x>0$ we have $c(x)>0$ this implies $c(x+k)>2c(x)$ and by induction $c(x+nk)>2^nc(x)\to\infty$. As exponentials grow faster than polynomials, we obtain a contradiction with $(3)$. We conclude $c(x)\le 0$ (that is: $f(x)\le x+k$) for $x>0$.


Increasing convex function eventually greater than increasing concave function

Question: Suppose that $f, g$ are non-negative and infinitely differentiable from $\mathbb{R}_+$ to $\mathbb{R}_+.$
Suppose that:

$f,g$ are increasing.
$f$ is strictly concave and $g$ is strictly convex.
$f(0) = g(0)$.
There exists $\epsilon > 0$ such that $f(\epsilon) > g(\epsilon)$

I want to show that there exists $M > \epsilon$ such that $x \ge M$ implies that $f(x) \le g(x)$, perhaps after adding some extra conditions (see answer below). Intuitively, it makes sense: $f$ will increase at a lower rate than $g$ more and more as $x$ increases. I've tried formalizing this argument with a Taylor expansion, but I didn't succeed.
Answer: This is not true, for example, if the functions are both straight lines.
Even if the functions are strictly convex and strictly concave, I would not expect this to be true, for example, if the slopes converge to certain values for both functions: the concave function can still have the slope greater than the convex function for all time $>0$. I have not worked this out though, completely, and I might be wrong.
Comment: Great, thanks. I expect it to be true under some extra conditions. I forgot to add strict concavity or convexity in the statement.


Laurent expansion of $\frac{e^{z^2}}{z^2}$

Question: I've come across a problem that, the question is as follows.
Determine the Laurent Series of $\frac{e^{z^2}}{z^2}$ about $z = 0$.
How would I get started on doing this problem? Any help is much appreciated.
Answer: You can use the power series for the exponential function:
$$e^u=\sum_{n=0}^{+\infty}\frac {u^n}{n!}$$
With this
$$\frac {e^{z^2}}{z^2}=\sum_{n=0}^{+\infty}\frac{z^{2n-2}}{n!}=\frac 1 {z^2}+ \sum_{n=0}^{+\infty}\frac{z^{2n}}{(n+1)!}$$
Answer: Start with the Taylor expansion for $e^x$:
$$e^x=\sum_{n=0}^{\infty} \frac {x^n}{n!}$$
Then substitute $x=z^2$:
$$e^{z^2}=\sum_{n=0}^{\infty}\frac {z^{2n}}{n!}$$
And divide by $z^2$:
$$\frac {e^{z^2}}{z^2} = \sum_{n=0}^{\infty} \frac {z^{2n-2}}{n!}$$
Then, it might be desirable to adjust the index with the substitution i=n-1:
$$\frac {e^{z^2}}{z^2} = \sum_{i=-1}^{\infty} \frac {z^{2i}}{(i +1)!}$$


GoogleSQL in BigQuery evaluating IF always True inside FOR-loop but False if manually checked

Question: Goodmorning everyone,
recently we started to use BigQuery in my current company to analyze an enormous amount of data (around 4TB) from a client.
Apparently a lot of columns in some table seems to be always Null, but since we are speaking of tables with more than 90 columns for something around 13 tables we tried to write down a function to get an Array of Columns with at least a Non-Null value, and then we'll create some views from the returned Array.
The SQL Script is the following:
DECLARE r ARRAY <STRING>;
SET r = [];

FOR var IN (SELECT column_name FROM `project-name.dataset.INFORMATION_SCHEMA.COLUMNS`
  WHERE table_name LIKE "table_name") DO
    IF EXISTS(SELECT var.column_name FROM `project-name.dataset.table_name`
      WHERE var.column_name IS NOT NULL) THEN
        SET r = ARRAY_CONCAT(r, [var.column_name]);
    END IF;
END FOR;

SELECT r;

I'm not quite fond of SQL, I'll be glad of any help, I've tried to follow the conventions and examples from the documentation of BigQuery
We tried to manually replicate the behaviour on a column with the following code, evaluating False returning 0:
IF EXISTS(SELECT column_name FROM `project-name.dataset.table_name` WHERE column_name IS NOT NULL) THEN
  SELECT 1;
ELSE
  SELECT 0;
END IF;

yet while executed inside the for loop seems to always evaluate as True.
Comment: Hi @zigb11 you should consider using Google Cloud Dataplex instead of using sql. See this documentation which allows you to run data quality scan across multiple tables https://cloud.google.com/dataplex/docs/use-auto-data-quality#create-scan and as well as using pre-defined rules for null checks, see the (Null check) rule in the documentation https://cloud.google.com/dataplex/docs/auto-data-quality-overview#predefined-rules
Answer:
Lets go to the definition of Exists in Big Query:

https://cloud.google.com/bigquery/docs/reference/standard-sql/subqueries#exists_subquery_concepts
Returns TRUE if the subquery produces one or more rows.

Now simple example in BQ
CREATE TEMP TABLE test
(
id INT64,
name STRING
);
INSERT INTO test
VALUES (1, NULL);
INSERT INTO test
VALUES (2, NULL);
INSERT INTO test
VALUES (3, NULL);

I created temp table called 'test'

Added two columns: id, name

'name' column contains only NULLS

Then let's do a simple trick
SELECT name FROM test
      WHERE test IS NOT NULL;

And then result will be

Or if we apply EXISTS to the query:

So, that's where's the problem hidden I believe. Hope this helps.


Problema com título e botão estáticos

Question: Estou tendo problema com um H1 e um link com classe dentro de uma div, que não sobem ou descem do jeito que quero. Já tentei resolver isso usando margin-top e margin-bottom, mas não obtive o efeito que almejo. Quando uso essas propriedades, acontece colapso. Eles ficam dentro de uma imagem, inserida via CSS Segue código:

.container {
    width: 980px;
    margin: 0 auto;
}

.hero-image {
    background: url('http://i.imgur.com/uCRNEAF.jpg');
    background-repeat: no-repeat;
    padding: 100px;
    text-align: center;
    margin-top: 1.2em;
}

.hero-image h1 {
    font-size: 28px;
    font-family: 'Oswald', sans-serif;
    text-transform: uppercase;
    color: #ffffff;
    margin-bottom: 0.5em;
}

/* Button */
.botao {
   font-family: 'Oswald', sans-serif;
   color: #ffffff;
   text-decoration: none;
   padding: 5px 10px;
   background-color: #1989ca;
   font-size: 0.9em;
   border-radius: 4px;
}

ESTE É MEU TÍTULO!

HISTÓRIA

Comment: Qual o comportamento que você está procurando?
Comment: Opa Thiago. É o alinhamento central desse título da tag H1 e o botão logo abaixo, porém com um espaçamento entre eles. O que estou tentando fazer é colocá-los ambos mais para cima.
Answer: Eu alterei um pouco os teus estilos para que ficasse mais fácil editar, eu apliquei um padding: 250px; na classe .hero-image e manipulei a margin-top e margin-bottom do H1 livremente:

.container {
    width: 980px;
    margin: 0 auto;
}

.hero-image {
    background: url('http://i.imgur.com/uCRNEAF.jpg');
    padding: 250px;
    text-align: center;
}

.hero-image h1 {
    font-size: 28px;
    font-family: 'Oswald', sans-serif;
    text-transform: uppercase;
    color: #ffffff;
    margin-top: -100px;
    margin-bottom: 25px;
}

/* Button */
.botao {
   font-family: 'Oswald', sans-serif;
   color: #ffffff;
   text-decoration: none;
   padding: 5px 10px;
   background-color: #1989ca;
   font-size: 0.9em;
   border-radius: 4px;
}

ESTE É MEU TÍTULO!

HISTÓRIA

Comment: Obrigado pela ajuda, **Thiago**! Grande abraço.

Problema com título e botão estáticos


Probability distribution of the distance of a point in a square to a fixed point

Question: The question is, given a fixed point with coordinates X,Y, in a square of size N. What is the probability distribution of the distance to a random point. More specifically, what is the probability distribution of the square root of the square sum of 2 randomly independent uniform variables (0,N).
Comment: Your "specifically" suggests the distance from a random point to the point $(0,0)$. Are you asking about the distance from a random point to an arbitrary $(X,Y)$ or to $(0,0)$?
Comment: Well, the calculation should be extremely similar, thats whay I thought about the simple case, and then I could extend it to a general one.
Answer: To find the distribution of the distance between the origin, $(0,0)$ and a random point on the unit square $(0,1)^2$ we can integrate over the area that is within $d$ of the origin. That is, find the cdf $P(\sqrt{X^2 + Y^2} \leq d)$, then take the derivative to find the pdf. Extensions to the square $(0,N)$ are immediate.
Case 1: $ 0 \leq d \leq 1$
$$
F_{D}(d) = P(\sqrt{X^2 + Y^2} \leq d) = P(X^2 + Y^2 \leq d^2) \\
= \int_{0}^{d} \int_{0}^{\sqrt{d^2-x^2}}1dydx \\
= \int_{0}^{d} \sqrt{d^2 - x^2}dx\\
= \frac{d^2\pi}{4}
$$
Case 2: $1 \leq d \leq \sqrt{2}$
$$
F_{D}(d) = \int_{0}^{\sqrt{d^2 - 1}} 1 dx + \int_{\sqrt{d^2 - 1}}^{1}\int_{0}^{\sqrt{d^2-x^2}}1dydx \\
=\sqrt{d^2-1} + \int_{\sqrt{d^2-1}}^{1}\sqrt{d^2-x^2}dx\\
= \sqrt{d^2 -1} + \frac{1}{2}\left\{t\sqrt{d^2-t^2}+d^2\tan^{-1}\left(\frac{t}{\sqrt{d^2-t^2}}\right) \right\}|_{\sqrt{d^2-1}}^{1} \\
= \sqrt{d^2-1} + \frac{1}{2}\left\{\sqrt{d^2-1}+d^2\tan^{-1}\left(\frac{1}{\sqrt{d^2-1}}\right) - \sqrt{d^2-1}\sqrt{1}-d^2\tan^{-1}\left(\frac{\sqrt{d^2-1}}{1}\right)\right\} \\
=\sqrt{d^2-1} + \frac{d^2}{2}\left\{ \tan^{-1}\left(\frac{1}{\sqrt{d^2-1}}\right)-\tan^{-1}\left(\sqrt{d^2-1}\right)\right\}
$$
Taking the derivative gives the density
$$
f_{D}(d) = \frac{d\pi}{2}, 0 \leq d \leq 1\\
f_{D}(d) = d\left\{\tan^{-1}\left(\frac{1}{\sqrt{d^2-1}}\right)-\tan^{-1}(\sqrt{d^2-1})\right\}, 1 \leq d \leq \sqrt{2} \\
$$
Comparing the result with @BruceET's simulation answer on Expected average distance from a random point in a square to a corner, we find it matches exactly.
<code>den <- function(d) {
  if(d < 0) {
    return(0)
  }
  if(d < 1) {
    return(d*pi/2)
  }
  if(d < sqrt(2)) {
    return(d*(atan(1/sqrt(d^2-1)) - atan(sqrt(d^2-1))))
  }
  if(d > sqrt(2)) {
    return(0)
  }
  stop()
}
ys <- xs <- seq(from=0,t=1.42,by=0.01)
for(i in seq_along(xs)){
  ys[i] <- den(xs[i])
}

set.seed(2021)
x = runif(10^6);  y = runif(10^6)
d = sqrt(x^2 + y^2)
hist(d, prob=T, br=seq(0,1.42,0.02),xlim=c(0,1.5),ylim=c(0,1.5))
lines(xs,ys,col="red",lwd=2)
</code>

Created on 2021-06-15 by the reprex package (v2.0.0)
By symmetry this is equal to the distance between random points and $(0,1)$, $(1,0)$, and $(1,1)$. Finding the distance to a point on the boundary or the interior of the square will require considering more cases in the cumulative probability function.
Comment: Thank you very much, this is really cool btw! This is tied now to my real objective. I have a stimuli at random fixed point in the grid, and measure the appearance of X,Y points in the experiment, and want to test if the distance to the stimuli is randomly distributed. Thank you a lot! In handsight, it probably would've just been a lot easier to test X and Y separately and perform multiple testing correction.


Building a select with optgroup from a SQL query

Question: I have the following table:
___Titles
| TIT_Id | TIT_en | TIT_Popularity |
| 1      | Sir    | High           |
| 2      | Madam  | High           |
| 2      | Emir   | Low            |

How can I have this select ?
<select>
  <optgroup label="High">
    <option value='1'>Sir</option>
    <option value='2'>Madam</option>
  </optgroup>
  <optgroup label="Low">
    <option value='3'>Emir</option>
  </optgroup>
</select>

I tried:
SELECT TIT_Id, TIT_en FROM ___Titles
GROUP BY TIT_Popularity
ORDER BY TIT_en ASC

Thanks.
Answer: How about this.  Fetch your results using a query like this:
SELECT * FROM ___Titles ORDER BY TIT_Popularity;

This will essentially group your results together by their TIT_Popularity.  You can then iterate over them like this:
echo "<select>\n";

$currentGroup = null;
foreach( $results as $result ) {
    // start a new optgroup
    if( $currentGroup == null || $result->TIT_Popularity != $currentGroup ) {
        // end the previous group
        if( $currentGroup != null ) {
            echo "</optgroup\n>";
        }

        // start a new group
        echo "<optgroup label='{$result->TIT_Popularity}'>\n";

        $currentGroup = $result->TIT_Popularity;
    }

    echo "<option value='{$result->TIT_Id}'>{$result->TIT_en}</option>\n";
}

// end the last opt group
if( $currentGroup != null ) echo "</optgroup>\n";

echo "</select>\n";

Comment: @MujahedAKAS It only outputs a new optgroup when the value of `TIT_Popularity` changes.  So the first time it changes, a new one is output, and another won't be output until the `TIT_Popularity` changes again.  So, as long as `TIT_Popularity` stays the same, all entries will be output in that same optgroup.  Just reason through the logic of the `if` statement until it makes sense.
Comment: Then you don't have any elements in `$results`.  Try `var_dump($results)` to see what's in there.  If nothing, try running your query manually to see if you get any results that way and also check if your query is giving you errors.
Comment: The var_dump game me:
array(3) { ["TIT_Id"]=> string(1) "1" ["TIT_fr"]=> string(8) "Monsieur" ["TIT_Popularity"]=> string(4) "High" }
Comment: That's one record, not a collection of records.  `$results` in this example would be all of the records.  You can replace the `foreach` with something like `while ($result = mysql_fetch_object($resultsIdentifier)) {` or however you've structured your program.
Comment: This answer should give you a general idea of how to solve your problem.  You'll have to adapt it to fit your exact situation.
Comment: I'm using PDO: $results = $query2->fetch(PDO::FETCH_ASSOC);
Comment: Then replace the `foreach` with `while($result = $query2->fetch(PDO::FETCH_OBJ) {`  Or, if you want to use an associative array, just change all of the object calls on $result to associative array calls.
Comment: Simple and straightforward. But how does this process happens?  How it echos option group only once if it is associated with every option. ? Plz explain. .
Answer: Alternatively, you could just process the array from the selected db (since the queries are not inside the question), and just build them and reorder them on that newly created array (provided the popularity is just high/low). Consider this example:
<?php

// dummy data, since no values are provided on the question
$values_from_db = array(
    array('TIT_Id' => 3, 'TIT_en' => 'Emir', 'TIT_Popularity' => 'Low'),
    array('TIT_Id' => 4, 'TIT_en' => 'Test', 'TIT_Popularity' => 'Low'),
    array('TIT_Id' => 1, 'TIT_en' => 'Sir', 'TIT_Popularity' => 'High'),
    array('TIT_Id' => 2, 'TIT_en' => 'Madam', 'TIT_Popularity' => 'High'),

);

$sorted_values = array();
foreach($values_from_db as $key => $value) {
    $sorted_values[$value['TIT_Popularity']][] = array(
        'TIT_Id' => $value['TIT_Id'],
        'TIT_en' => $value['TIT_en'],
    );
}

ksort($sorted_values);

?>

<select name="whatever">
    <option selected disabled>Select Value</option>
<?php foreach($sorted_values as $key => $value): ?>
    <optgroup label="<?php echo $key; ?>">
        <?php foreach($value as $index => $element): ?>
            <option value="<?php echo $element['TIT_Id']; ?>"><?php echo $element['TIT_en']; ?></option>
        <?php endforeach; ?>
    </optgroup>
<?php endforeach; ?>
</select>


$|\phi(G):\phi(H)|$ divides $|G:H|$

Question:
Let $\phi$ be a homomorphism defined on a finite group $G$, and let $H\subseteq G$. Show that $|\phi(G):\phi(H)|$ divides $|G:H|$.

Not quite sure where to start on this one. We have a theorem saying that $\phi(H)$ is a subgroup of $\phi(G)$, but what is $|\phi(H)|$? If $H$ contains the kernel $N$ of $\phi$, then I think everything behaves nicely and $|\phi(G):\phi(H)|=|G:H|$. But if $N\not\subseteq H$, I don't know what I can conclude.
Answer: Hint: $\phi(H) = \phi(NH)$ and $|\phi(G):\phi(NH)| = |G: NH|$.
Note that finiteness of $G$ is not necessary, we only need $|G: H|$ to be finite.
Comment: Are you saying that for every $\phi:G\longrightarrow G'$ group homomorphism, and for every $H$ subgroup of $G$, $(\ker \phi )H$ is a subgroup of $G$?
Comment: @julien This is well-known. It's enough that $NH = HN$ as sets, but since $N$ is normal, $Nh = hN$ elementwise for $h \in H$.
Comment: Right, thanks. I should review my basic algebra... I'll leave my comment for my punishment.
Answer: The important thing is finiteness, then we have that
$$|G:H|=|G|/|H|\text{,}$$
$$|\phi(G):\phi(H)|=|\phi(G)|/|\phi(H)|$$
and
$$|H:H\cap\ker\phi|=|H|/|H\cap\ker\phi|\text{.}$$
Here, remember that by the first isomorphism theorem and finiteness
$$|\phi(G)|=|G:\ker\phi|=|G|/|\ker \phi|$$
and
$$|\phi(H)|=|H:H\cap\ker\phi|=|H|/|H\cap \ker \phi|\text{.}$$
Now, do you see that everything is reduced to divide and rearrange terms in order to obtain the wanted divisibility?
Answer: In one answer it is claimed that $G$ must be finite, in one answer it is claimed that we only need that $|G:H|$ is finite. In fact, no finiteness assumptions are necessary (on the other hand, in the infinite case, the statement is rather boring due to cardinal arithmetic).
Here is an alternative bijective proof, which is perhaps more conceptual and works without any finiteness assumptions: The map $G/H \to \phi(G)/\phi(H), [g] \mapsto [\phi(g)]$ is a well-defined surjective homomorphism of $G$-sets. Thus it suffices to prove:

Lemma. If $f : X \to Y$ is a surjective homomorphism of $G$-sets and $X$ is transitive, then $|Y|$ divides $|X|$. Namely, if $y_0 \in Y$, then $|X|=|Y| \cdot |f^{-1}(y_0)|$.

Proof: Since $f^{-1}(gy)=g f^{-1}(y)$, every fiber of $f$ has the same cardinality $N$. Then $X = \coprod\limits_{y \in Y} f^{-1}(y)$ (as a set) witnesses $|X| = |Y| \cdot N$. $\square$
By the way, applying the Lemma to $G/K \twoheadrightarrow G/H$ for subgroups $K \subseteq H \subseteq G$, we get Lagrange's Theorem $|G:K|=|G:H| \cdot |H:K|$. It is also useful in other contexts.
Comment: @MartinBradenburg In my answer I use finiteness due to the question. However, I admit that your answer is much better conceptually. (Personally, I prefer this conceptual answer than the calculations approach I have shown.)

$|\phi(G):\phi(H)|$ divides $|G:H|$


Test whether random slopes are significantly different from 0 for individual subjects

Question: I am working (in R 3.2.3 using lme4 for doing mixed effect modeling) with vowel data from many different subjects. The question I'm interested is whether certain vowels undergo change over time (as in the English word 'I') as a function of the following consonant type, and in particular whether this is the case for all subjects, or only for some. Suppose, for simplicity, that I am only measuring a single vowel in many different words, and that there are no relevant differences between these words. My model would then looks as follows:
measure ~ (1|subject) + timepoint + (timepoint|subject) +
          following_segment + (following_segment|subject) +
          timepoint:following_segment + (timepoint:following_segment|subject)

where timepoint is a continuous variable referring to the timepoint in milliseconds of each measurement, and following_segment is a binary variable referring to either a neutral context or a context where I am expecting a change over time.
If I run ranef on this model and look in the final column, corresponding to the (timepoint:following_segment|subject) term, I indeed get either very large numbers (e.g. 500 Hz) or very small numbers (e.g. 100 Hz, just to name two random examples; there is a large amount of variability, because these estimates are correlated with the subject's physiological properties such as jaw size).
I now want to know whether these differences in random slope estimates between subjects are significant, for individual subjects (i.e. 'is this subject sensitive to the following_segment manipulation or not?'). Since I know that t = B/SE, all I believe I would need is the standard error for the individual participant within this specific term of the model, and then I can use pnorm to get a p value (please correct me if this is too simple). Regarding obtaining the estimated SE, this question gave me a starting point in suggesting summary(model)@REmat, which unfortunately returns only NULL. Another question suggests using ranef(model,condVar=TRUE), which unfortunately gives an error that conditional variances not currently available via ranef when there are multiple terms per factor. Is there another way to test whether the individual random slope estimates are significantly different from 0?
Here is a histogram of the random slopes:

The peak around 800 Hz looks interesting; any way I can test for each participant's slope estimates whether they are located around that 800-Hz peak, versus around the big peak near the 0 point?
Comment: Although asked in terms of `R`, I think this is a statistical question & merits staying open here.
Comment: You say that you get either very large or very small random effects. Are they bimodal or just high variance? Do the high & low groupings (clusters?) correspond to anything (eg, native speakers vs ESL)? Note that random effects are modeled w/ a normal distribution (which goes to infinity in both directions), so the model assumes there have to be people who are 0.
Comment: High variance: certainly (because the data is correlated with the subject's physiology). Bimodal & are there meaningful clusters: I suppose that's what my research question is - are there indeed people who are/are not sensitive to the manipulation, and if so, does this sensitivity vs nonsensitivity correlate with (in my case) geographical regions? [A plot does appear to show some bimodality](http://i65.tinypic.com/ranozb.png), but whether this is statistically meaningful and which subjects may be reasonably certainly grouped into which peak, that is exactly what I would like to figure out.
Comment: Do you have data on each person's geographical region?
Comment: Yes. I have 160 subjects hailing from 8 regions, all properly identified in the variable coding (i.e. my data frame contains a field 'region' with 8 levels). I was afraid to enter region as a predictor, however, because it should (by design) be completely collinear with the variable 'subject' (which I do still need to control for individual variation). This is why I am now trying to find some kind of structure within the individual's random slopes, and I was planning to then test posthoc whether such structure, if found, would happen to correlate with the regions the individuals would be from.
Comment: You only have `subject` as a random effect, AFAICT. You should be able to include `region` as a fixed effect w/o problems.
Comment: I really can't tell what you're doing or what's going wrong. Can you post your data & your code?
Comment: sorry, I made a stupid mistake (already deleted the comment). The model converges just fine with `measure ~ (1|subject) + region + timepoint + (timepoint|subject) + following_segment + (following_segment|subject) + timepoint:following_segment + timepoint:following_segment:region + (timepoint:following_segment|subject)`, but then I realized that I would also need a separate random slope for the new `timepoint:following_segment:region` term (and put them at the end of the formula rather than in the middle). I'll still have to see whether _that_ will converge; I'm running it now.
Comment: OK, if I take the model as formulated in the original question and add a main effect for `region` and append `+ timepoint:following_segment:region + (timepoint:following_segment:region|subject)`, the model fails to converge within 200k iterations. I can try giving it some more (it looked light it might have been fairly close, got to a rho of `2e-07`), but assuming it won't make a difference, is there any way to test this post-hoc? For instance, the peak around 800 Hz looks interesting in the histogram, any way I can test which subjects's slopes reliably/significantly group around that point?
Answer: The ranef(model,condVar=TRUE) method is not working because you have the random effects written in separate parenthesis blocks. In this specification, no covariances are estimated among the random slopes (because covariances are only included for terms that share a parenthesis block), but covariances are estimated between the the random intercept and each random slope (because each parenthesis block implicitly also includes the intercept). That's fine, but another totally reasonable specification (although with more parameters) is to allow all the random effects to have nonzero covariance. In other words, you can rewrite the model syntax as
measure ~ timepoint*following_segment + (timepoint*following_segment|subject)

For this rewritten model, the ranef(model,condVar=TRUE) method should work.
If you don't want to rewrite the model in this way and include the extra covariance parameters, then another way to implement the tests you want is via bootstrapping. In each iteration, sample with replacement from each subject's data (do not mix observations between subjects), fit your mixed model, and save the array of random effects. After some large number of iterations (1000? 10000?), you will have distributions for each subject's random effects, which you can compare to 0. Note that this could take a while for your complex model!
Comment: I've accepted your answer because this was indeed the problem with the condVar option, thank you! As a follow-up question: would it now be valid to take the conditional variance for the parameters I'm interested in, to take that value's square root, and to divide the individual subject's random-effect estimate by the resulting value, yielding a t-like statistic that can be checked against the normal distribution for significance? (In addition, am I correct in presuming that if I do this, I will need to correct for multiple comparisons, because I have 160 subjects to test?)
Comment: I think there is nothing technically incorrect about doing significance tests on the individual random effects in this way. There's of course going to be a big multiple comparisons issue, but it sounds like you've already thought of that. In my opinion, testing the individual effects would be a little odd -- if we really do have a priori interest in whether individuals' effects differ from 0 (or some other value), then the individuals should arguably be treated as a fixed rather than random factor -- but, like I said, I don't think it's technically incorrect.
Comment: The issue is that I don't a priori know which subjects, if any, are going to be the ones exhibiting significantly different behavior - I have a guess that it's correlated with their geographical region, but I don't feel that that guess is solid enough to warrant including region as a fixed effect a priori (even though I could do that). In other words, it seems more objective to me to let the data (of the individual subjects) itself tell me which subjects fall into my target group, and to check only post hoc whether that happens to correlate with e.g. region. Does that make statistical sense?
Comment: @LostLinguist Yeah, it does


İonic How to send notifications user to user via FCM?

Question: I can send notification  on firebase console but I want to when user send message on app then another user get notification.I searched but could not find.How can I do it ?
I use this for firebase console  to user <https://capacitorjs.com/docs/guides/push-notifications-firebase>
EDIT :
<code>public initPush(){
    if(Capacitor.platform!=='web'){
      this.registerPush();
    }
  }
  private registerPush(){
    PushNotifications.requestPermission().then((permission)=>{
      if(permission.granted) {
        PushNotifications.register();
      }
    });
    PushNotifications.addListener('registration',
      (token: PushNotificationToken) => {
        //alert('Push registration success, token: ' + token.value);
      }
    );

    PushNotifications.addListener('registrationError',
      (error: any) => {
        alert('Error on registration: ' + JSON.stringify(error));
      }
    );
     PushNotifications.addListener('pushNotificationReceived',
     async (notification: PushNotification) => {
        //alert('Push received: ' + JSON.stringify(notification));
        const toast = await this.toastController.create({
          position:"top",
          header:notification.title,
          message: notification.body,
          duration: 9000,
          buttons:[{text:"Aç", handler: () => {
            console.log('Favorite clicked');
            this.router.navigateByUrl(`/main/tabs/message`);
          }},
        {text: 'Kapat',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        } }],
        });

        toast.present();
      }
    );

    PushNotifications.addListener(
      'pushNotificationActionPerformed',
     async (notification:PushNotificationActionPerformed)=>{
       //const data =notification.notification.data;
       console.log('Action performed:'+JSON.stringify(notification.notification));
         this.router.navigateByUrl(`/main/tabs/message`);
    });
}
</code>
Comment: in which technology your backend/API code is ?
Comment: I am using ionic, angular and firebase @TaylorRahul
Comment: I have added my comment below please refer this
Comment: thanks for your answer :) I'll try and come back.
Comment: Can you show us some code?
Comment: @AvivLo yes ofcourse I put the code but it's just as I said send notification firebase console to all users
Answer: NodeJS module is available for this I have added its link below. but for this you need device token of the user whom you want to send notification this might not be available at application end it should be in your database so a good practice is to send this notification from backend API.
https://www.npmjs.com/package/fcm-node
Comment: "Warning: on February 2, 2017, the Firebase Team released the admin.messaging() service to their node.js admin module. This new service makes this module kind of deprecated"    is it working ?


Erro PDO - Call to a member functio on null

Question: Criei uma função para fazer uma consulta no BD e retornar um Usuário a partir da variável $nome passado por parâmetro, porém, ao testa-la ela entra no else, alguém saberia onde esta o erro?
Obs.: A conexão do PDO está funcionando e existe um usuário com o nome do teste dentro do BD.
Função:
public static function obtemUsuarioPorNome($db,$nome){
        $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
        $stmt->bindParam(":nome", $nome);
        $stmt->execute();
        if($row = $stmt->fetch(PDO::FETCH_ASSOC) == $nome){
            extract($row);
            $usuario = new Usuario($id,$nome,$senha);
            return $usuario;
        } else {
            return null;
        }
    }

Código de teste:
$objUsuario = Usuario::obtemUsuarioPorNome($dblink,"barba-ruiva");
print("
".$objUsuario->getNome()." ".$objUsuario->getId()."
");

Comment: O erro é em qual linha?
Comment: Aparamente, invés de entrar no if, ele está entrando no else e retornando null
Comment: Se cai no else sua conexão não é válida ou é nula.
Comment: Adicione apenas `if($row = $stmt->fetch(PDO::FETCH_ASSOC))`.
Comment: erro resolvido, obrigado pela ajuda
Answer: Você não pode comparar o NOME com o resultado do FETCH_ASSOC, pois este, retorna para a variável ROW, um array associativo contendo os dados de resposta do SELECT.
public static function obtemUsuarioPorNome($db,$nome) {
   $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
   $stmt->bindParam(":nome", $nome);
   $stmt->execute();
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   if(count($row) > 0) {
      // extract($row);
      $usuario = new Usuario($row["id"], $row["nome"], $row["senha"]);
      return $usuario;
   } else {
      return null;
   }
}


What's the percent of mango trees?

Question: I know this is simple stuff compare to the questions I've seen on this site but please be nice. :) Would be great if anyone could show me how to solve the problem below.
Question:
On a piece of land, 3/8 of the trees are lemon trees. Of the other trees are 8/15 orange trees and 2/5 palm trees. The rest of the trees are mango trees. What's the percent of mango trees? (Answer: 4.2%).
Answer: Lemon trees: $\dfrac{3}{8}$
Other trees: $1-\dfrac{3}{8}=\dfrac{5}{8}$
Orange trees: $\dfrac{5}{8}\cdot\dfrac{8}{15}=\dfrac{1}{3}$
Palm trees: $\dfrac{5}{8}\cdot\dfrac{2}{5}=\dfrac{1}{4}$
Mango trees: $1-\left(\dfrac{3}{8}+\dfrac{1}{3}+\dfrac{1}{4}\right)=\dfrac{1}{24}$
Comment: I'm sorry but math is like kryptonite to me, how do you get the 1 (on other trees)?
Comment: @Lattja: When you work with percentage, you use $100\%$ in order to denote the total amount, right? Do you understand why? The reason is, that $1$ percent of the amount is equivalent $\frac{1}{100}$ of the amount. So when you work with percentage, you use $100\%$ in order to denote the total amount, and when you work with fractions, you use $1$ in order to denote the total amount. Got it?
Comment: Yes, I get that, total amount, 100% and 1. The rest, it's like, I get it, but I don't get it. Well, I've been staring at math all day; maybe I'll understand it tomorrow and laugh at all of this.

What's the percent of mango trees?


Cloudfront 502 error with ALB origin in different region

Question: I have a CloudFront which has one of its origins as an application load balancer, this load balancer is available in a different region from the CloudFront which is only available in N.Virginia and is using a different SSL certificate, as its domain name is different.
I need to have this alb in its region and can't move it to N.Virginia as well. I am not sure why I am getting the 502 error on the CloudFront domain.
When I visit the A Record DNS Name provided in the load balancer description tab it still does not work, so I think the error is with the load balancer but I am not sure, as the domain name to which the load balancer is supposed to route traffic is working.
I am new to AWS and this is all the information I could think of, so please let me know if any more information is needed.
I am sorry if I am confusing you but this is my first time working on AWS, and I don't have any terminology down yet, I will immediately clear things up if you ask me something.
Answer: Typical reasons for this can be the following

CNAME record for the certificate not set correctly -> go to Certificate Manager, select your certificate and in the tab "Domains" click "create records in Route53
ALB is not internetfacing -> when using CloudFront is must be internetfacing. Go to EC2 -> Load Balancing and select your Target / Origin Load Balancer. You can also check the DNS name of it there and try to access it directly. If the direct call works, your ALB is fine, but the Cloudfront connection with ALB is bad :)
CloundFront is not having the certificate (and it is mandatory for CloudFront to have Certificate in No. Virginia) or the "Alternate Hostenames" is not set correctly (which should be your Domain name and eventually *.YourDomainName)

Hope it helps to point you to the right way :)


Maximize the product of two integer variables with given sum

Question: Let's say we have a value $K$. I want to find the value where
$A+B = K$ (all $A,B,K$ are integers) where $AB$ is the highest possible value.
I've found out that it's:

$a = K/2$; $b = K/2$; when $K$ is even
$a = (K-1)/2$; $b = ((K-1)/2)+1$; when $K$ is odd.

But is there a way to prove this?
Comment: I think $n=K$ is an integer and also you seem to want $A,B$ to be integers. If these guesses are right, you should edit the question to make these clear.
Answer: In the even case, assuming $A\leq B$, the numbers will be of the form $A=\frac{K}{2}-m$ and $B=\frac{K}{2}+m$ in order to get $A+B=K$, with $m=0,1,\ldots,\frac{K}{2}$.  Then multiplying gives $AB=\left(\frac{K}{2}\right)^2 - m^2 \leq \left(\frac{K}{2}\right)^2$.
In the odd case, you'll have $A=\frac{K}{2}-m-\frac{1}{2}$ and $B=\frac{K}{2}+m+\frac{1}{2}$, with $m=0,1,\ldots,\frac{K-1}{2}$.  Multiplying gives
$\begin{align*}
AB &= \left(\frac{K}{2}\right)^2 - \left(m+\frac{1}{2}\right)^2 = \frac{K^2}{4} - m^2 - m - \frac{1}{4} \\
   & = \frac{K-1}{2}\left(\frac{K-1}{2}+1\right) - m^2 - m \leq \frac{K-1}{2}\left(\frac{K-1}{2}+1\right).
\end{align*}$
Alternatively, you can think of optimizing a quadratic function by finding the vertex.  If you write $AB$ as a quadratic function of $A$ or $B$ alone using the constraint $A+B=K$ (as indicated in PEV's answer), then the closest integer to the vertex will solve your problem because the parabola opens down.
Answer: We know that $B = K-A$. So you want to maximize $AB = A(K-A)$. So we have:
$$AB = A(K-A)$$
$$ = AK-A^2$$
Find the critical points and use some derivative tests.


ADFS 3.0 sign on page is not accessible using FQDN or IP but accessible using localhost.

Question: I am trying to access ADFS 3.0 sign on page using server name or ip address but not able to brows . If I brows by using localhost instead ip or FQDN its working .
Can anybody tell me what are the possibilities of not able to browsing using ip or FQDN ?
There are solution like IIS setting but ADFS 3.0 no need of IIS.
Comment: I have a similar issue, I found that turning off IE Protected Mode in Server Manager helped to some extent, but the only way I can access the idpinitiatedsignon page locally now is as follows: 127.0.0.1 - NO, localhost - YES, FQDN - NO, IP - NO, Alternative DNS A-record - YES
Answer: I ran into the same issue, and it was due to the fact that I had used an invalid DNS name for 'Federation Service Name' when configuring the ADFS role.  After I removed the role (just fixing it didn't seem to make a difference), and added the role again, and putting the FQDN under 'Federation Service Name' while going through the configuration wizard.


tableselect form doesn't work

Question: I can't get form-table of '#type' => 'tableselect' to work.  I've lifted the example from 8.3.x core/lib/Drupal/Core/Render/Element/Tableselect.php Tableselect. The table works and there are no log messages.
What happens is the page reports that there are no users found (ie. the table is empty) even though the $form array has the row data in it.
If I change the type to '#type' => 'table' the table is populated as expected.
This is the code I am using.
<code>namespace Drupal\simpleForm\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayTable_1 extends ControllerBase
{

    public function description_one()
    {
        $header = [
            'first_name' => $this->t('First Name'),
            'last_name' => $this->t('Last Name'),
        ];

        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $form['table'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
            '#empty' => $this->t('No users found!!!'),
        );

        return $form;
    }

}
</code>
Any help would be appreciated.
Comment: Clearing cache makes no difference.
Answer: Found the issue: the #type' => 'tableselect has to be built inside a class that extends FormBase.
This Works:
<code>  class DisplayTable_1 extends FormBase {
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $options = [
            1 => ['first_name' => 'Indy', 'last_name' => 'Jones'],
            2 => ['first_name' => 'Darth', 'last_name' => 'Vader'],
            3 => ['first_name' => 'Super', 'last_name' => 'Man'],
        ];

        $header = [
            'first_name' => t('First Name'),
            'last_name' => t('Last Name'),
        ];

        $form['table'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Users'),
            '#header' => $header,
            '#options' => $options,
            '#empty' => t('No users found'),
        ];

        // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#description' => $this->t('Submit, #type = submit'),
        ];
        return $form;
    }

    public function getFormId() {
        return 'fapi_example_input_demo_form';
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Find out what was submitted.
        $values = $form_state->getValues();
        foreach ($values as $key => $value) {
            $label = isset($form[$key]['#title']) ? $form[$key]['#title'] : $key;

            // Many arrays return 0 for unselected values so lets filter that out.
            if (is_array($value)) {
                $value = array_filter($value);
            }

            // Only display for controls that have titles and values.
            if ($value && $label) {
                $display_value = is_array($value) ? preg_replace('/[\n\r\s]+/', ' ', print_r($value, 1)) : $value;
                $message = $this->t('Value for %title: %value', array('%title' => $label, '%value' => $display_value));
                drupal_set_message($message);
            }
        }
    }
}
</code>
Comment: Yes, ControllerBase would not provide any form building capabilities.
Comment: Any way to use tableselect outside the form?
Answer: try
<code>$header = [
  'first_name' => ['data' => $this->t('First Name')],
  'last_name' => ['data' => $this->t('Last Name')],
   ...
 ];

$options = [
    1 => ['first_name' => ['data' => ['#title' => 'Indy']], 'last_name' => ['data' => ['#title' => 'Jones']],
    ...
];
</code>
I checked the code over here.
Comment: Remy, I'm afraid that did not work.

tableselect form doesn't work


Setting the id of a self reference on create using active record

Question: Using rails and active record, is it possible to set the id to a self reference on create?
I am coming across an issue where a person is their own supervisor.  I would like to set the supervisor_id field in the create statement for the person.
<code>class Person < ActiveRecord::Base
  belongs_to :supervisor, :class_name => "Person", :foreign_key => "supervisor_id"
  ...

Person.create(:name => "John Smith", :supervisor => ?self?)
</code>
From a mysql perspective, I don't see how this is possible in a single query.  Does rails have a built in way to do this?  My current plan is a flag and an after create.
Answer: Since id's aren't assigned until after the object is created the cleanest way to do this in rails is with an after_create callback.
You might be able to do a mysql trigger if you want to get really advanced... but that seems like more trouble than its worth.


How to refresh DOM after changing data attribute

Question: I'm coding little CMS for translations of static pages to many languages. It dynamically refreshes and loads translations etc, but I've got a few bugs which I cannot fix. One of them is when you try to preview page of id 1, but before you were editing page of id 2, it always redirects you to preview of page of id 2.
That's my button in template:

   //other code
   <button id="a-preview" href="#" class="btn btn-block" target='_blank'>
      Preview template
   </button>

And it's function to load preview in new window:
$('#a-preview').on('click', function () {
    var pageId = $('#language-choice-select').data('page-id');
    console.log(pageId);
    window.open('/main/staticPages&staticPageId=' + pageId, '_blank');
});

Then I've read some articles about event-delegation and assumed it could be my problem so changed that code to:
$('.edit-template-container').on('click', '#a-preview', function () {
    var pageId = $('#language-choice-select').data('page-id');
    console.log(pageId);
    window.open('/main/staticPages&staticPageId=' + pageId, '_blank');
});

But it stills redirects to page of id 2 if it was edited before. In DevTools Elements I can see that data-page-id is changed, but console.log always prints for example id: "2" if it was edited before.
Data 'page-id' attribute is changed when I choose page to edit in table, on function which looks like that:
$('table').on('click', '.edit-table-btn', function () {
    var pageId = $(this).data("page-id");
    //the rest of code
    $('#language-choice-select').attr('data-page-id', pageId);
});

What should I do to change page-id data-attribute dynamically in DOM? What should I know about this, are there any fine articles?
Comment: `.data()` != `.attr("data` .. Take a look here http://stackoverflow.com/a/7262427/3611180
Comment: That's right, it fixed all my problems! Thank you very much
Comment: A [``](https://www.w3.org/TR/html5/forms.html#the-button-element) has no `href` or `target` attribute
Answer: Please refer to this existing post:
jQuery Data vs Attr?
Basically, when you use data() on a node, jQuery sets the value on the node object, not on the DOM element.
So, I suggest you to use attr() both to set and to read the value.


How can a cloud-config script copy a file to a server?

Question: How can a cloud-config script copy a file to a server?  write_files requires the file content in the script.  How can I specify an external file that contains the content?
Answer: You haven't given enough context to know for sure, but for the purposes of this answer I'll assume you're running in Amazon Web Services.

As per the cloud-init documentation here, the only way to create a file directly via cloud-init is to include the file content in the script, either raw, base64-encoded, gzipped or base-64+gzipped.
Apart from doing that, the most straightforward way to do this would be to download the file - either via HTTP or an API call (for example, to S3).
Another way of getting the file onto the server would be to create a custom OS image (AMI) containing the file, by using something like Packer.
Comment: It also strikes me that cloud-config scripts are meant only to bootstrap a server, not fully provision it. A provisioning tool like Ansible seems more appropriate for more sophisticated configuration.
Comment: I'm using CoreOS, but my question refers to the `cloud-config` (or `cloud-init`) specification, not any particular implementation.  I was wondering if there was some command that I had overlooked.  It seems that `cloud-config` scripts are designed to pull, not push files to the target server.
Comment: At that point why not use Ansible for everything. This absence of a decent way to get configuration files into instances its just bs.
Answer: scp in the runcmd section can retrieve files, albeit in the final stage of cloud-init.


Fill GAS ModalDialog box with HTML - no white ? Alternative?

Question:
Is there an alternative to showModalDialog for Google Spreadsheet?  I am willing to learn new software. What software would be reasonable for lightly skilled teacher to learn?
I have a Connect 4 game for my students built in a Google spreadsheet. Random questions are pulled from various tabs with menu items and I want a pretty display of the question. There are dimensions possible in the showModalDialog and HTML. I complicated it by having dimensions in a BODY and a DIV or only in the DIV. The dialog box always has some white showing and the HTML often popups up scroll bars (very ugly). Probably need something more robust than Google App Script to create a clean display of the question. What would anyone suggest?
This is the html:
<!DOCTYPE html>

    <base target="_top">

        <?!= nextQuestion ?>

        <input type="button" value="Okay!" onclick="google.script.host.close()" />

This is the code that displays the question. Some questions are long and have html markup to appear on multiple lines ().
/**
 * Displays an HTML-service dialog in Google Sheets that contains
 */
function popupNextQ(inQuestion) {

//  var html = HtmlService.createHtmlOutputFromFile('Index');

  var htmlTemplate = HtmlService.createTemplateFromFile('Next-Question-Popup');
  htmlTemplate.nextQuestion = inQuestion;
  var html = htmlTemplate.evaluate();
//            .setHeight(400)
//            .setWidth(600);
  SpreadsheetApp.getUi().showModalDialog(html, " ");
}

This is the best I have come up with so far.  If I add a border to the html it only appears on the top and left sides. At least with the current dimensions there are no scroll bars for my longest question.
Questions are not vertically aligned so short ones appear toward the top of the green area.
Comment: Can you provide your HTML dialog script and a visual example of what you mean?
Comment: Done - @Rafa Guillermo  - Did not know if you would know this happened if I did not comment?
Answer: Alan Wells in googlegroups.com wrote, you can't get rid of the white space around the edges of a dialog box. If you want to stay with Google products and want an alternative, you'd need to use an Apps Script Web App for your app.
He suggested creating the question box with a Web App rather than the triggered from the menu on the sheet.
My discovery of the nested CSS has fixed the problem of all the text appearing at the top.
I have FINALLY found a way to add a border on all sides of the html.  Putting the border in the parent causes it to display on the top and left. Putting it in the child makes it display on the top, bottom, and left. The bottom border is in the middle of the green square - not at the bottom.
The trick was to decrease the size of the parent div from 100% to 97%. I tried 99% and 98% also. The width of your border may affect how much you have to decrease.


Use Calimero for Java to read and write signed int values of KNX system

Question: Using Calimero, I want to read and write signed int values in a KNX system.
I use the readUnsigned and write methods of ProcessCommunicatorImpl for unsigned ints but there are no methods for reading and writing signed ints.

For example these types I can not access:
DataPoint 6.x  (8 bit 2's complement)
DataPoint 8.x  (16 bit 2's complement)
DataPoint 13.x  (32 bit 2's complement)

The only methods available are:
String read(Datapoint)
String readString(GroupAddress)
int readControl(GroupAddress)
double readFloat(GroupAddress, boolean)
int readUnsigned(GroupAddress, String)
bool readBool(GroupAddress)

And I only have a GroupAddress, no Datapoint.

Does anyone know how I can read and write those types of datapoints?

Thanks!
Comment: Ah, seems to be a very recent addition to their github which isn't in your version of the library yet. After browsing some more I think you can create your own StateDp (datapoint) instance using your address then read and write as string, e.g. https://github.com/calimero-project/calimero-core/blob/master/test/tuwien/auto/calimero/process/ProcessCommunicatorTest.java#L451 there is a DPTXlator for signed types
Comment: Just a guess but maybe it's `double readNumeric(..)` since a double can represent all ints without precision loss
Comment: I added the available methods to my question. I have no idea where I can find a readNumeric method.
Comment: Thank you zapl, I got it solved thanks to you!
Answer: Using zapl's comment as inspiration, I came up with this code:
<code>int getIntFrom8Bit2Complement(GroupAddress groupAddress) throws KNXException, InterruptedException {

    final Datapoint dp = new StateDP(groupAddress, "my datapoint "+groupAddress.toString());
    dp.setDPT(0, DPTXlator8BitSigned.DPT_VALUE_1_UCOUNT.getID());
    String result = processCommunicator.read(dp);
    try {
        return Integer.parseInt(result);
    } catch (NumberFormatException e) {
        throw new KNXException("Error Parsing 8 bit 2 complement result as int -- result = "+result);
    }
}
</code>
I'm not 100% sure about parsing the result as an int, but I can't test because I don't have a KNX device that will send me a signed int.
When I get the chance to test one, I will confirm or adjust this answer.


facing with "list index out of range" error when using objects

Question: I want to make list of objects. My code is:
std_list_instance = list()
for i in range(0, std_cls_1_num):  #std_cls_1_num set by user
    std = Student(std_cls_1_list[0][i], std_cls_1_list[1][i], std_cls_1_list[2][i])  #Student has 3 fields that given from a list
    std_list_instance[i].append(std)

class def is:
class Student:
    count = 0
    def __init__(self, age, height, weight):
        self.age = age
        self.height = height
        self.weight = weight
        Student.count += 1
    def get_ave_age(self):
        print('age is %i' %self.age)

std_cls_1_list is:
std_cls_1_list = list()
for i in range(0, 3):
    std_cls_1_list.append([int(std_cls_1_num) for std_cls_1_num in input().split()])

and finally user input is like:
5 #number of student
16 17 15 16 17  #age of 5 std
180 175 172 170 165 #height of 5 std
67 72 59 62 55 #weight of 5 std

then I faced with "list index out of range error".
I know there is a problem in my code, but I can't fix it.
Comment: Please add the definition of `Student`, and how does `std_cls_1_list` looks like
Comment: You want `std_list_instance.append(std)`
Answer: I believe that you need to switch accessing list elements. Instead of [0][i] do [i][0]:
std_list_instance = list()
for i in range(0, std_cls_1_num):  #std_cls_1_num set by user
    std = Student(std_cls_1_list[i][0], std_cls_1_list[i][1], std_cls_1_list[i][2])  #Student has 3 fields that given from a list
    std_list_instance[i].append(std)

But you will still get the error if:

std_cls_1_num > len(std_cls_1_list) - std_cls_1_num greater than number of elements in std_cls_1_list
not all(len(st) > 3 for st in std_cls_1_list) - not every element of std_cls_1_list has at least 3 elements
Answer: You must ensure the size of "std_cls_1_num" must be equal or less then the size of "std_cls_1_list" rows..if its greater then the row size the program will throw index error.
Also if possible please put the related code/definitions/input then only we can comment..


Correlation between an original variable and a principal component

Question: I am looking at this link http://strata.uga.edu/8370/lecturenotes/principalComponents.html where it says

In interpreting the principal components, it is often useful to know the
  correlations of the original variables with the principal components.
  The correlation of variable $X_i$ and principal component $Y_j$ is
$$ r_{ij}  = \sqrt{a_{ij}^2\times \mathrm{var}(Y_j)/s_{ii}}$$

where $a_{ij}$ is the $i$-th's variable principal component weight on on principal component $j$ and $Y_j$ is the $j$-th principal component score and I am not sure what $s_{ii}$ is.
I do a simple PCA on the iris dataset below and would like to calculate the correlation of sepal width and legth to PC score 1 and PC score 2 but what is $s_{ii}$?
The $\mathrm{var}(Y_j)$ is the variance of the principal component score. I have that in the VarofSCores object below.   In that link the author says $S_Y$ is the varcov matrix of the scores so if $s_{ii}$ is the diagonal of $S_Y$ then that is the same value I have in VarOfSCores.
data(iris)
names(iris)
dat = data.frame(iris$Sepal.Width, iris$Sepal.Length)
pca= prcomp(dat)
PC = pca$rotation
VarOfScores = pca$sd^2
scores = pca$x

#correlation of sepal width to score 1
sqrt(PC[1,1]^2*  VarOfScores[1]/??   )

#correlation of sepal width to score 2
sqrt(PC[1,2]^2*  VarOfScores[2]/??   )

#correlation of sepal LENGTH to score 1
sqrt(PC[2,1]^2*  VarOfScores[1]/??   )

#correlation of sepal LENGTH to score 2
sqrt(PC[2,2]^2*  VarOfScores[2]/??   )

Also - Why does the author say "loadings"  instead of "principal components".  The eigenvectors are "principal components" not "loadings" and the data times the eigenvectors are "scores".  I think that is poor terminology. See here
http://www.cs.princeton.edu/courses/archive/spr08/cos424/scribe_notes/0424.pdf where the author states on on page 4 "V" is the principal components.
Comment: s is diagonal matrix of eigenvalues. Therefore, s_{ii} gives the eigenvalues of the sample covariance matrix.
Answer: Correlation coefficient between variable $X_i$ and principal component $Y_j$ is given by $$r=v_{ij}\cdot \mathrm{std}(Y_j) / \mathrm{std}(X_i)=v_{ij}\cdot \sqrt{e_{j}} / \mathrm{std}(X_i),$$
where $v_{ij}$ is an $i$-th element of the $j$-th unit-length eigenvector of the covariance matrix, $e_j=\mathrm{var}(Y_j)$ is the corresponding eigenvalue which gives variance of this PC, and $\mathrm{std}(X_i)$ is standard deviation of $X_i$.
Please see my answer to How to find which variables are most correlated with the first principal component? for the derivation and additional explanations. Note that $v_{ij}\cdot \sqrt{e_{j}}$ are called "loadings" $L_{ij}$.
I think the formula in your quote says the same thing: $a_{ij}$ are the elements of the eigenvectors, $\mathrm{var}(Y_i)$ are the respective eigenvalues, and $s_{ii}$ stands for the diagonal elements of the original covariance matrix, i.e. for the variances of $\mathrm{var}(X_i)$.
Regarding terminology, please see What exactly is called "principal component" in PCA? and Loadings vs eigenvectors in PCA: when to use one or another?
Answer: Correlations with factors are called loadings. In PCA, eigenvectors can be scaled differently but if normalized to their eigenvalues, they are loadings (if memory serves). For other types of factor analysis, loadings and factors can differ but loadings are always refer to correlations.
Comment: Ok so what are your thoughts on what s_ii should be?
Comment: This applies only to PCA on correlation matrix.
Comment: @amoeba I am doing pca on correlation matrix with my real data. This is just an example.  Do you know what the author means for s_ii?
Comment: @user3022875 Yes. See my answer :)


Actionscript 3.0 - Using an if-statement with colorTransform

Question: I am assigning colors to movie clips when buttons are clicked. These movie clips are vector shapes contained within an oval shape imported from Illustrator.
Each oval has a top color, a bottom color and an edge/rail color. I want the edge color to change to a combination of the top & bottom colors based on the selection of the bottom color.
I have been trying to use a conditional statement (at the bottom of the following code) with colorTransform to do this, but am not having any luck.
Any tips??
(I've included an image below to help visualize what I'm trying to do.)
<code>//Define Red Colors
var red1:ColorTransform = new ColorTransform();
red1.color = 0xE66B5B;

//Define Blue Colors
var blue1:ColorTransform = new ColorTransform();
blue1.color = 0x00467F;

//Define Red/Blue Edge Color
var redBlue:ColorTransform = new ColorTransform();
redBlue.color = 0x1D113F;

//toggle red top colors
redDeck_btn.addEventListener(MouseEvent.CLICK, toggleRedDeck);
function toggleRedDeck(e: MouseEvent) {
    deckColor_mc.transform.colorTransform = red1;
}

//toggle blue bottom colors
blueBtm_btn.addEventListener(MouseEvent.CLICK, toggleBlueBtm);
function toggleBlueBtm(e: MouseEvent) {
    btmColor_mc.transform.colorTransform = blue1;

    //deck = red, rails = purple color
    if (deckColor_mc.transform.colorTransform == red1){
    deckRail1_mc.transform.colorTransform = redBlue;
    btmRail_mc.transform.colorTransform = redBlue;
        }else{
            deckRail1_mc.transform.colorTransform = redBlue;
            btmRail_mc.transform.colorTransform = redBlue;
            }
}
</code>
Comment: Check also if my `blendRGB` function (blends between two colours) is useful to you: https://stackoverflow.com/a/71553488/2057709. If you give it the two top & bottom colours as function inputs, then you'll get a new blended colour (number) back for using as the rail's colour.
Answer: You need to compare the color property of the colorTransform Objects, like so:
<code>deckColor_mc.transform.colorTransform.color == red1.color
</code>
Comment: The exact reason of why direct comparison of `colorTransform` doesn't work is that they are objects, and object equality is compared by pointers. Setting a color transform to an object actually modifies the nested `colorTransform` property instead of assigning a link, thus comparing color transforms always returns false.


Excel mudar apenas parte de um texto da célula

Question: Em um documento excel eu quero que um determinado texto de uma célula faça enumeração automática quando faço copy paste de todo o grupo de celulas.
Exemplo da explicação.
- O que eu quero é copiar o todo o texto e que apenas me modifique a celula que diz "text,50,Num" de forma a que fique " text,51,Num" e na próxima copy paste que fique "text,52,Num" e que na proxima copy paste fique "text,53,Num".

Explicação está na imagem. Agradecia imenso a ajuda se alguém se disponibilizasse.
 Ora eu quero uma fórmula ou algo que faça automático porque eu vou repetir esse contexto quase até ao nº 10.000.
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,50,Num **Aqui onde diz 50, eu queria que no proximo copy paste ficasse
51  De uma forma automática porque eu vou fazer até por exemplo 10,000
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,51,Num ***Ficando assim 51
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,52,Num ***Ficando asim 52...
sleep,1000,Delay

O que eu consegui fazer é pôr uma fórmula numa célula vazia e alterar o valor que eu quero, mas tenho que fazer isso manualmente vezes sem conta ! Existe por aí alguma forma automática ?
 Segue em anexo uma imagem do que eu consigo fazer
Comment: coloca o texto na pergunta para que eu consiga copia-lo
Comment: Não está claro o que você deseja fazer. Uma pergunta ampla pode ter muitas respostas distantes do que você deseja. Seja específico.
Comment: @RenatoSilva tudo o que eu quero é copiar o todo o texto e que apenas me modifique a celula que diz "text,50,Num" de forma a que fique " text,51,Num" e na próxima copy paste que fique "text,52,Num" e que na proxima copy paste fique "text,53,Num". Estou a ser claro?
Answer: Como seu objetivo é "Automatizar a cópia" do texto, não necessariamente no excel, fiz em C#. Basta você acessar no .NET Fiddle e copiar o resultado.
Acesso .NET Fiddle: https://dotnetfiddle.net/6uViYu
Segue o código:
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        for (int i =50; i <= 10000; i++)
        {
            Console.WriteLine("tap,31,55,false,1,Seta andar p/tras");
            Console.WriteLine("sleep,1000,Delay");
            Console.WriteLine("tap,522,967,false,1,Tocar na mensagem");
            Console.WriteLine("sleep,1000,Delay");
            Console.WriteLine("tap,90,126,false,1,Tocar secao \"a quem escrever\"");
            Console.WriteLine("sleep,1000,Delay");
            Console.WriteLine("text,"+i+",Num");
            Console.WriteLine("sleep,1000,Delay");
            Console.WriteLine("");
        }

    }
}

Resultado:
tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,50,Num
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,51,Num
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,52,Num
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,53,Num
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,54,Num
sleep,1000,Delay

tap,31,55,false,1,Seta andar p/tras
sleep,1000,Delay
tap,522,967,false,1,Tocar na mensagem
sleep,1000,Delay
tap,90,126,false,1,Tocar secao "a quem escrever"
sleep,1000,Delay
text,55,Num
sleep,1000,Delay

...Continua...
o .NET Fiddle Limitou os resultados, mas basta alterar a numeração.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/64017/discussion-between-goncalo-rodrigues-and-rovann-linhalis).


Passar dados de Fragments para Activity

Question: Possuo uma aplicação com uma activity principal e dentro dele há um viewpager com fragments gerados por uma lista e um botão flutuante. O que eu quero é que ao clickar nesse botão eu consiga retornar dados de todos os fragments gerados para essa activity. Mas sempre retorna apenas o dado do último fragment.
<code>    public class QuestionFragment extends Fragment {
    private TextView tvQuestionNumber;
    private TextView tvQuestion;
    private RadioGroup rgAnswer;
    private RadioButton rb1, rb2, rb3, rb4, rb5;
    private ImageView ivPhoto;
    private Question question;
    private FloatingActionButton fab;

    // declaração da interface de comunicação
    public interface communication {

        // aqui, um ou mais métodos de comunicação
        void setData(int data); // por exemplo, este método retorna a idade inserida no fragment
    }

    /* variável que representa quem vai receber a atualização dos dados, no caso a activity principal, que vai implementar a interface de comunicação */
    private communication listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof communication) {
            listener = (communication) activity;
        } else {
            throw new RuntimeException("Activity deve implementar ExemploFragment.Communication");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.question_fragment, container, false);

        tvQuestionNumber = (TextView) view.findViewById(R.id.tv_question_number);
        tvQuestion = (TextView) view.findViewById(R.id.tv_question);
        rgAnswer = (RadioGroup) view.findViewById(R.id.rg_answer);

        ivPhoto = (ImageView) view.findViewById(R.id.iv_photo);

        rb1 = (RadioButton) view.findViewById(R.id.rb_option_1);
        rb2 = (RadioButton) view.findViewById(R.id.rb_option_2);
        rb3 = (RadioButton) view.findViewById(R.id.rb_option_3);
        rb4 = (RadioButton) view.findViewById(R.id.rb_option_4);
        rb5 = (RadioButton) view.findViewById(R.id.rb_option_5);

        fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final Bundle data = getArguments();

        if (savedInstanceState != null && savedInstanceState.getParcelable("question") != null) {
            question = savedInstanceState.getParcelable("question");
        } else {
            question = ((MainActivity) getActivity()).questionObject(data.getInt("position"));
        }

        tvQuestionNumber.setText("Questão " + (data.getInt("position") + 1) + ":");
        tvQuestion.setText(question.getQuestion());

        if (question.getUrl() != null) {
            float scale = getActivity().getResources().getDisplayMetrics().density;
            int width = getActivity().getResources().getDisplayMetrics().widthPixels - (int)(14 * scale + 0.5f);
            int height = (width / 16) * 9;

            Glide
                    .with(getActivity())
                    .load(question.getUrl())
                    .centerCrop()
                    .crossFade()
                    .into(ivPhoto);

            ivPhoto.getLayoutParams().height = height;
            ivPhoto.setVisibility(View.VISIBLE);
        }

        rb1.setText(question.getA());
        rb2.setText(question.getB());
        rb3.setText(question.getC());
        rb4.setText(question.getD());
        rb5.setText(question.getE());

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id = rgAnswer.getCheckedRadioButtonId();

                listener.setData(id);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("question", question);
    }
}
</code>
Esse é código do fragment.
Answer: Você pode usar eventos. https://developer.android.com/training/basics/fragments/communicating.html
Na seu fragment voce declara uma interface e implementa esta interface na sua Activity. Quando criar seu fragmento, crie um método que espera como parâmetro o evento, passe a referência da sua activity para este fragment(já que sua activity implementa este evento).

Passar dados de Fragments para Activity


Finding the points of intersection of a circle and a line

Question: In a test (of math in arabic language) we we're asked to find the points of intersection of a circle and a line. Their equation is given.
In the test I solved system of equations made of their equation and in the process I explain my line of thought using the words therefore, then, so, ... etc (in arabic) but in describing that process I acknowledge that the structure of my proof is done by equivalence, that can be easily seen from the context, we're solving an equation so we proceed by equivalence.
But my professor said that it was all wrong and that I should have used the statement is equivalent (in arabic) in each part of my proof and I got all of my exercises wrong, and there were some exercises in the test where in the process we had to solve an equation so he also said that I was wrong because of that reason so I only got 4 out of 20.
Is the professor wrong or I am?

My computer crashed so i couldn't edit so i made a new question. I've added the equations and system of equations with my solutions

Exercise 1
Circle has equation $x^2+y^2+(m+2)x-2my+m^2-36=0$, find center, radius
I found it to be center $(-\frac{m}{2}-1,m)$ radius r= $\sqrt{\frac{m^2}{4}+m+37}$

Exercise 2
Circle has equation $x^2+y^2+2 x - 2y - 4 = 0$ line has equation $x+y-1=0$ find points of intersection
i found $\left(\frac{-1+\sqrt{11}}{2},\frac{3-\sqrt{11}}{2}\right)$ and $\left(\frac{-1-\sqrt{11}}{2},\frac{3+\sqrt{11}}{2}\right)$
for exercise 3 and 4 it is the same and i checked my calculations again and again with the calculator there's no error but yet all of that was marked with 0 for not saying "is equivalent", i didn't use the symbol $\Rightarrow$  All i got was 4 from exercise 5 which had calculation of dot product and of area of triangle where we are given coordinates of two vectors in the plane
Comment: You should have edited: http://math.stackexchange.com/questions/1074894/is-my-professor-wrong-or-i-am instead of making a duplicate post. Also, why did you start a new user account since you must be the same user as the other post?
Comment: In Exercise 2, your two points do not satisfy $x + y - 1 = 0$.
Comment: this is comment: i made a typo it should be $$(\frac{-1-\sqrt{11}}{2},\frac{3+\sqrt{11}}{2})$$ and $$(\frac{-1+\sqrt{11}}{2},\frac{3-\sqrt{11}}{2})$$ sorry again my computer crashed i made an edit but it should be approved
Comment: This was cross posted at https://matheducators.stackexchange.com/questions/6056/professor-gave-me-0-in-all-my-answers-because-i-didnt-explicitly-say-is-equiva
Answer: The posted solutions are correct, below is a possible derivation.

Exercise 1
In this exercise you need to find the center and radius of this circle which depends on $m$.
$$x^2+y^2+(m+2)x-2my+m^2-36=0$$
Notice that $(y-m)^2=y^2+m^2-2my$ and rewrite as
$$x^2+(y-m)^2+(m+2)x-36=0$$
Add $0=1-1+m+\frac{m^2}4-m-\frac{m^2}4$
$$x^2+(y-m)^2+(m+2)x-37+1+m+\frac{m^2}4-m-\frac{m^2}4=0$$
Notice that $\left(x+\frac{m-2}2\right)^2=x^2+(m+2)x+\frac{m^2}4+m+1$ and rewrite as
$$\left(x+\frac{m+2}2\right)^2+(y-m)^2=37+m+\frac{m^2}4=0$$
We can now easily see that the center is
$$\left(-\frac{m+2}2,m\right)$$
And that the radius is
$$r=\sqrt{37+m+\frac{m^2}4}=\frac12\sqrt{m^2+4m+148}$$
Which is equivalent to your solution.

Exercise 2
Circle has equation  line has equation  find points of intersection
You need to find the intersections of the following:
$$
\begin{array}{l}
0=x^2+y^2+2 x - 2y - 4\\
0=x+y-1
\end{array}
$$
This simply means solving a system of equations:
From the second equation we get the solution for $x$ as
$$x=1-y$$
Now plug this into the first equation:
$$0=(1-y)^2+y^2+2 (1-y) - 2y - 4$$
Remove the paranthesises
$$0=2y^2-6y - 1$$
Solve for $y$ using the quadratic formula or complete the square
$$y_1=\frac12 (3+ \sqrt{11})$$
$$y_2=\frac12 (3- \sqrt{11})$$
Plug this into the formula for $x$ from earlier: $x=1-y$
$$x_1=1-\frac12 (3+ \sqrt{11})$$
$$x_2=1-\frac12 (3- \sqrt{11})$$
Simplify
$$\begin{array}l
x_1=-\frac12(1+\sqrt{11})\\
x_2=\frac12(\sqrt{11}-1)
\end{array}$$
This gives the two solutions:
$$\left(-\frac12(1+\sqrt{11}),\frac12 (3+ \sqrt{11})\right)$$
and
$$\left(\frac12(\sqrt{11}-1),\frac12 (3- \sqrt{11})\right)$$
Which is equivalent to the posted solutions.


Spring SAML: SAMLException: Unsupported request

Question: I am getting
Caused by: org.opensaml.common.SAMLException: Unsupported request
    at org.springframework.security.saml.processor.SAMLProcessorImpl.getBinding(SAMLProcessorImpl.java:265) ~[spring-security-saml2-core-1.0.3.RELEASE.jar:1.0.3.RELEASE]
    at org.springframework.security.saml.processor.SAMLProcessorImpl.retrieveMessage(SAMLProcessorImpl.java:172) ~[spring-security-saml2-core-1.0.3.RELEASE.jar:1.0.3.RELEASE]
    at org.springframework.security.saml.SAMLProcessingFilter.attemptAuthentication(SAMLProcessingFilter.java:80) ~[spring-security-saml2-core-1.0.3.RELEASE.jar:1.0.3.RELEASE]
    ... 62 more exception

while testing SSO between SP and client IdP.
According to the org.springframework.security.saml.processor.SAMLProcessorImpl#getBinding(org.opensaml.ws.transport.InTransport) method source code, this exception is thrown when suitable message decoder was not found.
In my security context I have defined next bindings:

    <bean id="processor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
        <constructor-arg>
            <list>
                <ref bean="redirectBinding"/>
                <ref bean="postBinding"/>
                <ref bean="artifactBinding"/>
                <ref bean="soapBinding"/>
                <ref bean="paosBinding"/>
            </list>
        </constructor-arg>
    </bean>

Can anyone helps me to understand why it is being happening?
UPDATE:
If I use http://idp.ssocircle.com as an IdP everything works fine, the issue occurs only when I am trying to link with a different IdP.
Here is debug log:
2019-03-04 16:46:42.315 DEBUG [211 default task-43][ExceptionTranslationFilter] Calling Authentication entry point.
2019-03-04 16:46:42.315 DEBUG [211 default task-43][ChainingMetadataProvider] Checking child metadata provider for entity descriptor with entity ID: com:my:app
2019-03-04 16:46:42.315 DEBUG [211 default task-43][AbstractMetadataProvider] Searching for entity descriptor with an entity ID of com:my:app
2019-03-04 16:46:42.315 DEBUG [211 default task-43][AbstractMetadataProvider] Metadata document did not contain a descriptor for entity com:my:app
2019-03-04 16:46:42.315 DEBUG [211 default task-43][AbstractMetadataProvider] Metadata document did not contain any role descriptors of type {urn:oasis:names:tc:SAML:2.0:metadata}SPSSODescriptor for entity com:my:app
2019-03-04 16:46:42.316 DEBUG [211 default task-43][AbstractMetadataProvider] Metadata document does not contain a role of type {urn:oasis:names:tc:SAML:2.0:metadata}SPSSODescriptor supporting protocol urn:oasis:names:tc:SAML:2.0:protocol for entity com:my:app
2019-03-04 16:46:42.316 DEBUG [211 default task-43][ChainingMetadataProvider] Checking child metadata provider for entity descriptor with entity ID: com:my:app
2019-03-04 16:46:42.316 DEBUG [211 default task-43][AbstractMetadataProvider] Searching for entity descriptor with an entity ID of com:my:app
2019-03-04 16:46:42.316 DEBUG [211 default task-43][KeyStoreCredentialResolver] Building credential from keystore entry for entityID apollo, usage type UNSPECIFIED
2019-03-04 16:46:42.316 DEBUG [211 default task-43][KeyStoreCredentialResolver] Processing PrivateKeyEntry from keystore
2019-03-04 16:46:42.317 DEBUG [211 default task-43][EvaluableCredentialCriteriaRegistry] Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableEntityIDCredentialCriteria for criteria class org.opensaml.xml.security.criteria.EntityIDCriteria
2019-03-04 16:46:42.317 DEBUG [211 default task-43][KeyStoreCredentialResolver] Building credential from keystore entry for entityID apollo, usage type UNSPECIFIED
2019-03-04 16:46:42.317 DEBUG [211 default task-43][KeyStoreCredentialResolver] Processing PrivateKeyEntry from keystore
2019-03-04 16:46:42.317 DEBUG [211 default task-43][EvaluableCredentialCriteriaRegistry] Registry located evaluable criteria class org.opensaml.xml.security.credential.criteria.EvaluableEntityIDCredentialCriteria for criteria class org.opensaml.xml.security.criteria.EntityIDCriteria
2019-03-04 16:46:42.318 DEBUG [211 default task-43][StaticBasicParserPool] Setting DocumentBuilderFactory attribute 'http://javax.xml.XMLConstants/feature/secure-processing'
2019-03-04 16:46:42.318 DEBUG [211 default task-43][StaticBasicParserPool] Setting DocumentBuilderFactory attribute 'http://apache.org/xml/features/dom/defer-node-expansion'
2019-03-04 16:46:42.318 DEBUG [211 default task-43][StaticBasicParserPool] Setting DocumentBuilderFactory attribute 'http://apache.org/xml/features/disallow-doctype-decl'
2019-03-04 16:46:42.319 DEBUG [211 default task-43][SAMLContextProviderImpl] No IDP specified, using default AAMC-External
2019-03-04 16:46:42.319 DEBUG [211 default task-43][ChainingMetadataProvider] Checking child metadata provider for entity descriptor with entity ID: AAMC-External
2019-03-04 16:46:42.319 DEBUG [211 default task-43][AbstractMetadataProvider] Searching for entity descriptor with an entity ID of AAMC-External
2019-03-04 16:46:42.319 DEBUG [211 default task-43][SAMLUtil] Index for AssertionConsumerService not specified, returning default
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selecting default IndexedEndpoint
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selected IndexedEndpoint with explicit isDefault of true
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAMLEntryPoint] Processing SSO using WebSSO profile
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selecting default IndexedEndpoint
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selected IndexedEndpoint with explicit isDefault of true
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selecting default IndexedEndpoint
2019-03-04 16:46:42.320 DEBUG [211 default task-43][SAML2MetadataHelper] Selected IndexedEndpoint with explicit isDefault of true
2019-03-04 16:46:42.321 DEBUG [211 default task-43][SAML2MetadataHelper] Selecting default IndexedEndpoint
2019-03-04 16:46:42.321 DEBUG [211 default task-43][SAML2MetadataHelper] Selected IndexedEndpoint with explicit isDefault of true
2019-03-04 16:46:42.321 DEBUG [211 default task-43][WebSSOProfileImpl] Using default consumer service with binding urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST
2019-03-04 16:46:42.321 DEBUG [211 default task-43][BaseMessageEncoder] Beginning encode message to outbound transport of type: org.opensaml.ws.transport.http.HttpServletResponseAdapter
2019-03-04 16:46:42.321 DEBUG [211 default task-43][HTTPRedirectDeflateEncoder] Deflating and Base64 encoding SAML message
2019-03-04 16:46:42.321 DEBUG [211 default task-43][BaseMessageEncoder] Marshalling message
2019-03-04 16:46:42.323 DEBUG [211 default task-43][HTTPRedirectDeflateEncoder] Building URL to redirect client to
2019-03-04 16:46:42.323 DEBUG [211 default task-43][HTTPRedirectDeflateEncoder] Generating signature with key type 'RSA', algorithm URI 'http://www.w3.org/2000/09/xmldsig#rsa-sha1' over query string 'SAMLRequest=fVJNb9swDP0rAu%2B2bNfNFiFOka0rVqBDg9jdYTdGZhIVtuSJctb9%2BymJi3aXHgW9L%2FJxcfPSd%2BJIno2zFeRpBoKsdq2x%2BwqemrvkM9wsF4x9VwxqNYaD3dDvkTiISLSsLj8VjN4qh2xYWeyJVdCqXv14UEWaqcG74LTrQKyYyYdo9dVZHnvyNfmj0fS0eajgEMKgpNxjoD%2F4N0XsdTpiSDuDhp3VyKl2vcRhSCaMPLnLun4EcRsjGYvhPMZJiaNUhHLKAfdxmoue83vpBooZT7QNtcaTDrKngKvow%2FLbSyBvsZOmHUDcOa%2FpPHUFO%2ByYQNzfVoBlSUTb50%2FFbq6f5%2BX1rN1e77bzfKbNYZZHEK%2BR2RzpjcY80r2NYWyooMjyeZJdJVnZFLkqZ6os0qsi%2FwViPe3qi7GXDj5a7PYCYvW9adbJ%2BrFuQPx87TICYGpOnd39%2B8o%2BFsbXnmAZV66mBqgdFQ8L%2BV5zOT3%2FP47lPw%3D%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1'
2019-03-04 16:46:42.323 DEBUG [211 default task-43][JCEMapper] Request for URI http://www.w3.org/2000/09/xmldsig#rsa-sha1
2019-03-04 16:46:42.323 DEBUG [211 default task-43][JCEMapper] Request for URI http://www.w3.org/2000/09/xmldsig#rsa-sha1
2019-03-04 16:46:42.324 DEBUG [211 default task-43][SigningUtil] Computing signature over input using private key of type RSA and JCA algorithm ID SHA1withRSA
2019-03-04 16:46:42.327 DEBUG [211 default task-43][SigningUtil] Computed signature: 3a5c9d8b1d8e3f70adf34fef3e73ff986a79de8a387232e2d37ed4c6fa217293c5e42fb1c2102dc761bbdeba9ba310aa53fdbe826b0b10478089cdcf5ce0813a6b1347d532a2126e51c08fbc09e42b9844a11fb4694a330e056522a2802e7c3418d7d6fbcae83472f7a15000836423b47fcd98f6e5b8ca645ef15ab8fd7c6d8b68de9a8ca5bb3db7887fa5d5a6a15714a2f942f136c837e125e8fd26fac7a40d0aa519fd8a9cc15f7c9282ca76be20b16a6ba80d5e75c786fa962f261592a99fd94e0949cee406f62a5fd8026bec11d21bc2823f5b68d9e45740f4f2845a0a58f0e4b2b046b664811062de5c42cc4bbb49ea51bab0a39ca7e78acc3fffbb1e74
2019-03-04 16:46:42.327 DEBUG [211 default task-43][HTTPRedirectDeflateEncoder] Generated digital signature value (base64-encoded) Olydix2OP3Ct80/vPnP/mGp53oo4cjLi037UxvohcpPF5C+xwhAtx2G73rqboxCqU/2+gmsLEEeAic3PXOCBOmsTR9UyohJuUcCPvAnkK5hEoR+0aUozDgVlIqKALnw0GNfW+8roNHL3oVAAg2QjtH/NmPbluMpkXvFauP18bYto3pqMpbs9t4h/pdWmoVcUovlC8TbIN+El6P0m+sekDQqlGf2KnMFffJKCyna+ILFqa6gNXnXHhvqWLyYVkqmf2U4JSc7kBvYqX9gCa+wR0hvCgj9baNnkV0D08oRaCljw5LKwRrZkgRBi3lxCzEu7SepRurCjnKfnisw//7sedA==
2019-03-04 16:46:42.328 DEBUG [211 default task-43][HstsHeaderWriter] Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@550312e6
2019-03-04 16:46:42.328 DEBUG [211 default task-43][HttpSessionSecurityContextRepository] SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.

Answer: Check the certificate used on Client IdP side. If expired, root certificate expired or using an invalid algorithm, it will be rejected.


Gitlab CI timeout manual job

Question: I have a pipeline with 4 stages:

compile
test
package
deploy

The package stage is manual. I would like the pipeline to timeout if no manual action has been taken after x minutes. I know that there is a timeout option but it's only taken into account after the job started.
package_staging:
  image: maven:3.6.3-jdk-11
  stage: package
  script:
    - mvn $MAVEN_CLI_OPTS -DskipTests clean install -Pstaging
  only:
    - branches
  except:
    - master
    - /^release/.*$
  when: manual

Comment: I have the same question and no help from documentation... :/
Comment: try to set a variable and check after the timeout if the variable is set (true/false)
Answer: If I got your problem right, you want to achieve the following:
if manual action is triggered --> run package and deploy stage jobs
if manual action is triggered --> do not run deploy stage jobs
This can be achieved by using the needs keyword for your deploy stage jobs, where your need is a dependency to the manual job (which would need allow_failure:true in order to keep the pipeline working) - as this can lead to other problems, this seems to be no good solution.
Correct behavior
In terms of correctness, you could do the following:

change your package_staging job to make use of the trigger keyword

your manual job will trigger a separate pipeline that contains two jobs

the child pipeline (triggered in 1.) will

first build your project
deploy it to the desired location

In case this is the correct understanding of your problem, I could come up with a more extensive example
Answer: There is simply no such feature. Consider upvoting and commenting with your use case on the relevant feature request issue: https://gitlab.com/gitlab-org/gitlab-runner/-/issues/29574

Gitlab CI timeout manual job