Baire functions question

Question: I have some doubts regarding a question in a Lebesgue theory book by Spiegel.
The question is as follows:

$\begin{align}
&\text{Given}\\
&\quad\text{a) } f_n(x)=e^{-nx^2} \text{ in } \;0\leq{x}\leq{1}\;\text{ and}\\
&\quad\text{b) } F(x)=\lim\limits_{n\to\infty}f_n(x)\;,\\
&\text{then what are the Baire functions classes that a)}\\
&\text{and b) belong to ?}
\end{align}$

Thanks in advance, greetings.
Answer: Do you understand why $F(x)$ is discontinuous? Compare $F(0)$ to $F(x)$ for $x\neq 0$.
This proves $F(x)$ is Baire class 1, at least according to the Wikipedia definition.
Comment: thank you!! to be honest, it seems to me to be the case that functions a) are continuous functions; on the other hand, given that the limit of a sequence of continuous function be a discontinuous function, would yield the result: that is, functions a) to be Baire class 0 while functions b) to be Baire class 1.
Comment: That's my understanding too.
Comment: ps: Beside that, i wonder whether the discontinuity of F(x) could be brought about by means of some interval relation like $\lvert x-x_0 \rvert \leq{ε} \longrightarrow{\lvert F(x)-F(x_0) \rvert }\leq{ξ}$ greetings
Comment: No matter how small you take $\delta > 0$, $|x-0| < \delta$ fails to imply $|F(x) - F(0)| < 1$.
Comment: thanks a lot!! i'll think about it and probably make some additional comment later on. greetings
Comment: could it be the following case: just as $x$ departs from $0$, $F(x)$ value "collapse" from its value at $0$, that is, from 1? if so, the function $F(x)$ would have a discontinuity point at $0$; namely, a "skip" type of discontinuity?; perhaps the notion of "nowhere dense set" could be called upon to explain something about such a discontinuity? thanks!

Baire functions question


Passing the `...` argument to lapply

Question: I am having trouble writing a function that takes ... as an argument and then has lapply(..., length) in the body of the function.
Currently, my code is (the important part is in line 2):
paste1 <- function(..., sep = " ", collapse = NULL) {
    if(isTRUE(unique(as.logical(lapply(X = ..., FUN = length)))))
        if(length(sep)) paste(..., sep = sep, collapse = collapse)
        else paste0(..., collapse = collapse)
    else
        ""
}

The trouble is the lapply(X = ..., FUN = length) part. If I have more than one element in the ... argument, it tries to apply length to all of the argument at once, which throws an error as length only has one argument.
I cannot use something like lapply(X = as.list(...), FUN = length) because some of the elements of ... may be NULL and the list representation of ... will have lost information.
All I need to do is apply length to the individual elements of ... without coercing them first.
Comment: Use `list` instead of `as.list`?
Comment: Can you show an example input/use? I can't reproduce your issue if I do `dots <- list(...)` then `lapply(dots, length)`.
Comment: Thanks, I wasn't aware that `list` differed from `as.list`.
Comment: @JonClaus I don't even see that `as.list(...)` can even work - fails for me.
Comment: Do you mean that it throws an error or that it does not work as expected? It seemed to work for me (meaning it didn't throw errors), but I didn't test it much as I already knew it would fail in some circumstances.
Comment: It throws error `Error in as.list.default(x = ...) :
  argument "x" is missing, with no default`
Comment: What happens without the `X =` part, i.e. `as.list.default(...)`.
Comment: @JonClaus I didn't do that. Try `foo <- function(...) as.list(...)` with `foo(A = 10)` and you'll get that error. It is method dispatch that results in `as.list.default(x = ...)` being called like that and that gives the error. But I only ever used `as.list(...)`.
Comment: It's very unclear what you're trying to achieve and you code is quite obfuscated. I think instead of `isTRUE(unique(as.logical(...))` you perhaps want `all(... > 0)`.  And why are you inspecting the `length` of sep?
Answer: This version uses dots <- list(...) which seems not to fail on this input:
> paste1(A = "foo", B = NULL, C = c("bar","foo"))
[1] ""

I haven't looked at what your function is trying to do nor whether this is valid input, but lapply(X = dots, FUN = length) does what you want and dots <- list(...) preserves the NULL.
paste1 <- function(..., sep = " ", collapse = NULL) {
    dots <- list(...)
    if(isTRUE(unique(as.logical(lapply(X = dots, FUN = length)))))
        if(length(sep)) paste(dots, sep = sep, collapse = collapse)
        else paste0(dots, collapse = collapse)
    else
        ""
}

Comment: Are there any `as.list` methods that actually use the `...` argument? I can't seem to find any that do. Is it there just for "future" options?
Comment: Indeed - I couldn't reproduce the issue the OP mentioned as `as.list()` just errored out.

Passing the `...` argument to lapply


Express Hadamard product as a normal matrix product

Question: I have $N^2$ equations which I can write as the following Hadamard product. Is there a way I can get rid of the Hadamard product and express this using usual matrix operations?
$\left[
\begin{matrix}
0 & a_{21} & \cdots & a_{n1} \\
a_{12} & 0  & \cdots & a_{n2} \\
 \vdots & \vdots & \ddots & \vdots\\
a_{1n} & a_{2n} &\cdots & 0\\
\end{matrix}
\right]\bigcirc \left[\begin{matrix}
b_1 & b_2 & \cdots & b_n \\
b_1 & b_2 & \cdots & b_n \\
 \vdots & \vdots & \ddots & \vdots\\
b_1 & b_2 & \cdots & b_n\\
\end{matrix}
\right]=\left[
\begin{matrix}
c_{11} & c_{21} & \cdots & c_{n1} \\
c_{12} & c_{22}  & \cdots & a_{n2} \\
 \vdots & \vdots & \ddots & \vdots\\
c_{1n} & c_{2n} &\cdots & c_{nn}\\
\end{matrix}
\right]$
Comment: You could write the first matrix as a column vector, and the second as a row vector.
Answer: You can achieve the stated goal by applying the vec operation to both sides of the equation
$$\eqalign{
 A\circ B &= C \cr
 {\rm vec}(A)\circ {\rm vec}(B) &= {\rm vec}(C) \cr
 {\rm Diag}\Big({\rm vec}(A)\Big)  {\rm vec}(B) &= {\rm vec}(C) \cr
 {\cal A}\,b &= c \cr
}$$
but why on earth would you want to do that?
Since $\,b,c\in {\mathbb R}^{N^2}$ and $\,{\cal A}\in{\mathbb R}^{N^2\times N^2}$ the operation count went from $N^2$ to $N^4$
Answer: As stated in this thread given task is impossible in general. If you try to express it in terms of being
$$
        A \circ B = X \cdot B
$$
for your case counter-example reduces to the following:
$$
        A=\begin{pmatrix}
        0 & 1 \\
        1 & 0 \\
        \end{pmatrix},\,
        B=\begin{pmatrix}
        1 & 1 \\
        1 & 1 \\
        \end{pmatrix}
$$
then
$$
        2 = rank (A) = rank(A \circ B) = rank(X \cdot B) \le rank (B) = 1
$$
which is obviously incorrect. The same could be deduced for other cases of general A or B, satisfying your conditions.
I believe this still may be possible if you restrict A and B to meet rank, and maybe other conditions.
Answer: Define the ${\mathbb R}^n$ vectors
$$b = \pmatrix{b_1\\b_2\\ \vdots\\b_n},\quad u = \pmatrix{1\\1\\ \vdots\\1}$$
and note that
$B=ub^T$
Then we can use the Diag() operator to write
$$\eqalign{
C &= A\circ ub^T \cr
  &= {\rm Diag}(u)\cdot A\cdot{\rm Diag}(b) \cr
  &= I\cdot A\cdot{\rm Diag}(b) \cr
  &= A\cdot{\rm Diag}(b) \cr
}$$


How to test master behaviour in a Node.JS cluster?

Question: Suppose you are running a cluster in Node.JS and you wish to unit-test it.  For instance, you'd like to make sure that if a worker dies the cluster takes some action, such as forking another worker and possibly some related job.  Or that, under certain conditions, additional workers are spawned.
I suppose that in order to do this one must launch the cluster and have somehow access to its internal state; then (for instance) force workers to get stuck, and check the state after a delay.  If so, how to export the state?
Answer: You'll have to architect your master to return a reference to its cluster object. In your tests, you can kill one of its workers with cluster.workers[2].kill(). The worker object also has a reference to the child's process object, which you can use to simulate various conditions. You may have to use a setTimeout to ensure the master has the time to do its thing.
The above methods however still creates forks, which may be undesirable in a testing scenario. Your other option is to use a mocking library (SinonJS et al) to mock out cluster's fork method, and then spy the number of calls it gets. You can simulate worker death by using cluster.emit('exit') on the master cluster object.
Note: I'm not sure if this is an issue only with me, but cluster.emit always seems to emit twice for me, for some reason.


Logit with dummies when certain number of dummies must be used

Question: In Stata 12, I'm using logit to model a process that is successful or fails and requires seven workers. I have a larger pool of potential workers and am using dummies to signify which seven individuals were working on the process, which resulted in a success or fail. So the coefficients will report the impact each individual worker will have on probability of success if they are included.
However, (again) this process requires seven workers. All of the observations show exactly seven of the 30-something worker dummies activated. In reality, it doesn't make sense to imagine the addition or removal of a worker - the process will be fundamentally different if only six workers are present. My results can still show the relative impacts across workers, but I'm worried about the conceptual problem of having only six workers.
I would be interested in comparing the impact of each worker relative to some "average" or "benchmark" worker, but I'm not sure how to do that.
Comment: @Wayne, "The problem would be the combinatorial explosion". Indeed, ${30\choose 7} = 2035800$ ;-). Of course, you could always just create dummies for the combinations that exist... still, this asks a different question, whether the combinations differ, rather than the contribution of each individual to the group. What's important to determine here is which question you want to answer.
Comment: @gung: I missed the *30* part. But as I read the question more carefully I'm not sure what's being asked. I'm not sure how a number of workers other than 7 becomes an issue, since the all training data will have 7 non-zero dummies.
Comment: Is it infeasible to transform your problem to use dummies standing for each possible combination of seven workers? That way, you're guaranteed that you are always comparing a group of seven to a group of seven. The problem would be the combinatorial explosion.
Comment: @gung: I'm interested in knowing individual workers' contribution to the likelihood of success.
Comment: When I get results, the interpretation of the coefficients is, holding all other factors equal (including other workers), adding a certain worker will change the likelihood by a certain amount.

