ASP.NET MVC 2 VirtualPathProvider GetFile every time for every request

Question: I have implemented a VirtualPathProvider. The VirtualPathProvider reads the view from File system.
However my problem is the method GetFile(string virtualPath) is not executed every time for every request. I think it is related to the caching, isn't it? What I want is getting file every time for every request. Because for some cases, the page in the file system will be modified and users want the system shows the changes immediately.
Thanks.
Comment: Does your provider get called every time when in debug mode?  If so, then it's caching, as the view caching is disabled when debug is enabled.
Comment: Thank you for your response. The VirtualPathProvider is called for every request, but only the `bool FileExists(string virtualPath)` method is called for every request. I have tried to override all methods in the VirtualPathProvider, but I still cannot find the solution.
Comment: In fact, I just directly run an example from http://padcom13.blogspot.com/2009/04/virtualpathprovider-example.html.
Answer: I found the solution myself on the internet.
Really thanks jbeall replied on 07-15-2008, 11:05 AM.
http://forums.asp.net/t/1289756.aspx
In short words, overrides the following methods

GetCacheDependency - always return null
GetFileHash - always return different value

After these modifications, for every request, MVC gets the file from source directly.
Answer: public class MyVirtualPathProvider : VirtualPathProvider
{

    public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
    {
        return null;

    }

    public override String GetFileHash(String virtualPath, IEnumerable virtualPathDependencies)
    {
        return Guid.NewGuid().ToString();

    }
}


complex eigenvalues and invariant spaces

Question: I am currently reading Guillemin and Pollack's Differential Topology, and the following claim is made without proof:
Given a linear isomorphism $E: \mathbb{R}^k \to \mathbb{R}^k$, with $k>2$ and such that $E$ can be represented by a matrix with real entries, $E$ has a one- or two-dimensional invariant space.
I understand that the Fundamental Theorem of Algebra implies that $E$ has at least one real or complex eigenvalue; if it is real, then $E$ clearly has a one-dimensional fixed space. If it is complex, however, I don't see how there needs to be a two-dimensional invariant space.
If $E$ has complex eigenvalue $a+bi$, then $a-bi$ must also be an eigenvalue (as $E$ contains real entries). These eigenvalues correspond to eigenvectors $v_1$ and $v_2$. I assume that the subspace spanned by $v_1$ and $v_2$ is the desired invariant space, but can't figure out how to prove it. Any help would be most appreciated.
Comment: I wonder why they have $k>2$; it also works for $k=2$ and $k=1$.
Answer: No, the space spanned by $v_1$ and $v_2$ is not the space you are looking for: $v_1$ and $v_2$ have complex entries in fact.
So we assume that $v_2=\bar v_1,$ and consider $w_1=v_1+\bar v_1$ and $w_2=(v_1-\bar v_1)i\in\mathbb R.$
Then we see that $$E(w_1)=aw_1+bi(v_1-\bar v_1)=aw_1+bw_2$$
$$E(w_2)=aw_2-b(v_1+\bar v_1)=-bw_1+aw_2.$$
Thus the space spanned by $w_1$ and $w_2$ is invariant under $E.$
Hope this helps.
Comment: @Goob In fact $E(w_1) = E(v_1+\overline{v}_1)=(a+bi)(v_1)+(a-bi)(\overline{v}_1)$.  Notice that $w_1$ is not an eigen-vector of $E$.  $v_1$ and $\overline{v}_1$ are instead.
Comment: why is $E(w_1)=aw_1+bi(v_1-\overline v_1)$ not $E(w_1)=aw_1+bi(v_1+\overline v_1)?$ $E(w_1)=aw_1+biw_1$ no?
Comment: Thanks this makes sense! I found a different? way to do it? Could you take a look at it because when we my subspace is the same as yours it seems but when we apply the transformation to the vectors my result is different from yours. Wondering if you could explain why that happens. Its on the bottom on this page. Thanks!
Answer: As you indicated the result is easy if there are any real eigenvalues, so I'll focus on the contrary case.
Note that your complex eigenvectors don't live in $\Bbb R^k$ at all, but in $\Bbb C^k$. In order to get back to $\Bbb R^k$, you may view it as a real subspace of $\Bbb C^k$ (vectors with all coordinates real) and try to construct from the eigenspaces in$~\Bbb C^k$ an invariant subspace in $\Bbb R^k$. It turns out that the complex span of a single eigenvector intersects the real subspace $\Bbb R^k$ trivially, but the complex span of an eigenvector together with its component-wise complex conjugate, which is an eigenvector for the conjugate eigenvalue, does intersect $\Bbb R^k$ in a real $2$-dimensional subspace, invariant under the real linear operator. In fact the component-wise real and imaginary "parts" of a complex eigenvector $v$ (which van be obtained as linear combination of $v$ and its conjugate) span such an invariant subspace. The answer by @awllower details this approach.
There is another approach that avoids complexifying the vector space to begin with. The minimal polynomial $P$ of the linear operator $E$ has real entries (so does its characteristic polynomial, which could be used in this argument as well, invoking the Cayley-Hamilton theorem). It can therefore be decomposed as product $P=P_1\ldots P_m$ of monic irreducible polynomials over the real numbers, where each factor $P_i$ has degree $1$ or $2$ (due to the FTA). Now by definition of the minimal polynomial $P[E]=0$, which becomes
$$
  P_1[E]\circ P_2[E]\circ\cdots\circ P_m[E]=0.
$$
Clearly at least one of the $P_i[E]$ fails to be injective (in fact they all do). Let $0\neq v\in\ker(P_i[E])$. If $\deg(P_i)=1$ then $P_i=X+c$ for some $c\in\Bbb R$ and $v$ is an eigenvector for$~{-}c$ (the easy case). Otherwise $P_i=X^2+bX+c$ for some $b,c\in\Bbb R$, so $E^2(v)+bE(v)+cv=0$ or equivalently $E^2(v)=-bE(v)-cv$ which shows that the span of $v$ and $E(v)$ is an invariant subspace for $E$.
Answer: I think here is another way. A has eigenvalue $\lambda$ and eigenvector $\textbf{v}\in \mathbb{C}^n$. We can say $\lambda = a+bi$ and $v_j=x_j+iy_j \text{ for }j=1,2,...,n\Rightarrow \textbf{v}={\textbf{x}}+i\textbf{y}  \text{ where }\textbf{x,y}\in \mathbb{R}^n$ . So now we have: $$(1)\quad A\textbf{v}=\lambda \textbf{v}=\lambda (\textbf{x}+\textbf{y}i)=(a+bi)(\textbf{x}+\textbf{y}i)=(a\textbf{x}-b\textbf{y})+i(b\textbf{x}+a\textbf{y})\\$$
But now you also know that $$(2) \quad A\textbf{v}=A(\textbf{x}+\textbf{y}i)=A\textbf{x}+A\textbf{y}i.\\$$
So I can set (1) and (2) equal:
$$A\textbf{x}+A\textbf{y}i=(a\textbf{x}-b\textbf{y})+i(b\textbf{x}+a\textbf{y})$$
But now we can set the real and imaginary parts equal. We have:
$$A\textbf{x}=(a\textbf{x}-b\textbf{y}) \text{ and } A\textbf{y}=(b\textbf{x}+a\textbf{y}), \text{ where }A\textbf{x}, A\textbf{y} \in \mathbb{R}^n$$
So the invariant subspace is the plane spanned by $\textbf{x}$ and $\textbf{y}$ and is two dimensional.
Could you help me understand the connection between my x and y and your $w_1$ and $w_2$. I think my $2x=w_1$ and $2y=w_2$ so the span is the same, but then when we multiply by A the stuff is different? How?


O-notation: composing functions

Question: Big-oh and little-oh notation make things much simpler, and there are convenient rules for combining functions, for example, the ones mentioned here.
One rule conspicuously missing from the above list is a rule for function composition. If $f = O(\mu(x))$ at $a$, and $g=O(\nu(y))$ at $f(a)$, then what do we know about $g \circ f$ at $a$?
Some things which lead me to believe such a rule might exist, under certain conditions:

Suppose $f$ and $g$ are $n$ times differentiable functions. It is a
theorem in calculus that if $p$ is the Taylor polynomial of degree
$n$ for $f$ at $a$, and $q$ is the Taylor polynomial of degree $n$
for $g$ at $f(a)$. Then $q \circ p$, truncated at degree $n$, is the
Taylor polynomial for $g \circ f$ at $a$. In other words, if  $$f= p
 - o((x-a)^n)\quad \text{and} \quad g = q + o((y-f(a))^n),\\ \text{then}\quad g \circ f = q \circ p + o((x-a)^n).$$
In the simple case of polynomials, there is a very convenient
composition rule: Suppose $p(x)-p(a)=O((x-a)^n)$ at $a$, and $q(y) =
   O((y-p(a))^m)$ at $p(a)$. Then $q \circ p$ is $O((x-a)^{mn})$ at $a$.
