Cannot get MOXy (JAXB) to work in my application

Question: I tried to use MOXy's ObjectGraph feature to marshal a subset of class fields to a xml string. I have done the followings:

Put the eclipselink.jar in the classpath
Created a jaxb.properties file, have the content to be  javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory, and put it in the same package as my domain class that I want to marshal or unmarshal.

I wrote a method in the domain class, which marshals the subset of fields to a xml string. I called this method in the classes main() method, and I got the correct result.
My application is in an ear file, and the domain classes are packaged in a model.jar file. The marshalling method is called by a service class which is in the same jar file. After I deployed to WebLogic server and ran the function which uses this marshalling function, I always got the exception at the line:
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "dbstring");

Basically I cannot set this OBJECT_GRAPH property, and cannot get the correct marshalling result. However if I ran the domain class in the model.jar, it was fine.
Any ideas? Thanks!
Comment: What exception do you get?
Answer: We introduced the Object Graph feature in EclipseLink 2.5.0 (see:  http://blog.bdoughan.com/search/label/Object%20Graphs). EclipseLink MOXy is the default JAXB provider in WebLogic (as of 12.1.1, see:  http://blog.bdoughan.com/2011/12/eclipselink-moxy-is-jaxb-provider-in.html) but as of today (Nov 7, 2013) this version of EclipseLink has not been included in a release version of WebLogic.  The following article will help you use a newer version of EclipseLink in WebLogic.

http://blog.bdoughan.com/2012/10/updating-eclipselink-in-weblogic.html


Array para Table PHP

Question: Eu tenho o seguinte código que conecta em um ftp e volta uma lista.
Mas não estou conseguindo fazer com que ele monte um Table com essa lista.
Alguém sabe como fazer?
$ftp_server = "ftp.site.com.br";
$ftp_user = "USER_FTP";
$ftp_pass = "SENHA_FTP";

$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "
$ftp_server";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

ftp_pasv($conn_id, TRUE);

$dir = "/diretorio/";

function filecollect($dir,$filelist) {
    global $conn_id; //Retorna FTP
    $files = ftp_nlist($conn_id,$dir); //Retorna o Directory
    foreach ($files as $file) {
        $isfile = ftp_size($conn_id, $file);
        if($isfile == "-1") { //É um arquivo ou diretorio?
            $filelist = filecollect($dir.'/'.$file,$filelist,$num); //Se for diretório, faça "filecollect()"
        }
        else {
            $filelist[(count($filelist)+1)] = $file; //Se não,adicione a uma arquivo para a lista
        }
    }
    return $filelist;
}

$list = filecollect($dir,$filelist);
$list = implode("
$ftp_server", $list);

    echo $list;

ftp_close($conn_id);

Sei que tem algumas falhas mas o principal é transformar esses dados em uma table.
Desde já, obrigado pela ajuda.
Comment: Os dados voltam do ftp como array ou como objeto?
Comment: @AdrianoLuz com $list = implode("$ftp_server", $list); volta uma String, se eu eu tirar o implode e colocar print_r($list) volta um array
Comment: e esse array você já tentou dar um var_dump pra ver o que tem nele? Se ele retornar um array com os campos da tabela basta dar uma foreach e montar a tabela
Answer: $ftp_server = "ftp.site.com.br";
$ftp_user = "USER_FTP";
$ftp_pass = "SENHA_FTP";

$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "
$ftp_server";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

ftp_pasv($conn_id, TRUE);

$dir = "/diretorio/";

function filecollect($dir,$filelist) {
    global $conn_id; //Retorna FTP
    $files = ftp_nlist($conn_id,$dir); //Retorna o Directory
    foreach ($files as $file) {
        $isfile = ftp_size($conn_id, $file);
        if($isfile == "-1") { //É um arquivo ou diretorio?
            $filelist = filecollect($dir.'/'.$file,$filelist,$num); //Se for diretório, faça "filecollect()"
        }
        else {
            $filelist[(count($filelist)+1)] = $file; //Se não,adicione a uma arquivo para a lista
        }
    }
    return $filelist;
}

$list = filecollect($dir,$filelist);

ftp_close($conn_id);

No HTML
<?php
    foreach ($list as $row)
     {
        echo"
";
        echo "www.site.com.br" . $row . "	" ;
        echo"
";
     }

?>

Agora está certo, para quem precisa está ai. @AdrianoLuz eu estava fazendo um foreach, mas não sei o que estava fazendo de errado que estava retornando com erro.

Array para Table PHP


How to determine where an object was instantiated in VisualVM Heap Dump

Question: I have a bug in my program that is generating a lot of String instances (7000+ in Heap according to VisualVM). I am trying to isolate which class is responsible for this so I can understand why it is happening.
The following is an example of the heap dump for String:

How do I figure out which class is responsible for generating each of the String? I am working with about 40 classes together so I would like to be able to identify the culprit class through VisualVM if possible.
Comment: Have you been able to resolve the problem?
Comment: @Ales0x I will be revisiting the problem in 1-2 days and iwll be able to answer then
Answer: You should have a look at this Q/A: How to view memory allocation stacktrace in Java VisualVM - a heap profile, which is a "memory allocation stacktrace" is what you want.
Here is a nice tutorial : Analyzing Memory Leak in Java Applications using VisualVM.
In general, there is several ways howto diagnose this problem, using a Java profiler:

use CPU profiling, the best in a instrumentation mode, this will record all method invocations, look at String.<init> - this will show you all the possible methods that execute new String(). The best tools are e.g. jProfiler, Java Mission Control, where you can easily identify all the callers of the String.<init>. The same applies for VisualVM. I think using CPU profiling is the most straightforward way of idenifying where in the code the new String occurs the most.
collect a heap dump in MAT, and analyze that, this will allow you to traverse the heap, you will again search for String finding all the references to a String object.
use Heap profiling option of a Java profiler (e.g. VisualVM), is similar to collecting a heap dump, only this heap profiling is usually collected online. So just enable heap profiling in VisualVM and follow the references from the String instances (i.e. find objects referencing String).
Comment: That tutorial link was very useful! Thank you


Angular alignment of points on two concentric circles

Question: I have two concentric circles $C_1$ and $C_2$ with radii $r_1,r_2$ such that $r_1< r_2$and a set of finite points $P=\left \{ p_1,p_2...p_n \right \}$ and $Q=\left \{ q_1,q_2...q_n \right \}$ are identified on circles $C_1,C_2$ respectively.
Now I would like to rotate the circle $C_1$ such that the sum of squares of the Euclidean-distances $\sum_i^nd(p_i,q_i)^2$ is minimized, where $d(.)$ indicates the Euclidean-distance.
Note that both $p_i$ and $q_i$ are 2-d coordinates in real space. What is the angle of optimal rotation, in either a clockwise or anti-clockwise direction that minimizes these sums of Euclidean distances?
I was looking at it as $P$ being hit by a rotation matrix and was finding the gradient w.r.t $\theta$ in the rotation matrix.
Answer: Let $p_i=(r_1\cos\phi_i,r_1\sin\phi_i)$ and $q_i=(r_2\cos\theta_i,r_2\sin\theta_i)$. Then rotating by $\psi$ leads to
$$
\begin{align}
\sum_{i=1}^nd(p_i,q_i')^2
&=
\sum_{i=1}^n\left((r_1\cos(\phi_i+\psi)-r_2\cos\theta_i)^2+(r_1\sin(\phi_i+\psi)-r_2\sin\theta_i)^2\right)
\\
&=
n(r_1^2+r_2^2)-2r_1r_2\sum_{i=1}^n\cos(\phi_i-\theta_i+\psi)
\\
&=
n(r_1^2+r_2^2)-2r_1r_2\Re\sum_{i=1}^n\mathrm e^{\phi_i-\theta_i+\psi}
\\
&=
n(r_1^2+r_2^2)-2r_1r_2\Re\left(\mathrm e^\psi\sum_{i=1}^n\mathrm e^{\phi_i-\theta_i}\right)
\;.
\end{align}
$$
This is minimal for
$$\psi=\arg\left(\sum_{i=1}^n\mathrm e^{\theta_i-\phi_i}\right)\;,$$
and the minimal value is
$$
n(r_1^2+r_2^2)-2r_1r_2\left|\sum_{i=1}^n\mathrm e^{\theta_i-\phi_i}\right|
\;.
$$
Comment: Wonderful. I like the way you used the polar coordinates and the Euler representations. You may wanna look at this as well, http://math.stackexchange.com/questions/378662/optimal-rotation-to-align-a-circle-with-external-points as it may interest you!


Prove the limit of a function approach to a derivative

Question: So here is the question:
Suppose that $f:(-1,1)\to\mathbb{R}$ is differentiable at $0$ and that $(x_n)$ and $(y_n)$ are sequences in $(-1,1)$ such that $x_n\to 0, y_n \to 0$, and $x_n < y_n$ for all $n$. Let $$D_n = \frac{f(y_n)-f(x_n)}{y_n - x_n}$$
Show that if $f'$ is defined and continuous in $(-1,1)$ then $D_n \to f'(0)$
I've thought to prove this by holding $x_n$ fixed and take $y_n\to0$, then take $x_n\to0$.
But I then have a concern that the limit by taking $x_n\to0,y_n\to0$ separately may not be equal to the limit by taking $x_n\to0,y_n\to0$ at the same time.
Is there another approach for this?
Or is there any evidence to show that the limits by taking $x_n,y_n\to0$ separately or at the same time are the same?
Comment: Try [the mean value theorem](https://en.wikipedia.org/wiki/Mean_value_theorem).
Comment: The result is true without continuity of $f'$ but then we must have $x_n<00>y_n$.
Comment: Oh, I think that'll work, since $x_n < y_n$ for all $n$ so we can take a sequences of intervals that goes to 0
Comment: Paramanand, yes, that's the first part of problem, and I got that part, this is the third and I'm stuck
Comment: If the limits $y_n/(y_n-x_n)$ and $x_n/(y_n-x_n)$ exist, you only need that $f'(0)$ exists...
Comment: ^^That's the second part of the problem, and I got that part as well. Thanks for the hint though.
Answer: Hint:
By mean value theorem, for every $n$ there exists a $c_n\in(x_n,y_n)$ with
$$ D_n = \frac{f(y_n) - f(x_n)}{y_n - x_n} = f'(c_n).$$
Now, as $y_n - x_n \to 0$ it follows $c_n \to 0$ and $D_n\to...?$


how to get scroll position for tablet in android

Question: I am trying to make application like single page scroll website. I have some menus; if i click the menu, it will start scroll down and show the corresponding Paragraph; in that I have added videoview, everything is working fine, but when I test with the tablet - if I click menu its not showing corresponding paragraph but its scrolling. kindly suggest some solution thanks in advance
this is my code.
  scroll.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
            @Override
            public void onScrollChanged()
            {

                int scrollY = scroll.getScrollY();
                System.out.println(+scrollY);
                tv.setText("Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado");
                tv1.setText("Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado Escriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviadoEscriba el mensaje y luego clickee el canal a ser enviado");
                if(scrollY>350)
                {
                    top.setVisibility(View.VISIBLE);
                    System.out.println("Success");
                    top.setX(400);
                    top.setY(550+scrollY);
                     if(link=="")
                    {
                        videoView.setVisibility(View.GONE);
                    }
                     videoView.setVisibility(View.VISIBLE);
                    mediaController.setAnchorView(videoView);
                    Uri video = Uri.parse(link);
                    videoView.setMediaController(mediaController);
                    videoView.setVideoURI(video);

                    videoView.setOnPreparedListener(new OnPreparedListener() {
                      public void onPrepared(MediaPlayer mp) {
                          //first starting the video, when loaded
                        videoView.start();
                          //then waiting for 1 millisecond
                          try {
                              Thread.sleep(1);
                          }
                          catch (InterruptedException e) {
                              //     TODO Auto-generated catch block
                              e.printStackTrace();
                          }
                          videoView.pause();
                          mediaController.show();
                      }
                  });
                    top.setOnClickListener(new View.OnClickListener()
                    {

                        @Override
                        public void onClick(View v)
                        {
                            // TODO Auto-generated method stub
                            scroll.fullScroll(scroll.FOCUS_UP);

                        }
                    });
                }
                else
                {
                    top.setVisibility(View.INVISIBLE);
                }

            }

        });

        b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            scroll.scrollBy(0, +400);
        }
    });
    b3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            scroll.scrollBy(0, +1000);
        }
    });