The problem is, in this case, you never simply add or remove a worker; you always substitute them with another one. I guess I'm just concerned how I should interpret my results.
Answer: If the additive model's a good fit there isn't any problem. You could use it to make predictions for success of the process with six, eight or two dozen workers; but you needn't, just as if the ambient temperature were a predictor you shouldn't be tempted to use the model to predict success of the process at -50°C or 300°C. If Smith's the reference level, then when you substitute him with Jones, Jones' coefficient gives the change in the logit; when you substitute Jones with Brown, the difference between Brown's & Jones' coefficients gives the change in the logit.
You could pick a typical worker as the reference level, or use effect (sum-to-zero) coding, if you think it aids interpretation. The coding scheme makes no substantive difference to the model.


Java out of memory error when memory is in fact available

Question: I keep running into OOM errors and subsequent JBoss  crashes, even though the heap shows that all of the memory allocated to it isn't used up.
For eg: If I have 1200MB allocated as the heap size (Xmx), crashes occur well below that limit with none of the individual generations in the heap (young / old / perm) at a 100%.
The box has plenty of RAM. Why might java be reporting this error when its really not out of memory?
 Heap

 PSYoungGen      total 67456K, used 9525K [0x57540000, 0x5c170000, 0x5fa90000)
  eden space 66432K, 12% used [0x57540000,0x57d91520,0x5b620000)
  from space 1024K, 98% used [0x5c070000,0x5c16c198,0x5c170000)
  to   space 3008K, 0% used [0x5bb90000,0x5bb90000,0x5be80000)

 PSOldGen        total 466048K, used 313530K [0x14a90000, 0x311b0000, 0x57540000)
  object space 466048K, 67% used [0x14a90000,0x27cbea38,0x311b0000)

 PSPermGen       total 226432K, used 141461K [0x04a90000, 0x127b0000, 0x14a90000)
  object space 226432K, 62% used [0x04a90000,0x0d4b55e8,0x127b0000)

Comment: You should edit your post above and paste the *actual and complete* error message that you have received.
Comment: The message is - OOM - Unable to create a new thread
Answer: Yes it is possible to get an OOME when you've still got plenty of free heap space.
When you create a thread the JVM needs to allocate memory for the thread's stack.  However the JVM doesn't allocate the thread stack in the heap.  (The thread stack needs to be in memory that won't be moved by the garbage collector.)  Instead, it requests it directly from the OS.  If the OS can't satisfy that request, you get an OOME ... irrespective of your heap size.
Apparently, an OOME can also occur during thread creation if your application exceeds the operating system's per-process thread limit.  (On Linux / Unix this is controlled by ulimit -u ...)

It is a bit difficult to say what is happening in your case.  I suspect that your application is simply trying to create too many threads and running into one of the limitations above.  You could try reducing the thread stack size, but a better approach would be to figure out why you are creating so many threads and stop it.  (Huge numbers of threads tend to waste resources ... and make your application slower in various ways.)
Answer: Have a look at this answer on the JBoss community site as to why you'd get the Unable to create a new thread OOM


Every $v \in V - \{ 0 \}$ is cyclic iff the characteristic polynomial of $T : V \to V$ is irreducible over $F$

Question: Let $V\neq \{0\}$ be a vector space over $F$, and $T$ a linear operator on $V$. Prove that every $0\neq v \in V$ is a cyclic vector if and only if the characteristic polynomial of $T$ is irreducible over $F$.
I can't seem to get anywhere on either side... Can someone please help?
Answer: One direction is easy: if $v\neq0$ is not a cyclic vector, then the span of the vectors $T^i(v)$ for $i\geq0$ is not the whole space but is $T$-stable; therefore the characteristic polynomial of $T$ restricted to that space is a nontrivial strict divisor of the characteristic polynomial of$~T$, which is therefore reducible.
The other direction is harder; it requires showing that if the characteristic polynomial is reducible then there exists a nonzero non-cyclic vector for $T$. I seem to need the following trick: pick any nonzero vector; if it is non-cyclic, we are done, so assuming it is cyclic the minimal polynomial in $T$ that kills this vector has degree $\dim V$, so it must be equal to the characteristic polynomial. Then the minimal polynomial is equal to the characteristic polynomial, and hence (also) reducible. Now take a proper nontrivial factor $P$ of the minimal polynomial and evaluate it in $T$ giving a linear operator $P(T)$. Using minimality of the minimal polynomial show that $P(T)$ is neither zero nor invertible; its kernel then is a nonzero proper $T$-stable subspace, and the nonzero vectors in it are not cyclic.
Added. Thinking about this, it strikes me that the statement to prove, although pleasingly compact, is not really the best formulation; the situation is more completely described as follows, with the statement as corollary.
Proposition. Let the operator $T$ on the finite dimensional $F$-vector space $V$ have minimal polynomial $\mu_T\in F[X]$. If $\deg\mu_T<\dim V$ then $V$ has no cyclic vectors at all, if $\mu_T$ is reducible then $V$ has nonzero non-cyclic vectors, and when neither of these is the case one has $\deg\mu_T=\dim V$ and all nonzero vectors of$~V$ are cyclic.
Then by the Cayley-Hamilton theorem (which is not used for the proposition itself), if the characteristic polynomial irreducible then the minimal polynomial must be equal to it and we are in the final case; conversely if all nonzero vectors are cyclic then $\mu_T$ must be irreducible (or $1$, if $\dim V=0$) and equal to the characteristic polynomial.
Proof. For a vector$~v$ denote by $\mu_{T,v}$ the monic polynomial$~P$ in$~F[X]$ of least degree for which $P(T)(v)=0$; then $\deg\mu_{T,v}\leq\dim V$, and $v$ is a cyclic vector if and only if $\deg\mu_{T,v}=\dim V$. Since $\mu_T(T)(v)=0$ one always has $\mu_{T,v}\mid\mu_T$, which implies that if $\deg\mu_T<\dim V$ there cannot be any cyclic vectors. If $\mu_T=PQ$ with $P,Q\in F[X]$ non-constant, then neither $P(T)$ nor $Q(T)$ are zero operators by minimality of $\mu_T$; but their composition is zero, so the subspace $\ker P(T)$ contains the image of $Q(T)$ and is a nonzero proper $T$-stable subspace, whose nonzero vectors are therefore non-cyclic; this establishes the second case. Conversely if $\mu_T$ is irreducible then every nonzero vector$~v$ has $\mu_{T,v}=\mu_T$, so in particular $\deg\mu_T\leq\dim V$, and if $\deg\mu_T=\dim V$ these vectors are all cyclic.
Note that the proposition does not say whether there are any cyclic vectors when $\mu_T$ has degree$~\dim V$ but is reducible; this is in fact true, but requires more detailed considerations to prove.
Comment: @izikgo: If $W$ is a $T$-stable subspace, then the characteristic polynomial factors as the product of the characteristic polynomials of $T$ acting on $W$ and on $V/W$. Concretely, express $T$ on a basis that extends a basis of$~W$, then the matrix becomes block-upper-triangular $\binom{A~X}{0~B}$ and its characteristic polynomial the product of those of $A$ and $B$, by the corresponding property of determinants.
Comment: I might be missing some basic ideas around this topic. "therefore the characteristic polynomial of $T$ restricted to that space is a nontrivial strict divisor of the characteristic polynomial of $T$" - why is this true?


Using the DbConfiguration class with Entity Framework ObjectContext

Question: I have a C# application using Entity Framework and ObjectContext. I wish to implement connection resiliency like mentioned here: https://msdn.microsoft.com/en-us/library/dn456835(v=vs.113).aspx
How do I assign the DbConfiguration class to the ObjectContext (i.e. how do I 'tell' the ObjectContext to use the configuration)?
Comment: https://msdn.microsoft.com/en-us/library/jj680699(v=vs.113).aspx
Comment: Thanks, but it says: "Place your DbConfiguration class in the same assembly as your DbContext class". I do not use DbContext but ObjectContext. Will this still work?
Comment: Nope, it does not work with ObjectContext. Tried in dummy application for DbContext and it works as advertised. Any other suggestions to make it work with ObjectContext?
Answer: You can provide a configuration class which is extended from DbMigrationsConfiguration<YourContext>
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "YourContext_";
    }

    protected override void Seed(YourContext context)
    {
        //Migrate your data
    }
}


Full width input in collapsed bootstrap navbar