Answer: By the assumptions made,
$$\limsup_{x\to a} \frac{|f(x)|}{|\mu(x)|}<\infty\quad \text{ and }\quad
\limsup_{x\to a} \frac{|g(f(x))|}{|\nu(f(x))|}<\infty \tag1$$
If the function $\nu$ is doubling, meaning that there is $C$ such that
$$ |s|\le 2|t|\implies |\nu(s)|\le C|\nu(t)| \tag2$$
then we can conclude from the first part of (1) that
$$\limsup_{x\to a} \frac{|\nu(f(x))|}{|\nu(\mu(x))|}<\infty$$
and combining this with the second part of (1),
$$\limsup_{x\to a} \frac{|g(f(x))|}{|\nu(\mu(x))|}<\infty \tag3$$
which is what one might have expected: $g\circ f=O(\nu\circ \mu)$.
Non-doubling case
Without (2) we don't get an explicit asymptotic like (3) because the constant implicit in the first part of (1) actually matters. For example, if $f(x)=O(x)$ as $x\to 0$ and  $g(x)=O(\exp(-1/x^2))$ as $x\to 0$, the asymptotic behavior of $g\circ f$ depends quite a bit on the implicit constant in $f(x)=O(x)$. We can state that
$$g(x) = O(\exp(-C/x^2)) \quad \text{for some } \ C>0$$
which is less precise that having $O(\cdot )$ with a concrete comparison function in it.
Remark
Constant $2$ in the doubling condition (2) could be replaced by any constant greater than $1$; the meaning of the condition does not change. Doubling condition includes all polynomials (as in your example), but does not  include the functions growing or decaying at super-polynomial rate.
Comment: Fantastic answer! Thanks
Answer: The argument about the Taylor polynomial is sound...but not every function's Taylor polynomial converges to the function, so it may have no impact on the functions themselves.  For instance, for
$$
f(x) = \begin{cases} 1 - e^{-\frac{1}{x^2}} & x \ne 0 \\ 0 & x = 0\end{cases}
$$
the Taylor series converges everywhere (it's the zero series!), but converges to $f$ only at $x = 0$. So knowing something about the degree of the Taylor series doesn't tell you much about $f$.
For nice enough functions, with series representations that converge everywhere, there might be something reasonable to say...but if $f$ and $g$ have everywhere convergent series, is it obvious that $f\circ g$ does as well? (It's not obvious to me!)

O-notation: composing functions


The pager on a form doesn't update upon first submit of the form

Question: I have a form with filter checkboxes, submit button, results in tableselect and pager.
When I set some checkboxes and press the submit button, a query should be reexecuted, data should be placed into the tableselect and pager should be updated, because new data size can be different with old one.
When I do it the first time, query is executed successfully, tableselect also is updated without problems. But the pager doesn't want to be updated.
And to update the pager I have to press the submit button second time.
But it occurs only I pressed the submit button after the page with the form has been loaded.
Could you clarify me, how can I update the pager after first submission of the form ?
Here is a fragment of my code with the tableselect and the pager.
<code>$q = \Drupal::entityQuery('node');
        $q = $q->condition('type', 'my_node_type')
            ->condition('status', 1);

        $pager_params = [];
        if ($event_types != []){
            $q->condition('field_art_der_veranstaltung', $event_types, 'IN');
        }

        $events = $q->sort('created', 'DESC')->pager(10)->execute();

        $nodes = Node::loadMultiple($events);

        $rows = [];

        foreach($nodes as $node){
            $rows[$node->id()] = [
                'nid' => $node->id(),
                'title' => $node->getTitle(),
            ];
        };

        $form['nodes_container']['nodes'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Events'),
            '#options' => $rows,
            '#header' => $header,
            '#empty' => $this->t('No events found'),
        ];

        $form['nodes_container']['pager'] = [
            '#type' => 'pager',
        ];
</code>
Answer: Seemingly, I have fould the solution.
Namely, to avoid it, I set the Element property for the pager explicitely.
Here are fragments of code.
<code>$nodes = $q->sort('created', 'DESC')->pager(10, 0)->execute();

/// code here

$form['nodes_container']['pager'] = [
  '#type' => 'pager',
  '#element' => 0,
  '#parameters' => $pager_params,
];
</code>
Unfortunately, I didn't have a time to debug and find out why it didn't worked before but it works now. Newertheless, it works.


Probability of having exactly $v$ different letters in password

Question: Consider a password with $t$ characters, with a character set of length $n^2$. What is the probability there are $v$ distinct letters in the password.
So if the password was "abccdadde" $v$ would be $5$ and $t=9$.
So far I have deduced if $t=n=v$ the probability is given by: $$\frac{n^{2}!}{\left(n^{2}-n\right)!n^{2n}}$$
And when $t=v+1=n+1$ the probability is given by:$$\frac{n\left(n+1\right)!n^{2}!}{2n!\left(n^{2}-n\right)!n^{2\left(n+1\right)}}$$
Answer: Denote $n^2=N$ for ease of notation, then the number of ways to assign $v$ "dummy" characters (to be replaced by actual characters later under a bijective map) is the definition of the second-kind Stirling number $S(t,v)$. Then there are ${}^NP_v=\binom Nvv!$ ways to assign the actual characters, so the number of admissible passwords is
$$\binom Nvv!S(t,v)$$
and the probability is this over the total password count $N^t$.
Answer: This is a collection of hints, but too long for a comment.
First, one approach which I feel often helps in these cases is to use the relation
$$\Pr(\text{exactly} \ v) = \Pr(\text{at most} \ v) - \Pr(\text{at most} \ v-1).$$
Perhaps you can try to work out an estimate on $\Pr(\text{at most} \ v)$. Here are some starting points.
Define $p_{k,t,v}$ to be the probability that at most $v-k$ new letters are used in $t$ draws when $k$ letters have already been used. Now "take one step and see what happens", as my old Markov chains teacher used to say. Taking one step reduces $t$ by $1$, as there is now one fewer draw required. If the new letter drawn has yet to be seen, then $k$ increases by $1$; otherwise, it remains fixed.
Might be quite rough computationally to do this recurrence relation. There might be some easier way; I'm not sure. Certainly some combinatorial argument, counting the ways of drawing things, seems plausible, but I was trying to avoid that as it would likely be pretty unwieldy!


How to set up AZURE PHP SDK to SAS connection string

Question: there!
I am trying to fetch messages from topic and subscription of my client in Azur Service Bus. the connection string looks like this:
<code>$connectionString =
"Endpoint=<namespacename>.servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<your_key_from_the_portal>"
</code>
This is what my client gave to me and this is new Shared Access Signature (SAS) format. But as I admit Azur PHP SDK using the old ACS format connection string looks like this:
<code>$connectionString =
"Endpoint=sb://mynamespace.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=[MyVal]";
</code>
I saw some answers here wich recommended to set up Azur portal to use ACS connection string format. Is there any way to change or set up Azur PHP SDK to use the new type of connection string?
Answer: As far as I know, the current PHP Service Bus APIs(v5.0.0) only support ACS connection strings.
Currently, you can create ACS connection strings via Azure Powershell:
First, make sure you have Azure PowerShell installed, then in a
PowerShell command prompt, run
<code>Add-AzureAccount # this will sign you in
New-AzureSBNamespace -CreateACSNamespace $true -Name 'mytestbusname' -Location 'West US' -NamespaceType 'Messaging'
</code>
You can refer to https://github.com/Azure/azure-sdk-for-php#service-bus-queues for more info.


Isomorphism of $k$-Algebras

Question: Let $k$ be a field an $A$ a finitely generated $k$-algebra (think of the polynomial ring).
Suppose I have an isomorphism of $k$-algebras
$$
A \cong A/I
$$
for some ideal $I$. If $A$ were a finitely generated $k$-vector space we can conclude $I=0$, as opposed to the non finitely generated case. So can we still get $I=0$, even though $A$ is not f.g. as a vector space over $k$, only as an algebra?
Comment: If you mean finitely generated as a $k$-algebra, you can reduce the problem to finding ideals $I$ in $A=k[x_1,\ldots, x_n]$ such that $A\cong A/I$.
Answer: Your question is usually phrased as follows:

is a finitely generated algebra Hopfian?

A well-known theorem of Maltsev states that every presentable finitely generated algebra is Hopfian —presentable means here that the algebra embeds in a matrix algebra $M_n(R)$ for some commutative ring $C$. This condition holds for an algebra $A$ if one can separate elements in $A$ with maps to algebras of finite dimension, for example (One says in this case that the algebra $A$ is residually finite dimensional)
But not all finitely generated algebras are Hopfian. For example, there exist finitely generated groups $G$ with surjections $G\to G$ which are not injective, and the induced morphisms of group algebras $k G\to k G$ are surjective algebra maps which are not injective. The classical example is the Baumslag-Solitar group
Comment: A (left or right) noetherian ring is hopfian, so nothing interesting happens there.
Comment: But every such group is non-abelian. I assume the OP meant to ask about *commutative* $k$-algebras, given the (commutative-algebra) tag on this question...
Comment: (That is proved [here](http://math.stackexchange.com/questions/802413/noetherian-implies-hopfian) for groups, and the same argument, *mutatis mutandi*, works here)
Comment: Right, and I think this statement, together with a sketch of the easy proof, would be a better answer to the OP's question.
Comment: You are free to provide that.
Answer: The answer is yes for finitely generated commutative $k$-algebras (Mariano's answer deals with the non-commutative case). More generally, if $A$ is a Noetherian ring and there is an isomorphism $f\colon A/I \to A$, then $I = (0)$.
Why? Let $\pi\colon A\to A/I$ be the quotient map. If $I\neq (0)$, then $f^{-1}[I]$ is a nonzero ideal in $A/I$, so $\pi^{-1}[f^{-1}[I]]$ is an ideal in $A$ which properly contains $I$. Repeating, we can build an infinite ascending chain of ideals.
Edit: Here are a few more details. We start with $I_0 = (0)$ in $A$, and we set $I_{i+1} = \pi^{-1}[f^{-1}[I_i]]$ for all $i$. Let's check by induction that we get a proper increasing sequence $I_0 \subsetneq I_1 \subsetneq \dots$ of ideals in $A$. In the base case, $I_1 = \pi^{-1}[f^{-1}[(0)]] = \pi^{-1}[(0)] = I$, and we've assumed that $(0) \subsetneq I$. And given the inductive hypothesis $I_{i-1} \subsetneq I_i$, we have $I_i = \pi^{-1}[f^{-1}[I_{i-1}]] \subsetneq \pi^{-1}[f^{-1}[I_{i}]] = I_{i+1}$.
Comment: Either there is a flaw or I'm overlooking something: in the "repeating" part, we get a sequence of ideals all containing $I$, but not necessarily their predecessor, as $\pi$ is mapping into the fixed quotient ring $A/I$.
Comment: I've added a few more details to my answer.

Isomorphism of $k$-Algebras


JSON.stringify () error in javascript

Question: I have the following code
var number = 0618260587

JSON.stringify(number)

the stringified result is 618260587 , the first zero is automatically truncated.
I tried the following fix
if(number.length<8)
        {
        var book1 = "0" + number;
        alert(book1);

but it alerts undefined.  I am not sure
1) Why the stringified data truncates the first zero
2) I thought javascript adds two variables irrespective of type
Answer: Leading zeroes are a display thing, and not normally part of numbers. There's an infinite number of invisible zeroes before/after every number, but they're not normally shown. If you want the leading zero, treat the number as a string:
var number = '0618260587';

As well, in most, numbers with a leading zero are treated as octal, not decimal. Bare leading zeroes can cause hard-to-track bugs because of this - it looks like a decimal to you, but it's some completely different number to the interpreters, eg..
0618260587 octal = 1616431 decimal

Comment: +1 for the warning about octals. In his case (at least on Firefox), it actually works as a decimal, because he has the digit 8. If you changed 8 to 6, it will become octal. Is this fallback to decimal in the presence of invalid octal digits spec'd somewhere?
Comment: Thank you for the explanation !! I would have done it , but I require the input to be a number and then stringify it . What is wrong with the fix I tried making?
Comment: @alex: you're not using `number`in your fix. `book` is undefined, making the whole result undefined.
Comment: MarcB , apologies , I had changed the variable while putting the question up , I left that change , The problem still remains
Comment: if `number` is still an int, then it has no `.length`. You have to convert it to a string first. That means your `if()` is failing, since a number can never have a length, so it's doing `if (undefined < 8)`.

JSON.stringify () error in javascript


Loop through directory zip folders with bat and 7zip

Question: I am trying to loop through a directory with folders in it.
I want to compress the folders trough 7zip (As some of them are really big files)
What I mean with this is as example:

Main folder

Backup 1
Backup 2
Backup 3

I want it so that it creates for the folders Backup 1-3 each a separate 7zip file.
Here is what I got:
<code>@echo off
set zip=7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on
set directory="E:\Backup\"
for /d %%i in (%directory%) do %zip% "%%i.7z" "%%i%\*"
pause
</code>
But as soon as I do it like this, it just creates 1 7zip file called Backup, it does not make a seperate 7zip file for each folder inside it.
Answer: You have it almost done.
<code>@echo off
    set "zip=7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on"
    set "directory=E:\Backup"
    for /d %%i in ("%directory%\*") do %zip% "%%~fi.7z" "%%~fi\*"
    pause
</code>
Answer: This is another option:
<code>@echo off
cd /d "E:\Backup\"
set zip=7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on
for /d %%i in (*) do %zip% "%%i.7z" "%%i%\*"
</code>


$\{f_n\}$ continuous such that $\inf f_n$ and $\sup f_n$ are not continuous

Question: Find a sequence of continuous functions on $[0,1]$, $\{f_n\}$, such that $f(x):=\sup\{f_n(x):n\geq 1\}$ and $g(x):=\inf\{f_n(x):n\geq 1\}$ are both not continuous.
I kept finding examples where one was discontinuous but the other was continuous like $f_n(x)=|x|^\frac{1}{n}$ and $f_n(x)=x^n$
Answer: You may consider $f_n(x) = \sin(nx)$. Then you can check that for all $n \ge 2$, $f(\frac{\pi}{2n}) = 1$ and $g(\frac{3\pi}{2n}) = -1$ (because $f_{n}(\frac{\pi}{2n}) = 1$, $f_n(\frac{3\pi}{2n}) = -1$, and clearly $f_k(x)$ is always between $-1$ and $1$).  We also have $f(0) = g(0) = 0$. So neither $f$ nor $g$ is continuous at $0$.
Answer: $f_n(x) = 1/2$ for $1/n < x < 1-1/n$, $f_n(0)=0, f_n(1)=1$, $f_n$ continuous and affine linear on $(0,1/n]$ and $[1-1/n,1)$. The $\inf$ is $1$ for $x=1$ but $=1/2$ for $ x<1$ close to $1$. The $\sup$ is $0$ for $x=0$ but $=1/2$ for $x$ close to $0$, but not equal to zero.
Answer: Let $(f_n)_{n\geq 1}$ be a sequence of continuous functions such that $f(x) = \sup\{f_n(x) \mid n \geq 1\}$ is not continuous, but is bounded, that is $|f(x)| < M$. Then
$$
g_n = \begin{cases}
M + g_{\frac{n}{2}} & \text{ for } 2 | n \\
-M - g_{\frac{n+1}{2}} & \text{ otherwise}
\end{cases}$$
is a sequence you are looking for. Clearly, for odd $n$ we have $g_n(x) < 0$ and $g_n(x) > 0$ for $n$ even. For this reason, for any $x$, the upper bound is $f(x)+M$ and the lower bound is $-f(x)-M$, and that completes the proof.
Hope that helps ;-)
Answer: $$
f_n:x\mapsto(1+\mathrm e^{n(x-a)})^{-1},\qquad a\in(0,1)
$$


Why does NTP daemon keep listening on UDP6?

Question: I have a clean Debian 7 installation, and I manually entered the following lines in /etc/ntp.conf:
interface ignore wildcard
interface listen <local_nic_ip>

Hoping that NTP will no longer listen on UDP6, but after a restart, it still does:
5:udp        0      0 <local_nic_ip>:123       0.0.0.0:*                           9172/ntpd
6:udp        0      0 127.0.0.1:123           0.0.0.0:*                           9172/ntpd
8:udp6       0      0 ::1:123                 :::*                                9172/ntpd

The command line of NTP shows nothing unusual:
/usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 121:130

How to stop NTP from listening on that UDP6 port?
Comment: @Semirke It makes me nervous when I tell a program to do something, yet it does something totally unexpected. Why does NTP listen on UDP6 when I told it not to?
Comment: It's listening on localhost on both IPv4 (127.0.0.1) and IPv6 (::1). Are you sure you haven't configured it to listen on localhost? Or maybe it always listens on localhost. Not sure about that. In either case it will not hurt.
Comment: What is your problem with listening? Isnt it enough for you if ntpd uses ipv4 for DNS resolution? Im asking this as ntpd will always bind to all wildcard addressess. But you can specify IPv4 only DNS, use firewall to block ip6 traffic, or use ntp.conf to restrict ipv6 traffic.
Answer: I have been able to disable IPv6 for NTP on my Debian 5/6/7 and Ubuntu 12.04 this way :
Edit file /etc/default/ntp and replace
NTPD_OPTS='-g'

by
NTPD_OPTS='-4 -g'

Then, you can keep your directives in ntp.conf, they are not ignored :
interface ignore wildcard
interface listen <local_nic_ip>

Without interface ignore wildcard NTP will also listen on 0.0.0.0
Without interface listen <local_nic_ip> NTP will only listen on
127.0.0.1 (of course)

This will results in :
# netstat -anp | grep :123
udp    0      0 192.168.0.38:123     0.0.0.0:*                 2901/ntpd
udp    0      0 127.0.0.1:123        0.0.0.0:*                 2901/ntpd

Also, i confirm that OpenNTPD listens where you ask him to listen more friendly (no need to edit multiple config files). By default it listens nowhere until you configure it to do so (very secure) ;)
In config file, just uncomment line
listen on 127.0.0.1

And add line
listen on <local_nic_ip>

Results in :
# netstat -anp | grep :123
udp   0    0 192.168.0.38:123     0.0.0.0:*                 8581/ntpd
udp   0    0 127.0.0.1:123        0.0.0.0:*                 8581/ntpd

Comment: Thanks. In case this helps someone, on CentOS 6.6 (and, thus, probably on Fedora and RHEL) the options are in this file: /etc/sysconfig/ntpd.
Comment: @Semirke I agree with you about the `-4` option and DNS queries, but the fact is that, by doing this, i have no more listener on my ipv6 interfaces for ntp (assuming i trust `netstat` output).
Comment: hi, ntpd -4 will only make it to do ipv4 DNS queries. Ntpd will keep listening on IPV6. Also I agree with your OpenNTPD notion, that you can configure to not listen on ipv6.
Comment: @krisFR Thanks for the suggestion. Where is OpenNTPD configuration file?
Answer: If you consider this a bug (and I certainly do: ntpd is ignoring a configuration directive) you're going to have to take it up with the package maintainer or upstream authors. I don't believe any of them hang out here - refer to the package information for their contact details.
Alternatively you could try another NTP implementation (like OpenNTPD - I've not used it personally, but the OpenBSD folks tend to be absolutely paranoid about security, so I imagine it only listens where it's told to).
As Sander pointed out though, your NTP daemon is listening on localhost (127.0.0.1 & ::1) - If you're worried about being hacked from localhost you probably have bigger problems than your NTP daemon.
I'm a bit miffed that the daemon is ignoring a configuration directive, but I wouldn't consider this a serious security concern.
Comment: Always be wary of recommendations/suggestions when the person giving the recommendation confesses to never having used the product in question. If you need an alternative to ntp reference implementation try chrony. It is important to note that chrony and openntpd do not support a lot of the extended features of the reference implementation.
Comment: @dfc Beware of recommendations in general: *All* software recommendations should be evaluated for suitability in a given environment before blindly implementing them. In this case I know a number of folks who use OpenNTPD (on OpenBSD), and they speak very well of it as a "basic NTP daemon". Obviously if you're using features of the reference implementation that it doesn't support it's not going to work for you.
Answer: ntpd is not doing that; ntpdate is. See below for explanation.
I didn't have either of these in my conf file:
    interface ignore wildcard
    interface listen <local_nic_ip>

I booted and sudo netstat -tunlp gave me this:
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    udp        0      0 127.0.0.1:123           0.0.0.0:*                           1433/ntpd
    udp        0      0 0.0.0.0:123             0.0.0.0:*                           1433/ntpd

I turned on my network connection and netstat gave me this:
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      4432/dnsmasq
    udp        0      0 127.0.1.1:53            0.0.0.0:*                           4432/dnsmasq
    udp        0      0 0.0.0.0:123             0.0.0.0:*                           4501/ntpdate
    udp6       0      0 :::123                  :::*                                4501/ntpdate

Note the first two are DNS, not ntp. Scroll right to see the program name.
I waited a bit, then netstat gave me this:
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      4432/dnsmasq
    udp        0      0 127.0.1.1:53            0.0.0.0:*                           4432/dnsmasq
    udp        0      0 192.168.5.5:123         0.0.0.0:*                           4542/ntpd
    udp        0      0 127.0.0.1:123           0.0.0.0:*                           4542/ntpd
    udp        0      0 0.0.0.0:123             0.0.0.0:*                           4542/ntpd

Strange. Anyway it looks like ntpdate is what (temporarily) gives you the udp6 connection. You have to use sudo to see the PID and program name, otherwise it is very misleading.
(later)
Ah, never mind, it looks like yours really is ntp...


"Someone logged on to your SQL server from an unusual location."

Question: I'm using SQL Server on Azure and just received this security threat message.

Unauthorized access that exploits an opening in the firewall; legitimate access from a new location.

Google searches don't seem to give me any usable results.
Does this imply that someone actually logged on to my server or just access the API from a new location?
What does this message mean and how should I react to it?
Update: screenshots
Firewall settings

Threat message
Comment: Was it you or someone else with credentials? If not, then it was an unauthorized user and you have had a data breach. Why on earth do you have SQL Server open to the Internet?
Comment: I have no ip's listed in firewall rules. Not even my own.
Comment: What do you have, then? It's a bit difficult to answer, since you're being overly vague about everything. You left out most of the details of the message you received, and you didn't show what you do have in your firewall rules...
Comment: @MichaelHampton I updated my question with screenshots to give better info.
Comment: Possibly the "Allow access to Azure services" could be the problem? Other Azure services are being allowed to access this server?
Answer: https://docs.microsoft.com/en-us/azure/sql-database/sql-database-threat-detection-overview

This alert is triggered when there is a change in the access pattern to SQL server, where someone has logged on to the SQL server from an unusual geographical location. In some cases, the alert detects a legitimate action (a new application or developer maintenance). In other cases, the alert detects a malicious action (former employee, external attacker).

I would check if any users/developers that normally works with the SQL have been in Washinton or used any VPN taht terminates in washington. If you can't find a legitme reason for the alert I you should treat it as a breach and re-evaluate your security.
Comment: Just to add to this a little, Azure SQL Query editor is an in browser SQL code runner so whoever triggered this alert has access to the Azure subscription that the database is located in and it's unusual more than likely because it's their first time accessing the resource. Also the editor pokes a hole in the firewall I think to let the connection through so I don't think firewall setup applies here.


saving data safely before Activity is destroyed

Question: i need to save some crucial importance data when user closes my app. i prefere to do this in Activity's onPause(), as it is the latest method guaranteed to be called before the application is destroyed no matter what is the reason of its destruction. however, i save the data in a database, so i use an AsyncTask. from my AsyncTask, when it's finished, i call a callback method on my Activity reference i have saved in the AsyncTask before, where i put some variables to SharedPreferences indicating that the data has been successfully put to database.
my question is: is the AsyncTask guaranteed to finish and the callback to be called on an alive Activity reference before it gets destroyed? If not, how to ensure that data is written to database before Activity is destroyed?
Comment: it's not an issue. i'm just asking a technical question about application behaviour. the situation is described in my question.
Comment: Have you tried any code before? If so please get me the code here i will let you know the issue
Answer: You don't need to implement a CallBack method to save in your SharedPreferences that you have updated the Database.
You can simply, if you really need a database for your info, create a flag in your SharedPreferences called isDataExistToLoad
This flag has to be initially False, and within the Thread that will store your info into the Database set it to True.
public void updateUserStatus(ArrayList<Object> data){
    try{
         DBController.save(data);
         SharedPReferencesController.setDataExistToLoad(true);
    }catch(Exception e){
         e.printStackTrace();
         SharedPReferencesController.setDataExistToLoad(false);
    }
}

Whenever you open your app, check on this flag. If it is True go load from database then set it to False. If it is False leave it as it is because the previous transaction was not successfully done.

My question is: is the AsyncTask guaranteed to finish and the callback
  to be called on an alive Activity reference before it gets destroyed?
  If not, how to ensure that data is written to database before Activity
  is destroyed?

My Answer is: Part of the AsyncTask runs in a separate Thread which is DoInBackground and you cannot ensure that the Activity will still be survived until it is done. If you tried to perform any other task in postExcute() which runs on UITread after finishing the background thread work. Your app might crash. That's why I don't recommend that.
Comment: i need all transactions to be successfully done, that's why i have written this question.
Comment: The method `Save` that will store your data should `Throw` exception in case of any failure happened. In this way you will ensure that all the transactions have been done successfully. @Salivan
Comment: but the callback is a very comfortable think in my situation. i just need somebody to tell me whether the `Activity` is going to survive until the `AsyncTask` finishes so i can be sure the callback is called.
Comment: @Salivan Part of the `AsyncTask` runs in a separate `Thread`  which is `DoInBackground` and you cannot ensure that the `Activity will still be survived. If you tried to perform any other task in `postExcute()` which runs on UITread. Your app might crash. That's why I don't recommend that.
Comment: @Salivan When you use `Try/Catch` and edit the preference at the end of the `Try` this will ensure that all the previous code has to be successfully done without any exception before editing the preferences :)
Comment: but if `Activity` is destroyed then i have no `Context` for my `SharedPreferences`... how to use it in my `AsyncTask` then?
Comment: @Salivan don't use the `AsyncTask` use a normal `Thread` and you can use the `ApplicationContext` instead of the `Activity`
Comment: why can't i use an `AsyncTask`? i can pass an `ApplicationContext` for later use.
Comment: @Salivan The main function of the AsyncTask to is communicate with an API or perform any HTTP request from the UI thread (Activity or Fragment). That's why it provide you with `onPreExcute` to show your progressBar for example and `postExcute` to hide the progress and display the data on the UI
Comment: If your question is can I pass the `ApplicationContext`? As long as it is a context, then you can pass it. But this is not how you should use it @Salivan
Comment: how should i use it then?
Comment: new Thread(new Runnable() {
            @Override
            public void run() {
                //Your code her
            }
        });
Answer: The ASyncTask executes in background parallely to the main thread. In case if the  Activity is closed, still the ASyncTask continues to execute till end. And it need not to return the control to the main process.
So, you can surely use this method of saving data before closing the application.
I am not sure whether after onPause of Activity (ie; when onPause() callback is called) you might be able to use the share-preference, feature. So, you should handle it on the backbutton or some event in onCreate()
Comment: When you close the activity, the activity gets destroyed, but sill the ASyncTask continues to execute till end.
Comment: No, Activity doesn't survives when it is destroyed, even then the ASyncTask continues to execute
Comment: i know what you mean, but i would like to know whether the `Activity` survives while `AsyncTask` executes and whether the callback will be called.


Does $\mathrm A \mathrm A^T \succeq x^2 \mathrm I$ imply $\frac{\mathrm A + \mathrm A^T}{2} \succeq x \mathrm I$?

Question: Let $A $ be an $n \times n $ matrix such that $AA^T \geq x^2I, x\geq 0 $, which means that the matrix  $AA^T-x^2I$ is positive semidefinite. Can we show that $(A+A^T)/2 \geq xI$?
Thanks
Comment: You made a sign error in the first sentence. (Either $A A^T \leq x^2 I$ or $A A^T - x^2 I$ is positive semidefinite. Either way is fine, but what you wrote isn't consistent with standard notation.)
Comment: Maybe you mean that $ AA^T-x^2I$ is positive semidefinite
Comment: Why is it not consistent? What do you mean by consistent?
Comment: However I think that the statement should be reformulated, because as it is, it is trivially false simply because of the sign of $x$. Infact, assume $A$ to be simply a one-by-one matrix, then you say that if $A^2\geq x^2$, then $A\geq x$
Comment: $x $ is nonnegative real number.
Comment: @Zhale For symmetric matrices $A,B$, $A \geq B$ means $A-B$ is positive semidefinite. This matches up with the order on real numbers when you look at just one dimension. Sometimes we use a different symbol to avoid confusion with the usual real number $\leq$.
Answer: Let
$$\mathrm A := \begin{bmatrix} 1 & 0\\ 0 & -1\end{bmatrix}$$
Then,
$$\mathrm A \mathrm A^T = \mathrm A^2 = \begin{bmatrix} 1 & 0\\ 0 & 1\end{bmatrix} \succeq \mathrm I_2$$
However,
$$\frac{\mathrm A + \mathrm A^T}{2} = \mathrm A \preceq I_2$$
Comment: @Zhale  At least the converse is true (i.e., $A+A^\dagger\succeq 2x\,I$ and $x\geq 0$ implies that $AA^\dagger\succeq x^2I$).
Comment: Thanks for the answer.  Do you know what assumption is needed in order to have the desired inequality?


Last $n$ digits of $a^b$

Question: Last year I came acoss the following problem in a mathematics competition

What are the last $2$ digits of $2012^{2012}$? $\ \ \ \ \ $(Ans: 56)

I found the last two digits using the standard technique involving some modular arithmetic.
Another student came up with a very clever technique that did not rely on modular arithmetic but rather on  logarithms and the floor function (scientific calculators were allowed, but no graphing calculators or computer algebra systems). I've forgotten the details of this technique, which was really just a function that could be written in a single line, but remember that it easily generalized to give the last $n$ digits of any number of the form $a^b$ without causing overflow errors on little scientific calculators, even with sizable $a$ and $b$.
I've searched stackexchange and the web for information on this technique but found nothing. I spent a fair amount of time thinking about the problem but not made any progress. Has anyone seen such a technique? If so, please help me reproduce the function he used.
I am specifically interested in the technique described above; without any modular arithmetic, Chinese Remainder Theorem, Euler's Generalization, Repeated Squaring, etc.
Comment: If the floor function was used, it throws away precision. Note that the last two digits before the decimal point for $(1012+\epsilon)^{2012}$ are $57$ if $\epsilon\approx 10^{-2019}$ so this story does not sound feasible to me. - Can you possibly contact that fellow contestant?
Comment: It should be noted that the method was really just a function that could be written in a single line. I wrote a program of the generalized version on TI-84 but it has since inadvertently been erased.
Comment: $$f(a,b,n) = {a^b} - {10^n}\left\lfloor {\frac{a^b}{{10}^n}} \right\rfloor$$

Is an example of a function that gives the last $n$ digits of $a^b$, however it would not be useful on a scientific calculator and was not what the fellow contestant used.
Comment: The first two digits are 79.
Comment: @HagenvonEitzen I don't think so. I had programmed this into my calculator Ti-84 before!
Answer: Let's start with some modular arithmetic. I know you don't want an answer explicitly using any modular trickery, but often an answer can hide the means used to get it.
The goal is to calculate $a^b\bmod 10^n$, which as you have pointed out is equal to $a^b-10^n\left\lfloor a^b10^{-n}\right\rfloor$, although that formula is plainly useless if $a$ or especially $b$ are even moderately large. The identity $x\bmod y=x-y\lfloor x/y\rfloor$ will come in handy though. Let $m=10^n$ be the base for the mod operation.
The way we can proceed is by reducing $a$ and $b$ as much as possible, using modular arithmetic. The easy one is $a$: since modular arithmetic preserves products, $a^b\equiv (a\bmod m)^b$. Thus, we need only consider $a\le m$.
The most useful formula in this context is Euler's theorem $a^{\phi(m)}\equiv 1\pmod m$, where $\phi(m)$ is the totient function. In general, $\phi(m)$ is quite difficult to compute, but by a stroke of luck we happen to know $m=10^n$, so we know the prime factorization, and by the formula
$$\phi(m)=\phi(p_1^{e_1}\dots p_n^{e_n})=m\left(1-\frac1p_1\right)\dots\left(1-\frac1p_n\right),$$
we find that $\phi(10^n)=10^n(1-1/2)(1-1/5)=4\cdot 10^{n-1}$.
Unfortunately, Euler's theorem comes with the caveat that $a$ and $m$ must be coprime, so it doesn't work in full generality like you want. An even stronger result is Carmichael's theorem, which is just the same as Euler's, but with a smaller function in the exponent: $a^{\lambda(m)}\equiv 1\pmod m$, where $\lambda(10^n)=2\cdot 10^{n-1}$. Furthermore, $a^{\lambda(m)+b}\equiv a^b\pmod m$ for any integer $a<m$ and any $b\ge k$, where $k$ is the largest exponent in the prime factorization of $a$. Now we want a general formula that doesn't need any factorization, so let's upper-bound $k$. The worst-case scenario is if $a$ is a high power of $2$ less than $10^n$. In this case, $a=2^k<2^{n\log_2 10}=10^n$, so $k<n\log_2 10$. (Note that $n\log_2 10$ is not an integer, but with our floor trick for calculating $\bmod$ this won't be a problem. It is just as well to use $\lfloor n\log_2 10\rfloor$ instead.)
We're ready to put it all together now. We have $a^b\bmod m=c^d\bmod m$ as long as $a\bmod m=c\bmod m$ and $b\bmod\lambda(m)=d\bmod\lambda(m)$ and $b,d\ge n\log_2 10$. (I'm assuming $a$ and $b$ are "large", and we are trying to reduce them to reasonable proportions. If $b<n\log_2 10$, then just plug the damn thing into your calculator.) Thus, the optimal choices that satisfy the criteria are
$$c=a\bmod 10^n=a-10^n\left\lfloor a10^{-n}\right\rfloor,\quad\rm and$$
$$\begin{align}
d&=((b-n\log_2 10)\bmod2\cdot 10^{n-1})+n\log_2 10 \\
&=b-2\cdot 10^{n-1}\left\lfloor\frac{b-n\log_2 10}{2\cdot 10^{n-1}}\right\rfloor, \end{align}$$
and we finish by plugging those into $a^b\bmod 10^n=c^d-\left\lfloor c^d10^{-n}\right\rfloor$.

For the case in the OP, $a=b=2012$, and $n=2$. Then $c=12$, $\phi(10^n)=40$, $\lambda(10^n)=20$, $n\log_2 10=6.64\dots$, $\lfloor n\log_2 10\rfloor=6$, and $d=12$, so $$2012^{2012}\bmod 100=12^{12}\bmod 100=8916100448256\bmod 100=56.$$
The numbers are still somewhat large, but certainly within the realm of scientific calculators. The problem becomes of course much more tractable if you split the exponent in half. This is step one of exponentiation by repeated squaring (but I claim to be avoiding the restriction on the OP, since I'm not advocating the whole iterative process ;) ). Better yet, we can divide the exponent into $q$ equal pieces (more on choosing $q$ in a bit). The way it goes is (after having reduced $a$ and $b$ to $c$ and $d$ as above) to calculate $c^{qr+s}\bmod m=(c^r\bmod m)^qc^s\bmod m$, where $d=qr+s$ is the quotient and remainder of $d$ on division by $q$, i.e. $r=\lfloor d/q\rfloor$ and $s=d\bmod q$. Now our final result is
$$a^b\bmod 10^n=(c^{\lfloor d/q\rfloor}\bmod 10^n)^qc^{d\:\bmod\:q}\bmod 10^n,$$
where as before $x\bmod y$ is shorthand for $x-y\lfloor x/y\rfloor$. Using this formula instead, with the original numbers, and choosing $q=3$, we get
$$\begin{align}
a^b\bmod 10^n&=(12^4\bmod 100)^312^0\bmod 100\\
&=(20736\bmod 100)^312^0\bmod 100=46656\bmod 100=56,\end{align}$$
which is well within the range of an 8-digit pocket calculator.
But where does $q$ come from? The two big numbers in our calculation are $c^{\lfloor d/q\rfloor}=20736=h$ and $(h\bmod 100)^{d\:\bmod\:q}=46656$. The bigger $q$ is, the smaller the first number is and the larger the second is. On a rough heuristic, both $c$ and $h\bmod 100$ are large numbers mod $100$, so they should be approximately 50, if I pretend the numbers are uniformly distributed. (Don't read too much into this estimate.) Thus a good choice of $q$ would approximately equalize the exponents, i.e. $q=\lfloor\sqrt d\rfloor$ (which is equal to $3$ in our example).
Comment: Excellent answer! I just read through it quickly and it looks to answer the question in a manner that works but is very different from what I expected. I will look over it more thoroughly tonight. Thanks!
Answer: Are you sure the problem asked about the last few digits? If it was first few digits, the one-line solution using logarithms would sounds a lot more likely:
$$g(a,b,n)=\left\lfloor 10^{b\log_{10}a - \lfloor b\log_{10}a\rfloor + 1 + n} \right\rfloor$$
Of course, this is just a disguised version of $\left\lfloor \frac{a^b}{10^{k-n}}\right\rfloor$, where $k$ is the number of digits of $a^b$.
Comment: Indeed, for the *first* few digits, I can't imagine any other way to find them than this method. I don't think this would be a likely candidate for an "unorthodox" solution, since there aren't any modular arithmetic tricks that one could apply here; there are no shortcuts. (It's certainly a useful and clever way of getting the answer, though.)
Comment: Yes, I'm familiar with the standard way of getting the first few digits off $a^b$, but I'm quite certain this was the last digits.

Last $n$ digits of $a^b$


Prove that if $R$ is a symmetric, transitive relation on $A$ and the domain of $R$ is $A$, then $R$ is reflexive on $A$.

Question: Assume, $R$ is a symmetric, transitive relation on $A$ and the domain of $R$ is $A$.
$Dom(R)=A$ implies $(\forall x \in A)(\exists y \in A)[xRy]$.
Since, $xRy$ is true it follows that $yRx$ is true, by the symmetric property.
By transitivity, $xRy$ and $yRx$ give $xRx$. Therefore, it follows that, $(\forall x \in A)[xRx]$, which means x is reflexive on A.
Please critique or give any advice, thank you!
Comment: Your logic is absolutely fine.
Answer: Apart from the fact that your proof could benefit from some better wording, it is perfectly correct. I would still suggest you try to reword it more clearly as that will help you later on. Make it more clear what you want to do. Something like:

We wish to prove that $R$ is reflexive i.e. that for every $x$, $xRx$ is true:
$$\forall x: xRx$$
Let $x_0\in A$ be an arbitrary element. Then, because we know that
$$\forall x\in A \exists y\in A: xRy,$$
we know there exists some $y_0$ such that....
...
Therefore, we know that $x_0Rx_0$.
Because $x_0$ was chosen arbitrarily, we know that this is true for every $x\in A$, so $R$ is reflexive.

Such a proof is clearer because:

You state in the beginning what you want to prove
You show clearly how each step follows from the previous.
You do not mix up the quantified variables and the bound variables (in your proof, you take an arbitrary $x$, but then you also cite a relation as $\forall x$, which can be confusing and can lead to serious mistakes in harder proofs).
Comment: Yes, point number 3 is something I must pay attention to from now on.
Comment: @Ibrahim I'd say all three points are worth remembering. Also, note that point 3 is not *necccesary* (i.e. if you are careful enough, you can get away with some variable bending), but it's still better to be on the safe side.
Comment: Of course, I will try to take all of them to heart. Thank you!


Difference of two KL-divergence

Question: The Kullback-Leibler (KL) divergence between two distributions $P$ and $Q$ is defined as $$\mbox{KL}(P \| Q) = \mathbb{E}_P\left[\ln \frac{\mbox{d}P}{\mbox{d}Q}\right].$$
My question is that suppose there are three distributions $P, Q, R$, is it possible to give an upper bound for the difference of KL-divergence? More precisely
$$\mbox{KL}(P\|R) - \mbox{KL}(Q\|R) \leq~?$$
The right-hand side should demonstrate some difference between $P$ and $Q$ and be independent of $R$. [I guess some additional boundedness assumptions are necessary.]

A desired result for the squared norm is as follows. For any three vectors $x,y,z\in \mathbb{R}^d$, we have $$\|x - z\|^2 - \|y-z\|^2  = \langle x - y, x+y -2z\rangle \leq 4D\|x - y\|,$$
  where $D$ is the maximal norm of the vectors, namely, $\|x\|, \|y\|, \|z\| \leq D$.

Is it possible to achieve a similar result for general distributions with KL-divergence? Thanks!
Answer: I don't think there is an upper bound that doesn't involve having constrains on $R$.
In order to see this, you can think of a special case where $Q=R$, which means $\mbox{KL}(Q||R)=0$. In this case, you just need to find finite upper bound for the $\mbox{KL}(P||R)$ which doesn't exist for any possible distribution, because KL divergence approaches infinity when one of the probabilities in $R$ approaches $0$.
One obvious way to bound $R$ is by ensuring that every value is bounded by some variable $\epsilon$, such that $R(x) \ge \epsilon$ for every possible $x$. This restriction limits distribution families that you are allow to use, because values should have bounded domain (for example, it cannot be gaussian distribution). With this assumption we can find upper bound for for the discrete distributions (but the same could be done for the continuous distributions as well)
$$
\begin{align}
\mbox{KL}(P\|R) - \mbox{KL}(Q\|R) &= H(P) - H(Q) - \sum_{i=1}^{N}(p_i - q_i) \log r_i \\
                                &\le H(P) - H(Q) - \sum_{i=1}^{N}|p_i - q_i| \log r_i \\
                                &\le H(P) - H(Q) - \log \epsilon \sum_{i=1}^{N}|p_i - q_i| \\
\end{align}
$$
where $H(P)$ is an entropy of $P$ and $N$ is a number of categories in a distribution.
In addition, it might be important to note that $\epsilon \le \frac{1}{N}$, where equality holds for the discrete uniformal distribution, otherwise, for larger values, sum over all probabilities will be greater than $1$.
UPDATE:
In general, it looks to me that any constrain (or set of constrains) should be quite restrictive. The difference could be written in the following way
$$
\begin{align}
\mbox{KL}(P\|R) - \mbox{KL}(Q\|R) &= H(P) - H(Q) - \sum_{i=1}^{N}(p_i - q_i) \log r_i
\end{align}
$$
$H(P)$ and $H(Q)$ have a finite upper and lower bounds which means that difference approaches infinity only when the last sum $\sum_{i=1}^{N}(p_i - q_i) \log r_i$ approaches negative infinity. The $\log r_i$ term is the only part of this sum that can push everything to infinity. There are two ways to prevent this from happening. $\log r_i$ term can be controlled directly, meaning that we need to make sure that $r_i$ never approaches $0$ (exactly what I did) or we need to control $\log r_i$ with the $(p_i - q_i)$ term. One way to do it is to make sure that any time we have case where $r_i$ approaches $0$ the difference between $(p_i - q_i)$ also should approach $0$. This last observation creates a dependency between all 3 distributions, basically, when $r_i$ approaches $0$, $p_i$ should approach $q_i$. Another way to do it is to make sure that values approaching infinity and negative infinity can cancel each other out (e.g. $p_i - q_i = a$ and $p_j - q_j = -a$ at least for the cases when $r_i$ approaches 0).
Comment: Of course, the bound you provided makes sense, thanks! But it is not exactly what I am pursuing. Two reasons: (1) the uniform lower bound for distribution $R$ would be too restricted, which might result in a very loose upper bound (for example, when $\epsilon$ is very small); (2) the upper bound does not reflect the difference of $P$ and $Q$. Probably my requirement description is kind of vague, I guess the example of square functions in the question could better illustrate the requirements (upper bounded by a distance between $P$ and $Q$, with some **general** bounded assumptions on $P,Q,R$).
Comment: The desired upper bound is allowed to be a function of $P$ and $Q$, but independent of $R$. For the special case of $Q=R$ as mentioned, $\mbox{KL}(P\| R) - \mbox{KL}(Q\| R) = \mbox{KL}(P\| Q) - \mbox{KL}(Q\| Q) = \mbox{KL}(P\| Q)$, this is a desired bound (measuring difference between $P$ and $Q$ without involving $R$)!
Comment: Maybe I'm missing something, but would you say that upper bound in my answers depends on $R$? It's controlled by $\epsilon$ parameter, which is just a part of the constraint and it will work for any distribution $R$ that follows specified constraint. Or do you mean that constrain on distribution $R$ should be dependent on $P$ and $Q$ distributions?
Comment: I don't think you can do it without making distributions either too restricted or dependent. I added a few more observations to my answer

Difference of two KL-divergence


Regex to match `xyz` in `abc|qw|xzy mno`

Question: It's driving nuts.
The input strings are:
abc|qw|xzy mno
abc||xzy mno
abc|qw|xzy
abc|qw|

I need to extract the first word (if any) after the 2nd vertical bar, in all cases above xyz but in general words in multiple (natural) languages.
Also, all lines must be considered as a block so single line does not apply, iow, the EOL is the break to account for.
Thank you, guys.
Comment: Does it have to be regex?  I could C# this together in seconds with its string match stuff.
Comment: What code did you try? The "all lines must be considered as a block" part is rather unclear.
Comment: Split by newline, loop over elements, split by `|`, take the third element, split by space, take the first element. Don't know C#, but this shouldn't be too difficult.
Comment: `var res = s.Split('|')?.Skip(2)?.Take(1)?.FirstOrDefault()?.Split(' ')?.FirstOrDefault();`
Comment: how about ```"abc|qw|xzy mno".Split(' ')[0].Split('|')[2]``` ?
Comment: Thanks but split won't do. The input is fed to a library that requires a regex.
Comment: And what are the restrictions then? Can you access groups? What have you tried?
Comment: Barmar below got it. Thank you all.
Answer: You can use the following regexp with the RegexOptions.Multiline option.
(?<=^(?:[^|]*\|){2})\w+

(?<= begins a positive lookbehind, so this matches a word that must be preceded by the beginning of the line followed by two pipe-delimited sequences.
Comment: This one did it `(?<=^(?:[^|]*\|){2})\S+`


How to transfer a trained ElasticNet model to a new dataset? Can Lambda and Alpha determine a unique ElasticNet model?

Question: I have trained a ElasticNet model on a A dataset and also I get the two hyperparameters of the trained ElasticNet model Lambda (ratio of Lasso and Ridge) and Alpha (penalty). I want to see the generalization of the model on the B dataset. If I don't use sklearn's predict method directly, can I directly specify the previous Lambda and Alpha to build a new model and see the performance in the new database? In other words, can Lambda and Alpha determine a unique ElasticNet model?
Any help is greatly appreciated!
Ito
Answer: Both hyperparameters ($\alpha$ and $\lambda$) are specific to a dataset, they are chosen such as to optimize some criterion for the specified data. Training the model on a different dataset will probably return different optimal values of the two, so these hyperparameters are not really transferable, not unless these two datasets contain more or less similar data. But if you were to do this then it is as easy as specifying a value for the two hyperparameter and a model will be trained with exactly these hyperparameter values, then you can check how well the model performs on a different dataset with given hyperparameters, although what will you compare this to?
Comment: Thanks, your answer is very enlightening. It is quite true that both hyperparameters (α and λ) are specific to a dataset. Then, the features in the model and their corresponding coefficients are transferable. Is this right?
Comment: @KengoIto What do you mean by `the model and their corresponding coefficients are transferable`?
Comment: Thanks! For an ElasticNet model, if I have 200 features at the beginning, there are 150 features left after training. I want to apply this model to new data, I just need to substitute the values of 150 features of the new data into the original model (y_new = feature1_new x coefficient1 + feature2_new x coefficient2 + ... +feature150_new x coefficient150), get y (response), and then calculate the performance of the model on new data.
Comment: In other words, for an ElasticNet model (a linear model with a penalty term), y_new = feature1_new x coefficient1 + feature2_new x coefficient2 + ... +feature150_new x coefficient150 can fully represent the model. It's a bit long-winded, please forgive me.
Comment: @KengoIto I'm not sure I understand. LASSO and RIDGE shrink coefficients but they still keep all the coefficients in the model, they don't drop them, even if they are zero. So if you have two datasets A and B with the same variables, you could train the model on dataset A and then use the model to make predictions on dataset B, no modification is necessary.


Full term path as product url

Question: Im using D7 and UC3. A product is multiple levels down:.
product list = cat1/sub2/sub-sub1/
Now using pathauto i'm trying to make the path of the product cat1/sub2/sub-sub1/product1 however i cant find the right tokens to do this. Best is can get is sub-sub1/product1 loosing the first two steps. In the breadcrum i do see the other levels, so the product knows its nested like that.But i cant seem to get the url to correspond.
Answer: Taxonomy reference of the content type must be set to 1. New tokens will become availible and differect ways to create a url like the above become possible
Answer: This is not something given out-of-the-box, unfortunately. Been through this.
I have never used Ubercart, just Commerce, but I assume in both cases we have some kind of product entity and content type for displaying the product.
For the correct path and Pathauto, you'd have to use a pattern like this:
<code>products/[product-category-field:parents:join:/]/[product:name]
</code>
However you might need to install Entity API and enable its submodule called Entity Tokens.
For the breadcrumb paths, I would suggest that you try out Path Breadcrumbs. Even though it requires some setup work for all the context, I found it more reliable than Context or other Taxonomy Breadcrumbs or Menu Breadcrumbs modules out there.

Full term path as product url


How to execute service functions using keys from an object

Question: I have an array which contains information from separate services, some of which may or may not be present and are interchangeable.
e.g.    $scope.services = [{facebook: data}, {twitter: data}, {instagram: data}];
I then have to get data from the given services via methods named with the same conventions e.g facebookTimeline.get(); or instagramTimeline.get();
How can I make it so that I can execute these functions based on the key values that are present inside the $scope.services array? I've considered for (key in $scope.services) although not sure how to execute the functions with the keys as a string. I'm unable to modify how the objects are formatted and stored in $scope.services.
EDIT: code example
angular.module('app').controller('TimelineController', ['$scope', 'instagramTimeline','facebookTimeline', 'twitterTimeline', function($scope, instagramTimeline, facebookTimeline, twitterTimeline){

    $scope.services = {facebook: tokenString, instagram: tokenString, twitter: tokenString};

    for(var key in $scope.services){
        //how would i access <key>Timeline service?
        ('key' + 'Timeline').get()
    }

}])

//example factory

.factory('instagramTimeline', [function(){
   var api = {};
   api.data = [1,2,3,4];
   api.get = function(){
       return data;
   }
}]);

Comment: and what's your angular service? edit your question, put your code and what you've tried already, please
Comment: for (key in $scope.services) { $scope.services[key].get(); } ???
Comment: $scope.services[key] would just be the value of `data` which is just an object, and not the angular service i'm trying to use (so it would have no get() method)
Answer: Make a 4th factory called something like 'socialTimeline' that returns the following API (you need to inject this new factory service with facebookTimeline, twitterTimeline and instagramTimeline) :
{
     facebookTimelineService: facebookTimeline, // this is your existing factory
     twitterTimelineService: twitterTimeline,
     instagramTimelineService: instagramTimeline
}

Then call each by doing
socialTimeline[key + 'TimelineService' ].get()

PD: you can avoid the new factory and just create the object if you like. You just need some key-value pairing that has your other factories in order to get the one you want.
Answer: If anyone else comes across this same problem, I've solved it using another service
.factory('apiLayer', ['instagramTimeline', 'facebookTimeline', 'twitterTimeline', function(instagramTimeline, facebookTimeline, twitterTimeline){

    var factory = {};

    factory.instagramTimeline = function(){ return instagramTimeline; }
    factory.facebookTimeline = function(){ return facebookTimeline; };
    factory.twitterTimeline = function(){ return twitterTimeline; };

    return factory;
}]);

and accessed it in the controller using
for(var key in $scope.services){
    apiLayer[key+'Timeline']().get();
}


Remover números ímpares de uma pilha

Question: Em C como se faz para remover apenas os números ímpares de uma pilha? Eu estava pensando em remover item a item e passar para um vetor, porém o tamanho da pilha não é dado.
Comment: Inclua o que você já tentou fazer, como você implementou sua estrutura de dados pilha, etc., desta forma fica mais claro sua dúvida, tornando mais fácil ajudá-lo.
Comment: Qual o código que você está usando, poderia postar uma parte pra gente ver?
Comment: Se o tamanho não é dado, então você precisa ou de uma lista encadeada ou de alguma outra estrutura de dados que cresça conforme a necessidade. Assumindo que isso seja um exercício, creio que o melhor é uma lista encadeada mesmo. Você está familiarizado com esse conceito?
Answer: Você tem uma pilha de números que vamos chamar de A.
O objetivo é tirar todos os números ímpares desta pilha. Como trata-se de uma pilha, não há como percorrer os elementos sem necessariamente destruí-los (caso contrário não seria uma pilha).
Então o que você faz é mais ou menos o que está no seguinte algoritmo:
<code>B = nova pilha;

while (A não está vazia) {
    int t = remove elemento do topo de A;
    if (t % 2 == 0) {
        empilha t em B;
    }
}

while (B não está vazia) {
    int t = remove elemento do topo de B;
    empilha t em A;
}

apaga B;
</code>
Desta forma, você vai movendo os elementos de A para B e filtrando os ímpares. Na pilha B eles ficarão na ordem inversa. Quando terminar você faz o movimento contrário, e eles ficarão a ordem correta na pilha A, que também era a pilha original. O resultado é que a pilha A terá os elementos ímpares removidos.

Remover números ímpares de uma pilha


Predicting forecasts for next 12 months using Box-Jenkins

Question: I am building a Box-Jenkins model in Excel using solver. The model is AR(2).
The data that I have contains trend and seasonality both.
I know how to remove seasonality using seasonal indexes and add it back to the forecast.
But, how do I handle trend? If I remove trend from the data, how should I add it back to the forecast?
Also, is the excel solver best way to find the AR parameters?
Answer: If you are at all familiar with R (if you're building time series models, you should be), check out the forecast package. It's designed to choose parameters for Arima as well as exponential smoothing models, and uses a solid methodology to do so.  It will probably get you a lot farther than what you are building in excel, especially because it will also allow you to explore exponential smoothing models.  The two functions you are interested in are 'auto.arima' and 'ets.'
/Edit: auto.arima can also be used to fit ARMAX models, which (if properly specified) can solve many of the problems identified by IrishStat.
Comment: Any automation that ignores the possibilities of Level Shifts, Local Time Trends, Seasonal Pules and/or One-Time Pulses should be reviewed very carefully as these kinds of structures in the error process "blind-side" identification strategies.
Comment: @IrishStat: Abhishek asked "is the excel solver best way to find the AR parameters?"  I think using R in this case to find the AR parameters would be better than using excel.
Comment: You are right R would be the best of two bad choices.
Comment: Thanks @Zach and @IrishStat . I will be using R to get more reliable results.
Answer: The time series are usually decomposed into 3 parts, trend, seasonality and irregular. (The link gives 4 parts, but cyclical and seasonality are usually lumped together). Strictly speaking ARIMA type of models are only used for irregular part and by their design these model do not incorporate any trend (I am assuming that trend is some function which varies in time). So if you simply want to estimate AR(2) model no software will estimate the trend for you, since if it did, it would not be fitting AR(2) model.
To forecast the trend you will first need to create some sort of model and test it, and only after you are confident that your model truly estimates the trend, then you can use it to forecast the trend. Without such model any forecasting is impossible. Sadly the majority of time series textbooks do not stress this when talking about forecasting.
Comment: I agree you need to find a specification for the X partof the ARMAX Model.Classical ARIMA modelling died in about 1979 when work was done to empirically identify via Intervention Detection Pulses,Level Shifts and Local Time Trends (see I.Chang or G.C. Tiao or Ruey Tsay's literature on this). Their work and in some rare cases my developments of their work have lead to much more usable ARIMA structures incorporating Deterministic Structure such as multiple time trends and/or multiple Level Shifts.Level Shifts are simply first differences of a time trend as Pulses are to Level Shifts.
Comment: @:mpiktas full fledged ARIMA software can include differencing factors ,a trend coefficient and an arbitrary ARMA structure . Full fledged Transfer Function software can include ( in lieu of the differencing operator and the trend coefficient ) one or more TIME VARIABLES ( E.G. 0,0,0,0,0,1,2,3,4... ) reflecting specific points in time where a time trend has been identified. Basic time series texts,as you suggested, do not cover this extension.
Comment: @IrishStat, good remark, but my main point is still valid, if you want to forecast trend, you need to go outside classical ARIMA framework. I think the features you mention fall into definition of ARIMAX, but the X part remains the obstacle,  you need to have an external model.
Answer: Your approach suggests initially adjusting in a deterministic manner the impact of seasonality. This approach may or may not be applicable as the impact of seasonality may be auto-projective in form. The best way to answer this question is to evaluate alternative final models for adequacy in terms of separating the observed observations to signal and noise. There are a number of possible pitfalls awaiting you . One of them " does the series have one or more trends AND/OR one or more level shifts " ? Another possible issue "does the series have a constant set of monthly indicators or have some months had a statistically significant change in the their effects ? In terms of a seasonal ARIMA model this question translates to " have the model parameters changed over time " ?. My experience with Excel Solver has not been very positive.
Comment: I am removing the seasonality using time series decomposition by calculating the seasonla indexes for each of the 12 months. If you mean that seasonality may change over time, an adaptive model whose parameters are recalculated when new data is available should work. Currently I am using time series decomposition to identify randomness and working on data without seasonality and randomness. I add the seasonality back to the forecasts but don't know how to deal with adding randomness to the forecast. May be R will deal with this.
Comment: @Abhishak.Unfortunately your seasonal indices assume a specific weighting structure i.e.the # of periods to use to compute the "weights" and that there are no Pulses or Level Shifts or Time Trends. In terms of seasonality changing over time you are not quite correct. Adapting to change requires a model form. For example if you had 6 years of data and thee was no June effect for the the first 3 years . The correct seasonal factor would reflect the June impact for the last three years. There is no adaptivity here in the sense you are using the word. Your approach has too many presumptive steps.
Answer: As mentioned, Use R, not excel.
My understanding of this process you are asking for.
Say you have a data set with a linear trend.  Let's assume that trend to be Y = 3t+1, also assume you have 15 data points.
Use that model and find the residuals from that.  Fit your time series model to these residuals.  To forecast, use the 'predict' function in R. Get the next point.  Let's assume the model tells you the next error will be -2.
(If you wanted to predict the next point, this would be the 16th data point.)  Take Y= 3*16+1 = 49,,, and now add in the -2 from the time series prediction.  Your forecast is now :49+(-2) = 47.
Comment: Adam and @IrishStat, I have removed your exchange of comments because they do not advance the solution to the original question.  If I may paraphrase (and read into) Adam's comment, now deleted, it seemed to suggest that although a good response to this question might indeed discuss "transfer functions" and "ARMAX models," it would need to *explain* what these things are, *why* they might be appropriate here, and *how* to apply them.  Without such explanations, many readers might be impressed but not enlightened.  Let's work to *improve,* rather than attack, each other's replies.
Comment: this approach appears to be piecemeal rather than simultaneous. Rather than " doing this and then that" simply estimate a model that has both the regression component and the arima component. This model is called a TRansfer Function or an ARMAX Model.


Listagem de um array dentro de um JSON angular

Question: Bom dia senhores, estou utilizando a api do IGDB (Games) para a realização de um site angular 7(typescript), nela ao receber um JSON recebo apenas o ID de gênero, mas se na chamada contextualizar consigo receber dentro do json, o id e o name(dentro de um array secundário), gostaria de imprimir na tela de profile que estou criando todos os generos dentro do array secundário, ou caso não exista um "Não preenchido", no caso do print a baixo, tentei realizar apenas um teste pegando a primeira posição do vetor, ele imprime, mas quando não existe nada ele da erro no restante da tela.
HTML :

{{game.name}}

Desenvolvedora: {{game.involved_companies[0].company.name}}

Engine: {{game.game_engines[0].name}}

Gêneros: {{game.genres[0].name}}

Service :
getGameById(id: string): Observable<Game[]> {

return this.http.post<Game[]>(`${FACELIST_API}` + '/games',`fields *, genres.name; where id = (${id});`, httpOptions);

E o typescript do componente.
export class GameprofileComponent implements OnInit {

  games: Game[]
  imgs: Cover[]

  constructor(private gammelistService: GammelistService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.gammelistService.getGameById(this.route.snapshot.params['id']).subscribe(
      list => {
        let containsCover = list.filter(function (elem, i, array) {
          return elem.cover !== undefined;
        });
        this.games = containsCover;

      });
  }
}

E o JSON
[
    {
        "id": 81249,
        "cover": {
            "id": 67245,
            "image_id": "m5v5rte27ri2rj8i0e1j"
        },
        "genres": [
            {
                "id": 12,
                "name": "Role-playing (RPG)"
            },
            {
                "id": 31,
                "name": "Adventure"
            }
        ]
    }
]

Comment: tenta colocar um *ngIf="game" ai ele só vai mostrar se achar alguma coisa
Answer: Tente desta forma:

{{game.name}}

Desenvolvedora: {{game.involved_companies[0].company.name}}

Engine: {{game.game_engines[0].name}}

<ng-container *ngIf="game?.genres; else naoPreenchido">

Gêneros:

        {{genre.name}}

</ng-container>

<ng-template #naoPreenchido>

Gêneros: NÃO PREENCHIDO
</ng-template>


Problem using signerMustLoginToSign with embeeded signing and rest api

Question: I'm using embedded signing with rest api and signerMustLoginToSign=true configuration to force users to login before sign.
I realised that just docusign account owner is abble to sign. If I try to sign with other users I get the message:
Authentication Error
The login information provided does not match the account for this envelope. Please try again and login with the same email address where you received this envelope.
I'm doing a POST to /evelopes with data:

    *{
       "emailSubject":"Document Signing",
       "documents":[
          {
             "documentId":192691,
             "name":"mydoc.docx",
             "fileExtension":"docx",
             "documentBase64":"base64"
          }
       ],
       "recipients":{
          "signers":[
             {
                "roleName":"HR",
                "name":"User 1",
                "email":"firstname.lastname@example.com",
                "recipientId":"845a9b97-b31f-4823-842e-91c1e963eca2",
                "routingOrder":null,
                "clientUserId":null,
                "userId":null,
                "tabs":{
                   "signHereTabs":[
                      {
                         "anchorString":"#HR",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "dateSignedTabs":[
                      {
                         "anchorString":"#todaydate",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "textTabs":[

                   ],
                   "fullNameTabs":[
                      {
                         "anchorString":"#HiredFullName",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "titleTabs":[
                      {
                         "anchorString":"#HiredTitle",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ]
                }
             },
             {
                "roleName":"CR",
                "name":"User 2",
                "email":"firstname.lastname@example.com",
                "recipientId":"9d1f5d02-8006-452c-918d-ddeb07fa799f",
                "routingOrder":null,
                "clientUserId":null,
                "userId":null,
                "tabs":{
                   "signHereTabs":[
                      {
                         "anchorString":"#CR",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "dateSignedTabs":[
                      {
                         "anchorString":"#todaydate",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "textTabs":[

                   ],
                   "fullNameTabs":[
                      {
                         "anchorString":"#ContractorFullName",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ],
                   "titleTabs":[
                      {
                         "anchorString":"#ContractorTitle",
                         "anchorXOffset":0,
                         "anchorYOffset":0,
                         "anchorIgnoreIfNotPresent":false,
                         "anchorUnits":"inches",
                         "locked":true
                      }
                   ]
                }
             }
          ]
       },
       "status":"sent",
       "sentDate":{
          "year":2020,
          "dayOfYear":88,
          "dayOfMonth":28,
          "dayOfWeek":6,
          "era":1,
          "hourOfDay":11,
          "centuryOfEra":20,
          "weekyear":2020,
          "minuteOfHour":54,
          "yearOfCentury":20,
          "yearOfEra":2020,
          "minuteOfDay":714,
          "monthOfYear":3,
          "millisOfSecond":189,
          "secondOfMinute":49,
          "millisOfDay":42889189,
          "secondOfDay":42889,
          "weekOfWeekyear":13,
          "millis":1585407289189,
          "zone":{
             "fixed":false,
             "uncachedZone":{
                "cachable":true,
                "fixed":false,
                "id":"America/Sao_Paulo"
             },
             "id":"America/Sao_Paulo"
          },
          "chronology":{
             "zone":{
                "fixed":false,
                "uncachedZone":{
                   "cachable":true,
                   "fixed":false,
                   "id":"America/Sao_Paulo"
                },
                "id":"America/Sao_Paulo"
             }
          },
          "equalNow":false,
          "afterNow":false,
          "beforeNow":true
       },
       "completeDate":null
    }*
Comment: Please also share the code you're using for the embedded signing
Answer: I don't see how you generate the embedded signing but I can answer what the error means.
This error comes from an API call that is made in a different account that does not match the envelope. I suspect you're trying to login with a different account, not just a different user of the same account. This login you're doing as part of embedded signing, should not have this issue if the request was made correctly.
Edit: please ensure clientUserId is not null or empty. this value is used to identify the embedded sending application for a specific recipient.
Comment: Hi, thank you for the respose. Bellow I'm show the request for signing URL:

Endpoint - /views/recipient
Data:

"userName": "User",
    "email": "email@example.com",
    "recipientId": "9b6953e0-1215-4ab1-a807-c99a02df90cb",
    "clientUserId": null,
    "userId": "xxxxx-xxxx-xxxx-xxx-xxxxx",
    "authenticationMethod": "email",
    "returnUrl": "http://localhost:8080/signed"

If a sign using the link on the e-mail sent by docusign works fine, but if a sign using the link generared by the API I get the issue reported.
Comment: clientUserId should not be null. Can you try to put a value in there? that value is a unique ID for your integration and a specific recipient.


Call powershell v4 and above from Visual Studio 2008

Question: I have Powershell scripts in my system, which require Powershell v4 at least.
I have powershell v5, I am able to run those scripts using Powershell console.
But I want to call those scripts from C#-Visual Studio 2008(.net 3.5).
I am restricted to use Visual Studio 2008. I have referred System.Management.Automation in my solution from path
"C:\WINDOWS\assembly\GAC_MSIL\System.Management.Automation\18.104.22.168__31bf3856ad364e35\System.Management.Automation.dll"
But this supports only Powershell v2.
I downloaded latest System.Management.Automation.dll from NuGet and my solution does not recognize it. Is this possible to achieve?
Answer: Well, it's been years, since I've even seen anyone with Visual Studio 2008. ;-}
However, this is not really a PowerShell non working code question (which is what we are here to help with) but a Visual Studio environment / operational configuration one, in order to  run PowerShell at all.
Visual Studio is bound to the .Net version on its release as is PowerShell.
Microsoft .NET Framework Requirements
Windows PowerShell 5.1 requires the full installation of Microsoft .NET Framework 4.5. Windows 8.1 and Windows Server 2012 R2 include Microsoft .NET Framework 4.5 by default.
Windows PowerShell 5.0 requires the full installation of Microsoft .NET Framework 4.5. Windows 8.1 and Windows Server 2012 R2 include Microsoft .NET Framework 4.5 by default.
Windows PowerShell 4.0 requires the full installation of Microsoft .NET Framework 4.5. Windows 8.1 and Windows Server 2012 R2 include Microsoft .NET Framework 4.5 by default.
…
Of course since you say you have and have used PowerShell v5 on your system, then you have the needed .Net dlls, and you should not have had to download the dll you did separately. Lastly, each of those System.Management.Automation.dll are located / registered in their own folders.

C:\Windows\assembly\GAC_MSIL\System.Management.Automation\22.214.171.124__31bf3856ad364e35
  C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_22.214.171.124__31bf3856ad364e35
  C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~17718.104.22.168\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\f
  C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~177184.108.40.206\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\r
  C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~17718.104.22.168\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\f
  C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~17722.214.171.124\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\r
  C:\Windows\WinSxS\msil_system.management.automation_31bf3856ad364e35_220.127.116.11_none_6340379543bd8a03
  C:\Windows\WinSxS\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0
  C:\Windows\WinSxS\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\f
  C:\Windows\WinSxS\msil_system.management.automation_31bf3856ad364e35_10.0.17763.134_none_3a18c3b5ad9702a0\r
  C:\Windows\WinSxS\msil_system.management.automation_31bf3856ad364e35_10.0.17763.1_none_b60c54e2801db2ff

You also, don't say or show how you tried toe register that .dll so that Visual Studio 2008 would see it. So, this appears, this is a Visual Studio 2008 specific limitation, and your only option is to shell out to PowerShell.exe independently, as you would cmd.exe,  to run your .ps1 files.
Have you already seen / tried the following approaches / details?
Visual Studio 2008 PowerShell
PowerShell Visual Studio 2008 templates

Visual Studio 2008 project and item templates for Windows PowerShell
  including Cmdlet,

Calling a PowerShell Script From Your .NET Code

An article on embedding and/or launching PowerShell scripts from a C#
  program.

Use VSCmdShell to run a PowerShell script from within Visual Studio 2008


Initiating controls on webforms in FormView at class level

Question: I am maintaining a c# webforms project. There are many methods that carry out various functions by getting values form TextBox Controls, DropDownList Controls etc using FindControl as they reside on a FormView. Currently Controls are initialized in each Method, but the same Control may be initialized in say 7 Methods. Like so :-
    protected void GetGPPCM()
    {
        CheckBox Mortgage = (CheckBox)FormView1.FindControl("Mortgage");
        Literal Gross_Profit_PCM = (Literal)FormView1.FindControl("Gross_Profit_PCM");
        TextBox Rental_PCM = (TextBox)FormView1.FindControl("Rental_PCM");
        if (Mortgage.Checked)
        {
            TextBox Revrsionary_Rate_ABR = (TextBox)FormView1.FindControl("Revrsionary_Rate_ABR");
            decimal currentrate = GetRate() + System.Convert.ToDecimal(Revrsionary_Rate_ABR.Text.ToString());

            TextBox Capital_Amount = (TextBox)FormView1.FindControl("Capital_Amount");

            Gross_Profit_PCM.Text = "£" + String.Format("{0:n}", (Convert.ToDecimal(Rental_PCM.Text) - (((currentrate / 100) * Convert.ToDecimal(Capital_Amount.Text.ToString())) / 12)));
        }
        else
        {
            Gross_Profit_PCM.Text = "£" + String.Format("{0:n}", Convert.ToDecimal(Rental_PCM.Text));
        }
    }

What I want to do is declare all controls once only at class level, however when I move say :-
TextBox Rental_PCM = (TextBox)FormView1.FindControl("Rental_PCM");

directly under the class like
public partial class WebForm1 : System.Web.UI.Page
{

DropDownList ddlPropertyID = (DropDownList)FormView1.FindControl("ddlPropertyID");

}

I get a compile error Compiler Error CS0236 A field initializer cannot reference the non-static field, method, or property 'name'. Instance fields cannot be used to initialize other instance fields outside a method.
Is there any way I initialize all the controls I want, just once and not do it repeatedly in each method?
Thanks in advance.
Comment: _"I am maintaining a c# webforms project"_ - you have my sympathy
Comment: Webforms can be painful to work with when you want to apply modern approaches. Your best bet is to have a single method that works much like a constructor would and call this during the appropriate page event. Look through the documentation [here](https://learn.microsoft.com/en-us/previous-versions/ms178472(v=vs.140)?redirectedfrom=MSDN) to get an idea of the events that are available. This [page](https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/) has the event sequence and explanations.
Comment: Better is to use a user control - they are fantastic - and in most cases give you a better choice than even what MVC pages give you. See my post below for how this works.
Comment: Albert Many thanks for the very professional presentation of the 'how to' bit, it indeed works. So thank you again!
Answer: You have several approaches.
You can continue to say drop those controls on the current webform, and then say build helper routines. Those helper routines will load up the control, but not allow you to have event code outside of the current page. This can often work well.
If you looking to have event code for a given control, then create what is called a user control. They are not only brilliant but allow you to create controls (and more important event code) that can be used over and over.
So, don't try to create your own class - use the built-in choice that does all the work for you.
So, say I have a hotel drop down. Let's say we need this SAME combo box on many pages - used over and over.
So, create a user control, this choice:

This choice lets you:
Define the markup - place as many controls as you want into this "one thing".
And you now have event code, and now have your own re-useable control that you can use over and over.
So, let's make a hotel drop down.
You get a plain jane markup page - but it is ONLY markup.
It looks like this:

Select Hotel

<asp:DropDownList ID="cboHotels" runat="server" Width="150px"
    DataValueField="ID"
    DataTextField="HotelName"
    OnSelectedIndexChanged="cboHotels_SelectedIndexChanged"
    AutoPostBack="True"
</asp:DropDownList>

And that control has its "own" page load.
Also, any public member becomes part of the property sheet and settings for that control!!!
So, let's have a "extra" setting that we are to type in the target text box, and upon selecting we fill out that text box with the hotel name.
So, this code:
    private string _TargetBox = "";

    public string TargetBox
    {
        get { return _TargetBox; }
        set { _TargetBox = value; }

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // load up combo
            string strSQL = "SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    cboHotels.DataSource = cmdSQL.ExecuteReader();
                    cboHotels.DataBind();
                    cboHotels.Items.Insert(0, new ListItem("Select", "0"));
                }
            }
        }
    }

    protected void cboHotels_SelectedIndexChanged(object sender, EventArgs e)
    {
        // user made selection

        if (TargetBox != "")
        {
            TextBox txtTarget = (TextBox)Page.FindControl(TargetBox);
            if (cboHotels.SelectedIndex == 0)
            {
                txtTarget.Text = "";
            }
            else
            {
                txtTarget.Text = cboHotels.SelectedItem.Text;
            }
        }
    }

That is it, we are done.
Now, we can start a brand new blank web page.
And we can then simple drag + drop in this new re-usable control
Like this:

Our markup is now this, but NOTE how the property sheet has that optional Targetbox property.
So this:

When we run this page, we see this:

We also can add events to this control - they can and will run code behind on the current page.
so, don't try and roll your own system, the user control feature of web forms will do all this work for you.
Once that "user" control is created, then you have a drag + drop control that you can drop into any page.
Comment: Albert thankyou for taking the time on this, I have some free hours at the weekend and I will try this approach and let you know. :-)


What happens if the wicket-keeper removes the bails on a free hit?

Question: In a recent game the batsman charged the bowler on a "Free hit". He missed the ball, which was taken by the wicket-keeper, who broke the wicket with the batsman out of his ground, and appealed.
The decision was given as "not out". We debated and decided that as the batsman did not continue running but turned and returned towards his crease the decision was correct. Is this the correct interpretation?
Answer: The batsman can only be Run Out in this situation if it is attempting to score by running between the creases. If no such attempt is made, the batsman is Stumped instead (Law 39.1, Out Stumped and Law 38.2.b, Batsman not Run Out).
As a delivery is a free hit, the batsman cannot be out Stumped (Law 28.17, Out from a No ball, which is further applied to the free hit itself). Whether the batsman was or was not attempting to run between the creases cannot be determined by anybody who was not present and does not have access to conclusive video or audio evidence.
In the case that it is not clear even to witnesses or by examination of evidence (and in particular, it is not clear to the umpires of the match in question) benefit of the doubt is presumed for the batsman (Law 27.6, Consultation by umpires), and therefore the decision should be not out.
Comment: Ah yes - I'd missed the last paragraph of 38.2(b), and got confused by the reference to 38.2(b)(ii) in 39.3(b). I wonder why the bit starting "If No Ball has been called" isn't 38(b)(iii).
Comment: I *think* this is correct (although a batsman can definitely be "run out" by fielders other than the wicketkeeper even if not attempting a run), but I'm having trouble putting together the actual Laws which mean that this can't be classified as a run out. Could you add references to the specific sections you're using to come to this conclusion?
Comment: Well, the definition of Stumped is per Law 39, and Law 38 completes the exclusion of Stumped from being used as Run Out if the batsman is not attempting to run while out of the crease on a no ball.
Answer: Law 39 Stumped states that a batsmen may be out stumped from a delivery that is not a no ball.  Hence from a free hit he can not be out stumped.
The key section in that law is 1(iv) and 1(iv) b which say if without the intervention of another fielder the batsmen would be given out stumped even if he would have been run out.
So if he is not attempting a run he would always be ruled out stumped unless the keeper passes the ball to a fielder, so the batsmen would be not out stumped off a no ball.
However if the ball had been passed to say 1st slip and then the wicket broken the batsmen would be out run out.
Comment: I do think 38.2(b)(ii) is crucial here - without that section, 39.3(b) would mean that the batsman is run out, as 39.1(a)(i) means the batsman is never ever considered to be stumped. I fully admit this is being pedantic, as the intent of the Laws are relatively clear.
Comment: Good day. We concluded that there was no intent to run, a double step to the bowler is using your feet, not running. As the batsman then turned to return to his crease we saw this as a stumping. WE also agreed if the WK had passed the ball to a fielder who then broke the wicket it would have been a "run out". Thanks for the chat.


Probability and expectation of an indicator multiplied by random variable

Question: Could you advice me on the following inequality
$P(|Z_n\mathbb{1}_{|Z_n|<n^{0.75}}|>\epsilon)\le P(|Z_n|<n^{0.75})$
and equality
$E(Z_n^2)E(\mathbb{1}^2_{|Z_n|\ge n^{0.75}})=P(|Z_n|\ge n^{0.75})$.
Answer: Assuming $Z_n = 0$ happens infrequently, the first inequality has a positive LHS when the indicator is 1 (then $P[|Z_n| > \epsilon] \le 1$).
For the second one you have for any event $A$: $$\mathbb{E}[1^2_A] = \mathbb{E}[1_A] = \mathbb{P}[A]$$ and apparently we are assuming $\mathbb{E}[Z_n^2] = 1$.
Comment: thanks @gt6968b for help. The second point I got it but the first one is unclear to me.