Answer: You are passing absolute value in pixels in scrollBymethod. Of course it wouldn't work everywhere because android runs on thousands different screens.
So I suggest you to start from this article, and after, when you will clearly understand everything here, you should go with something like:
scroll.scrollBy(0, paragraphOneHeight + paragraphTwoHeight);

Where paragraphOneHeight and paragraphTwoHeight is dynamically calculated heights of proper paragraphs in your ScrollView.


Query to get one entry from multiple rows

Question: Query:
select machinename, StatusCode, max(size) as size, statusID
from machine where MachineID In( '33','22') and StatusCode = 166
group by machinename, StatusCode, statusID
order by max(size) DESC

Result:
   machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1
    test1        166         25       2
    test2        166         75       3
    test2        166         48       4

Requirement:
I need to display only one entry for each machine.
I have to do this by taking the max size value between the two entries as shown above.
like for test1 i have two sizes 50 and 25 I have to show the row which has 50 and ignore row which has 25.
Thanks
Desired Result:
 machinename  StatusCode  size statusID
    -----------  ----------  ---- --------
    test1        166         50       1
    test2        166         75       3

Comment: +1 At first look I thought this was going to be really simple, but I can't figure it out without using some form of Mark's solution!
Comment: It should also be noted that you *MIGHT* have some normalization issues with your database. You said that StatusID is the primary key, so the fact that you have repeating groups suggests there might be a problem. Is StatusCode functionally dependent on StatusID or machinename? And since machinename is presumably dependent on MachineID, that appears to be an anomaly on its own.
Comment: thanks john. was about to fix it.. that was quick.. :)
Answer: SELECT machinename, StatusCode, size, statusID
FROM (
    SELECT
        machinename,
        StatusCode,
        size,
        statusID,
        ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn
    FROM machine
    WHERE MachineID IN ('33','22')
    AND StatusCode = 166
) T1
WHERE rn = 1
ORDER BY size DESC

Comment: This worked perfect, can you explain me the "ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn" if you dont mind. Like what is it actually doing


Variance of sample autocorrelation (Ljung-Box)

Question: The Ljung-Box and Box-Pierce tests make use of the sample autocorrelation
$$ r_k = \frac {\sum_{t=k+1}^n a_ta_{t-k}} {\sum_{t=1}^n a_t^2}$$
and the Ljung-Box test exploits the result that
$$Var(r_k) = \frac {n-k}{n(n+2)}$$
Here, the lag order is $k$, $n$ is the length of the series, and $a_t$ is the (true) error, and thus not the residual of some preliminary estimation.
In the original paper by Box and Pierce, we find

My question: For those among us who cannot readily show this, how can we establish this result?
Box and Pierce work under the assumption of (jointly and independent) normal innovations $a_t$, so that exact variances are within reach. In particular, the distribution of the sample correlation coefficient should then provide a starting point, as discussed e.g. here, What is the distribution of sample correlation coefficients between two uncorrelated normal variables? and here.
However, I have not been able to use these results to establish that of Box and Pierce, nor have found any other proof.
FWIW, a little simulation suggests that the stated result is indeed quite a bit more accurate than the $1/n$ approximation, with the difference however, as expected, shrinking with $n$:

<code>n1 <- 25
n2 <- 100
max.lag <- 14
autocorrs.small <- replicate(20000, acf(rnorm(n1), lag.max=max.lag, plot=F)$acf[-1])
autocorrs.large <- replicate(20000, acf(rnorm(n2), lag.max=max.lag, plot=F)$acf[-1])

plot(1:max.lag, apply(autocorrs.small, 1, var), ylim=c(0, 0.04), col="brown")
points(1:max.lag, apply(autocorrs.large, 1, var), col="green")