Question: I've modified bootstrap navbar to change the collapse breakpoint from 768px to 992px. Here's the solution I've used : stackoverflow.com/questions/18192082/bootstrap-3-navbar-collapse
Problem : search input is not full width under the following conditions
1) screen size is between 768px & 992px
2) collapse is toggled
I've tried width 100% & many other suggestions found on stackoverflow. Here's a demo on codepen
Expectation (https://ibb.co/mwx4Qa), reality (https://ibb.co/jZAfyv)
HTML

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mynav" aria-expanded="false">
        Toggle navigation

      </button>

Link 1

        <form class="navbar-form navbar-left">

            <input type="text" class="form-control" name="q" placeholder="Search Google">
            <button type="submit" class="btn btn-primary">Search</button>

        </form>

Comment: Have you tried to remove the container class div?
Comment: The input is full width on mobile as shown in your "expectation". If the question is solved accept an answer.
Comment: @ZimSystem "Mobile" is vague. It works for `< 768px` but breaks for `< 768px & < 992px` which is the width band that falls in the modified collapse breakpoint
Answer: The container div is what gives the width of your navbar, so if you remove it, it should work:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#mynav" aria-expanded="false">
      Toggle navigation

    </button>

Link 1

      <form class="navbar-form navbar-left">

          <input type="text" class="form-control" name="q" placeholder="Search Google">
          <button type="submit" class="btn btn-primary">Search</button>

      </form>

Comment: I've removed the container from this codepen (http://codepen.io/anon/pen/aJBQqR?editors=1100). Still the same issue for `768px < width < 992px`
Answer: Add this code at the bottom of your style sheet. Tested on your codepen.
@media (min-width: 768px) and (max-width: 991px) {
  .navbar-form .input-group .input-group-btn {
    width: 1%;
  }
}


How do I update a user profile with entity_metadata_wrapper()?

Question: I got an error while updating user profile data such as name,password and email. I am using entity_metadata_wrapper() for processing update.

exception 'EntityMetadataWrapperException' with message 'Unknown data property original.' in C:\xampp\htdocs\phone_bay\sites\all\modules\entity\includes\entity.wrapper.inc:335\nStack trace:\n#0

This is my code.
require './includes/password.inc';
function commerce_services_user_update($uid, $data, $flatten_fields) {
    $user = user_load($uid);
    $wrapper = entity_metadata_wrapper('user', $user);
    dpm($wrapper->value());

    $name = $data['name'];
    $password = $data['password'];
    $email = $data['email'];

    if ($name != null) {
        $wrapper -> name  = $name;
    }
    if($password != null){
        $wrapper -> pass = user_hash_password($password);
    }
    if ($email != null) {
        $wrapper -> mail = $email;
    }

    try {
        user_save($wrapper);
        $message = "successessfully update!";
    } catch (Exception $e) {
        $message = "not success! -> ". $e;
    }

    $reply = (array('status' => $status,'message' => $message));
    return $reply;
}

Answer: Since you are using an entity wrapper, you must use $entity->save to save the updated user object. In your case, use $wrapper->save.
user_save() can be used when the user entity is loaded using user_load().
Comment: Have you given correct values in the user object? Because mail validation also happens here.
Comment: Not ok yet after changing code to $wrapper -> save();  exception still occurs. (exception 'EntityMetadataWrapperException' with message 'Invalid data value given. Be sure it matches the required data type and format.' in C:\\xampp\\htdocs\\phone_bay\\sites\\all\\modules\\entity\\includes\\entity.wrapper.inc:737\nStack trace:\n#0)
Answer: The user entity needs to be also saved. The full code for changing the username and the email address is then the following one.
$wrapper->name->set('Jean louis');
$wrapper->mail->set('email@example.com');
$wrapper->save();


Find the best approximation with Legendre polynomials

Question: Can you help me with this problem?
I have the Legendre polynomials $ψ_{k}(x):= \frac{k!}{(2k)!}\frac{d^k}{(dx^k)}(x^2-1)^k$.
They are orthogonal with respect to the $L^2$ scalar product on $[−1, 1]$.
I want to find an orthonormal basis of $span \left \{ψ_0, ψ_2  \right \}$ and of $span \left \{ψ_0, ψ_1, ψ_2  \right \}$.
And how can I calculate the best approximation of
$sin(x)$ with respect to the $L^2$ scalar product on $[−1, 1]$ and the calculated orthonormal basis?
Comment: Best approximation of $\sin$ under what constraints?
Comment: I have corrected my question with all given informations from the problem
Comment: Also to be clear, $\{\psi_0, \psi_2\}$ and $\{\psi_0, \psi_1, \psi_2\}$ represent the linear span of those polynomials in $L^2$?
Comment: yes it is correfct
Answer: The Legendre polynomials are already orthogonal, so an orthonormal basis just needs to scale them to have norm $1$. $|\psi_n|^2 = 1/(n+1/2)$, so $\sqrt{n+1/2}\psi_n$ will be orthonormal. Thus, $\{\sqrt{2}\psi_0, \sqrt{5/2}\psi_2\}$ and $\{\sqrt{2}\psi_0, \sqrt{3/2}\psi_1, \sqrt{5/2}\psi_2\}$ will be the desired orthonormal bases.
As for approximating $\sin$, the best you're going to do for an orthonormal set $b_i$ is the orthogonal projection onto that set. That is, $\sum_i \langle \sin, b_i\rangle b_i$. Unfortunately for the first set, $\langle\sin, \psi_{2n}\rangle = 0$ for any integer $n$, so the best approximation of $\sin$ is $0$. The addition of $\psi_1$ makes things much better for the second set. The best approximation will be $\langle \sin, \sqrt{3/2}\psi_1\rangle \sqrt{3/2}\psi_1 = 3/2\langle \sin, \psi_1\rangle \psi_1$. Evaluating the inner product integral gives
$$
\int_{-1}^1 \sin(x) \psi_1(x) dx = \int_{-1}^1x\sin(x)dx = 2(\sin 1 - \cos 1)
$$
So the best approximation for $\sin$ in the second basis is $3(\sin 1 - \cos 1)\psi_1$. Which doesn't look too bad for a simple linear approximation.


Prove that $\left | \cos x - \cos y \right | \leq \left | x - y \right |, \forall x,y \in \mathbb{R}.$

Question: This is one of the problem in my text book where the section which the problem is stated talks about the mean value theorem and Rolle's theorem. By looking at this, I have no idea where to start. Can I have some hints??
Comment: The derivative of $\cos t$ has absolute value $\le 1$.
Answer: $\cos(x)$ is differentiable in $\mathbb{R}$.
By Mean value theorem $|\cos(x) - \cos(y)| = |sin(\xi)||x - y|$ where $\xi \in (x,y)$ or $(y,x)$.
$|\sin(x)| < 1$ $\forall$ $x \in \mathbb{R}$.
Now get your answer.
Answer: This follows also from the standard $|\sin(x)| \leq |x|$:
$$\left| cos(x) - \cos(y)  \right|=2  \left| \sin(\frac{x+y}{2}) \sin(\frac{y-x}{2})  \right| \leq 2 \cdot  1 \cdot \left|\frac{y-x}{2}  \right|$$
Comment: This is more fundamental and simpler than the other techniques involving differentiation and integration. Differentiation/integration of trig functions are ultimately dependent on $\sin x < x < \tan x$ inequality for $x \in (0, \pi / 2)$. (+1)
Comment: On the other hand, $\sin x < x < \tan x$ is a geometric fact, just as the proof for $\sin(x+y)=\sin(x)\cos(y)+\cos(x)\sin(y)$. Maybe you'd argue you can use complex exponentials, but then you really need complex analysis--i.e. calculus.
Answer: By integration:
$$|\cos y - \cos x| = \left|-\int_x^y \sin t dt \right| \leq \int_x^y |\sin t dt| \leq \int_x^y 1 dt = |y-x|$$
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
By ${\it Mean Value Theorem}$,
$\exists\ \xi \in {\mathbb R}\quad \ni\quad \min\braces{x,y} < \xi < \max\braces{x,y}$ which satisfies
$$
{\cos\pars{x} - \cos\pars{y} \over x - y}  = -\sin\pars{\xi}
\quad\imp\quad
\verts{\cos\pars{x} - \cos\pars{y} \over x - y}  = \verts{\sin\pars{\xi}} \leq 1
$$


Release memory aquired by CreateTexture2D()?

Question: as the MSDN is not very specific at this point: in my application I create a texture by calling CreateTexture2D().
On success, do I have to release the created texture? If yes, how?
Thanks!
Answer: TL;DR: This is documented on MSDN in this article: Programming DirectX with COM
Direct3D uses COM reference-counting for lifetime management.

All the objects are derived from IUnknown and when they are created have a refcount of 1.

When you call Release it decrements the refcount. Once the refcount is 0, the object is eligible for cleaning up all it's memory and resource use. For performance reasons, Direct3D uses deferred destruction so typically all these objects are cleaned up a frame or two later.

Once the "external" refcount is 0, the Direct3D Runtime will deal with cleaning it up. You don't have to do anything else. If you want to force all deferred destruction, you can use ID3D11DeviceContext::Flush, but you shouldn't do it often as it severely impacts performance.

If you want to have more than one pointer reference the same object, you call AddRef to increment it's refcount.

For Direct3D 10, 11, and 12, there is a slight modification of the COM lifetime rules. Specifically, if a "device" hits a refcount of 0, then all "device child objects" created from that device are invalid even if their refcount is non-zero.

For Direct3D 10, 11, and 12, if you 'bind' an object to the rendering pipeline, this does not increment the refcount. You have to ensure the object remains valid until the rendering is complete. See Reference Counting (Direct3D 10).

For C++ development, the strong recommendation is to use a COM smart-pointer of some kind to automatically increment/decrement refcounts as needed. Options here include:

WRL's Microsoft::WRL::ComPtr**
C++/WinRT's winrt::com_ptr
WIL's wil::com_ptr

For completeness there is also:

ATL's CComPtr (WRL is basically "ATL 2.0", and ATL is only installed with Visual Studio as an opt-in feature)
Visual Studio's _com_ptr_t (a half-hearted attempt, so not a great choice)

** =  This is my preference currently since it's available in the Windows 8.0 SDK or later and works for Win32 desktop, UWP, and Xbox. See DirectX Tool Kit Wiki: ComPtr for reasoning and examples.

See also MSDN: Managing Object Lifetimes Through Reference Counting and Wikipedia: Reference counting
Comment: Note that per [this question](https://stackoverflow.com/questions/66060481/release-resources-allocated-with-d3d11createdevice), ``ID3D11Device`` is itself derived from ``IUnknown`` and also uses COM refcounts.


Probability of two people winning a prize, according to the number of tickets each person has

Question: Since I find it hard to abstractly describe what I want to understand, I came up with the following example.
Suppose that 6 people hold each a given number of a very special type of lottery tickets. Person A holds 2 tickets, person B holds 3 tickets, person C holds 1 ticket, person D has 5 tickets, person E has 6 tickets and person F has 3 tickets.
The probability of each person winning a prize is directly proportional to the number of tickets each holds.
So, in the end, N different contenders are going to be chosen winners. What I would like to learn is how can I calculate the probability of A, B, C, D, E and F of being one of the N winners?
We can assume N=2 or whatever, if it makes it easier.
Summary of probabilities:
$$\begin{cases}P(A)=\frac{2}{20}\\P(B)=\frac{3}{20}\\P(C)=\frac{1}{20}\\P(D)=\frac{5}{20}\\P(E)=\frac{6}{20}\\P(F)=\frac{3}{20}\end{cases}$$
Comment: the "fun part" is totally unclear
Comment: @GCab Hope me edit made it clear.
Comment: @MCCCS Hope my edit made the unfunniness less of a problem....
Answer: You haven't specified the method for choosing. I'll suppose that one of the 20 tickets is chosen at random. Then the five people who have no prize join a second similar lottery with their tickets.
Let's figure out the probability that A wins a prize.
Her chances are $2/20$ for the first draw. If she's not chosen (with probability $18/20$) her chance of succeeding the next time depends on who won at first. If it was B (with probability $3/20$) then her three tickets are removed and A's second chance is $2/17$. For C, D, E, and F her chances are $2/19$, $2/15$, $2/14$ and $2/17$ so her chance for on if of the two prizes is
$$
\frac{2}{20} + \frac{18}{20}\left(
  \frac{3}{ 20}\frac{2}{ 17} +  \frac{1}{ 20}\frac{2}{19 } + \frac{5}{ 20}\frac{2}{15 } + \frac{6}{ 20}\frac{2}{14 } + \frac{3}{ 20}\frac{2}{17 }
\right) .
$$
You can work this out for the other folks, and for $N$ participants. One check: you should get probabilty $1$ if $N$ is the number of participants.
I don't know a pretty way to do this.
Answer: $$\begin{cases}P(A)=\frac{2}{20}\\P(B)=\frac{3}{20}\\P(C)=\frac{1}{20}\\P(D)=\frac{5}{20}\\P(E)=\frac{6}{20}\\P(F)=\frac{3}{20}\end{cases}$$
You originally asked with regard to two candidates being selected.  Let's look at that case.  Call the first candidate to be selected $X_1$, the second candidate to be selected $X_2$ and so on... The Probability of $X_1$ being selected is $P(X_1)$.
You want to represent $X_1$ and $X_2$ as being selected.  You haven't stated whether they will be selected in one go, or one at a time.  Let's assume it's the latter.  Time to use some conditional probability, because choosing one affects the probability of choosing the next..!
$$P(X_1 \cap X_2 )=P(X_2|X_1)P(X_1)$$
You choose the first person  $X_1\in\{A,B,C,D,E,F\}$, with their probability $P(X_1)$. Easy enough.
Then you select the second person $X_2$, out of the remaining people. If $X_1=A$ then $X_2\in \{B,C,D,E,F \}$.  Find $P(X_2|X_1)$ by re-calibrating the likelihood of B,C,D,E & F being chosen now that A is no longer a viable candidate for selection.  Then you have the ability to multiply this answer for your chosen $X_2$ and $X_1$ per the conditional probability formula stated above.
You can extend this to the Nth case using further conditional probability. Let N=4:
$$P(X_1 \cap X_2 \cap X_3 \cap X_4)=P(X_4|X_1 \cap X_2 \cap X_3)P(X_3|X_1 \cap X_2)P(X_2|X_1)P(X_1)$$
Have fun!


Prove that for every $p\in N$ we have $(dF^{-1})_{F(p)}=(dF)^{-1}_p$, with $F:N\to M$ a diffeomorphism

Question: Let $M,N$ be smooth manifolds and $F:N\mapsto M$ a diffeomorphism. Prove that for every $p\in N$
$(dF^{-1})_{F(p)}=(dF)^{-1}_p$

Foremost because $F$ is  a diffeomorphism $\text{dim}N=\text{dim}M$ and the matrix $(dF)_p$ is invertible.
My idea was to take the matrix  $(dF^{-1})_{F(p)}$ and do the multiplication with $(dF)_p$, if the final product is $I_n$ then the inverse is $(dF^{-1})_{F(p)}$ as we wanted.
Here is where I stuck:
$\left [ \frac{\partial (F^i)^{-1}}{\partial x^j} \right ]\cdot \left [ \frac{\partial (F^i)}{\partial x^j} \right ]=$
\begin{bmatrix}
\frac{\partial (F^1)^{-1}}{\partial x^1}\cdot \frac{\partial (F^1)}{\partial x^1}+\frac{\partial (F^1)^{-1}}{\partial x^2}\cdot \frac{\partial (F^2)}{\partial x^1}+...+\frac{\partial (F^1)^{-1}}{\partial x^n}\cdot \frac{\partial (F^n)}{\partial x^1} &.  &.  &.  &\frac{\partial (F^1)^{-1}}{\partial x^1}\cdot \frac{\partial (F^1)}{\partial x^n}+...+\frac{\partial (F^1)^{-1}}{\partial x^n}\cdot \frac{\partial (F^n)}{\partial x^n} \\
 .&  .&  &  & \\
 .&  &  .&  & \\
 .&  &  &  .& \\
 \frac{\partial (F^n)^{-1}}{\partial x^1}\cdot \frac{\partial (F^1)}{\partial x^1}+...+\frac{\partial (F^n)^{-1}}{\partial x^n}\cdot \frac{\partial (F^n)}{\partial x^1}&  .&  .&  .& \frac{\partial (F^n)^{-1}}{\partial x^1}\cdot \frac{\partial (F^1)}{\partial x^n}+...+\frac{\partial (F^n)^{-1}}{\partial x^n}\cdot \frac{\partial (F^n)}{\partial x^n}
\end{bmatrix}
in order for the above to be $I_n$ it  must be true that $\frac{\partial (F^i)^{-1}}{\partial x^i}\cdot \frac{\partial (F^i)}{\partial x^i}=\frac{\partial (F^i)^{-1}\circ F^i }{\partial x^i}=1$ and the rest should be zeros
but I dont think this is correct, I have never seen $\frac{\partial (F^i)^{-1}}{\partial x^i}\cdot \frac{\partial (F^i)}{\partial x^i}=\frac{\partial (F^i)^{-1}\circ F^i }{\partial x^i}=1$
Can someone clarify this for me, if my idea is correct how should I proceed ? and if it's not can you give a hint ?
Comment: You must make use of the fact that $F^{-1}(F(x)) = x$.
Comment: @Thomas As I said above, if the product of the partials is the compositions then I am using this. That's what I am asking, how to use that.
Comment: $(F^i)^{-1}$ does not make sense, you mean $(F^{-1})^i$. Anyway, this just comes down to the chain rule. I think writing the chain rule out in coordinates is probably doing more confusion than help (and also less clear since you're omitting the points at which we're evaluating).
Comment: @Thorgott in order to apply the chain rule I must have a product of 2 functions, also I can't see how the product will eventually give me composition.
Comment: The chain rule is about compositions, not products..
Comment: @Thorgott you are right I got confused, what  I mean is that  now I have a product of partials, I don't have a composition  to use the chain rule
Comment: That's what the chain rule looks like in coordinates. It's a matrix multiplication after all. My point, however, is that you really don't need to spell it out in coordinates and should just apply the chain rule at the level of linear maps.
Comment: @Thorgott you mean something like this $I_n=\left [\delta ^i_j  \right ]=\left [ \frac{\partial {x^i} }{\partial x^j}\right ]=\left [ \frac{\partial(F^i(F^{-1})^i) }{\partial x^j} \right ]=\left [ \frac{\partial F^i(F^{-1})^i }{\partial x^j} \right ]\underbrace{\left [ \frac{\partial (F^{-1})^i }{\partial x^j} \right ]}_{(dF^{-1})}$
Comment: @Thorgott  I think I'm still missing something thought
Answer: One the one hand, we have $d(F^{-1})_{F(p)}$, which is the differential of $F^{-1}:M\to N$, calculated at $F(p)\in M$. This is a map of the form $d(F^{-1})_{F(p)}:T_{F(p)}M\to T_p N$, and more precisely the one acting on tangent spaces $[\gamma]\in T_{F(p)} M$ as (I'm using parentheses to stress the order of the operation and who's who's input):
$$\color{red}{(} d(F^{-1})_{F(p)} \color{red}{)}([\gamma])
= [F^{-1}\circ \gamma] \in T_p N,$$
On the other hand, consider $dF_p^{-1}\equiv (dF_p)^{-1}$. More precisely, this is the inverse of $dF_p:T_p N\to T_{F(p)}M$, and thus $(dF_p)^{-1}:T_{F(p)}M\to T_p N$.
Using the properties of the differential operation, we have $$d(F^{-1})\circ dF = d(F^{-1}\circ F)=d(\text{id}_N) = \text{id}_{TN},
\\
dF\circ d(F^{-1}) = \text{id}_{TM.}$$
It follows that $d(F^{-1}):TM\to TN$ is the inverse operation of $dF:TN\to TM$. Considering their restricted action to specific fibers, this then in particular means that $d(F^{-1})\big|_{F(p)}\equiv (dF^{-1})_{F(p)}$ is the inverse of $dF\big|_p\equiv dF_p$. Which can be equivalently expressed writing that
$$d(F^{-1})\big|_{F(p)} = (dF\big|_p)^{-1} \equiv (dF_p)^{-1}.$$
Answer: This follows from the functoriality of $dF_p$. I will denote $dF_p$ by $F_{*,p}$ or $F_{*}$. Once you prove the following data:
$1.$ If $id:M\rightarrow M$ denotes the identity then for each $p\in M$, $id_{*,p}=id_{T_pM}$
$2.$ $(F\circ G)_{*}=F_{*}\circ G_{*}$
You obtain the result you seek by taking $G$ to be the inverse of $F$.


git rebase -i foo/dev gives noop

Question: When I try to get into the interactive rebase mode as explained here, all I'm getting is noop which is weird but I cannot figure out why.
I am inside a temp branch in my machine and when I try to view the difference between, I get this:

Tugberk@TUGBERKPC /D/Dropbox/AppsPublic/gulp-aspnet-k (temp-a)
$ git log --pretty=oneline  temp-a..ajryan/dev
f0ef4ee40fde4de5360515fd556de9c3ed40431c update readme with new optionsfcba1ae3306ae041a1d82647e4cf65a0c96fe2f7 do not loop for build, restore8bedd238660908f06d698815ef12fce786d716ed fix command concat
e2e3a0d00e3950911c00c0e6e51a671f5f2ac2d3 bump version
d65923ff91eb9d6b9782bc2bf5ab606d19733203 add quiet option
91a1faff0a3aa1ca552df2151190a3ecd87cfc6f allow caller to loop all comma962c55854457314324d81457c42913532875cc85 trailing whitespace, tabs > sp

However, when I run the following command, I'm getting noop:

Tugberk@TUGBERKPC /D/Dropbox/AppsPublic/gulp-aspnet-k (temp-a)
$ git rebase -i ajryan/dev

Any idea why and what am I doing wrong?
Comment: if `temp-a` is an ancestor of `ajryan/dev` then this is expected I think.
Answer: Your git log command is showing commits that are on ajryan/dev but not on temp-a.  Your rebase command is told to rebase commits that are on temp-a but not on ajryan/dev, but presumably there are no such commits.  Pictorially:
... - o - o - o                   <-- HEAD=temp-a
                \
                  o - o - o - *   <-- ajryan/dev

Therefore, there are no commits to pick up and rebase onto the commit I have marked with a star *.  So rebase -i generates a single no-op command.
If you execute that no-op, the rebase operation should conclude by moving temp-a to point the last commit added on after *, which should make temp-a point to commit *.  (If that doesn't happen, it's a small bug in rebase.)  If you delete the no-op, though, the rebase operation will be aborted, and temp-a will not be moved.

Note that if you did have different items on temp-a you could rebase them, or rebase the other branch.  Here are two more illustrations, starting with almost the same base, but with one commit that's on temp-a that is not on ajryan/dev:
... - o - o - o - @               <-- HEAD=temp-a
                \
                  o - o - o - *   <-- ajryan/dev

In this case, you can either put the @ commit on top of the other commits:
... - o - o - o
                \                     (illustration 1)
                  o - o - o - * - @

or at the bottom, below the other commits:
... - o - o - o
                \                     (illustration 2)
                  @ - o - o - o - *

Here I have left out the labels (temp-a and ajryan/dev).  This is on purpose: in git, branch labels are easy to move around (and are actually expected to move as long as it's in a "forward" fashion); all of the actual branch-iness is stored in the commits themselves.  What git rebase really does is copy old commits to new ones, so that you can change their parent-age and/or contents.
In Illustration #1, we've re-parented commit @: it now has commit * as its parent.  All the other commits are unchanged, and hence only commit @ has to be copied.
In Illustration #2, however, we've re-parented the entire chain of commits that were originally only on ajryan/dev.  Commit @ itself is unchanged, but we had to copy all four of the original o - o - o - * commits: we copy the first o to set its parent to @.  This new commit has a new and different SHA-1 ID, so we copy the second o to use the new commit's ID as its parent.  This second copy forces the third copy, which then forces the last copy of the * commit.  See the next section as to what can be bad about that.

In git, to join two different chains of commits, you would normally use git merge:
          A - B
        /       \
... - o           M   <-- HEAD=branch
        \       /
          C - D

Here merge commit M joins the two chains A - B and C - D that fork off from o.  If all of A through D exist, and you create new commit M, nothing happens to A through D: they are still the same as before.
For simple development, though, it's usually nicer to "rebase" work: to make C and D sit "on top" of A - B.  But to do that you must copy the commits, because a commit in git is permanent and unchanging.  You copy C to a new, slightly different C', and copy D to a new, slightly different D'.  The main thing that's different about C' is that its parent is B, not o, and the main thing that's different about D' is that its parent is C', not C:
          A - B - C' - D'   <-- HEAD=branch
        /
... - o
        \
          C - D            [abandoned]

Once the rebase copy is done, you simply abandon the old C and D commits and start pretending C' and D' were the original commits:
          A - B - C - D   <-- HEAD=branch
        /
... - o

Now we no longer need the little kink in the graph since we've forgotten all about the original C and D, and history just looks like this:
... - o - A - B - C - D   <-- HEAD=branch

The dirty secret (not so secret, not that dirty) is that the original C and D are still in there, they're just invisible (to you).  The part that makes it truly dirty happens if someone else has the original two C and D commits.  Git commit IDs are cryptographic checksums of their contents, including the parent SHA-1 IDs, so the original C and D are still there and are different from the new C and D, and anyone else.
This matters when you pull commits from someone else: if you rebase their commits onto your work, you change the IDs.  You make new copies and you might forget they had the originals, but they don't know about your new copies yet and they have not forgotten their original IDs.
If you later present them with rebased copies of their commits, they need to do more work to pick up your copies of their commits and maybe move any additional work they've done.
In short, unless you've made arrangements with them (whoever "they" may be) in advance, a rebase like that shown in Illustration #2 is usually not a good idea.

What about "fast forwards"?  Well, let's take a look at Illustration #1 again.  Let's assume the o - o - o - @ chain came from someone else (a "pull request"), and that you add commit * on top of it by rebasing your work onto theirs.  Let's re-draw the graph too, adding one more kink, and put the ajryan/dev label back:
... - o - o - o     [your original '@' commit, before rebasing, was here]
                \
                  o - o - o - *       <-- ajryan/dev
                                \
                                  @   <-- HEAD=(something, maybe "dev")

Now let's further assume that they, whoever they are, have the o - o - o - * sequence on their dev branch and have not done any additional work, so that their stuff ends at the commit marked *.  If you make this commit-sequence available to them, they can pick it up and add commit @ to their dev branch, by simply sliding their dev label down-and-right to point to the @ label.  Now let's also erase our ajryan/dev label, and straighten out the kinks in these drawings, and use the label dev.  Here's the result:
... - o - o - o - o - o - o - * - @   <-- HEAD=dev

This is what they will have, and what you will have, once you're both in sync.  It's a very simple looking history, even if it's a slight deviation from the actual development process (you wrote commit @ without first seeing their chain that ended in *).  But this is the kind of "rebase" that makes following the development work a lot easier, and is in general what people want to do.
Sliding a label "rightward" (including down-and-right, or up-and-right, in drawings like these) is a "fast forward" operation.  If you run git merge with --ff-only, it will only do the "merge" if it is really this kind of non-merge fast-forward.

Bottom line: I think you wanted to rebase your @ commit onto the ajryan/dev work, but you didn't have an @ commit to rebase.  That's why rebase gave you a noop.  In this case, a simple non-merge fast-forward git merge suffices to make your label match their label.

It's also worth thinking about this: when you do git log X..Y you're asking git to draw the graph like I did here:
... - o - o - o       <-- X
        \
          o - o - o   <-- Y

The X..Y notion essentially says: starting with this graph, take out a highlighter and highlight the commit that X points to, and all commits left-and/or-up-or-down from there.  (That leaves the three os pointed-to by Y un-marked.)  Then, find all commits pointed-to by Y that are not already highlighted, and log those.
If you reverse the X and Y, as in git log Y..X, you ask git to "run the highlighter" on commits marked by Y, which leaves only the two os only on X, and then log all commits pointed-to by X that are not already highlighted.  So here you get the two os on X, and none of the shared ones.
Comment: what should be the command than? `git rebase -i --onto temp-b ajryan/dev`? it doesn't work as well :s
Comment: What result would you like?  There are no commits on `temp-a` that are not already on `ajryan/dev`.  You can do a `git merge --ff-only ajryan/dev` to tell git that you'd like branch `temp-a` to catch up with `ajryan/dev` if (and only if) it can do that without making a real merge (which I believe is true, but I don't have your repo).
Comment: what I am trying to do is to get the changes made inside the remote pull-request branch into my `temp-a` branch with an interactive rebase session.
Comment: In that case, try the `git merge --ff-only` method: if it says it can't, you can do that kind of rebase to put your changes on top of their changes (see added illustration #1), or their changes on top of your changes (#2).

git rebase -i foo/dev gives noop


Definition of point processes

Question: We say a finite point process $X$ on $[N]=\{1,…,N\}$ can be understood as a random subset. It is defined either via its inclusion probabilities, that is $\mathbb{P}(S \subseteq X)$ for $S \subseteq [N]$ or its likelihood $\mathbb{P}(X=S)$ for $ S \subseteq [N]$.
I would like to ask about the interpretation of the inclusion probabilities. My mental picture of the situation is that $X$ pulls out a random subset from $\{1, 2, ..., n\}$. So the likelihood picture makes a lot of sense here (the probability that the subset which I pull out happens to be $S$). However, how do the inclusion probabilities relate to this picture? What is the equation $\mathbb{P}(S \subseteq X)$ for $S \subseteq [N]$ actually saying, and why does it help? Why do we define the correlation functions using the inclusion probabilities? How can this be generally interpreted and viewed?
How can each part of the definition of a point process be related to our intuition, in particular the inclusion probabilities and their correlation functions?
Answer: There'a a lot going on here, but it is primarily a matter of mathematical notation and language. I will discuss a bunch of related in issues in the context of a simple running example.  I won't attempt to write fully general formulas for everything, remaining content to show the calculations in enough detail to enable you to write such formulas if you care to.

One issue of substance is the PIE: Principle of Inclusion-Exclusion.  It says that when a finite set $S$ is expressed as a union of proper subsets, $S = S_1\cup S_2\cup \cdots \cup S_k,$ you can count the elements of $S$ by summing the counts of its subsets and then adjusting that count by subtracting the number of elements in their mutual intersections (which subtracts too much), then adding back in the number of elements in their three-fold intersections, and so on.
Ultimately the PIE will show how the inclusion probabilities alone determine the probability distribution of the random sets.
Let's get to the matter of notation.  We may view this "point process" equivalently as (a) taking random samples of (potentially) random sizes; (b) a stochastic process; (c) a multivariate distribution; or (d) a subset-valued random variable.  To explain this I will describe one specific, simple such process in various ways.  Let's begin with the example.
Use the notation $[0]=\emptyset$ and $[N]=\{0,1,\ldots, N-1\}$ (Indexing starts at $0$ rather than $1.$)  For instance, $[N]=[3]$ has $2^3$ subsets, a collection known as its power set $\mathcal{P}([N]).$  Let's use the first eight letters of the Greek alphabet to identify them, as shown in this tabulation.
$$\begin{array}{clcccl|rr}
\text{Name} & S & \mathcal{I}_0 & \mathcal{I}_1 & \mathcal{I}_2 & \text{Proper Subsets} & k & F \\
\hline
\alpha & \{0,1,2\} & 1 & 1 & 1 & \beta,\gamma,\delta,\epsilon,\zeta,\eta,\theta & 1 & 1\\
\beta & \{0,1\} & 1 & 1 & 0& \epsilon,\zeta,\theta & 1 & \frac{5}{12}\\
\gamma & \{0,2\} & 1 & 0 & 1& \epsilon,\eta,\theta & 2 & \frac{5}{12}\\
\delta & \{1,2\} & 0 & 1 & 1& \zeta,\eta,\theta & 3 & \frac{7}{12}\\
\epsilon& \{0\} & 1 & 0 & 0& \theta & 1 & \frac{2}{12}\\
\zeta& \{1\} & 0 & 1 & 0& \theta & 2 & \frac{3}{12}\\
\eta& \{2\} & 0 & 0 & 1& \theta & 1 & \frac{2}{12}\\
\theta& \{\} & 0 & 0 & 0& & 1 & \frac{1}{12}\\
\end{array}$$
This table describes many interesting things:

Its rows $\alpha,\ldots, \theta$ correspond to the sample space $\Omega=\mathcal{P}([N]).$  It is the collection of all possible values of the random sets -- all $2^N$ of them.

The columns headed $\mathcal{I}_j$ are the indicators of the elements.  By definition, for any $j\in [N],$ $$\mathcal{I}_j(S) = \left\{\begin{array}{ll} 1 & j \in S \\ 0 & j \notin S.\end{array}\right.$$

The vector $\mathbf I = (\mathcal{I}_0,\mathcal{I}_1,\mathcal{I}_2)$ is a binary representation of each set.  This permits us to identify $\Omega$ with the set of $N$-digit binary sequences.

The collection of proper subsets of each set $S$ determines a partial order on the sets.  We may write, for instance, $\zeta \le \beta$ because $\zeta=\{1\}$ is a subset of $\beta=\{0,1\}.$  However, neither of the relations $\eta\le\beta$ nor $\beta\le\eta$ holds: that's why this is only a partial order.

To this description I have added two columns $k$ and $F.$  The $k$ determine a probability distribution: divide any $k$ by their sum ($12$) to obtain the probability.  For example, the chance that a random set obtained by this process is $\delta=\{1,2\}$ is $\Pr(\delta) = 3/12=1/4.$

If you were to print this table on paper (several times) and cut out eight strips for the eight rows on each sheet, $k$ tells you how many copies of each strip to place into a box.  This box will therefore wind up with $1+1+2+\cdots +1 = 12$ strips, or "tickets."

A random set (with distribution determined by $k$) is a random draw of a ticket from this box.

Consequently, $\mathbf I$ is a vector-valued random variable and each of the indicators $\mathcal{I}_j$ is an (ordinary, real-valued) random variable.

Alternative Descriptions
The last column $F$ gives the "inclusion probabilities" mentioned in the question.  There are several equivalent ways of looking at them.

For any outcome $S$ listed in the table, $F(S)$ is the sum of probabilities of $S$ and all its proper subsets.   That is, $$F(S) = \sum_{T\subseteq S} \Pr(T)= \Pr(S) + \sum_{T\subset S, T\ne S} \Pr(T).$$  For instance, $$F(\delta) = \Pr(\delta) + \Pr(\zeta) + \Pr(\eta) + \Pr(\theta) = \frac{3 + 2 + 1 + 1}{12} = \frac{7}{12}$$ as you can read directly from the "Proper Subsets" column and $k$ column.

The vector-valued random variable $(\mathcal{I}_0, \mathcal{I}_1, \mathcal{I}_2)$ has (by a standard definition) a cumulative distribution function $G$ defined by $$\begin{array}{rl} G:&\mathbb{R}^3\to[0,1] \\ G(x_0,x_1,x_2) &= \Pr(\mathcal{I}_0 \le x_0 \text{ and } \mathcal{I}_1\le x_1 \text{ and } \mathcal{I}_2\le x_2).\end{array}$$
(Because the ranges of the indicator variables are within the unit interval $[0,1],$ this exhibits $G$ as a copula.)

$F$ and $G$ are equal.  A neat choice of notation will make this apparent.  The vector-valued random variable $\mathbf{I} = (\mathcal{I}_0,\mathcal{I}_1,\mathcal{I}_2)$ sets up a one-to-one correspondence between each possible random set and the value of $\mathbf I$ via
$$S\subseteq [N] \longleftrightarrow \mathbf{I}(S) \in \mathbb{R}^N.$$
The standard partial order on $\mathbb{R}^N$ is componentwise comparison: we write $\mathbf{x}\le \mathbf{y}$ if and only if $x_i\le y_i$ for every component $i.$  Under the foregoing correspondence, comparison of subsets is the same as comparison of their indicators.  That is, for $S,T\subseteq[N],$ $$S\subseteq T\ \text{ if and only if }\ \mathbf{I}(S) \le \mathbf{I}(T).$$
We have seen

The inclusion probabilities of the subsets $X\subseteq [N]$ specify the distribution function $F$ of the indicator $\mathbf I.$

The PIE merely restates how multivariate distribution functions work. See https://stats.stackexchange.com/a/386409/919 for a full algebraic explanation.  The point, of course, is that the inclusion probabilities completely determine the probability distribution on $\Omega.$
Correlations
The natural sense of "correlation" in the question concerns the correlations (and covariances) of the indicators.  First let's look at the means: these are the expected fraction of time a particular value $i$ will appear in a random set, equal to the chance that $i$ appears:
$$E[\mathcal{I}_i] = \Pr(\mathcal{I}_i=1)\times 1 + \Pr(\mathcal{I}_i=0)\times 0 = \Pr(\mathcal{I}_i=1).$$
By definition, the covariances are
$$\operatorname{Cov}(\mathcal{I}_i, \mathcal{I}_j) = E[\mathcal{I}_i\mathcal{I}_j] - E[\mathcal{I}_i]E[\mathcal{I}_j].$$
On the right we see (a) the chance that both $i$ and $j$ appear in a random set $S,$ adjusted for the chance both would appear if they were independent.
For instance, in the running example $$E[\mathcal{I}_0] = \Pr(0\in S) = \Pr(\alpha) + \Pr(\beta) + \Pr(\gamma) + \Pr(\epsilon) = 5/12,$$ with similar calculations giving $E[\mathcal{I}_1] = 7/12 = E[\mathcal{I}_2].$
Likewise,
$$E[\mathcal{I}_0\mathcal{I}_1] = \Pr(\alpha) + \Pr(\beta) =2/12,$$
whence
$$\operatorname{Cov}(\mathcal{I}_0,\mathcal{I}_1) = \frac{2}{12} - \frac{5}{12}\times \frac{7}{12} = -\frac{11}{144}.$$
Finally, because $\mathcal{I}_i^2 = \mathcal{I}_i$ (since $0^2=0$ and $1^2=1$), the variances don't require any more computation.  Indeed, these indicators are (obviously) Bernoulli random variables. So, for instance, the variance of $\mathcal{I}_0$ is $(5/12)\times(1-5/12) = 35/144$ and the variance of $\mathcal{I}_1$ is the same.  Thus, according to the usual formula,
$$\operatorname{Cor}(\mathcal{I}_0, \mathcal{I}_1) = \frac{-11/144}{35/144} = -\frac{11}{35}.$$
Sampling and Point Inclusion Probabilities
A random subset $S$ of $[N]$ can be considered a random sample of $[N].$  Crucial in the statistical theory of estimating properties based on a sample are the (point) inclusion probabilities
$$\pi_i = \Pr(i\in S)$$
and joint inclusion probabilities
$$\pi_{ij} = \Pr(\{i,j\}\subset S).$$
They are the chances that element $i$ will appear in the sample and, for $i\ne j,$ the chances that both $i$ and $j$ appear together in the sample.
In our running example, we may directly compute the point inclusion probabilities.  For instance, consider $\pi_1.$  Because subsets $\alpha,\beta,\delta,\zeta$ are those that include $1,$ we may sum their chances $k/12$ to obtain
$$\pi_1 = \frac{1 + 1 + 3 + 2}{12} = \frac{7}{12}.$$
Notice that $\pi_{ii}=\pi_i.$  Generally,
$$\pi_{i,j} = \sum_{S:\{i,j\}\subseteq S} \Pr(S).$$
Here are the point inclusion and joint inclusion probabilities in the example as computed this way.
$$\begin{array}{cc}
i,j & \pi_{ij} \\
\hline
0,0 & \frac{5}{12}\\
1,1 & \frac{7}{12}\\
2,2 & \frac{7}{12}\\
0,1 & \frac{2}{12}\\
0,2 & \frac{3}{12}\\
1,2 & \frac{4}{12}
\end{array}$$
As we saw in the preceding section on correlations, the joint inclusion probabilities yield formulas for expectations, variances and covariances of any random variables created from the indicator $\mathbf I.$  These formulas are the basis of variance and standard error estimates for complicated surveys involving unequal inclusion probabilities and nonzero correlations (created, for instance, by stratification and other forms of hierarchical sampling schemes).

Code
Often, seeing programming instructions to carry out computations can be revealing.  The following R code performs all the calculations described here for the running example.  It then simulates $10^7$ such random sets and uses those results to estimate properties of the process.  Among other things, it estimates the mean and covariance as
$$E[\mathbf I] = \frac{1}{12}(5,7,7);\quad \operatorname{Cov}(\mathbf I) = \frac{1}{144}\pmatrix{35 & -11& 1\\ -11 & 35 & -1 \\ 1 & -1 & 35},$$
agreeing with all the example results.
https://en.wikipedia.org/wiki/Incidence_algebra explains the meanings and computations of the Zeta and Mobius arrays used to convert between the $k$ and $F$ columns in the first table.
#
# A sample space.
#
Omega <- c("alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta")
#
# The sets.
#
Sets <- list(alpha=c(0,1,2), beta=c(0,1), gamma=c(0,2), delta=c(1,2),
             epsilon=0, zeta=1, eta=2, theta=c())
#
# Indicator functions.
#
I <- as.matrix(expand.grid(0:1, 0:1, 0:1))[c(8, 4, 6, 7, 2, 3, 5, 1), ]
rownames(I) <- Omega
colnames(I) <- paste0("I", 0:2)
#
# A probability distribution.
#
k <- c(1,1,2,3,1,2,1,1); names(k) <- Omega
p <- k / sum(k)
#
# Set inclusion probabilities.
#
Zeta <- matrix(0, length(Omega), length(Omega), dimnames=list(Omega, Omega))
for (i in seq_along(Omega)) {
  for (j in i:length(Omega)) {
    Zeta[i, j] <- min(I[i,] >= I[j,])
  }
}
FF <- Zeta %*% p; colnames(FF) <- "F"
#
# Show how to compute the probability distribution from the inclusion probabilities.
#
Mobius <- solve(Zeta)
Pr <- Mobius %*% FF; colnames(Pr) <- "Pr"
#
# Display the first table.
#
df <- data.frame(Omega, I, k, F=round(12*FF,2), Pr=round(12*Pr, 2))
names(df) <- c("Omega", "I0", "I1", "I2", "k", "12*F", "12*Pr")
(df)
#
# Simulate the process.
#
set.seed(17)
S <- sample(Omega, 1e7, replace=TRUE, prob=p)
#
# Show the first few sets generated.
#
(Sets[head(S)])
#
# Estimate means, the covariance matrix, and the correlation matrix.
#
mu <- colMeans(I[S, ])
Sigma <- cov(I[S, ])
Rho <- cor(I[S, ])

round(mu*12, 2)     # Compare to the worked example
round(Sigma*144, 1) # Ditto
round(Rho, 3)       # Ditto
#
# Point inclusion probabilities.
#
Pi <- crossprod(I[S,]) / length(S)
round(Pi*12, 2)
```

Comment: Thank you so much for the informative answer and code makes complete sense!

Definition of point processes


Use of Multiple "if and only if" statements

Question: I apologize in advance if this question is too basic to warrant a post. I just ran into the following question:
Let $f: A \to B$. If $A$ and $B$ are finite sets with the same number of elements, then $f: A \to B$ is bijective if and only if $f$ is injective if and only if $f$ is surjective.
The use of two "if and only if" statements has confused me; I am not exactly sure what I am trying to prove. I understand the function concepts being presented in the question, but I'm just not sure what I need to show. Therefore, I ask not for hints toward the solution of the question, but only the meaning of the question.
Thanks!
Comment: +1 for your nice question. May I ask why did you remove [this](http://math.stackexchange.com/q/428680/8581) ? I voted it to be undelete again and think it deserves to be alive again here at the site. Keep it on. Thanks.
Answer: The question is precisely equivalent to the following question:

Let $f:A\to B$, where $A$ and $B$ are finite sets with the same number of elements. Show that the following three statements are equivalent:

$f:A\to B$ is bijective.
$f:A\to B$ is injective.
$f:A\to B$ is surjective.

In other words, given the hypotheses, each of the three statements implies and is implied by each of the others.
Answer: This sentence is the same as saying that the three statements are equivalent (after all, "if and only if" is the same as logical equivalence).  Usually you'd see it written like this:
The following are equivalent (or, TFAE for short):
(1) $f$ is bijective,
(2) $f$ is injective,
(3) $f$ is surjective.
A nice way to prove these is circularly; show that (1) implies (2), that (2) implies (3), and that (3) implies (1).  Of course, you could rearrange the statements if certain implications are easier to prove than others.


SMS raw pdu in Android

Question: 1) Is there any way that I can send a raw SMS PDU from an Android device?
Or,
2) are there any classes available that can give me access to the PDU headers (for example TP-DCS) so that I can construct the PDU as I like?
I have searched the net and found:
http://www.androidjavadoc.com/1.0_r1_src/com/android/internal/telephony/gsm/ISms.html
but the above classes are private and as such are not available to me(haven't actually understood why).
Is what I'm asking possible in any way or not? If not then why can't I have that kind of functionallity?
Thanx
Answer: This is a requested feature for the public API.
The developer comments hint at using the sendRawPdu from the internal SMSDispatcher API, which can be done via reflection. However, the use of private APIs for production code is highly discouraged
It is not clear if it's possible to send using the public TelephonyManager API.
/*
 * TODO(cleanup): It looks like there is now no useful reason why
 * apps should generate pdus themselves using these routines,
 * instead of handing the raw data to SMSDispatcher (and thereby
 * have the phone process do the encoding).  Moreover, CDMA now
 * has shared state (in the form of the msgId system property)
 * which can only be modified by the phone process, and hence
 * makes the output of these routines incorrect.  Since they now
 * serve no purpose, they should probably just return null
 * directly, and be deprecated.  Going further in that direction,
 * the above parsers of serialized pdu data should probably also
 * be gotten rid of, hiding all but the necessarily visible
 * structured data from client apps.  A possible concern with
 * doing this is that apps may be using these routines to generate
 * pdus that are then sent elsewhere, some network server, for
 * example, and that always returning null would thereby break
 * otherwise useful apps.
 */

/**
 * Get an SMS-SUBMIT PDU for a destination address and a message
 *
 * @param scAddress Service Centre address.  Null means use default.
 * @return a SubmitPdu containing the encoded SC
 *         address, if applicable, and the encoded message.
 *         Returns null on encode error.
 * @hide
 */
public static SubmitPdu getSubmitPdu(String scAddress,
        String destinationAddress, String message,
        boolean statusReportRequested, byte[] header) {

In conclusion:
It's not clear if it's possible. I have the same question as you.
Comment: After so much time and after being able to log in to my account again. Thanks very much for the answer!
Answer: I know how. http://www.silentservices.de/products/android-hushsms/ and xposed framework http://repo.xposed.info/module/de.robv.android.xposed.installer
You'll need to root your phone to make use of the the xposed module 'raw-pdu', but it works. Hush-sms provides the api functionality / extensibility to send the 7 raw sms types.
Comment: When I posted this question I was hopping for a solution that doesn't involve rooting so that the app you develop can work/be installed seamlessly in almost every phone. As it seems, there is no such solution available. Eventhough I don't have the time to check right now I will upvote your answer as it looks like a nice alternative/workaround for people that are still interested.

SMS raw pdu in Android


Linear mixed model as discriminative model

Question: I just started learning about linear mixed models and was curious about using a linear model as a discriminative model. This example comes from Linear Mixed Models for Longitudinal Data - Verbeke.
In this dataset, the results of an experiment on the effect of a testosterone inhibitor on the craniofacial growth is recorded. There were 50 rats in the study where they were randomized to control group, low dose, and high dose group. The model used in the book assumes subject-specific intercepts as well as slopes:
$$
Y_{ij} = (\beta_0 + b_{1i}) + (\beta_1 L_i + \beta_2 H_i + \beta_3 H_i + b_{2i})t_{ij} + \epsilon_{ij}, \quad j = 1,\ldots,n_i
$$
Say we have a new rat's response (Show in blue in the graph below) but do not know which group it was in (not very realistic but just to illustrate the question). Can we use a linear mixed model to predict which group it comes from, e.g. use the linear mixed model as discriminative model? Does this extend if we have more than one fixed effect?
I saw there was at least one paper that described it but could not read it behind a paywall:
Discriminant analysis using a multivariate linear mixed model with a normal mixture in the random effects distribution (2010)
The code below shows the model for the linear mixed model with predictions shown with the red line and the "new" rat which we want to classify in blue.
library(lme4)
library(ggplot2)
library(effects)

set.seed(13)

rats <- read.csv("rats01.txt",sep="\t")
rats$TIME2 <- log(1+(rats$TIME-45)/10);
rats$SUBJECT <- as.factor(rats$SUBJECT)
rats$GROUP <- as.factor(rats$GROUP)
levels(rats$GROUP) <- c("Control", "Low Dose", "High Dose")

# This model has fixed effects only for the interaction
fit1.lmer <- lmer(RESPONSE ~ TIME2:GROUP + (1 + TIME2|SUBJECT),data=rats)

# Create a new rat which we want to determine which group it is in
fixed_ef <- fixed.effects(fit1.lmer)
time <- seq(50, 110, by = 10)
time2 <- log(1 + (time - 45) / 10)
# Coefficients from low dose group, with some noise.
new_rat <- data.frame(
  RESPONSE = fixed_ef[1] + fixed_ef[2] * time2 + rnorm(length(time2), 0, 2),
  TIME2 = time2
  )

new_rat

ee <- as.data.frame(Effect(c("GROUP", "TIME2"), fit1.lmer))
ggplot() +
  theme_bw() +
  facet_wrap(vars(GROUP), nrow = 2) +
  geom_line(aes(x = TIME2, y = RESPONSE, group = SUBJECT), alpha = 0.3, data = rats) +
  geom_line(aes(x = TIME2, y = fit), color = "red", data = ee) +
  geom_line(aes(x = TIME2, y = RESPONSE), color = "blue", data = new_rat) +
  geom_ribbon(aes(x = TIME2, ymin=lower,ymax=upper),colour=NA,alpha=0.2, fill = "red", data = ee)

Answer:
Can we use a linear mixed model to predict which group it comes from, e.g. use the linear mixed model as discriminative model?

Linear mixed models can be used as the first step in a 2-stage process to perform classification, based on multivariate clustered data. The basis for such clustering is a mixture of multivariate generalized linear mixed models.
This has been implemented in R, by the first-named author of the journal article you linked to, called mixAK utilising a Bayesian framework, and is based on prior work, published by the same author (Komarek & Komarkova, 2013). The package is documented as usual on CRAN and also has a paper available for free in the Journal of Statistical Software.

Does this extend if we have more than one fixed effect?

Yes, multiple fixed effects are supported.
References:
Komarek A & Komarkova L (2013). Clustering for Multivariate Continuous and Discrete
Longitudinal Data." The Annals of Applied Statistics, 7(1), 177{200.
Komárek, A. and Komárková, L., 2014. Capabilities of R package mixAK for clustering based on multivariate continuous and discrete longitudinal data. Journal of Statistical Software, 59(1), pp.1-38.


Change path of uploaded files in zip

Question: I've a form that allow the customer to download every photos that a photograph uploaded before.
Here is my submit form :
<code> public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $parameters = \Drupal::routeMatch()->getParameters();
    $shooting = Node::load($parameters->get('shooting_id'));

    $destination = \Drupal::service('file_system')->realpath('temporary://');

    $zipname = $destination . '/vos_photos_'.$shooting->id().'.zip';

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));

    $zip = new \ZipArchive();

    $zip->open($zipname, constant("ZipArchive::CREATE"));

    foreach ($shooting->field_shooting_photos as $media) {

      $uri = $media->entity->field_media_image->entity->uri->value;
      $file_path = \Drupal::service('file_system')->realpath($uri);

      // Ajout de chaque fichier dans le zip //
      $zip->addFile($file_path, $media->entity->field_media_image->entity->name);

    }

    $zip->close();

    readfile($zipname);
    exit;

  }
</code>
This works great.
The only problem is when I unzip it, I get var/www/drupalvm/web/sites/defaults/files/{My content}
I would like to just have a simple folder files/{my content} without the long path before, or if it's not possible, simply {my content} when you extract the zip. Thank you
I'm pretty the problem can be solved in the addFile by giving a localname, I just can't figure out how to
Answer: I finally found the solution, instead of
<code>$zip->addFile($file_path, $media->entity->field_media_image->entity->name);
</code>
I simply put
<code>$zip->addFile($file_path, basename($file_path));
</code>
and it does the job.

Change path of uploaded files in zip


How to schedule the execution of a Rules Action based on a webform submission date field?

Question: How do I schedule the execution of a Rules Action based on a webform submission date field?
I have installed Webform Rules so I am able to use the Rules Event Webform submitted  to trigger the execution of a Rules Action. In my case, I want to schedule the execution of the Rules Action based on the date input of a webform field.
I have no problem scheduling the execution using node:creation time, but I need to use the date the user inputs.
I have not found any data-selector that let's me do this.
Any hint's will be much appreciated.
EDIT: I have found a link on StackOverflow that seems related to what I want to achieve.
https://stackoverflow.com/questions/5192108/how-do-i-schedule-a-rule-using-fields
That would reduce my question to : how do I use the Entity has field on a webform in order to make the field available ?
Comment: [rules_forms](http://drupal.org/project/rules_forms) does not pertain to webforms
Comment: I haven't tried this module myself nor do i know if you have already; but, this maybe what you need: http://drupal.org/project/rules_forms
Comment: I have installed this module but no new _Data selectors_ appear under the _Scheduled evaluation date_ field.
Comment: drcelus: check that link, it is referencing a work-around for a Rules bug that was actually fixed in March 2011
Comment: Merci (thank you) for the accept (and upvote) of my  (late) answer ... Too bad I seemed to have missed some bounty when you first posted this question ...
Answer: I'm not really familiar with Rules but this might be a step in the right direction.
If node:created worked you could give http://drupal.org/project/webform_tokens a try, it should define tokens for your form components, however I'm not sure if the date will be in the correct format.
If it's not in the correct format you could alter it for the compontent in a presave hook.
function hook_webform_submission_presave($node, $submission) {
  // Use dpm() to find out how the date is formatted, and make it into a timestamp.
  $date = strtotime($submission->data['COMPONENT_ID']['value'][0]);
  $submision->data['COMPONENT_ID']['value'][0] = $date;
}

Now you have altered the data for the submisison, converting a date into a timestamp which should then be used through webform_tokens just like node:created.
Comment: I tried to use webform_tokens on my site but it has integration issues when I tried to use it with the Rules module.  I can't wait for the module to become more stable.
Answer: Edit:  Okay, re-read the question and I totally missed the point.  Removed all the stuff about e-mail processing.
Step #1: Create a hidden field "processed" which can be used to make sure it only gets processed once
Step #2: create a condition, Execute PHP code:
<?php

  // Load the webform by its Node ID
  $webform = node_load(123);

  // Load the webform's submissions by the Node ID
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submissions = webform_get_submissions(123);

  // The submission array uses component ids,
  //   so search through the webform and reference component ids by their field name
  foreach($webform->webform['components'] as $component_id => $component)
  {
    if ($component['form_key'] == 'processed')
    {
      $processed_comp_id = $component_id;
    }
    elseif ($component['form_key'] == 'date')
    {
      $date_comp_id = $component_id;
    }
    elseif ($component['form_key'] == 'time')
    {
      $time_comp_id = $component_id;
    }
  }

  // Check all submissions and see if any need to be processed
  foreach($submissions as $submission)
  {
    // First check if the submission has already been processed
    if (isset($submission->data[$processed_comp_id]) &&
        empty($submission->data[$processed_comp_id]['value'][0]))
    {
      // Check the Scheduled Release time
      if (isset($submission->data[$date_comp_id]) && isset($submission->data[$time_comp_id]))
      {
        if (!empty($submission->data[$date_comp_id]['value'][0]) ||
            !empty($submission->data[$time_comp_id]['value'][0]))
        {
          $now = date("U"); // Current UNIX timestamp
          // Check if the current time is still prior to the scheduled time
          if($now < strtotime($submission->data[$date_comp_id]['value'][0]." ".
                                   $submission->data[$time_comp_id]['value'][0]))
          {
            // If it is, continue on to the next submission
            continue;
          }
        }
      }

      // Set the submission to successfully sent, and then update it
      $submission->data[$processed_comp_id]['value'][0] = 1;

      // If it couldn't be updated, change e-mail settings to notify of the error
      if (!webform_submission_update($webform, $submission))
      {
        $email_to = "email@example.com";
        $email_subject = "Error processing scheduled webform rule";
        $email_message = print_r($submission,true);
      }

      // Return True so that it passes the condition
      return true;
    }
  }

?>

Comment: Totally missed your question and had all this fancy stuff for e-mailing.  This should accomplish what you need.
Comment: I found this workaround a bit of an overkill. I would like to solve this without having to _hardcode_ so much. Thanks anyway.
Comment: Meh.  If there was an easier way I'd like to use it on our system as well.
Answer: Turns out the webform submission data is wrapped with it's own type and thus the date fields from webform submissions are not recognized as Dates by the Rules module.
The only workaround I found was to turn my webform into a different node type and use Views to emulate the webform results. The date fields in my custom node types are recognized by the rules module and I can schedule the mails to send.
There is an open issue on d.o. to change the way webform stores it's data.
Answer: The "clue" to what you're trying to get to work, is that you have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

All that's left to fully answer your question is to have your rule use similar tokens.
For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.
Answer: Shooting in the dark, but perhaps the Entity API module's "Entity Token" sub-module would help. Here is a quote about that sub-module (from the module's project page):

... makes sure there are tokens for most entity properties and fields, i.e. it provides token replacements for all entity properties (or fields) that have no tokens and are known to the entity module.
Comment: I already have this module activated. The problem is I need access to a webform date field to schedule an action.
Answer: I believe what you are trying to do is not possible. The reason being that webform submission data are not stored in the database. Therefore you can access the webform data only on a event like "When a form is submitted."
But maybe you could give a little more information on the field you are trying to create a rule frοm. Is it a field that you could possible write to a user's profile so you can have access to it without the need to know the sid of the submission? Maybe after saving it to the profile you could find another way to create a rule around that specific field now that is linked exclusively to the user that submitted the form.
Comment: Every form submission data _is_ stored on the data base. The user field is a hack I may consider, thx.
Comment: Yes the submission data is stored to the database but with no easy way of retrieving them through drupal. If you are going to code something like this yourself then you could add a cron job to run and parse through all you submission data and retrieve the specified field. If you are using drupal 6 do check Webform MySQL Views as you might find it useful later on http://dev.nodeone.se/node/666


String to Hashtable

Question: I wrote a simple program which reads IpTables log results , remove 90% of the output , and what is left is:
192.168.1.1 152
192.168.1.1 17485
192.168.1.1 5592

Where, the first column contains source IP , the second one destination Port. Those values are stored in a string. I would like to transfer the values from that string to a Hashtable, but I don't have any idea how.
Hashtable<String, String> IpDpt = new Hashtable<String, String>();

        hmIpDpt.put(IP1,DPT1);
        hmIpDpt.put(IP1,DPT2);
        hmIpDpt.put(IP1,DPT3);
        hmIpDpt.put(IP2,DPT4);

Comment: Use a HashMap instead..Hashtable was deprecated long ago...
Answer: if you transferred to hashtable then you will not have all the logs available because hashtable does not allows duplicate values and in your log there may be chances of duplicate values . so hashtable overrides values.
Comment: This is not exactly an answer though.
Comment: Please add this as a hint in the comments section.
Answer: Try this program.
String info = "192.168.1.1 152";
    Hashtable<String, List<String>> IpDpt = new Hashtable<String, List<String>>();
    String[] values = info.split( " " );
    String key = values[0];
    String value = values[1];
    if ( IpDpt.containsKey( key ) )
        IpDpt.get( key ).add( value );
    else
        IpDpt.put( key, new ArrayList<String>( Arrays.asList( value ) ) );

To check whether the key has at least 100 values
if(IpDpt.containsKey( key ) && IpDpt.get( key ).size() >=100)
{
    // business logic here
}

Comment: I should be reading my results live from a string , and deciding whether one 1 IP address is checking more than 100 ports on my machine... So the values from the string should go the the hasmap and I should check wheter the key has at least 100 values.
Comment: You can put extra check to check if the key has at least 100 values.

if(IpDpt.containsKey( key ) && IpDpt.get( key ).size() >100)
{
  // business logic here
}
Comment: Also you can replace List with Set if there are duplicate entries for the port number with same IP address. Like 192.168.1.1 152 entry is multiple times.
Answer: For every line you read, split the string on space like that:
    String line = "192.168.1.1 152";
    String[] parts = line.split(" ");
    you_map.put(parts[0], parts[1]);

That should do it.
Comment: But this does not allow n:m mappings of IPs to ports. Note that the same IP address might appear multiple times!
Answer: A Map cannot hold multiple values per key. So you should either use a third party library that offers something like a MultiMap, or use a Set to hold the values:
Map<String, Set<String>> ipToPortMap = new HashMap<>();

public void addEntry(String ip, String port) {
    Set<String> ports = ipToPortMap.get(ip);
    if (ports == null) {
        ports = new HashSet<>();
        ipToPortMap.put(ip, ports);
    }

    ports.add(port);
}

Now just iterate over your input (maybe using a Scanner) and call addEntry.
Answer: Use Guava Multimap to allow duplicate key.
  Multimap<String,String> multimap=ArrayListMultimap.create();

  //put your ips and port.

String to Hashtable


specify ractive animation on view

Question: Consider such a code (available live at http://jsfiddle.net/w1n3rqvc/1/):

//js code
var viewModel={
    opacity: 0
};

var ractive = new Ractive({ el: 'root', template: '#rootTemplate', data: viewModel, magic: true, lazy: true });
ractive.on('click', function(){
    ractive.set("opacity", 0.0);
    ractive.animate("opacity", 1.0, {duration: 1000});
});

This works. But please note that on the js side (view model) I specify values that should be part of the view, not view model: first that anything should be animated at all, secondly that the duration should be one second. On the view model side I would expect to have only a boolean variable that would turn into animation on the view side. Or fire an event that would trigger the animation. But certainly the view model should not know that there will be any animation at all.
So how should it be done properly with ractivejs? With knockoutjs I would have used a custom binding to accomplish the task.
Answer: Just noticed this question from quite awhile ago. In this example, you could just run the animation from the template (see http://jsfiddle.net/w1n3rqvc/5/):

<input type="button" value="Click me!"
       on-click="animate('opacity', 1, { duration: 1000 })">

For more complex uses, you could look at using a custom event or a decorator to separate that code from the controller/view model.

specify ractive animation on view


Open Links with Java On Other Computers

Question: So I'm currently programming a game right now where I want to create in-game voting. I managed to get sites to pop up, however, they don't pop up on the player's computer, but rather the server. I was wondering how to make it pop up on another person's computer...
<code>    public static void openLink(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>
This currently of course opens the link on the server. I have methods to retrieve the player's client, but what exactly do I have to do to be able to do this?
I'm deving a game called Maplestory right now for educational purposes. I'm not too versed with dealing with anything concerning network, but I assume posting some code pertaining to the client might help.
<code>public MapleClient(MapleAESOFB send, MapleAESOFB receive, IoSession session) {
    this.send = send;
    this.receive = receive;
    this.session = session;
}
</code>
That's the constructor class for the client. I know there's not enough information, but if it's requested I can continue to add more until it's solved. I tried looking online for help, but I have no clue.
Answer: If you could post what game, the engine used, the server technology used, etc, we might be able to help more.
In general, this process is going to be a bit more involved than just a few lines of code on the server. As you've noticed, any action you take on the server is only going to happen on the server unless you architect it out.
Step one is to host your voting site somewhere/somehow (looks like you're already doing this.
Step two is to link this voting site to the clients somehow, so they know when/where to go.
After notifying the clients that they need to open the link, you need to actually open the link on each client.
I'd assume you already have the logic for sending the result back to the server in place based on your answer.
If you can post more details about the architecture of your project, it might be possible to give more specific help, but this isn't something that there is a built-in solution for, as far as I'm aware.
Comment: I'll continue adding edits until there seems to be an adequate amount of information. I'm not too versed with networking.
Comment: And yes I do. I have a method of retrieving it (API from the voting site).

Open Links with Java On Other Computers


Some equivalences for Ideals of the ring of real valued functions

Question: Let $I_{N}=\{f\in\Omega(\Bbb R,\Bbb R)|\forall x \in N\subset \Bbb R: f(x)=0\}$, where $\Omega(\Bbb R,\Bbb R)=\{f:\Bbb R \to \Bbb R|f\space is \space a\space function\}$, then the following statements are equivalent:

1) $I_{N}$ is a maximal Ideal
2) $I_{N}$ is a prime Ideal
3) $|N| = 1$

I could do 1) -> 2) by contradiction, but now I don't know how to continue, can somebody help me please?
Answer: For $2) \implies 3)$, assume that $I_N$ is prime, but $N$ has two distinct points $x, y$. Construct functions $f, g$ that don't belong to $I_N$, but their product does. (Hint: let $f$ be zero on $x$, but not on $y$).
For $3) \implies 1)$, note that if $A \subset B$, then $I_B \subset I_A$, and the latter inclusion is strict whenever the former is.


Wildcard DNS setting in Windows Server 2008 R2 DNS Server not working

Question: We've got a windows server 2008 R2 DNS server that we are trying to setup a wildcard DNS entry in. So we want proxy.domain.com and *.proxy.domain.com to go to the same IP. Right now, it seems as if the windows server has registered the actual asterisk as the subdomain. So *.proxy.domain.com resolves to the right IP but something like login.proxy.domain.com doesn't.
This seems to be a problem specifically with 2008 because we were able to get this working on a 2003 server. Has anyone come across this yet?
Answer: Try using dnscmd
dnscmd servername /recordadd proxy.domain.com * A IPAddress
http://support.microsoft.com/default.aspx?scid=kb;en-us;840687
Answer: The DNS Console GUI just happens to present it as though it is a subdomain though in fact it is not.  If you look at the true data by doing a conventional zone transfer, for example, you will see that the wildcard RR is there.