lines(1:max.lag, (n1-1:max.lag)/(n1*(n1+2)), lwd=2, col="brown")
segments(1, 1/n1, max.lag, 1/n1, lwd=2, col="brown", lty=2)
lines(1:max.lag, (n2-1:max.lag)/(n2*(n2+2)), lwd=2, col="green")
segments(1, 1/n2, max.lag, 1/n2, lwd=2, col="green", lty=2)
</code>
One difference that comes to mind is that the sample autocorrelation coefficient can only make use of $n-k$ observations in the numerator due to the lags, unlike the standard correlation coefficient. E.g., the last provided link would suggest $Var(r_k)=1/(n-1)$ under independence.
Can anyone see further steps from here?
Note: This question has been asked before, without answer so far.
Comment: @User1865345, thank you! Appreciate it.
Comment: Yes. You are right, Christoph. In situations like these, I consult the books by Kendall and Anderson. I checked Kendall and they dealt in large sample theory and deduced the Bartlett's formula. I will check Anderson.
Comment: BTW, Christoph, I have left the post's link in the [chat](https://chat.stackexchange.com/rooms/18/ten-fold); the veterans do peek in the room. In any case, if nothing happens, a bounty could be thought about. On another note, I searched extensively in Anderson but of no avail.
Comment: @RichardHardy, by Kendall I meant [The Advanced Theory of Statistics, Vol. 3](https://archive.org/details/TheAdvancedTheoryOfStatisticsVolume3SirMauriceG.KendallAlanF.Stuart/mode/1up) and by Anderson, I meant [The Statistical Analysis of Time Series](https://onlinelibrary.wiley.com/doi/book/10.1002/9781118186428).
Comment: There is no particular reason to search in these books; it's that they were the contemporary books of that period extensive enough to be taken as the authority (mainly, I only have access to them right now). @RichardHardy
Comment: @User1865345, I now also try a bounty.
Comment: At this point, I would be able to sleep peacefully if we are able to decipher "readily" done deduction which apparently we are failing to detect and the books didn't bother to cover. @ChristophHanck.
Comment: Have you considered using the Bartlett's formula? I would play around it to see what happens.
Comment: Thanks, that had crossed my mind, too. But Bartlett's formula gives the asymptotic variance, doesn't it? See e.g. https://stats.stackexchange.com/questions/610737/maq-show-sqrtn-hat-rhoq-l-oversetd-to-n0-1-2-sum-j-1/610745#610745 Box and Pierce seem to be able to give a finite sample result (under normality). (As B&P also state in their above approximation, as $n$ becomes large, their result collapses to what Bartlett's formula would give asymptotically.)
Comment: @User1865345, full references would be nice. Neither a book by Kendall nor one by Anderson rings a bell to me...
Answer: Edit (05/07/2023)
When answering this question, I realized the job actually can be done by only summoning Lemma 1 below (hence avoid touching the much more difficult Lemma 2), which will substantially reduce the machinery and calculations.  The argument (largely  exploiting the independence between $T(X)$ and $r$) may be how authors discovered the variance expression.
With the notations introduced in my old answer, the goal is to prove
\begin{align}
& E[T_iT_j] = 0, & 1 \leq i \neq j \leq n, \tag{i} \\
& E[T_i^2T_j^2] = \frac{1}{n(n + 2)}, & 1 \leq i \neq j \leq n, \tag{ii} \\
& E[T_i^2T_jT_k] = 0, & i, j, k \text{ distinct}, \tag{iii} \\
& E[T_iT_jT_kT_l] = 0, & i, j, k, l \text{ distinct}. \tag{iv}
\end{align}
We assume normality of $X$ from now on.  To prove (i), write $X_iX_j = T_iT_j \times r^2$. Since $T_iT_j$ is independent of $r^2$ ($T_iT_j$ is a function of $T(X)$), $E[X_iX_j] = E[T_iT_jr^2] = E[T_iT_j]E[r^2]$. But then $E[X_iX_j] = E[X_i]E[X_j] = 0$ (by normality) and $E[r^2] > 0$ imply that $E[T_iT_j] = 0$. In the same manner, (iii) and (iv) hold.
Similarly, $X_i^2X_j^2 = T_i^2T_j^2 \times r^4$ and independence imply that $E[X_i^2X_j^2] = E[T_i^2T_j^2]E[r^4]$, whence
\begin{align}
E[T_i^2T_j^2] = \frac{E[X_i^2]E[X_j^2]}{E[r^4]} = \frac{1}{E[r^4]}.
\end{align}
So it suffices to determine $E[r^4]$, which is straightforward:
\begin{align}
E[r^4] &= E[(X_1^2 + \cdots + X_n^2)^2] = nE[X_1^4] + 2\binom{n}{2}E[X_1^2X_2^2] \\
&= 3n + n(n - 1) = n(n + 2).
\end{align}
This completes the proof of (ii).
Old Answer (04/05/2023)
One way to show this result is to use the following two lemmas (Lemma 1 and Lemma 2 are Theorem 1.5.6 and Exercise 1.32 in Aspects of Multivariate Statistical Theory by R. Muirhead respectively):

Lemma 1. If $X$ has an $m$-variate spherical distribution with $P(X = 0) = 0$ and $r = \|X\| = (X'X)^{1/2}, T(X) = \|X\|^{-1}X$, then $T(X)$ is
uniformly distributed on $S_m$ and $T(X)$ and $r$ are independent.

Lemma 2. Let $T$ be uniformly distributed on $S_m$ and partition $T$ as $T' = (\mathbf{T_1}' | \mathbf{T_2}')$, where $\mathbf{T_1}$ is $k \times 1$ and $\mathbf{T_2}$ is $(m - k) \times 1$. Then $\mathbf{T_1}$ has density function
\begin{align*}
f_{\mathbf{T_1}}(u) = \frac{\Gamma(m/2)}{\pi^{k/2}\Gamma[(m - k)/2]}(1 - u'u)^{(m - k)/2 - 1}, \quad 0 < u'u < 1. \tag{1}
\end{align*}

Here $S_m$ stands for the unit sphere in $\mathbb{R}^m$: $S_m = \{x \in \mathbb{R}^m: x'x = 1\}$. The proof to Lemma 1 can be found in the referenced text, and the proof to Lemma 2 can be found in this link (NOT EASY!).
With these preparations, now let's attack the problem.  Denote $X = (a_1, \ldots, a_n) \sim N_n(0, I_{(n)})$, then by Lemma 1$^\dagger$, $r_k$ can be rewritten as
\begin{align*}
r_k = T_1T_{k + 1} + T_2T_{k + 2} + \cdots + T_{n - k}T_n,
\end{align*}
where $T := (T_1, \ldots, T_n)' = X/\|X\|$ has uniform distribution on $S_n$.
By Lemma 2, for $1 \leq i \neq j \leq n$, we have
\begin{align*}
& E(T_iT_j) = \int_{0 < t_i^2 + t_j^2 < 1}t_it_jf_{(T_i, T_j)}(t_i, t_j)dt_idt_j, \tag{2} \\
& E(T_i^2T_j^2) = \int_{0 < t_i^2 + t_j^2 < 1}t_i^2t_j^2f_{(T_i, T_j)}(t_i, t_j)dt_idt_j, \tag{3}
\end{align*}
where $f_{(T_i, T_j)}(t_i, t_j)$ is given by $(1)$ with $\mathbf{T_1} = (T_i, T_j)$.  To evaluate $(2)$ and $(3)$, apply the polar transformation $t_i = r\cos\theta, t_j = r\sin\theta$, $0 < r < 1, 0 \leq \theta < 2\pi$. It then follows that
\begin{align}
E(T_iT_j) = \frac{\frac{n}{2} - 1}{\pi}\int_0^1\int_0^{2\pi}r^2\sin\theta\cos\theta(1 - r^2)^{n/2 - 2}rdrd\theta = 0. \tag{4}
\end{align}
This is because $\int_0^{2\pi}\sin\theta\cos\theta d\theta = 0$.
In addition, it follows by
\begin{align}
& \int_0^{2\pi}\sin^2\theta\cos^2\theta d\theta = \frac{1}{4}\pi, \\
& \int_0^1 r^5(1 - r^2)^{n/2 - 2}dr = \frac{1}{2}B\left(3, \frac{n}{2} - 1\right) =
\frac{1}{(\frac{n}{2} + 1) \times \frac{n}{2} \times (\frac{n}{2} - 1)}
\end{align}
that
\begin{align}
E(T_i^2T_j^2) = \frac{\frac{n}{2} - 1}{\pi}\int_0^1\int_0^{2\pi}r^4\sin^2\theta\cos^2\theta(1 - r^2)^{n/2 - 2}rdrd\theta = \frac{1}{n(n + 2)}. \tag{5}
\end{align}
To complete the evaluation of cross-product terms from $\operatorname{Var}(r_k)$, it remains to show $E[T_a^2T_bT_c] = 0$ for distinct $a, b, c \in \{1, \ldots, n\}$ and $E[T_aT_bT_cT_d] = 0$ for distinct $a, b, c, d \in \{1, \ldots, n\}$.  These calculations are shown as follows.
To calculate $E[T_a^2T_bT_c]$, applying lemma 2 with $\mathbf{T_1} = (T_a, T_b, T_c)$ yields
\begin{align*}
E(T_a^2T_bT_c) = \int_{0 < t_a^2 + t_b^2 + t_c^2 < 1}t_a^2t_bt_cf_{(T_a, T_b, T_c)}(t_a, t_b, t_c)dt_adt_bdt_c. \tag{6}
\end{align*}
Under the spherical transformation
\begin{align*}
& t_a = r\cos(\theta_1), \\
& t_b = r\sin(\theta_1)\cos(\theta_2), \\
& t_c = r\sin(\theta_1)\sin(\theta_2),
\end{align*}
where $0 < r < 1$, $0 \leq \theta_1 < \pi$, $0 \leq \theta_2 < 2\pi$, the integrand in $(6)$ that includes $\theta_1, \theta_2$ is (after multiplying the Jacobian determinant) $\cos^2(\theta_1)\sin^3(\theta_1)\cos(\theta_2)\sin(\theta_2)$, which integrates to $0$ over $[0, \pi) \times [0, 2\pi)$. Hence $E[T_a^2T_bT_c] = 0$.
To calculate $E[T_aT_bT_cT_d]$, applying lemma 2 with $\mathbf{T_1} = (T_a, T_b, T_c, T_d)$ yields
\begin{align*}
E(T_aT_bT_cT_d) = \int_{0 < t_a^2 + t_b^2 + t_c^2 + t_d^2 < 1}t_at_bt_ct_df_{(T_a, T_b, T_c, T_d)}(t_a, t_b, t_c, t_d)dt_adt_bdt_cdt_d. \tag{7}
\end{align*}
Under the spherical transformation
\begin{align*}
& t_a = r\cos(\theta_1), \\
& t_b = r\sin(\theta_1)\cos(\theta_2), \\
& t_c = r\sin(\theta_1)\sin(\theta_2)\cos(\theta_3), \\
& t_d = r\sin(\theta_1)\sin(\theta_2)\sin(\theta_3), \\
\end{align*}
where $0 < r < 1$, $0 \leq \theta_1, \theta_2 < \pi$, $0 \leq \theta_3 < 2\pi$, the integrand in $(7)$ that includes $\theta_1, \theta_2, \theta_3$ is (after multiplying the Jacobian determinant) $\cos(\theta_1)\sin^5(\theta_1)\cos(\theta_2)\sin^3(\theta_2)\cos(\theta_3)
\sin(\theta_3)$, which integrates to $0$ over $[0, \pi) \times [0, \pi) \times [0, 2\pi)$. Hence $E[T_aT_bT_cT_d] = 0$.
To summarize all these pieces, we conclude that $E[r_k] = 0$ and
\begin{align}
 & \operatorname{Var}(r_k) = E[r_k^2] \\
=& E(T_1^2T_{k + 1}^2) + \cdots + E(T_{n - k}^2T_n^2) + \sum E[T_a^2T_bT_c] + \sum E[T_aT_bT_cT_d] \\
=& (n - k) \times \frac{1}{n(n + 2)} = \frac{n - k}{n(n + 2)}.
\end{align}
This completes the proof.  As a by-product, that both $(6)$ and $(7)$ are identical to $0$ also readily (now it is truly "readily") imply that $r_k$ and $r_l$ are uncorrelated when $k \neq l$, which is another proposition claimed by the original paper.

$^\dagger$: The condition of Lemma 1 implies that the main result still holds when the distribution assumption of innovations $(a_1, \ldots, a_n)$ is slightly generalized to spherical distributions (from Gaussian).
Comment: @User1865345 I complemented previously omitted calculations and added more comments (now this answer can also be used to show $\{r_k\}$ are uncorrelated).  So at least for this question, you may "sleep peacefully" now.
Comment: I cannot say for sure what was the "readily" done approach of Box, but this surely is ingenious. +1.
Comment: @User1865345 Yes, it's definitely a non-trivial result (as you can see, my answer still omitted some calculations).  To me, express $r_k$ in terms of $T_1, \ldots, T_n$ is quite natural, the difficulty lies in connecting the problem to Lemma 2.  By the way, the proof of Lemma 2 itself is formidable (as you may see from the mathoverflow link).
Comment: Lemma 2 is itself a powerful result. I am reading the [post](https://mathoverflow.net/a/359658/489645) which I can comprehend.
Comment: I have completed reading it slowly. And it can't be more clearer. Thanks.
Comment: Great answer, thanks - the other one is somewhat more accessible to me, while yours seems more general. Hence I hope splitting bounty and accepted answer is a useful compromise
Comment: @ChristophHanck  During the course of solving a similar problem, I found that there is a much shorter, more accessible proof.  Please check my edit.
Answer: This might not be the most elegant proof, but I believe it answers the question:
We assume $a_1,a_2,...a_n$ are i.i.d standard normal (we can assume as in Ljung-Box a constant variance $\sigma^2$, but then we can divide by $\sigma^2$ both the numerator and denominator in the expression for $r_k$, arriving at the standardized variables, so this doesn't lose generality).
Consider, for arbitrary $k \ne m$ $$ r = \frac{a_ka_m}{\sum_{t=1}^n a_t^2} = \frac{a_ka_m}{a_k^2 + a_m^2 + Z^2}$$
where $Z^2 \sim \chi^2_{n-2}$ and $Z^2,a_k,a_m$ are all independent. It follows from symmetry$^1$ that $r$ have zero mean, $E[r]=0$. Next introduce the rotated variables:
$$ u = (a_k+a_m)/\sqrt{2} , v = (a_k-a_m)/\sqrt{2} $$
which are also independent and standard normal, and observe that $a_k^2 + a_m^2 = u^2+v^2$, $a_ka_m = (u^2-v^2)/2$, so we have
$$r = \frac{1}{2}\left( \frac{u^2}{u^2+v^2+Z^2} - \frac{v^2}{u^2+v^2+Z^2} \right) \equiv \frac{1}{2}(U - V).$$
Now notice that $U$ and $V$ are ratios of Chi-squared random variables, which have a known Beta distribution:
$$U,V \sim \text{Beta}\left(\frac{1}{2},\frac{n-1}{2}\right)$$
with $E[U]=\frac{1}{n}$ and $E[U^2]= \frac{3}{n(n+2)}$ following from the properties of the Beta distribution. Furthermore,
notice that $UV = \left( \frac{uv}{u^2+v^2+Z^2} \right)^2 $ has exactly the same distribution as $r^2$, so $E[UV]=E[r^2]=Var(r)$.
From $r=(U-V)/2$ we also have
$$\begin{align*}
Var(r) &= \frac{1}{4}( Var(U) + Var(V) - 2Cov(U,V) ) \\
          &= \frac{1}{2}( Var(U)  - Cov(U,V) ) \\
          &= \frac{1}{2}( Var(U)  - E[UV] + E[U]^2 ) \\
          &= \frac{1}{2}( E[U^2]  - Var(r) )
\end{align*}$$
So finally,
$$ Var(r) = \frac{1}{3}E[U^2] = \frac{1}{n(n+2)} .$$
To complete the proof we can observe that $r_k$ is a sum of $(n-k)$ terms which all have the same distribution as $r$, namely $r_k = \sum_{t=k+1}^n r_{t,t-k}$, and they are uncorrelated since for any $k,m \ne s,t$,  $Cov(r_{k,m},r_{s,t}) = E[r_{k,m} \cdot r_{s,t}] = 0$, following again from symmetry. Therefore,
$$Var(r_k) = (n-k)Var(r) = \frac{n-k}{n(n+2)}.$$

$^1$ Since the joint distribution of $\{a_t\}$ is symmetric with respect to interchaning $a_t \leftrightarrow -a_t$, the expectation of any odd function  (with respect to any of its arguments) is zero. For example, define $\tilde a_k = -a_k$, such that $ r = -\frac{\tilde a_ka_m}{\sum_{t=1}^n a_t^2} \equiv -\tilde r$. Since $r$ and $\tilde r$ have the same distribution, $E[r] = E[\tilde r]=-E[r]$, implying that $E[r]=0$. The same argument holds for any other odd function such as $\frac{a_ka_ma_sa_t}{(\sum_{t=1}^n a_t^2)^2}$, provided that at least one of the $a_i$'s in the numerator has an odd power. (This is essentially the same argument as given, e.g., here )
Comment: @ChristophHanck It's a nice little "miracle" since otherwise just expressing $r$ as a difference of Beta variates would not be enough to find its variance!
Comment: both answers-proofs are incredible ( now picture loud applause from the crowd ). thanks to both of you.
Comment: Excellent! Could you provide a little more detail as to why "$UV = \left( \frac{uv}{u^2+v^2+Z^2} \right)^2 $ has exactly the same distribution as $r^2$"? I keep looking at the two expressions without success.
Comment: My question is:  how to get $E[r_{k, m} \cdot r_{s, t}] = 0$ "from symmetry"?
Comment: @ChristophHanck $UV$ is the same as $r^2 = \left(\frac{a_ka_m}{a_k^2 + a_m^2 + Z^2}\right)^2$, just with $u,v$ replacing $a_k,a_m$ (which have the same distributions). Is it not clear ?
Comment: @Zhanxiong Since the joint distribution of $\{a_t\}$ is symmetric with respect to interchanging $a_t \leftrightarrow -a_t$, then the expectation of any odd function is zero. I will add a clarification to the answer
Comment: @J.Delaney, oh, right, I think I was for some reason jumping over the "distribution" part, as all are N(0,1), and trying to establish algebraic equivalence.


Auto-incremento no Excel, baseado no valor da linha

Question: Tenho as seguintes células e colunas:

Necessitava de criar um auto-incremento,  na coluna B, incrementando apenas quando o valor da coluna A for diferente, iniciando com "1". A coluna C mostra o resultado pretendido.
Tentei com diversos "SE" mas sem sucesso.
Agradeço a vossa ajuda.
Comment: Tem razão, é o hábito. Corrigido. Obrigado
Comment: Este é o StackOverflow em Português. Por favor, faça perguntas na língua portuguesa :)
Comment: Sem problemas. Boa sorte!
Answer: Você pode alcançar isso com somente 3 funções SE.
Coloque a seguinte função na célular B2
<code>=SE(A2=A1;SE(ÉNÚM(B1);B1;1);SE(ÉNÚM(B1);B1+1;1))
</code>
Explicação da lógica:

O primeiro SE vai fazer a verificação se a célula que 1 casa a esquerda é igual a célula que está 1 casa a esquerda e 1 a cima (No caso de B2 a comparação seria feita em A2 e A1);
Se verdadeiro, então entramos na segunda função SE, ela confere se a célula acima da função tem um valor numérico, se SIM, então o número é duplicado, caso não é colocado o número 1.
Se falso, então entramos na terceira função SE, ela também irá conferir se a célula acima da função tem um valor numérico, se SIM, então o número é incrementado a 1, caso não é colocado o número 1.
Comment: {=ROUND(SUM(1/COUNTIF($A$2:$A$10;$A10:$A$10));0)}
Comment: Excelente! Funcionou em pleno. Muito obrigado pela fórmula e pela explicação.


panel's different controls to list

Question: I have a panel with controls in them. Controls are buttons and progressbars. I would like to add only the buttons to a list, how can I do it?
foreach (Control item in panel1.Controls)
{
    //if (item.GetType() == typeof(ButtonControl))   //i tried this too...
    if ((item is ButtonControl) && (item.Tag.ToString() == "It's not important"))
    {
        panel1.BtnList.Add(item);
    }
}

Here ButtonControl is my own Control, which is inherited from Button class.
Answer: Using LINQ you can do for System.Windows.Forms.Button
List<Button> buttonList = panel1.Controls.OfType<Button>().ToList();

If you want to check the Tag value as well then you can do
List<Button> buttonList = panel1.Controls.OfType<Button>()
                                         .Where(r => r.Tag.ToString() == "It's not important")
                                         .ToList();

EDIT:
If ButtonControl is your own class then you can do:
 List<ButtonControl> buttonList = panel1.Controls.OfType<ButtonControl>().ToList();

Comment: Yes, its' great, thank you!

But i would like specify previously my list to Button Type... (Buttoncontrol is my own control, which is inherited from Buttons class...)
Comment: @user1807523, in that case you can use `OfType`
Comment: @user1807523, do you want to get the `ButtonControl` from the panel and add in a list of `Button` ?
Comment: @Habib Just curious to know, what wrong did the OP done in his/her code?
Comment: Otherwise me too... :)
The error was here:

    `panel1.BtnList.Add(item);`

And it's said, i would like to add a non ButtonControl type of button to ButtonControl list...
Comment: @Mr_Green, without seeing the `BtnList` definition, I am not really sure what was going on

panel's different controls to list


MySQL Join with a subquery to select only one row from joined table

Question: Suppose there are two tables:
Table Parts:
Location PartNum Descrip
-------- ------- --------
Whse1    abc     Frobbitz
Whse2    abc     Frobbitz
Whse3    def     Widget
Whse3    def     Widget

Table Status:
Location  PartNum Status
--------- ------- --------------
*Default* abc     Ready To Ship
*Default* def     Ready To Ship
Whse1     abc     Backordered

In most cases, the default status should be used.
To get the status, the query might look like:
SELECT p.Location,p.PartNum,p.Descrip,s.Status FROM Parts p
LEFT JOIN Status s ON s.PartNum=p.PartNum AND
s.Location = (SELECT MAX(Location) FROM Status s1
WHERE s1.PartNum=p.PartNum AND s1.Location
IN('*Default*',p.Location))

The question is, is this the most efficient (or at least reasonably efficient) way of doing this? My actual application will have up to 7 tables joined in a single query.
Comment: So, are any of the three answers below a better method than the one in my question? After all, my question was "is this the most efficient (or at least reasonably efficient) way of doing this?"
Answer: I think you can use Limit 1 with Order by as below:
 SELECT p.Location,p.PartNum,p.Descrip,s.Status FROM Parts p
  LEFT JOIN Status s ON s.PartNum=p.PartNum AND
  s.Location = (SELECT Location FROM Status s1
        WHERE s1.PartNum=p.PartNum ORDER BY s1.Location ASC LIMIT 1);

Assuming *Default* will come at the top in order by retrieval.
Answer: SELECT p.Location,p.PartNum,p.Descrip,s.Status FROM Parts p
LEFT outer JOIN Status s ON s.PartNum=p.PartNum
where
s.Location = (SELECT MAX(Location) FROM Status s1
WHERE s1.PartNum=p.PartNum AND s1.Location
IN('*Default*',p.Location))

Answer: It appears like what you are trying to do is use a fallback default. You could try something like joining the table twice instead of using a subquery:
SELECT p.Location,p.PartNum,p.Descrip,s.Status
FROM Parts p
LEFT JOIN Status s1 ON s1.PartNum=p.PartNum AND p.Location = s1.Location
LEFT JOIN Status s ON p.PartNum = s.PartNum
   AND s.Location = IFNULL(s1.Location, '*Default*');

Essentially, s1 represents the non-default information. By checking whether s1.Location is NULL or not, we can tell if such a row exists and fallback to *Default* if it doesn't.
Hope that helps!
Comment: That may come down to what Keys and Indices you have. You can check out information about queries by using `EXPLAIN` (see http://dev.mysql.com/doc/refman/5.0/en/explain.html). Personally, I avoid subqueries when possible. It's been my experience that creating the temporary storage for subqueries, specifically for larger result sets, slows down execution a lot.


c# obtaining data from a website

Question: I am currently obtaining data from ebay.co.uk searches using this URL,
_url = "http://www.ebay.co.uk/sch/i.html?_sacat=0&_from=R40&_nkw=" +ItemName.Text +"&_sop=15";

i download the html of it then then do many string splits until I get to the data I require, example:
_itemImage[i - 1] = codes.StringGetter("<img  src=\"", "\" class=\"img\" alt='", items[i], 1);
// or a worse example
_itemPrice[i - 1] = codes.StringGetter("
\n\t\t\t\t\tÂ", "
\n\t\t\t\t
", items[i], 1);

//the function stringGetter is just
text = StringSplit(StringSplit(totalString, start)[number], end)[0];
//StringSplit is just a split with any string accepted

Is there a better way of doing this as it seems long winded and if the html layout changes my program will no longer work.
Answer: Did you check the eBay API ?
The following is the link to eBay's API. I think you can use this API to achieve the search functionality.
https://go.developer.ebay.com/developers/ebay/documentation-tools/sdks/dotnet
Seems you can use this API to get the item details
http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/GetItem.html
Comment: Cheers i will use this and mark it as a answer, but out of curiosity if i had a different website without a available api how would i do this faster?
Answer: That's why eBay has an API. Here's the Finding API: https://go.developer.ebay.com/developers/ebay/products/finding-api
Specifically, you can use the FindProducts to search for Products.
http://developer.ebay.com/DevZone/shopping/docs/CallRef/FindProducts.html

c# obtaining data from a website


Can a SIP call's media address changed mid-call?

Question: I am referring to the c value of an SDP header.

Is it possible that the media stream address changes during a call? And it what scenarios?
Answer: It may be changed with re-INVITE or UPDATE. Some example scenarios:

PABX system consisting of multiple machines decides to route media through another media endpoint because of e.g. high server load or some other problem with this machine
after receiving FAX CNG, CED and/or modem preamble PABX passes the call to fax server
call is passed to specialized music-on-hold or IVR server

Also, addresses advertised in SIP headers or in SDP quite often are not matching real addresses used for communication because of NAT or misconfiguration - for best results B2BUAs often may ignore them.


The cofinite topology is the infimum of the hausdorff topologies in a set $X$

Question: Let $X$ be any set and $\tau_c$ the cofinite topology in $X$ and $T$ be the set of Hausdorff topologies on $X$. Prove that $\tau_c=\inf T$ where the relation is inclusion in the set of all topologies on $X$, i.e. prove that:

$\tau_c\subseteq \tau$ for any $\tau\in T$.
If $\tau'$ is any other topology in $X$ satisfying 1. then $\tau'\subseteq \tau_c$.

It's easy to prove 1: For any $U\in T$, $U^c$ is finite (or $X$) and thus closed in any Hausdorff topology in $X$.
The problem is 2. Let $\tau'$ be any topology satisfying 1., one has to prove that if $U\in \tau'$ then $U^c$ is finite. One may proceed by contradiction and prove that if $U^c$ is infinite then there is a Hausdorff topology in $X$ in which $U$ is not open. So it comes down to:

Let $A$ be an infinite subset of $X$ different from $X$. Prove there is a Hausdorff topology in $X$ in which $A$ is not closed.

I think that's true but I couldn't construct $X$.
Answer: Suppose that $\tau'$ is a topology on $X$ such that $\tau'\nsubseteq\tau_c$, and let $U\in\tau'\setminus\tau_c$. Let $A=X\setminus U$; then $A$ is infinite, and as you say, we want to find a $\tau\in T$ such that $A$ is not closed in $\tau$.
We actually know a little more about $A$: $A\ne X$, for if $A=X$, then $U=\varnothing\in\tau_c$. Thus, we can find a point $p\in U$. We'll be done if we can find a Hausdorff topology $\tau$ on $X$ such that $p\in\operatorname{cl}_\tau A$. The simplest way to do this is to make every point of $X$ isolated except the point $p$, and make $\tau$ look like the cofinite topology at the point $p$:
$$\tau=\{V\subseteq X:p\notin V\text{ or }X\setminus V\text{ is finite}\}\;.$$
I'll leave it to you to check that $\tau$ really is Hausdorff, and that $p\in\operatorname{cl}_\tau A$.


Different REST url for one model

Question: I have an ember application with a few different models. All bar one model pull data from an api at http://example.com/version1/123/. However, one model needs to pull from http://example.com/version1/dogs/123. Is it possible to add a custom url for one model? I've tried changing my store.js file as follows-
App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://example.com/version1/123/'
});

App.Store.registerAdapter('App.Dogs', DS.RESTAdapter.extend({
  host: 'http://example.com/version1/dogs/123'
}));

but it hasn't had an effect. Any suggestions?
Comment: What version of Ember Data are you using? Is your model named "Businesses" or "Business"?
Comment: Sorry got confused while trying to make code generic- it's plural, see edit
Comment: Ember- Data 1.0.0-beta.5+canary.d6015888
Answer: remove the register adapter and just create a custom adapter for dogs (This might need to be singular)
App.DogsAdapter = DS.RESTAdapter.extend({
    host: 'http://example.com/version1/dogs/123/'
});

Answer: If I understand the question correctly, something like this should work
App.DogAdapter = DS.RESTAdapter.extend({
  host: 'http://example.com/version1/dogs/123'
});

I have it setup personally with namespace over host like this.
App.DogAdapter = DS.RESTAdapter.extend({
  namespace: "version1/dogs"
});

Different REST url for one model


SSIS 2012 - Redirect Rows with Special Characters

Question: Im using SSIS 2012 and im importing data from a flat file source -> Temp table -> Final table.
Any errors found are redirected to an error File.
However, im tio apply a new constraint that redirecting all rows of a specific column containing special charaters into a separate error file prior inserting it into the temp table.
Im trying to use a conditional split but it creates a case for each specific charaters ,using the Findstring() function.
What are the other options available?
Comment: My initial thought at this point is that I would import everything into the temporary table (A), then remove the rows containing the special characters into another temporary table (B), and produce the error file from (B) then update the final table from (A)
Comment: Can you post a bit of the data you're importing, along with your table structures, and the work you've already done please. It will help people to be able to help you.
Comment: Thanks, based on your suggestion i also though of creating 2 OleDB Command from the soource file with the "like '%-/&%$#%'",  one  will redirect the valid rows to the temp table and the other will redirect the wrong entries to the error file.
Answer: I'd look at adding a Script Component into your data flow and have it validate your data.
Add a column called HasJunkData to the output of type boolean (DT_BOOL). If you have multiple things to validate, depending on the level of granularity required, you might want a flag per input column or simply decide at the row level whether its good or bad.
Inside the script itself, I'd use something like How to recognize if a string contains unicode chars? to identify the presence of bad characters or potentially a regular expression depending on what "special characters" means to you.
Comment: There's a [technet example Script Component that redirects rows to a particular output depending on a column value](http://technet.microsoft.com/en-us/library/ms136114.aspx) which might help kick you off. (The "REDMOND" redirection example changed to do a different comparison would probably do the trick.)
Comment: I have only one column to validate against a list of pre-defined special characters. Do you have a ressource pointing in using the Script Component with a Flat file (source) and a table(destination). Im fairly new to SSIS.
Answer: How many specific characters are you going to be dealing with? If it's only a few, you can combine FINDSTRING()s together with the || "or" operator in the Conditional Split, e.g.:
(FINDSTRING( [test_column] , "A", 1) > 0) || (FINDSTRING( [test_column] , "B", 1) > 0) || (FINDSTRING( [test_column] , "C", 1) > 0)

would filter rows with test_columns containing "A", "B" or "C" to a single split.
If that's too unwieldy because of the number of characters, then a Script Component, as billinkc suggests is the way to go. (It's especially appropriate if the special characters can be represented as a regualar expression, as script components have access to very good regex functions.)
Comment: Cool. Bear in mind that backslash in an escape character in [SSIS string literals](http://technet.microsoft.com/en-us/library/ms141001.aspx), so you'll need to double it up as "\\" to match it.
Comment: The special characters are "-/\$#&*_" .I'll try both approaches


Zeros of an ideal in $k[x_1,\ldots,x_n]$

Question: Let $k$ be an algebraically closed field (of characteristic zero),
and let $F_1,\ldots,F_m \in k[x_1,\ldots,x_n]$, for some $m,n$.
Let $I$ be the ideal in $k[x_1,\ldots,x_n]$ generated by $F_1,\ldots,F_m$,
$I=\langle F_1,\ldots,F_m \rangle$
and assume that $I$ is a proper ideal of $k[x_1,\ldots,x_n]$.
Further assume that $\bar{a}=(a_1,\ldots,a_n) \in k^n$ is such that
$F_1(\bar{a})=\cdots=F_m(\bar{a})=0$,
namely, $\bar{a}$ is a common zero for $F_1,\ldots,F_m$.
As a proper ideal, $I$ is contained in some maximal ideal $M$ of $k[x_1,\ldots,x_n]$.
Since $k$ is algebraically closed, Hilbert's Nullstellensatz implies that
$M= \langle x_1-c_1,\ldots,x_n-c_n \rangle$, for some $c_1,\ldots,c_n \in k$.

Question: Is it true that $I \subseteq \langle x_1-a_1,\ldots,x_n-a_n \rangle$?

Perhaps this is related to one of the versions of Hilbert's Nullstellensatz.
See this (page 2): I guess I am looking for a result of the following form:
Let $I,J$ be two ideals of $k[x_1,\ldots,x_n]$. Then,
$V(J) \subseteq V(I)$ implies that $I \subseteq J$ -- applynig this to our above $I$ and $J=\langle x_1-a_1,\ldots,x_n-a_n \rangle$, for which $V(J)=\{\bar{a}\}$.
Thank you very much!
Comment: @ViktorVaughn, thank you for the relevant reference.
Comment: The answer for your question is yes. For the general case, $V(J) \subseteq V(I)$ implies $\sqrt I \subseteq \sqrt J$ by Hilbert's Nullstellensatz.
Comment: @mathmath, thank you for your comment, which is the result I vaguely had in mind.
Comment: [Related](https://math.stackexchange.com/questions/1854588/ker-phi-x-1-a-1-x-n-a-n-for-a-ring-homomorphism-phi-rx-1)
Comment: (I have just noticed that in the above related reference, which is another MSE question, one of the comments refers to https://math.stackexchange.com/questions/1352606/is-a-polynomial-f-zero-at-a-1-ldots-a-n-iff-f-lies-in-the-ideal-x-1-a, which is actually what I was asking here).
Answer: Yes, this is true. There is no need for your hypotheses on $k$, either. In fact, we have the following: for any ring $R$ and any $a_1,\dots,a_n\in R$, if $f\in R[x_1,\dots,x_n]$ satisfies $f(a_1,\dots,a_n)=0$, then $f$ lies in the ideal $I=\langle x_1-a_1,\dots,x_n-a_n\rangle$ of $R[\overline{x}]$. To see this, consider the quotient ring $R[\overline{x}]\big/I$. To show $f\in I$, it suffices to show $f\equiv_I 0$, where $\equiv_I$ denotes equivalence modulo $I$. But $x_i\equiv_I a_i$ for each $i\leqslant n$, and so, since addition and multiplication commute with $\equiv_I$, we have $$f=f(x_1,\dots,x_n)\equiv_I f(a_1,\dots,a_n)=0$$ as desired. (If this seems surprising, then it is perhaps more intuitive to think specifically of the case $a_1=\dots=a_n=0$. Then this fact amounts merely to saying that $\langle x_1,\dots,x_n\rangle$ consists precisely of those elements of $R[\overline{x}]$ with constant term $0$, which is hopefully not too surprising. One can recover the general case from this case by considering the unique $R$-algebra endomorphism of $R[\overline{x}]$ that takes $x_i$ to $x_i-a_i$ for each $i\leqslant n$; can you see how?)
Comment: Thank you very much! Nice answer.
Comment: Nice of you :) Yes, it helped!
Comment: @user237522 my pleasure, happy it helped!! :)


Javascript Função Onclick Em conflito com o form?

Question: Possuo um formulário que envia dados para outra página, gostaria de resetar alguns inputs após o envio do formulário logo tentei isso:
<form name='protocolo' id='protocolo' class='excluirclienteform' action='makeprotocolo.php'  target="_blank" method="POST" enctype="multipart/form-data">

                    Selecione uma empresa

                    <select name='id' class="selects2"  required>
                        <option value="">selecione a empresa</option>
                            <?php
                            $buscarid=$pdo->prepare("SELECT ID,nome FROM usuario WHERE permissao = 1 ORDER BY ID ASC");
                            $buscarid->execute();
                            while($linha=$buscarid->fetch(PDO::FETCH_ASSOC)){
                                echo "<option  value=".$linha["ID"].">".$linha["ID"]." ".$linha["nome"]."</option>";
                            }
                            ?>
                        </option>
                    </select>

                    Selecione um item

                    <select name='item' class="selects2"  required>
                        <option value="">selecione a empresa</option>
                            <?php
                            $buscarid=$pdo->prepare("SELECT id,nome FROM protocolo_item order by nome asc");
                            $buscarid->execute();
                            while($linha=$buscarid->fetch(PDO::FETCH_ASSOC)){
                                echo "<option  value=".$linha["id"].">".$linha["id"]." ".$linha["nome"]."</option>";
                            }
                            ?>
                        </option>
                    </select>

                    Quantidade

                    <input type='number' step="1" name='quantidade' id='quantidade' size='20' maxlength="10">

                    Descrição

                    <textarea rows="4" cols="50" name="descricao" id='descricao' maxlength="500"></textarea>

                    <button type='submit' id='inseriritem' name='enviar' onsubmit="document.getElementById('#descricao').reset();">Inserir</button>

                </form>

Porém não obtive sucesso, tentei resetar o input várias formas, colocando em uma função js (o que seria o certo no caso), tentei usar jquery entre outros porém não obtive sucesso, logo acredito que possa haver algum conflito dentro do meu formulário que possa estar causando esse problema da função não gerar o resultado esperado (que no caso é resetar o text area descricao).
Comment: Target _blank, a outra página é apenas um código php para inserir os dados, ela retorna uma mensagem e fecha automaticamente, essa página continua aberta.
Answer: O onsubmit está no lugar errado. Você deve colocá-lo na tag <form>. Outro problema é que o reset() só é aplicável ao objeto <form>, e não a um elemento individual de formulário.
Como você não pode limpar o campo no submit (senão ele será enviado vazio), chame uma função após um pequeno delay usando setTimeout no onsubmit:
<form onsubmit="setTimeout(limpa, 100)"...
                  ^^^^^^^

E coloque a função limpa() no JavaScript limpando o campo com value = '':

Ou poderia também fazer tudo no onsubmit sem chamar função:
<form onsubmit="setTimeout(function(){ document.getElementById('descricao').value = '' }, 100)"...

Comment: Cara, tentei isso de várias maneiras e nenhuma funcionou, inclusive tentando dentro do form, porém por alguma bruxaria a sua deu certo (já havia tentado o delay no form submit e não tinha conseguido sucesso), muito obrigado pela ajuda!


Finding the supremum and infimum of $\left\{n^{\frac{1}{n}}\;\middle\vert\;n\in\mathbb{N}\right\}$

Question: $\left\{n^{\frac{1}{n}}\;\middle\vert\;n\in\mathbb{N}\right\}$
What is the supremum and infimum of the above set?
The set is
$\left\{1, 2^{\frac{1}{2}}, 3^{\frac{1}{3}},....\right\}$
Now, $n^{\frac{1}{n}}\geq0$
Which implies that 0 is a lower bound of the set. Now if I can show that for some $\varepsilon>0$, there exists $k\in\mathbb{N}$ such that $0<k^{\frac{1}{k}}<0+\varepsilon$ then we may conclude that 0 is the infimum of the set, but I do not know how can I show the above.
Please anyone help me solve this problem. Thanks in advance.
Comment: Sorry, I have edited the problem.
Answer: Actually, you only have $n^{1/n}\leqslant1$ when $n=1$; for all other numbers, $n^{1/n}>1$. On the other hand, if $f(x)=x^\frac{1}{x}$, then $f'(x)=x^{x-2}\left(1-\log(x)\right)$ and therefore $f$ attains its maximum at $e$. It's not hard to deduce from this that$$\sup\left\{n^{\frac1n}\,\middle|\,n\in\mathbb N\right\}=\sqrt[3]3.$$
Comment: What about the infimum?
Comment: It is $1$, since $\sqrt[n]n=1$ if $n=1$ and it is greater than $1$ otherwise.
Comment: Ok, thank you Sir.
Comment: If my answer was useful, perhaps that you could mark it as the accepted one.
Comment: In many of resource like https://math.stackexchange.com/questions/1755360/derivative-of-xx-and-the-chain-rule derivative of $$ f(x)=x^x$$ is $$f^{'}(x)=x^x(1+logx)$$ but @JoséCarlosSantos used another equation and you reached $e$ as answer of the $f^{'}(x)=0$
Comment: @JoséCarlosSantos How can I deduce $3^{\frac{1}{3}}$ as the Supremum of the given set from the fact that $x^{\frac{1}{x}}$ is maximised at $x=e$? I still cannot get it.
Comment: Since $x^{\frac1x}$ increases to the left of $e$ and decreases to its right, the maximum value that $n^{\frac1n}$ can take is at one of the natural numbers which are closer to $e$, which are $2$ and $3$. And it turns out that $2^{\frac12}<3^{\frac13}$.


Create QML Element in C++?

Question: I have the following problem:
I load an initial interface into a QQuickView using a .qml file.
I then want to add QML types like an Image or Text to the interface using C++.
I know I can manipulate existing elements from C++ but how can I create new types and add them?
Answer: Unfortunately the docs are a bit out-of-date (uses Qt4 api), but If you read section Loading QML Components from C++ here: https://doc.qt.io/qt-4.8/qtbinding.html
Then you should have something like (with Qt5 api):
QQuickView view;
view.setSource(QUrl::fromLocalFile("MyView.qml"));
QQmlComponent component(view.engine()
        , QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();

This gives you a QObject from a .qml file, but what's missing is how to add this to the view. In qml, items won't get drawn unless they are parented to the view. One way of doing this is to add the item to the root context, like so:
QQmlProperty::write(object, "parent"
                    , QVariant::fromValue<QObject*>(view.rootObject()));

Also, note (again from the above link): "You should always use QObject::setProperty(), QDeclarativeProperty or QMetaProperty::write() to change a QML property value, to ensure the QML engine is made aware of the property change".
Next, we need to set the ownership of the item, otherwise the JavaScript garbage handler can delete your item and you can seg fault randomly.
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);

Finally, you need to remember to delete the object "object". Since it's a QObject you should use:
object->deleteLater();

Hope that helps someone!
Comment: dont forget to import
Answer: Go here: http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-definetypes.html, scroll to bottom and look at heading "Defining Visual Items with the QtQuick Module"
That gives you idea how it should be done.
This link provides examples how it should be done (thought it is written for Qt 4.7, but it shouldn't be much different from Qt 5): http://developer.nokia.com/Community/Wiki/Creating_a_custom_QML_element_with_Qt

NOTE: Don't forget to use (inherit) QQuickItem class instead of QDeclarativeItem.

Create QML Element in C++?


When buying slightly older servers, what features should I look for and what I should avoid?

Question: I'm about to purchase half a dozen slightly older servers. I see a lot of pretty good specifications quite cheap on ebay. So it won't be the latest CPU but it would still be good enough. The machines will all run Linux (Debian) and will be 64bit.
What brands would you recommend?
What gotchas should I be looking for?
Is any particular features in those slightly mature machines a must have?
Answer: When I buy a used previous generation server, I look for a vendor that sells used systems in volume and will provide a warranty. I personally have had good success with used Dell servers from Aventis Systems, but there are other reputable vendors out there.
If you want to buy on eBay or other non-reputable sources, consider the need to buy multiple items of the same model and maintain spares and/or parts inventory.
You have not specified what you are planning to do with half a dozen servers, so it is impossible to recommend a feature set. Generally speaking, though, you want failure-prone components like drives and power supplies to have redundancy.
Comment: One or two of these servers will be used as slaves for PostgreSql and MongoDB databases. The rest will run worker processes that perform various tasks on our application. Most machines I see on eBay come without drives which is fine - I will buy drives separately.
Answer: Miles is right. You should be looking for a reputable vendor that will provide a warranty. They are not difficult to find and it is a nice balance between servers coming in an unknown condition and a new product.
Buying on eBay should be a last resort for an enterprise environment. If I were buying for my home or something sure... but only in that case really.
Good luck.
Comment: I do have the benefit that most of the servers I need are hot plugged workers, and the loss of one translates to loss in capacity but not critical down time. I accept the answer though and I agree reputable vendors are better than random strangers.


Python - Comparing two text file and output differences using loops

Question: The first file:
This is text./n abc/n 123
The second file:
This is text./n xyz/n 123
I'm doing an assignment that is asking me to print("No") while also printing the part of the line that is different in both the first and second file if the file is different. They are asking me to use loops to compare and find the difference than to print the differences and break the loop if the differences are found. I can't seem to get to the second line of text to make my condition true.
secondFile = input("Enter the second file name: ")
first = open(firstFile, 'r')
second = open(secondFile, 'r')
if first.read() == second.read():
    print("Yes")
else:
    print("No")
    while True:
        firstLine = first.readline()
        secondLine = second.readline()
        if firstLine == secondLine:
            print(first.readline())
            print(second.readline())
            break```

Comment: In your code, you are breaking out of the loop when `firstline==secondline`. Make it `if firstline!=secondline`.
Comment: You've put `This is text./n abc/n 123`. If you want those to be newlines they should be `\n`
Answer: second.read() consimes all the data from the file, so once you reach first.readline() you get only empty strings. Read the file line by line and print "Yes" only if all the lines where already compare using for else. You should also close the files once done, you can do it by using with
with open(firstFile, 'r') as file1, open(secondFile, 'r') as file2:
    for line1, line2 in zip(file1, file2):
        if line1 != line2:
            print('No', line1, line2, sep='\n')
            break
    else:
        print('Yes')


Name of a design pattern: Moving data from one language to another

Question: I'm trying to determine the name of this pattern if it exists. Essentially taking data from one language and using it in another. i.e. PHP -> Javascript. I was thinking it may be delegation, but I've seen this done from time to time, and wanted to know if it was considered a pattern, or is is just a protocol.
Edit:
This more clearly defines what I'm talking about. You're not just generating one code or the other, but using it to send values. And so I guess this could be defined as source preprocessing.
<code><?php $foo = $_POST[MY_VAR]; ?>
<script>
    $bar = <?php echo $foo; ?>
    alert($bar)
</script>
</code>
Comment: How are you getting the data across - JSON or simply outputting the JavaScript vars, etc. via PHP? Either way, I think calling such a thing a design pattern is incorrect, although JSON probably comes close to an XDR in terms of data interoperability.
Comment: an example can be seen here: http://www.the-art-of-web.com/php/javascript-escape/
Comment: That's a great distance from being a design pattern or protocol. You're simply using PHP as a JavaScript generator - nothing more, nothing less.
Comment: Thanks for the example, I updated my answer to cover that possibility. I've done the same thing with JSP and JavaScript
Answer: If what you wanted to know is about communication between processes, then see sockets, TCP, HTTP and related technologies and data exchange formats like XML, JSON and similar.
If what you want to know is how to use code written in one language in a program written in another language, like what .Net or various JVM languages do, then it is interoperability you are talking about. Just keep in mind that in both cases I mentioned, programs in both languages are compiled to a common language (MSIL and Java bytecode, respectively).
In any case, I don't know if this has a name, or even if it is considered a pattern.
EDIT:
Since you specifically mentioned PHP and JavaScript, it is possible that you meant using PHP to generate a JavaScript variable with a literal value, so that you could pass a value from PHP to JavaScript code. This could be called source preprocessing or maybe code generation.
Comment: I think source preprocessing is more of what I was getting at.
Answer: In terms of the example you link to, that's not a design pattern or protocol and there's no interoperability between PHP and JavaScript whatsoever - the JavaScript interpreter isn't even running as far as PHP is concerned and vice-versa.
You're simply using PHP as a JavaScript code generator - nothing more, nothing less.
If you were using JavaScript to extract information in real-time (via "AJAX", etc.) then there would at least be some interaction between the two languages and you could (sort of) consider a data format like JSON (or indeed XML) to be a form of XDR. However, that's not the case in this instance.
Comment: It's not JUST a generator, for instance:
Comment: @Crewe - That's just code generation. i.e.: It's PHP generating JavaScript. The fact that it's interactively placing the contents of PHP variables into the JavaScript code is irrelevant. (It it wasn't it wouldn't be a code generator - just a means of concatenating chunks of static JavaScript.)
Comment: I see... I guess when I think "code generation" I think entire lines of syntax, not just a single variable.
Answer: I don't think it's a design pattern at all - well maybe in broader sense than the term is usually used. You basically have two applications talking to each other over HTTP protocol. Languages used are irrelevant.
Comment: True. But it's not really done on a protocol level. It's done where HTML is the medium. and then it's sent over HTTP


Problemas com retorno de data do DatePicker

Question: Eu estou usando um datePicker para uma aplicação que será usada no curso, mas quando vou convertar ela de int para Date, ela retorna a data 29/03/2018 da seguinte forma:

Wed Sep 08 00:00:00 GMT 34

Código que e chamado o datePicker
@SuppressLint("ValidFragment")
    public class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener{

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Sao_Paulo"));

            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);

            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month++;
            etDataNascimentoCondutor.setText(day+ "/" + month + "/" + year);
        }
    }

Convertendo para date
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String sDataNascimento = etDataNascimentoCondutor.getText().toString();
try {
    dataNascimentoCondutor = df.parse(sDataNascimento);
    Log.v("Data Capturada", dataNascimentoCondutor.toString());
} catch (ParseException e) {
    e.getMessage();
    throw new RuntimeException();
}

Answer: SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");//variavel na classe
Calendar calendar; //variavel na classe

/////////////////////
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
    calendar = Calendar.getInstance(); //faça variavel calendar na classe
    calendar.set(year,month,day);
    Date date = calendar.getTime();//metodo getTime converte o Calendar para Date
    etDataNascimentoCondutor.setText(df.format(date));
}


Allow only number in JS and verify past

Question: I have this function that only allows number in keypress how can i change this function ou method to call, so when i do ctrl+v verify too the values?
function isNumberKey(evt, obj) {
    var containsDot = obj.value.indexOf(".");
    var nrDecimals = Decimals(obj.value, ".");

    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 8 || charCode == 9) {
        return true;
    } else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        if (charCode == 46 && containsDot < 0) {
            return true;
        }
        return false;
    }
    if (nrDecimals > 2) {
        return false;
    }
    return true;
}

I call it this way

onkeypress="return isNumberKey(event,this);"
Comment: possible solution: http://stackoverflow.com/questions/15333668/javascript-trigger-on-keypress-and-paste
Comment: apart from copy-paste, a user can also drag-drop text, it would be better if u can validate on form submit
Answer: If you only want numbers in your input, you could do something like this:
onkeyup="this.value = this.value.replace(/[^0-9]+/, '');"

This replaces all non-number characters from the value. This does about the same as your whole function does, plus it works with the paste.
You need to change onkeypress to onkeyup.

For the full solution you need to switch to more complex code. As one of the comment below says, you can rightclick->paste aswell. This will not catch that. You need to bind multiple event (keypress, keyup, click are examples of events) to that one input. If you're lucky, focus will catch it (if rightclick blurs it, and after paste it focusses).
Comment: "plus it works with the paste." - well, it's [not working for me](http://jsfiddle.net/GaurangTandon/LRa8m/). I think it should be `onkeyup`
Comment: Wasn't really sure about the past, thats why I suggested the change to keyup. Fixed that :)
Answer: you can use jQuery. Change the below code as per your requirement.
$(document).ready(function() {
        $("#id")
           .bind('copy', function(e) {
                alert('copying!');
            })
            .bind('paste', function(e) {
                alert('pasting!');
            })
            .bind('cut', function(e) {
                alert('cut!');
            });
    });

If you want to use plane javascript. I think below will work, but not sure about the browser compatibility.
<input type="text" onpaste="callFunc()" />

Comment: I added the chaining. It was not needed in your code, but I thought it was a good idea to highlight the possibility for this user and others, for it is a powerfull strength in jQuery

Allow only number in JS and verify past


Compiling 32bit on 64bit machine : /usr/bin/ld: cannot find -l

Question: i'm currently trying to compile some code as 32bit on a 64bit Ubuntu 12.04 machine. If i compile the code with the normal make command it all works fine.
Now, in order to compile it as 32bit i added the -m32 option to the C- & CXXFLAGS. Works fine until i get some errors about missing librarys like -lGL, -lGLU, -lX11, -lXext, -lpng. Okay, the first lib (-lGL) I found in /usr/lib32/nvidia-304 which i added via the -L option.
The other libs are all found in /usr/lib/i386-linux-gnu but adding that via -L does not solve a thing.
What am I missing here? Thanks in advance!
Here is the full gcc-command leading to the error
gcc myprog.o -m32 (...) -lX11 -lXext -lpng -lm -L/usr/lib/i386-linux-gnu -lGL -L/usr/lib32/nvidia-304 -lpthread -o myprog
/usr/bin/ld: cannot find -lX11
/usr/bin/ld: cannot find -lXext
/usr/bin/ld: cannot find -lpng

Another thing: In the /usr/lib32/nvidia-304 i found a libGL.so PLUS an libGL.la while in /usr/lib/i386-linux-gnu I only can find .so files.
Comment: Just for clarification, there is a `libpng.so` in `/usr/lib/i386-linux-gnu` ?
Comment: Yes, `./usr/lib/i386-linux-gnu/libpng.so.3` exists.
Comment: Hm, seems like @lolando might be on the right track then. You need a `libpng.so`, which may be a symlink to `libpng.so.3`. Did you install the 32bit libs the official, Ubuntu-supported way?
Comment: Hi, creating symbolic links like `libpng.so` to `libpng.so.3` truly worked. I dont have root access to the system so i dont know how it got installed.
Answer: Not sure if it helps, but i had some time ago a similar problem where some symbolic links were missing under /usr/lib/i386-linux-gnu. Perhaps you are facing a similar issue?
Comment: Hi, as mentioned in the post above the creation of symbolic links worked so far. Thanks!


How to isolate $A$ in $A\%B=C$

Question: How do I solve for a in the equation: $a\mod b= c\text{ (same as }a\%b=c$)
Is there an inverse mod, so that I can put the equation in terms of a?
Thanks in advance!
b and c can be any real number
I know that $a \mod b =a-\lfloor a/b\rfloor\cdot b$, so I can say $a = c+kb$ (k being any whole number), but I was woundering if there is an easier way to write this.
Comment: It's not clear what you are asking.  $a$ and $c$ are numbers that leave the same remainder on division by $b$.  What is there to solve?
Comment: I ask _How to isolate A in A%B=C_, but the content has been updated
Answer: it means there exists $m \in \mathbb{Z}$ such that $a= bm+c$.
$a$ is not unique, for example if $b=2$ and $c=1$, then $a$ is the set of odd integers.
Comment: Thanks for your answer.

How to isolate $A$ in $A\%B=C$


Set theory (Disjoint union)

Question: Let $A_{1},A_{2},...,A_{n}$ be $n$ sets and let $A_{i}^{k}=A_{i}$ if $k=1$ and $A_{i}^{k}=A_{i}^{c}$ if $k=-1$
Consider $E_{k}=A_{1}^{k_{1}}\cap A_{2}^{k_{2}}\cap...\cap A_{n}^{k_{n}}$ and $k_{i}=\pm1$ where there are $2^n$ such $E_{k}$'s and here $k$ is like a vector with 0 and 1.
I need to verify that any $A_{i}$ can be expressed as $A_{i}=\cup\{{E_{k}}:k=(k_{1},k_{2},...,k_{i-1},1,k_{i+1},...,k_{n})\}$
If $x\in RHS$, then $x$ is in one of the $E_{k}$ with $k_{i}=1$ and $A_{1}^{k_{1}}\cap A_{2}^{k_{2}}\cap...\cap A_{i-1}^{k_{i-1}}\cap A_{i}\cap A_{i+1}^{k_{i+1}}\cap...\cap A_{n}^{k_{n}}$ is clearly a subset of $A_{i}$.
We then have $RHS\subseteq LHS$
How do I verify $LHS\subseteq RHS$? On a Venn diagram it is quite obvious that both sides are equal but how can I verify it algebraically?
Comment: Are the $A_{i}$'s disjoint? Suppose there are just $A_{1}$ and $A_(2)$ and neither is a subset of the other. Then both $A_{1} \cap A_{2}$ and $A_{1} \cap A_{2}^{c}$ are proper subsets of $A_{1}$.
Comment: The $A_{i}$'s need not be disjoint but the $E_{k}$'s are disjoint.
Answer: Let $x\in A_i$.
For $j\in\{1,\dots,n\}$ let $k_j=1$ if $x\in A_j$ and let $k_j=-1$ if $x\in A_j^{\complement}$.
Then evidently $x\in A_1^{k_1}\cap\cdots\cap A^1\cap\cdots\cap A_n^{k_n}=E_{(k_1,\dots,1,\dots,k_n)}$.
So every element of $A_i$ will be an element of the union on RHS.
Comment: Great! Thanks a lot!
Comment: You are welcome.

Set theory (Disjoint union)


Unknown number of matches in regex and font-lock

Question: I am trying to use font-lock and elisp's regex to highlight something like this:
class Foo implements A, B, C, D { }

The problem is unknown length of comma separated list after implements. I've already done regex which highlights all words on list (using re-buider, A, B, C and D are highlighted):
"implements\\s-+\\(?:\\(\\sw+\\)\\s-*,\\s-*\\)*\\(\\sw+\\)"

but I'm unable to combine this with font-lock.
Obviously
'("implements\\s-+\\(?:\\(\\sw+\\)\\s-*,\\s-*\\)*\\(\\sw+\\)"
  (1 font-lock-type-face) (2 font-lock-type-face))

doesn't work, because it highlights only to last occurances (C and D) ignoring star (*) after first backreference.
Is there a way to capture a list of all matched words or maybe enteirly different way to solve this problem?
Answer: If you don't want the commas to be highlighted too, your approach cannot work. When you use a subexp-highlighter of the form
(subexp facespec)

the subexp refers to the sub-group of your regex and highlights with the given facespec. Now, a sub-group of a regexp match is a continuous span of text with a beginning and end. In fact, whenever you do a regexp search, you can query those values with the functions (match-beginning subexp) and (match-end subexp).
But that means that you cannot match a variable number of classnames excludings commas with a single sub-expression, because that sub-expression would have to be a continuous span. And a continuous span that covers a variable number of classnames must always contain the commas, too, there's no way around that.
Here's another reason why your approach is not such a good ideas: your regexp explicitly uses whitespace. It doesn't matter if the whitespace is excluded from highlighting, but even using it in the regexp is not such a great idea, because wherever whitespace is allowed, you could always encounter comments as well.
Consider the following code line:
class Foo implements A, /*B, C,*/ D { }

In that case, you would want the characters in the span /*B, C,*/ to be highlighted using the font-lock-comment-face, and the surrounding classes in font-lock-type-face. You can still achieve this effect if you highlight comments only after everything else has already been hightlighted, and allow comments to override other font-lock matches. But this will lead to rather inefficient matching, because every comment would then first be highlighted as if it were code, and then be highlighted as a comment in a second pass.
A solution to both problems would probably be to divide the matching of the keywords ("implements") and the classes into two different matching rules, perhaps you could use as a starting point something along the lines of:
'(("\\bimplements\\b" . font-lock-keyword-face)
  ("\\b[A-Z]\\w*\\b" . font-lock-type-face))

Comment: I didn't solve the initial problem, tried to check cc-mode / java-mode sources, but that solution breaks when line break is added... So I guess it's more like you explained above. Thanks!
Answer: Something like this seems to work here:
'("\\(implements\\)\\s-+\\(\\(\\sw+\\s-*,\\s-*\\)*\\sw+\\)"
   (1 font-lock-warning-face)
   (2 font-lock-keyword-face))

(and obviously you probably want different faces...)
Comment: It's not exactly what I wanted, because it highlights commas (and whitespaces between words, because they are matched).
Comment: P.S. It's `font-lock-keyword-face` for first match (implements) and `font-lock-type-face` for rest ;)


Serielize() jquery não grava as variáveis

Question: Não estou conseguindo gravar as variaveis com o jquery serialize(), esotu fazendo assim, qual seria o problema?
//Executa em cada form:
$('.formAjax').on("submit",function() {

    // Pegar o ID do formulário para depois:
    //Captura o elemento que sofreu o evento de "submit"
    const formDetails = $(this);

    var formID=formDetails.data("formid");

    //Remove a palavra quitar_ e deixa somente "debitoX"
 $('.resultado_empresa_selecionada_'+formID).html('');

$.ajax({
     type: "post",
     url: "add_email.php",
     data: formDetails.serialize(),
     success: function(data) {
         //Faz alguma coisa

         $('.resultado_empresa_selecionada_'+formID).html(data);

$('.resultado_empresa_selecionada_'+formID).fadeIn('slow').html(data);

     }
 });
    return false;
});

Html
<form id="selecionar_empresa_form_273" class="formAjax formAjax2" data-formid="273" method="post" enctype="multipart/form-data">

<input type="hidden" name="id_usuario" id="id_usuario" value="273">

<select id="atendente" class="form-control atendente" name="atendente" required="">
    <option value="" selected="">Selecine um Atendente</option>
    <option value="email@example.com">Central de Vendas</option>
    <option value="email@example.com">Claudia</option>
    <option value="firstname.lastname@example.com">Céia</option>
    <option value="email@example.com">Claudia Lima</option>
    <option value="email@example.com">Neide</option>
    </select>

<button type="submit" class="botao_add">Adicionar atendente</button>

</form>

Comment: o que gera no `formDetails.serialize()`?
Comment: seria gerado as varaiaveis do formmulario
Comment: seria aqui $('.resultado_empresa_selecionada_'+formID).html(data); mas não funciona
Comment: certo mas o que não funciona? `formDetails.serialize()`  retorna alguma coisa, dá erro??
Answer: Tente o seguinte:
Troque
formDetails.serialize();

por
formDetails.toJSON();

e trate o controller para receber o arquivo JSON.
Comment: preciso que seja com o serialize(); obrigado pela atenção amigo
Comment: Por nada, estou a disposição!


Reducing the statement that a variety can be interpreted as a scheme to the case of an affine variety (Harshorne II. 2.6)

Question: In the proof of Chapter II, Proposition 2.6 of Hartshorne's Algebraic Geometry book, the author states that if $V$ is a variety over $k$, then $(t(V),\alpha_*(\mathcal{O}_V))$ is a scheme over $k$. In the book, $\alpha:V\to t(V)$ is defined by $\alpha(P)=\overline{\{P\}}$. $t$ is defined to be the functor that sends a topological space $X$ to a the set of (nonempty) irreducible closed subsets of $X$, with the topology of $t(X)$ defined by having sets of the form $t(Y)\subseteq t(X)$ be closed, where $Y\subseteq X$ is closed.
The author then states that since any variety can be covered by open affine subvarieties, it will be sufficient to prove the above statement in the case that $V$ is affine. Since a scheme is a locally ringed space $(X,\mathcal{O}_X)$ in which every point has an open neighborhood $U$ such that the restricted sheaf $\mathcal(O)_X|_U$ is affine, I am assuming that the author was thinking of covering $t(V)$ with open sets of the form $t(U_i)$, where $U_i$ are isomorphic to affine or quasi-affine varieties and $\{U_i\}$ cover V.
My confusions are that (1) sets of the form $t(U_i)$ don't necessarily cover $t(V)$ and (2) sets of the form $t(U_i)$ aren't necessarily open in $t(V)$. Was the author thinking of a different covering of $t(V)$ in his proof?
Comment: I think that the problem is notation. For a non closed $U$, you do not have $t(U) \subset t(V)$ since elements of $t(U)$ are not closed in $V$. For open $U$, define the map $f:t(U) \to t(V)$ sending each irreducible set to its closure in $X$. I think it is in this context where you have to prove that $f$ is a homeomorphism onto its image, which is the open set $t(V) \setminus t(V \setminus U)$, and conditions (1) and (2) are clearly satisfied since, for example, for the case you wrote to KReiser, $V$ irreducible implies $V$ is the closure of $U$ so it is in the image of $f$.
Comment: You want to use $U_i$ which are open affines in $V$ (saying that they're affine means that they're isomorphic to affine varieties, not just homeomorphic) and then (1) and (2) are actually true - why do you think they're false?
Comment: @KReiser Thanks, I should've said isomorphic. For (1), V is an irreducible subset of V, but V is not in $t(U_i)$ for any $i$ in the case that each $U_i$ is a proper subset of $V$. For (2), Suppose that $U\subsetneq V$ is a nonempty open subset. Suppose now that $t(U)$ is open in $t(V)$. Then $t(U)=t(V)\backslash t(Z)$ for some closed subset $Z\subseteq V$. In the case that that $Z$ is not $V$, we have that $V\in t(V)\backslash t(Z)$, but $V\not\in t(U)$, leading to a contradiction. Therefore, $Z=V$, implying $t(U)=\emptyset$. Therefore, $\{t(U_i)\}$ couldn't cover $t(V)$.
Comment: My apologies, I was incorrect in my first comment. I've explained in an answer below.
Answer: You're right, this isn't quite what Hartshorne had in mind here. One should not take $t(U)$ to be an open subset of $t(V)$- it's not even clear what that would mean, since the closed subsets of $U$ need not be closed subsets of $V$  in general. Instead, the bijection between open subsets of $V$ and open subsets of $t(V)$ proceeds in as follows: given an open subset $U$ with closed complement $W$, the open subset of $t(V)$ corresponding to $U$ is the open subset $t(V)\setminus t(W)$.
This fixes your covering problem: if $\{U_i\}$ cover $V$, then $\bigcap U_i^c=\emptyset$ and since $t$ commutes with intersections of closed sets, we see that $\bigcap t(U_i^c)=\emptyset$, so the sets $t(V)\setminus t(U_i^c)$ have union all of $t(V)$.
Comment: Still, one has to prove that $t(V) \smallsetminus t(W)$ is homeomorphic to $t(U)$ in order to show that one can reduce to the case where $V$ is affine
Comment: @AitorIribarLopez I feel like that's pretty clear.


Finding the value of p while solving a recurrence equation using Akra-Bazzi method?

Question: I am learning to solve recurrence equations using Akra-Bazzi method. I am stuck in figuring out how to find out the value of p by solving equations like:
$$\left(3\over4\right)^p + \left(1\over6\right)^p=1$$
$$\left(1\over2\right)^p + \left(1\over4\right)^p + \left(1\over8\right)^p=1.$$
I want to find it out with using a scientific calculator and not wolfram alpha as online tools are not allowed during my exam.
Answer: First off, in general $p$ will be some transcendental number without a clean closed form in terms of familiar constants.  So I assume you just want to find $p$ to some reasonable accuracy.
I would attack this with  the following method, illustrated for the first of your equations. I would convert (by multiplying the whole equations by the least common multiple of the fractions on the left) to
$$
9^p + 2^p = 12^p
$$
Then starting with a guess $p_{old} = 1$ I would iterate using $p_{old}$ on the left and the next guess $p_{new}$ on the
$$
p_{temp} = \log_{12} (9^{p_{old}} + 2^{p_{old}}) \\
p_{new} = 2 p_{temp} - p_{old}
$$
This algorithm converges geometrically, that is, each new guess has half the error of the previous guess.  FOr this example, going through this step (which can easily be set up to need just a couple of button pushes) converges to better that $.001$ accuracy after seven steps.  ($p_7 = 0.852537$; the correct value is $.851838$.)
However, you have to be careful.  Sometimes (for example if all of the fractions are greater than $1$), $p$ needs to be negative, and then this method will not converge.  You can generally manipulate it into some related equation where it does converge.
For your second example, this method for some reason converges really quickly. The fourth iteration already gives 6-digit accuracy.
Comment: Thanks for answering. I tried with another example and it works. Can you please provide any intuition or proof for the algorithm you mentioned?
Comment: It's a poor man's stab at Newton Raphson iteration.  You can probably do better in terms of rate of convergence by using the actual derivative, but I just took the simple road, saying that the best next guess will be some overshoot of ptemp, and the only scale that made sense was the difference between ptemp and $p_{old}$.


When creating a record off nesting, why isn't the parent id being added to the child?

Question: Given the following
<code>Thread
   belongs_to :user

User
   has_many :threads, :through => :thread_members
</code>
When I do:
<code>  @user.threads.create(:title => "hello")
</code>
In my Thread model I have a before_create, and in that method I and Rails.logger.info self.inspect which outputs:
<code>#<Thread id: nil, user_id: nil, title: "hello" ...
</code>
Why is user_id not being assigned? Thanks
Answer: Check that the @user is already saved, the parent records must be saved before the children get their foreign keys set. Please show the controller code that loads that @user object.


Alinhar Navbar Bootstrap-React

Question: Estou tentando alinhar o navbar para a direita, porém, sem sucesso, está assim atualmente:

index.js
    import React, { Component } from 'react';
    import 'bootstrap/dist/css/bootstrap.min.css';
    import { Nav, Navbar } from 'react-bootstrap';

    import Nav_Link from '../../components/index';
    import LogoImg from '../../assets/logo.png';
    import RetanguloImg from '../../assets/retangulo.png';
    import PredioImg from '../../assets/predio.png';
    import {
      Nav_Link_Line,
      Button,
      Title,
      Text,
      Text2,
      Button2,
      Table,
    } from './styles';

    export default class Main extends Component {
      render() {
        return (

            <Navbar expand="lg" variant="dark">
              <Navbar.Brand href="#home">

              </Navbar.Brand>
              <Navbar.Toggle aria-controls="basic-navbar-nav" />
              <Navbar.Collapse id="basic-navbar-nav">

                  <Nav_Link href="">QUESTINÁRIO</Nav_Link>
                  <Nav_Link href="">DÚVIDAS</Nav_Link>
                  <Nav_Link href="">FEEDBACK</Nav_Link>
                  <Nav_Link href="">CONTATO</Nav_Link>
                  <Nav_Link href="">SOBRE</Nav_Link>
                  <Nav_Link_Line href="">

                  </Nav_Link_Line>
                  <Nav_Link href="">LOGIN</Nav_Link>
                  <Button href="">CADASTRE-SE</Button>

              </Navbar.Collapse>
            </Navbar>

styles.js
export const Nav_Link = styled.a`
  margin-left: 31px;
  margin-top: 15px;
  color: white;
  display: flex !important;
  justify-content: end !important;

  &:link {
    text-decoration: none;
  }

  &:hover {
    color: #748aaa;
  }
`;

export const Nav_Link_Line = styled.text`
      margin-left: 31px;
      margin-top: 10px;
      color: white;
    `;

global.js
.navbar {
    background-color: #3D5975;
    color: #ffff;
    font-weight: bold;
    height: 64px;
    width: 100%;
  }

Answer: Use Display flex na sua nav, depois use justify-content: flex-end para alinhar o conteúdo no final do seu elemento.
Eu fiz um codepen usando div e lista para te mostrar, mas o conceito é o mesmo.
https://codepen.io/ianpbh/pen/OJVVbxa

Alinhar Navbar Bootstrap-React


Can't add a STORED column to MariaDB 10.7.3, Infamous "Error Code 1901"

Question: I'm trying to add a GENERATED ALWAYS column to a table that will decode two characters into a DATE.
It contains a function (returning DATE), but it was misbehaving the same way when the expression was in-lined. The function works fine in a SELECT. I've checked my character set and collation for consistency.
sql_mode is "ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Here is the table schema. Note I have a Location generated column, which is working fine.
CREATE TABLE `Photo_Gear_Date_Codes` (
  `ID` varchar(4) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL DEFAULT '....',
  `Location` varchar(253) GENERATED ALWAYS AS (case left(`ID`,2) when 'TN' then 'Tatsuno, Hyogo' else 'Unknown' end) STORED,
  `Note` varchar(1022) COLLATE latin1_general_ci DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci

Here is the function I defined to try to simplify things, although I got the same error when I in-lined this code:
CREATE DEFINER=`root`@`127.0.0.1`
FUNCTION `Date_from_OM_date_code`(id3 char(1), id4 char(1))
RETURNS date
DETERMINISTIC
COMMENT 'Decode the last two digits of a four-character OM date code.'
RETURN CONVERT(
    concat(
      case ID3
        when '1' then '1971'
        when '2' then '1972'
        when '3' then '1973'
        when '4' then '1974'
        when '5' then '1975'
        when '6' then '1976'
        when '7' then '1977'
        when '8' then '1978'
        when '9' then '1979'
        when '0' then '1980'
        when 'A' then '1981'
        when 'B' then '1982'
        when 'C' then '1983'
        when 'D' then '1984'
        when 'E' then '1985'
        when 'F' then '1986'
        when 'G' then '1987'
        when 'H' then '1988'
        when 'I' then '1989'
        when 'J' then '1990'
        when 'K' then '1991'
        when 'L' then '1992'
        when 'M' then '1993'
        when 'N' then '1994'
        when 'O' then '1995'
        when 'P' then '1996'
        when 'Q' then '1997'
        when 'R' then '1998'
        when 'S' then '1999'
        when 'T' then '2000'
        when 'U' then '2001'
        when 'V' then '2002'
        when 'W' then '2003'
        when 'X' then '2004'
        when 'Y' then '2005'
        when 'Z' then '2006'
        end,
      case ID4
        when '1' then '-01-00'
        when '2' then '-02-00'
        when '3' then '-03-00'
        when '4' then '-04-00'
        when '5' then '-05-00'
        when '6' then '-06-00'
        when '7' then '-07-00'
        when '8' then '-08-00'
        when '9' then '-09-00'
        when 'A' then '-10-00'
        when 'B' then '-11-00'
        when 'C' then '-12-00'
        when 'X' then '-10-00'
        when 'Y' then '-11-00'
        when 'Z' then '-12-00'
        end), DATE);

Here is how I'm trying to add the generated column:
USE `Personal`;
ALTER TABLE `Photo_Gear_Date_Codes` ADD COLUMN `Date` DATE AS
  (Date_from_OM_date_code(SUBSTR(`ID`,3,1), RIGHT(`ID`,1))) STORED;
SELECT ID,
  `Location`,
  Date_from_OM_date_code(SUBSTR(`ID`,3,1), RIGHT(`ID`,1)) `Date`
  FROM Photo_Gear_Date_Codes

When I execute those three statements, the second throws the 1901 error code:

Function or expression 'Date_from_OM_date_code()' cannot be used in
the GENERATED ALWAYS AS clause of Date
Error code 1901.

But I proceed through the error, and the SELECT works just fine!

ID
Location
Date

S7Y
Unknown
1977-11-00

TND1
Tatsuno, Hyogo
1984-01-00

TND4
Tatsuno, Hyogo
1984-04-00

TNGB
Tatsuno, Hyogo
1987-11-00

TNH9
Tatsuno, Hyogo
1988-09-00

TNI5
Tatsuno, Hyogo
1989-05-00

TNJ2
Tatsuno, Hyogo
1990-02-00

TNJ3
Tatsuno, Hyogo
1990-03-00

TNJ5
Tatsuno, Hyogo
1990-05-00

TNM6
Tatsuno, Hyogo
1993-06-00

TNM9
Tatsuno, Hyogo
1993-09-00

TNOA
Tatsuno, Hyogo
1995-10-00

It seems like it should work… I'm pulling my hair out over this one!
Thanks in advance for pointing out where I'm being stupid! :-)
Answer: As mariadb's documentation on generated column says:

This expression might generate the value based on the values of other columns in the table, or it might generate the value by calling built-in functions or user-defined functions (UDFs).

UDFs are functions written in c++, not in sql. As you can see, standard, sql-based user created functions are not included in the list, hence the error message.
Include your function's body as an expression as the generated column's code instead.
Comment: Thank you! I could swear I had already tried that, and then moved everything to a function to try to figure things out, but I must have had some other error in the expression before moving it to a function. It's really too bad they don't allow deterministic functions in generated columns — that would be good for abstraction and re-use!
Comment: UDF are written in c++? how can that be, they _are_ written in sql! You mean the reverse, Build-in functions are written in c++!
Comment: @theking2 please click on the link in my answer, find the link on that page that leads to the definition of UDF in mariadb and you will see those are written in c/c++.
Comment: @Shadow apart from the fact that UDF cannot physically be transpiled in C++ as they are written in SQL I don't see where in the link you proposed it shows otherwise as there is no mention of c++ as far as Ctrl+f tells. It would mean compiling Mariadb Sources and restart the server
Comment: @theking2 in the linked page above you should have looked for the definition of UDFs, which has the link to the corresponding page in mariadb documentation: https://mariadb.com/kb/en/user-defined-functions/
Comment: @theking2 or you could just simply do a mariadb udf c++ Internet search and check out the results. Would have been a lot faster for you...
Comment: Interesting. I come from an original MS-SQL server environment and the result of CREATE FUNCTION is called a [user defined function](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16).
Comment: @theking2 well, you need to get used to the mariadb concepts


Find the number of conjugacy classes of elements of order $2$ in $D_{2p}$ where $p$ is odd

Question:
Find the number of conjugacy classes of elements of order $2$ in $D_{2p}$ where $p$ is odd

So I am trying to solve this problem, and I know that if $p$ is odd and
$$D_{2p}=\langle r, s \mid s^2=1, r^p=1 , srs^{-1}=r^{-1}\rangle $$
then the only element of order $2$ in $D_{2p}$ is $s$, so I guess that there is only one conjugacy class of these elements.
Am I wrong? If yes, could anyone explain it to me?
Comment: It is not true that $s$ is the only element of order $2$.
Comment: (Consider $sr$.)
Comment: @DerekHolt so what other elements are of order 2?
Comment: That can be seen geometrically, since $D_{2p}$ is the group of symmetries of a regular $p$-gon.
Answer: Or alternatively, if we want $D_{2p}$ to be $\langle r, s \mid s^2=1, r^{p}=1 , srs=r^{-1}\rangle $
So that, for example $D_{10}$ is the ten symmetries of the pentagon.
Then all the ways to flip a pentagon have order two, because you can just flip twice to get back to where you were.
And all those flips are along axes which go through one corner and the midpoint of the opposite side. They're all conjugate because you can rotate them into each other.
None of the rotations have order 2.
So just one class, and it's the same for all the other odd polygons.
Comment: An example does not, a proof, make.
Comment: oh yes, it, does


Nginx: How to use a different php-fpm pool depending on url

Question: I have a site using the standard nginx approach for directing traffic via /index.php regardless of url:
location / {
    try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_index index.php;
    include fastcgi_params;
}

But I want to use a different php-fpm pool for a certain URL (but still going via /index.php). I could, I presume, use an "if" clause within the .php$ location block to use a different fastcgi_pass depending on the URL, but "if" is discouraged so is there another way?
Answer: You can use the map feature for this. For example, define the map in http context as follows:
map $request_uri $pool {
    "/path/to/special" unix:/run/php/special.sock;
    default unix:/run/php/php7.0-fpm.sock;
}

And then at the location:
location \.php$ {
    fastcgi_pass $pool;
}

I haven't tested this approach myself, so you might need to tweak the $pool variable contents.