C++: Why Position constructor are called when the argument type does not match?

Question: This will be a bit lengthy but anyhow i tried my best to simplify it using code.
I am building a binary tree but noticed something peculiar.

linked_binary_tree.h

#ifndef LINKED_BINARY_TREE_H
#define LINKED_BINARY_TREE_H

#include <iostream>
#include <list>
using namespace std;

typedef int Elem;

class LinkedBinaryTree {

protected:

    struct Node {
        Elem ele;
        Node *par;
        Node *left;
        Node *right;
        Node(): ele(), par(NULL), left(NULL), right(NULL) {}
    };

public:

    class Position {
        friend LinkedBinaryTree;
        private:
            Node *v;
        public:
            Position(Node *_v=NULL): v(_v) { cout << "Position constr" << endl;}
            Elem &operator*() const {
                return v->ele;
            }
            Position left() const {
                return Position (v->left);
            }
            Position right() const {
                return Position (v->right);
            }
            Position parent() const {
                return Position(v->par);
            }
            bool isRoot() const {
                return v->par==NULL;
            }
            bool isExternal() const {
                return v->left==NULL && v->right==NULL;
            }
    };

    typedef list<Position>  PositionList;

    LinkedBinaryTree();
    int size() const;
    bool empty() const;
    Position root() const;
    PositionList positions(int trv) const;
    void addRoot();
    void expandExternal(const Position &p);
    Position removeAboveExternal(const Position &p);

protected:
    void preorder(Node *v, PositionList &pl) const;
    void postorder(Node *v, PositionList &pl) const;
    void inorder(Node *v, PositionList &pl) const;

private:
    Node * _root;
    int n;

};

#endif

linked_binary_tree.cc

#include <iostream>
#include <list>
#include "linked_binary_tree.h"
using namespace std;

LinkedBinaryTree::LinkedBinaryTree(): _root(NULL), n(0) {}

int LinkedBinaryTree::size() const {
    return n;
}

bool LinkedBinaryTree::empty() const {
    return size()==0;
}

LinkedBinaryTree::Position LinkedBinaryTree::root() const {
    cout << "LinkedBinaryTree::root()" << endl;
    return Position(_root);
}

void LinkedBinaryTree::addRoot() {
    _root=new Node;
    n=1;
    _root->ele=n;
}

void LinkedBinaryTree::expandExternal(const Position &p) {
    Node *v = p.v;
    v->left=new Node;
    v->left->par=v;
    v->left->ele=++n;
    v->right=new Node;
    v->right->par=v;
    v->right->ele=++n;
}

LinkedBinaryTree::PositionList LinkedBinaryTree::positions(int trv) const {
    PositionList pl;
    if (trv==1)
        preorder(_root,pl);
    else if (trv==2)
        inorder(_root,pl);
    else postorder(_root,pl);
    return PositionList(pl);
}

void LinkedBinaryTree::preorder(Node *v, PositionList &pl) const {
    pl.push_back(Position(v));
    if (v->left!=NULL)
        preorder(v->left,pl);
    if (v->right!=NULL)
        preorder(v->right,pl);
}

void LinkedBinaryTree::postorder(Node *v, PositionList &pl) const {
    if (v->left!=NULL)
        preorder(v->left,pl);
    if (v->right!=NULL)
        preorder(v->right,pl);
    pl.push_back(Position(v));
}

void LinkedBinaryTree::inorder(Node *v, PositionList &pl) const {
    if (v->left!=NULL)
        preorder(v->left,pl);
    pl.push_back(Position(v));
    if (v->right!=NULL)
        preorder(v->right,pl);
}

linked_binary_tree_main.cc

#include <iostream>
#include "linked_binary_tree.h"
using namespace std;

int main() {

    LinkedBinaryTree lbt;
    lbt.addRoot();
    cout << "post addRoot()" << endl;
    LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root()); // --> STATEMENT 1
    cout << "post lbt.root()" << endl;
    //LinkedBinaryTree::Position pr = lbt.root();  // --> STATEMENT 2
    lbt.expandExternal(pr);
    cout << "LinkedBinaryTree.size() :- " << lbt.size() << endl;

    // 1-preorder 2-inorder 3-postorder
    auto iter=lbt.positions(3);
    auto cbeg=iter.cbegin();
    auto cend=iter.cend();

    for (; cbeg!=cend; cbeg++) {
        cout << cbeg->operator*() << " ";
    }
    cout << endl;

    return 0;

}

Results executing linked_binary_tree_main

post addRoot()
LinkedBinaryTree::root() --> STATEMENT 3
Position constr --> STATEMENT 4
post lbt.root()
LinkedBinaryTree.size() :- 3
Position constr
Position constr
Position constr
2 3 1

Note:

Statement 1

LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root()); // --> STATEMENT 1

a. The lbt.root() actually returned LinkedBinaryTree::Position instance.
b. There is no LinkedBinaryTree::Position constructor which takes in a Position instance.   Instead it has the following:

Position(Node *_v=NULL): v(_v) { cout << "Position constr" << endl;}

which is it takes a pointer to a Node argument. Yet STATEMENT 1 works showing that LinkedBinaryTree::Position(Node *v) constructor is called.
c. If you comment out STATEMENT 1 and use STATEMENT 2 that of course would work as well.
So why does STATEMENT 1 works?
Appreciate any insight.
Thanks.
Comment: The answer you accepted is exactly the hint I gave you in what you were not tracking -- the copy constructor.
Comment: *This will be a bit lengthy* -- In all honesty, you could have removed vast chunks of that code if your only concern is which constructor gets called.  It doesn't matter if the internals of those classes are building a binary tree -- that's all noise that could have been eliminated.
Comment: @PaulMcKenzie Sorry for that. Thought might as well put all in since at times there's been request for all the codes so that reviewer can test it out themselves. So any insight?
Comment: On an unrelated note: [`using namespace std;` is a bad habit](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) in normal cases. Doing it in a header file should be considered plain wrong.
Comment: @yapkm01 -- `LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root());` You are not testing all the possible constructors, such as the copy constructor for `Position`.  Also, `Position root() const;` -- the `root` member function returns a copy of the instance, not the actual instance.
Comment: @PaulMcKenzie Look at the results - STATEMENT 4. That is the output from the LinkedBinaryTree::Position(Node *v). So this constructor was executed from STATEMENT 1.
Comment: You asked about statement 1, and why does it "work" (whatever "work" means).  And to that, why not run your code in a debugger to see the chain of events that causes statement 1 to "work"?
Comment: @PaulMcKenzie What i am trying to say is simply this. STATEMENT 1  LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root()); when invoked called the LinkedBinaryTree::Position(Node *v). STATEMENT 4 which is the output of LinkedBinaryTree::Position(Node *v) constructor proves it. Issue is the argument between them is different.
Answer: The constructor you're seeing is not the one you think it is.
The constructor in STATEMENT 1 is the (compiler-generated) copy-constructor.
The constructor printing the output Position constr happens in the LinkedBinaryTree::root function:
return Position(_root);

This was much easier to see once I created a more minimal example (together with some extra output).


sum of the series and infinity

Question: If we have a series of numbers $$1^5 + 2^5 + 3^5 + \cdots + (10^n)^5.$$ Final sum of the series is approximately equal $16666\ldots$ .
If  there is more and more numbers in the series is the result of closer and closer to $16666\ldots$ .
For example if the last number $1000$ or $10000$ or $100000$ and so on, the final sum is closer to $16666\ldots$ . then $n\to \mathbb{\infty}$ $$1^5 + 2^5 + 3^5 + \cdots(10^n)^5 = \frac 1 6 * (10^n)^6$$
Now same story, If we have a series of numbers $$1^{59} + 2^{59} + 3^{59} + \cdots + (10^n)^{59}.$$ Final sum of the series is approximately equal $16666\ldots$ .
If there is more and more numbers in the series is the result of closer and closer to $16666\ldots$ .
For example if the last number $1000$ or $10000$ or $100000$ and so on, the final sum is closer to $16666\ldots$ .  if $n\to \mathbb{\infty}$  then $$1^{59} + 2^{59} + 3^{59} + \cdots(10^n)^{59} = \frac 1 {60} * (10^n)^ {60}$$
Whether we can concludeif $n\to \mathbb{\infty}$ $$1^5 + 2^5 + 3^5 + \cdots + (10^n)^5 = 1^{59} + 2^{59} + 3^{59} + \cdots + (10^n)^{59}$$ srbija
Comment: Hello. What exactly is your question? Feel free to edit your post and include it.
Comment: What is this $16666\dots$? This is not a number. In my opinion all of this is just nonsense.
Comment: Using the identity $\sum\limits_{i=1}^ki^5=\frac16k^6+$some terms in $k^5$ for $k=10^n$ shows that the result is $\frac1610^{6n}+$some rest of order $10^{5n}$, thus the leading part $166666\cdots$ of the base-$10$ expansion with $n$ or $n-1$ successive $6$s. Likewise with the exponent $59$ since $\sum\limits_{i=1}^ki^{59}=\frac1{60}k^{60}+$some terms in $k^{59}$.
Answer: Your answer is yes. However, both sums are all equal to $+\infty$ which is not actually a real number!
Answer: Which do you think is closer to 16666: 16666666666, or 20000?
As $n$ tends to infinity, the sum
$f(n) = 1^{59} + 2^{59} + 3^{59} + \cdots + (10^n)^{59}$ will grow
much, much faster than $g(n) = 1^{5} + 2^{5} + 3^{5} + \cdots + (10^n)^{5}$.
As noted in a comment, for large enough $n$,
$f(n)$ is approximately $\frac{1}{60} 10^{60n}$ whereas
$g(n)$ is approximately $\frac16 10^{6n}$.
That is,
$$\frac{f(n)}{g(n)} \approx \frac{\frac{1}{60} 10^{60n}}{\frac16 10^{6n}}
   = 10^{54n - 1}.$$
That's a very big difference in my opinion. Another way of looking at it is,
$$\lim_{n\to\infty} \frac{1^{5} + 2^{5} + 3^{5} + \cdots + (10^n)^{5}}
{1^{59} + 2^{59} + 3^{59} + \cdots + (10^n)^{59}} = 0.$$
So I would not say these are at all equal, except in the limited sense
that both grow without bound as $n$ tends to infinity.
But in that sense—that is, if you care only that both quantities
go toward the same "value", regardless of how quickly they go
toward it—you might as well say that as $n\to\infty$,
$$1^{5} + 2^{5} + 3^{5} + \cdots + (10^n)^{5}
\;\mathop{\unicode{x201C}\!=\!\unicode{x201D}}\; \sqrt n,$$
because
$\lim_{n\to\infty} 1^{5} + 2^{5} + 3^{5} + \cdots + (10^n)^{5} = \infty$
and $\lim_{n\to\infty} \sqrt n = \infty$.
(Notice the quotation marks around one of the equality (=) signs above,
indicating a place where I would not normally set an equality sign.)

sum of the series and infinity


Inject CDI não esta funcionando com produtor em um projeto .jar

Question: Criei um produtor de EntityManager em um projeto .jar mas o mesmo não funciona.
Configurei o POM.XML com a dependencia abaixo

<dependency>
   <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>1.2</version>
</dependency>

Criei um arquivo beans.xml vazio em  src/main/resources/META-INF
Criei um arquivo produtor conforme abaix
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JpaUtil {

    private static final String PERSISTENCE_UNIT = "PEROLAWEB";

    private static ThreadLocal<EntityManager> threadEntityManager = new ThreadLocal<EntityManager>();

    private static EntityManagerFactory entityManagerFactory;

    @Produces
    public EntityManager geraEM(){

        System.out.println("\n---------- injectou EntityManeger Criou ");

        if( entityManagerFactory == null || !entityManagerFactory.isOpen()) {
            entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
        }

        EntityManager entityManager = threadEntityManager.get();
        if(entityManager == null || !entityManager.isOpen() ) {
            entityManager = entityManagerFactory.createEntityManager();
            JpaUtil.threadEntityManager.set(entityManager);
        }
        return entityManager;
    }

    public void finaliza(@Disposes EntityManager entityManager) {

        System.out.println("\n---------- destruiu EntityManeger Criou ");
        if(entityManager!=null){
            EntityTransaction entityTransaction = entityManager.getTransaction();
            if(entityTransaction.isActive()){
                if(entityTransaction.getRollbackOnly()) {
                    entityTransaction.rollback();
                }else{
                    entityTransaction.commit();
                }
            }
            entityManager.close();
            threadEntityManager.set(null);
        }
    }

}

Fiz o teste abaixo mas retorna:

java.lang.NullPointerException na linha entityManager.getTransaction().begin();**

import javax.inject.Inject;
import javax.persistence.EntityManager;
import org.junit.Assert;
import org.junit.Test;

public class TesteEntityManagerFactory {

    @Inject
    private EntityManager entityManager;

    @Test
    public void testeDeConexao(){
        entityManager.getTransaction().begin();
        Assert.assertTrue(entityManager.getTransaction().isActive() );
    }

}

Comment: Quando você executa o jUnit o CDI  não é inicializado, logo os objetos não são instanciados.  Use o jGlue para testar, segue: http://jglue.org/cdi-unit/. Adiciona a dependência e segue esse tutorial de uso: http://jglue.org/cdi-unit-user-guide/.
Comment: Blz. Coloquei uma resposta para deixar registrado e ajudar outros que tem o mesmo problema. Abraços
Comment: Bem isso, Obrigado.
Comment: Veja se me ajudas.
Quanto não estou em @Test continua dando nullpointer
Comment: Você está colocando esse jar dentro de um container(wildfly, jboss, glassfish)?
Comment: Não neste momento. A ideia é criar um jar que vou utilizar em vários projetos war. Ou seja estou criando um projeto jar que o maven vai incluir num war
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/41462/discussion-between-adelmo00-and-marcelo).
Answer: O CDI precisa de um container para funcionar corretamente. Como você está executando testes com jUnit, não existe um container para o CDI. Para resolver isso, você pode usar o jGlue ou o Arquillian.
Se for usar o jGlue basta adicionar a seguinte dependência:
<dependency>
  <groupId>org.jglue.cdi-unit</groupId>
  <artifactId>cdi-unit</artifactId>
  <version>3.1.2</version>
  <scope>test</scope>
</dependency>

e colocar a seguinte anotação na sua classe de teste: @RunWith(CdiRunner.class)


Proof of Polynomial Identity

Question: I would like to prove the following identity:
$$\prod_{n=1}^\infty\frac{1+q^{3n}}{1-q^{2n}} = \frac{\prod_{k=1}^\infty(1-q^{6k-5})
(1-q^{6k-1})}{\prod_{m=1}^\infty(1-q^m)}.$$

From the components in $LHS$, $$\frac{1+q^{3n}}{1-q^{2n}} = \frac{1+q^{3n}}{(1+q^{n})(1-q^{n})}\\=\frac{(1+q^{n})(1-q^{n}+q^{2n})}{(1+q^{n})(1-q^{n})}\\=\frac{1-q^{n}+q^{2n}}{1-q^{n}}$$
Thus now I need to compare $1-q^{n}+q^{2n}$ and $(1-q^{6k-5})
(1-q^{6k-1})$, which is equal to $1-q^{6k-5}$.
How could I prove that $\prod_{n=1}^\infty(1-q^{n}+q^{2n}) = \prod_{k=1}^\infty (1-q^{6k-5})$?
Answer: $$
\prod_{m=1}^\infty (1-q^m) = \prod_{k=1}^\infty (1-q^{6k-5})(1-q^{6k-4})(1-q^{6k-3})(1-q^{6k-2})(1-q^{6k-1})(1-q^{6k}).
$$
$$
\begin{aligned}
&\frac{(1-q^{6k-5})(1-q^{6k-1})}{(1-q^{6k-5})(1-q^{6k-4})(1-q^{6k-3})(1-q^{6k-2})(1-q^{6k-1})(1-q^{6k})}\\
&=\frac{1}{(1-q^{6k-4})(1-q^{6k-3})(1-q^{6k-2})(1-q^{6k})}\\
&=\frac{(1-q^{6k})}{(1-q^{6k-4})(1-q^{6k-2})(1-q^{6k})(1-q^{6k-3})(1-q^{6k})}\\
&=\frac{(1+q^{3k})(1-q^{3k})}{(1-q^{6k-4})(1-q^{6k-2})(1-q^{6k})(1-q^{6k-3})(1-q^{6k})}.
\end{aligned}
$$
Starting from this, you need to claim that the term $(1-q^{3k})$ in the numerator cancels out "suitable terms" in the denominator.
Answer: Since $\;(1+x^3)/(1-x^2) = (1-x^6)/((1-x^2)(1-x^3)),\;$ all you need to do to prove the identity is to show that the infinite products are equal to $\;\prod_{n=1}^\infty (1-q^n)^{a_n}\;$ where $\;\{a_1,a_2,\dots\}\;$ is a period $6$ sequence with $\;a_n=0\;$ if $\;n\equiv 1,5\pmod{6}\;$ and $\;a_n=-1\;$ otherwise. Another way of stating this is $\;a_n=-1\;$ if $n$ is a multiple of $2$ or $3$ and $\;a_n=0\;$ otherwise. By the way, the infinite product is the generating function of OEIS sequence A007690 which states the second way.

Proof of Polynomial Identity


Why do we need PCA whitening before feeding into autoencoder?

Question: In the UFLDL tutorial, we saw that autoencoder can not compress data with uncorrelated random variables.
'If the input were completely random---say, each variable comes from an IID Gaussian independent of the other features---then this compression task would be very difficult.'
But, it is suggested to apply PCA whitening before feeding the data into autoencoder. Using PCA, the data can be represented using new orthogonal variables, which are uncorrelated.
Can the autoencoder compress the data using hidden layer after PCA preprocessing?
Comment: What is the UFLDL tutorial where "we saw" this? What is the autoencoder that you are using? What are you doing w/ it, are you predicting a known class for each pattern? Some more information would help here.
Comment: The UFLDL tutorial is here: http://ufldl.stanford.edu/wiki/index.php/Autoencoders_and_Sparsity.
Answer: Natural images have a lot of variance/energy in low spatial frequency components and little variance/energy in high spatial frequency components*. When using squared Euclidean distance to evaluate the reconstruction of an autoencoder, this means that the network will focus on getting the low spatial frequencies right, since the error scales with the variance of the signal. Whitening normalizes the variances so that the network gets punished equally for errors in low and high spatial frequencies.
Whitening effectively changes the objective function. Let $C$ be the covariance of the inputs and $W$ be PCA whitening,
\begin{align}
C &= QDQ^\top, & W &= D^{-\frac{1}{2}}Q^\top.
\end{align}
Further, let $x$ be some input, $\hat x$ be the output of the autoencoder and $y = Wx$ be the whitened signal. Then
\begin{align}
||y - \hat y||_2^2
&= ||W x - W \hat x||_2^2 \\
&= (Wx - W\hat x)^\top (Wx - W\hat x) \\
&= (x - \hat x)^\top W^\top W (x - \hat x) \\
&= (x - \hat x)^\top C^{-1} (x - \hat x) \\
&= ||x - \hat x||_{C^{-1}}^2.
\end{align}
That is, by optimizing $\hat y$ instead of $\hat x$, we are effectively optimizing a particular Mahalanobis distance instead of standard Euclidean distance.
*see http://tdlc.ucsd.edu/images/facescheung.jpg for an illustrative example of spatial frequencies
Answer: The tutorial only said "each variable comes from an IID Gaussian independent of the other features". Independence implies uncorrelation, but uncorrelation does not imply independence. Even if data get processed by PCA, features become uncorrelated, but it does not imply features become independent of each other.


Invariance of mutual information under invertible mapping

Question: If it is true then is there a reference of the fact that for discrete RVs X and Y the mutual information is invariant to the invertible mapping i-e
$I(X;Y)=I(X';Y')$ where $X'=h(X)$ and $Y'=g(Y)$ with $h$ and $g$ are invertible functions.
Answer: This is an almost trivial observation. Due to the invertible mappings considered, the random variables $X$, $X'$, $(X, X')$ are equivalent in terms of entropy as well as information they provide about $Y$ (or, equivalently, $Y'$, $(Y,Y')$).
A bit more formally, it holds
$$
\begin{align}
I(X;Y) &= I(X, X'; Y, Y')\\
&=H(X,X')-H(X,X'|Y,Y')\\
&=H(X')-H(X'|Y')\\
&=I(X';Y')
\end{align}
$$
The steps are intuitive, but you may want to explicitly prove them by computing the standard entropy expressions using the (joint) probability distributions of the quantities involved.


How to retrieve text from a select input option with java spring

Question: I have a JSP with a select input in a form, like so:
<form method="post" action="/confirm">
  <select id="dropdown" name="dropdown">
    <option value="1">1st choice</option>
    <option value="2">2nd choice</option>
    <option value="3">3rd choice</option>
  </select>
  <input type="submit" value="submit" name="submit" />
</form>

I have a spring controller that handles this form as follows:
@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirm(@RequestParam int dropdown,
                            HttpServletRequest request,
                            Model model)
{
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("selection", dropdown);
    modelAndView.setViewName("confirm");
    return modelAndView;
}

On my confirm view, if I want to display the value of the dropdown selection then I can do that like this:

${selection}

If the user selected the first option, "1st choice", for example, then the value that would be passed to the confirm page would be 1.
However, what if I want to pass along the text value from the select tag option? What if a user selected the first option and I needed the value 1st choice to be passed into the controller? How would I retrieve that?
Comment: http://stackoverflow.com/questions/17218693/how-to-pass-data-from-formselect-spring-mvc can help u.
Answer: You can't retrieve that value. In form submission it only pass value attribute of select, input tags.
Two options available

You can change value field text to description

If you have hard code that just change that to
<option value="3rd choice">3rd choice</option>

If you have dynamic code, then you can use this kind of approach
List<Answer> answerList = new ArrayList<Answer>();
Answer answer = new Answer();
answer.setAnswerId(3);
answer.setDescription(3rd choice);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("answerList", answerList);

<select id="dropdown" name="dropdown">
    <option value="">Select</option>
    <c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
        <option value="${answer.description}" label="${answer.description}"/>
    </c:forEach>
</select>

or keep options as it is and in controller level you can get that value from dropdown request parameter (example: 3)
And after that you can loop the answer list (answerList) and find value in controller level.
<c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
    <option value="${answer.answerId}" label="${answer.description}"/>
</c:forEach>

Note
answer.answerId = 3
answer.description = 3rd choice


How can I use 'xx time ago' as date format?

Question: How can I use 'xx time ago' for date format in Drupal 8 nodes ?
I want to replace "xx time ago" with {{ date }} in node.
In Drupal 7 it worked with this code :
<?php
 print format_interval(time()-$node->created);
?>

Comment: Can you expand on what you mean?  Just just pick that display format under Manage Display, and then pick your options.
Comment: Can you clarify what your objective is? Where do you want to display "time ago"? Which fields do you want to display "time ago"? Have you done any work on this?
Comment: I want replace "xx time ago" with {{ date }} in node
Comment: Please update the question with extra details.
Comment: So basically, http://drupal.stackexchange.com/questions/95376/trying-to-render-a-custom-date-format-with-twig?rq=1
Comment: More specifically, this answer, http://drupal.stackexchange.com/a/194883/42650, in the question I posted previously, is what you're looking for. You can find more information about Twig, date function, and string concatenation on other sites. Or use views.
Comment: @mradcliffe, timeago is what the OP needs here.  There's a twig filter for that but it does not seem to work `{{ date|time_diff }}`. The post you are linking to does not touch upon timeago.
Comment: I'm sure that a developer can come up with a solution with the resources provided.
Comment: The `time_diff` Twig function is provided by The Date Extension, which I don't think is provided by core (haven't looked for an issue, but may be an interesting feature request). @Bahman, we still need to know what you are trying to print out from the node in your Twig, field(s) or updated/created in timeago format?
Answer: There are two ways to tackle this.
One is to just use the field formatters.  If you have a DateTime field, just goto Manage Display, and change the Format to Time ago.  Then click the gear, and pick some options.  These are cache aware that will bubble up through the page, but you may end up with short cache lifetimes in some situations.
The other is to use a template_preprocess_node().  This is preferable when you have a timestamp that isn't a field.  Then you use the date formatter service to render out the timestamp in timeago format.  It is preferable to use the formatDiff() versions rather than formatInterval() (while not formally deprecated, it is discouraged).
function MYTHEME_preprocess_node(&$variables) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
  $date_formatter = \Drupal::service('date.formatter');
  $request_time = \Drupal::time()->getRequestTime();
  $variables['foo'] = $date_formatter->formatDiff($request_time - 12345, $request_time, [
    'granularity' => 3,
    'return_as_object' => TRUE,
  ])->toRenderable();
}

When you specify 'return_as_object' => TRUE with the formatDiff() functions, a FormattedDateDiff object gets returned, which contains the formatted string as well as a mostly accurate [#cache]['max-age'] entry in a render array to make this work with Drupal 8's new caching system.  Then you can just use {{ foo }} in your Twig template; the render engine will do the right thing with the render array instead of a plain string.
Also read the docs on DateFormatterInterface for the formatTimeDiffSince() and formatTimeDiffUntil() variants, and for the $options you can pass in.
Answer: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/function/DateFormatter%3A%3AformatTimeDiffSince/8.2.x
$this->date->formatTimeDiffSince($time_stamp);
or
\Drupal::service('date.formatter')->formatTimeDiffSince($time_stamp);
Comment: works perfectly
Answer: The easiest approach is to prepare it in ỳourtheme_preprocess_node() and then just print it in the twig template.
However, with D8's render caching, trying to do a time ago output on the server side can not work, unless you disable caching. It will be calculated on the first request and then never change again.
Instead, you want to send the time in an easy to parse markup, and then use JS to display it as a time ago format. See how d.o does that for comment dates: https://www.drupal.org/node/2704717 (it also includes functionality to switch between relative and absolute dates with a double click).
Comment: Looks like there is a module for this now, https://www.drupal.org/project/twig_extensions, see `Date: Adds a filter for rendering the difference between dates.` and then the documentation at http://twig.sensiolabs.org/doc/extensions/date.html, thus `{{ date|time_diff }}`
Comment: Well, https://www.drupal.org/node/2500525 landed, so timeago on anything using the formatters should work, which will set some reasonable TTLs on the elements.  You can also just set the max-age to 0 in #cache, and let that prevent caching for you, or pick your own lifetime.
Comment: @DannyEnglander Yeah, that is from one of the theme system maintainers.  Personally, I would opt for using the Drupal methods to take into account cache contexts, timezone, translation, etc.
Answer: Twig has a native Date extension that provides a "Time Ago" filter
See http://twig.sensiolabs.org/doc/extensions/date.html
|time_diff is the one you want. The problem is Drupal doesn't include this extension by default.
So to get this in your twig templates do the following

Install Twig Extensions Drupal Module (Be sure to follow the instructions) - https://www.drupal.org/project
In Terminal in your Drupal Site

$ composer require twig/extensions
(be patient ... it took a while)

Enable Module
Use the Filter in your Twig templates
{{ field_my_date|time_diff }}

Renders like "10 MONTHS AGO"
Comment: There isn't much documentation, so some experimentation may be in order. For me, I got it working with {{ node.getCreatedTime|time_diff }} . It may take some rooting through your theme templates to find what fields are available.
Comment: this isnt a Drupal module (or it would come from drupal/{project} in composer; so what does "enable module" mean?
Comment: This has to be added as a service. See here: https://stackoverflow.com/questions/26311197/twig-time-ago-format
Answer: Here is Answer,
in your .theme file add below code
function themename_preprocess_comment(&$variables) {

  $date = $variables['comment']->getCreatedTime();
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@author', array('@author' => $variables['author'], '!datetime' => '' . $variables['created'] . ' ago '));

}

and render in your comment.html.twig file below code
{{ created }} {{ 'ago'|t }}

hope it will helpfull thank you...


Parse iOS: NSInvalidArgumentException', reason: 'Cannot do a comparison query for type: (null)

Question: my Parse backends based aplication, is terminating, if not cooencted to the internet, with the error NSInvalidArgumentException', reason: 'Cannot do a comparison query for type: (null). When there is an internet connection, all is working fine, but when i disconect, then after few seconds the app is terminating with that error.
Here us my code
<code>- (void)queryParseMethod {
NSLog(@"start query");

PFQuery *query = [UserParseHelper query];
[query whereKey:@"username" notEqualTo:self.mainUser.username];
PFGeoPoint *userGeoPoint = self.mainUser.geoPoint;
[query whereKey:@"geoPoint" nearGeoPoint:userGeoPoint];

if (self.segmentedControl.selectedSegmentIndex == 0) {
    [query whereKey:@"isMale" equalTo:@"true"];

}
if (self.segmentedControl.selectedSegmentIndex== 1) {
   [query whereKey:@"isMale" equalTo:@"false"];

}

PFUser *chekUser = [PFUser currentUser];
NSString *vip = chekUser[@"membervip"];
if ([vip isEqualToString:@"vip"]) {

    NSLog(@"Unlim - vip member");
    self.upgradeVip.hidden = YES;
    self.upgradedVip.hidden = NO;

} else{

    NSLog(@"No Unlim - no vip member");
 //   query.limit = limitQueruNoVipUser;
    self.upgradeVip.hidden = NO;
    self.upgradedVip.hidden = YES;

}

[query whereKey:@"geoPoint" nearGeoPoint:self.mainUser.geoPoint withinKilometers:self.mainUser.distance.doubleValue];
</code>
Answer: Please add some nil checking code to make sure the instants you pass to query is not nil. I guess the problem happened because of the PFGeoPoint class need networking to get current location so can not instantiate properly without networking.
Comment: i was thinking on that too, but what happen if i cache PFGeoPoint result?
or there is a way to make app to warn that there is no internet connection and not to terminate suddenly
Comment: Sorry for my late reply. As I remember, PFGeoPoint can be instantiated with core location's location. So if you've check the network service seems to be disable, you can call the core location service and get the current location as an alternative. After you get the CLLocation or some what, you can manually instantiate a PFGeoPoint object and do the rest. But actually, you can't fetch query when there are not network, so why would you still like to get the GeoPoint in this case?


Proper manual deployment of a Java Application Server on Ubuntu Server 8.10 - Linux

Question: I am currently preparing to deploy a JBoss AS into production for the first time.  My Linux distribution is Ubuntu Server 8.10 .   My original plan was to use aptitude to install JBoss.  Currently JBoss AS 4 is the highest version available and my requirements are to use JBoss AS 5. So, I will need to install this manually.
I ask the following because I am under the belief that most of the automated installs using tools like apt-get and aptitude do all sorts of modifications, different than what you see from downloading the JBoss AS standalone.

What is the best way to layout my directory structure?
What about logs, should they map to any particular location?
What is the best way to manage start and stop scripts on Ubuntu Server 8.10 for a Java Application Server?
Any particular security concerns?
Answer:
What about logs, should they map to any particular location?

Traditionally, you use /var/log/, or a directory therein.

What is the best way to manage start and stop scripts on Ubuntu Server 8.10 for a Java Application Server?

Ubuntu 8.10 still uses sysvinit for it's setup.  Find the runlevel you need, and add a small initscript for run-parts.

Any particular security concerns?

Is there a reason you've selected Ubuntu 8.10 as the platform? It's only going to receive
support (security patches, bug fixes) for another 12 months.
If you want to know what an Ubuntu package does differently than you would:

apt-get source package-name
Open package-name.*.diff.gz
Make sure all the changes apply to files in debian/
review the build options in package-name/debian/rules
review patches to the source itself in package-name/debian/patches

That should pretty much demonstrate for you what all they changed.
Answer: If you want to build JBoss 5 in a similar way to the JBoss 4 package does, you should grab the source data which is used to build the ver4 package. The specific details relating to this package will be there.
You can find links to this and other resources relating to the packages at packages.ubuntu.com. There are also lots of guides for this (building dpkgs) on the Debian site, which is where the format originated.


Error of approximation of an integral $\int_0^3 e^{-\sin x}dx$

Question: Let:
$$
I=\int_0^3 e^{-\sin x}dx
$$
$I$ has been approximated using rectangle midpoint formula $S$ (so $S(f)=H\sum_{k=1}^n\frac{x_k+x_{k-1}}{2}$), dividing interval $<0;3>$ to $150$ equal subintervals.
Prove that:
a) $|I-S|<10^{-4}$
b) $I>S$
so for part a), I used a formula that calculates rectangle midpoint formula error:
$$
|I-S|=E(f)=\frac{1}{24}H^2(b-a)f''(\mu)
$$
Where $H$ is the length of subintervals and $\mu\in(a,b)$
From there I got that
$$
|I-S|<10^{-4}\frac{1}{2}f''(\mu)
$$
so I just needed to prove that
$$
f''(\mu)=e^{-\sin \mu}(-\sin^2 \mu+\sin \mu +1)<2
$$
here I subsidized $t=\sin \mu$, where $t\in <0;1>$
I got that $g(0),g(1)<2$ (where $g$ is the subsidized function $f''$)
Since $g'(t)=e^{-t}t(t-3)$, function $g$ has extremal values only is $0$ and $3$, which I already checked, as borders of the interval.
For the part b), unfortunately I have no ideas (except maybe calculating the integral analitically, and then writing a program that would calculate it's approximation, but I don't think that's the best solution)
Please verify my method for part a), and give me some tips on solving part b)
Comment: @LutzLehmann why? If you look at sine diagram, it gets negative before $0$ and after $\pi$ and they are both out of the domain. Or do I miss something?
Comment: You are right, I retract most of my comment, except the point where you say that 3 is an interval border for $t$. // You should also be more careful when using absolute values, make sure that then both sides of the equation are always positive.
Comment: @LutzLehmann ah, so I should use limes for calculating g(0) and g(1) here? Is that what you meant?
Comment: This is bordering on nitpicking, but: The conclusion from the form of $g'$ should be that $g$ is monotonic on $t\in[0,3]$, so that the values at $t=0,1$ are indeed the extremal values.
Answer: The error formula holds without the absolute value... You have that
$$
I-S = \frac{1}{24}H^2 (b-a) f''(\mu)
$$
If you show that $f''(\mu)>0$, you have your proof.


Polynomial Ring and Prime Ideals

Question: Let $A=k[X], k$ a field. I am reading in a Algebra book that the ideal $(m)$ of all polynomials in $A$ with zero constant term is maximal. At the other hand, since $(m)$ is principal ideal, all polynomials in $(m)$ will have zero constant term. But having zero constant term means that $m$ is not irreducible ( one can factorize $X$ ) and thus not prime. Here I have a conflict since a maximal ideal is a prime one.
Can somebody help me understand what is here wrong ?
Thanks.
Answer: You can't factor an $X$ from the polynomial $X$ itself, though (well, you can, but not in the sense of the element being reducible). And $X\in k[X]$ is exactly the element which generates the maximal ideal of polynomials with zero constant term.
Comment: @user249018 In a unique factorisation domain (such as the ring of polynomials over a field), irreducible and prime are equivalent. So $m$ irreducible $\Leftrightarrow$ $m$ prime $\Leftrightarrow$ $(m)$ is a prime ideal.
Comment: Many thanks. Why is $(m)$ maximal ? Can we say that in the case of $A$, where $k$ is a field, $m$ irreducible $\Leftrightarrow$ $m$ prime ?
Comment: @user249018 The ideal of polynomials with no constant term, which generated by $X$, and therefore usually denoted $(X)$ rather than $(m)$, is maximal because $k[X]/(X)\cong k$ is a field.
Comment: Thats right. Does the assertion in the second question hold ?

Polynomial Ring and Prime Ideals


Ideas to solve the following system of equations

Question: I am trying to solve an exercise with partial derivatives. I have no issue with the derivation part, but once you do that you are supposed to solve a system of equations to find the solution. I already did a few exercises of this kind. However, I found one with a particular system of equations that I can not figure out how to solve. Multiplying one equation by something to delete one variable and solve the other one does not seem to work. I need to know the value of $\frac{\partial x}{\partial u}$ and $\frac{\partial y}{\partial u}$.
Said system of equations is:
$
\left\{
\begin{aligned}
\left(2x+y\right)\frac{\partial x}{\partial u}+x\frac{\partial y}{\partial u}=-2 \\
y\frac{\partial x}{\partial u}+\left(x-2y\right)\frac{\partial y}{\partial u}=-1 \\
\end{aligned}
\right.
$
The answers are supposed to be:
$\frac{\partial x}{\partial u}=\frac{4y-x}{2\left(x^2-2xy-y^2\right)}$ and $\frac{\partial y}{\partial u}=\frac{y-2x}{2\left(x^2-2xy-y^2\right)}$
Comment: think about $v=xy$.
Comment: Can you show your work, even if you don't think it worked? This is just solving two equations in two unknowns, $\partial{x}/\partial{u}$ and $\partial{y}/\partial{u}$.
Answer: The system of equations can be written as
$$
\begin{pmatrix}
2x+y & x \\
y & x-2y \\
\end{pmatrix}
\begin{pmatrix}
\frac{\partial x}{\partial u} \\
\frac{\partial y}{\partial u}
\end{pmatrix}
=
\begin{pmatrix}
-2 \\
-1
\end{pmatrix}
$$
Using the formula for the inverse of a $2\times 2$ matrix, we get
$$
\begin{pmatrix}
\frac{\partial x}{\partial u} \\
\frac{\partial y}{\partial u}
\end{pmatrix}
=
\frac{1}{(2x+y)(x-2y)-yx}
\begin{pmatrix}
x-2y & -x \\
-y & 2x+y \\
\end{pmatrix}
\begin{pmatrix}
-2 \\
-1
\end{pmatrix}
\\
=
\frac{1}{2x^2-4xy-2y^2}
\begin{pmatrix}
(x-2y)(-2) + (-1)(-x) \\
(-y)(-2) + (2x+y)(-1)
\end{pmatrix}
\\
\frac{1}{2(x^2-2xy-y^2)}
\begin{pmatrix}
4y - x \\
y - 2x
\end{pmatrix}
$$
Comment: You are brilliant Sir. That's exactly what I was looking for. Thank you very much


How to publish referenced nodes at the same time node is published?

Question: I have a product content type and a review content type. A user can create a product node and then several users can review it. There is a node reference field in the review content type that links the product type using the node reference url widget.
The user can create and edit the product node but it is not published. However, there are links from the node reference url widget that allows for reviews to be attached that get published immediately. Now I have views on other pages with reviews that link to an unpublished node. This doesn't work.
How do I allow for reviews to be made but are not published if the product is unpublished and published if the product is published? Are there techniques using Rules?
Answer: Rules Views Bulk Operations is being worked on which will hopefully allow a change in a node trigger, through a Views argument, a VBO reaction that will, for example, unpublish a set of  referenced nodes.
However, I just needed to hide Reviews in Views that were spread around the website. This is done by using the Relationships content: reference and adding a filter content: published that uses the referenced node relationship to test if it's published.
The reviews will always remain published. They can be viewed if people know where to look which doesn't make a difference. However, now an anonymous user doesn't land on the front page sees a view with a new review that links to a product which isn't published resulting in a page not found error.
Answer: I would look into rules.  This should be a simple problem solve with them.  If not here is how you would code it in a custom module
Drupal 6:
<code>/**
 *  Implements hook_nodeapi()
 */
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      //check for correct type
      if ($node->type == 'review') {
        if ($node->field_product_node_reference[0]['value']) {
           $product = node_load($node->field_product_node_reference[0]['value']);
           if ($product->status == 0) {
             //product is unpublished, set review to unpublish
             $node->status = 0;
           }
        }
      }
      break;
  }
}
</code>
Drupal 7:
   hook_nodeapi() has been change.  Create MYMODULE_node_presave($node).  Use the same code.


Comparing multiple models with something like a Diebold-Mariano test

Question: I run many models on different samples (i.e., datasets which are slightly different from each other).
I calculate the MSE for each model on these datasets. Now I want to compare these models to see if there is a significant difference between their performance.
I decided to use Diebold-Mariano test as it can deal with dependent datasets. How can I choose the p-value as I have many tests? Should I compare model 1 to model 2 or model 1 with all models?
Comment: In what sense can the DM test deal with dependent datasets? You would need to account for the dependence explicitly, and that may be nontrivial. In which sense are the datasets slightly different from each other? For some potentially relevant tests for multiple models, consult the tag description for [`diebold-mariano-test`](https://stats.stackexchange.com/tags/diebold-mariano-test/info).
Answer: The Diebold Mariano test is a pairwise test, for comparing model forecasts, and not the models themselves. See Diebold's 2012 paper: http://www.nber.org/papers/w18391
Therefore, one approach would be to set the forecast with the lowest MSE as the benchmark and then compare each of the other sets of forecasts to the benchmark forecast to determine whether the benchmark forecast is significantly different to the other forecasts.
Another approach would be to use the Model Confidence Set (MCS) approach in which a subset of models is identified which contains the best models with a given confidence level, see Hansen et al. (2005): https://www.econstor.eu/bitstream/10419/100950/1/wp2005-07.pdf.
Comment: Regarding the second paragraph, how do you suggest to implement the comparison? A test like the Diebold-Mariano test only works when the pair of competing forecasts is selected ex ante. If they are selected ex post based on their performance, the winner's curse makes comparisons very difficult. Namely, the performance of the ex-post best model will be overestimated, and adjusting for that in a test is hard. Without an adjustment, you will get nonsense results. On the other hand, your suggestion regarding MCS is fine.
Comment: Already with 3 models, the results will be biased because of the winner's curse. The more models under consideration, the greater the bias.
Comment: Thank you for the comment, @Richard Hardy. If you have only two competing models, you would select the best using MSE and then use the DM test to check statistical significance as you explained [here](https://stats.stackexchange.com/questions/253314/diebold-mariano-but-how-to-say-which-one-is-more-accurate?rq=1). Now if you have three competing models then you select the one with the lowest MSE, and then check it against the other two models in turn for statistical significance, or is my reasoning mistaken here?


How do you find the optimal value for this function?

Question: Given
$$\sum_{i=1}^n x_i = 1,$$
what values of $x_i$ minimize the sum
$$\sum_{i=1}^{n}x_i^2\ ?$$
Comment: I assume you mean the following: Given $\sum_{i=1}^n x_i = 1$, minimize $\sum_{i=1}^n x_i^2$. I further assume you want $x_i$ real. It's not too difficult to show that the latter sum is minimized by $x_i = 1/n$ for all $i$, in which case the sum is $1/n$.
Answer: You can use the method of Lagrange multipliers; but the problem is much more simple here.
You have an equation that defines a plane, and you want the vector on the plane that is closest to $\mathbf{0}$. The normal vector to the plane is $(1,1,\ldots,1)$, so you want to find the vector $(x_1,\ldots,x_n)$ in the plane such that $(x_1,\ldots,x_n)+t(1,1,\ldots,1) = (0,0,\ldots,0)$ for some $t$.
Hence we must have $x_1=\cdots=x_n$, and to lie on the plane you must have $nx_1=1$, so the answer is the vector
$(\frac{1}{n},\frac{1}{n},\ldots,\frac{1}{n})$.
(This can also be seen by symmetry, since whatever the answer is, it should be invariant under swapping variables, since they all play symmetric roles).
Comment: +1.  A side comment on your parenthetic remark: It's not always true in the presence of symmetry that the optimal solution has all variables equal.  See, for instance, [When does symmetry in an optimization problem imply that all variables are equal at optimality?](http://mathoverflow.net/questions/58721/when-does-symmetry-in-an-optimization-problem-imply-that-all-variables-are-equal)
Comment: Of course, but in this example the objective is convex, in fact strictly convex.  So the minimum is unique, and therefore must be invariant under the symmetry.
Comment: @Robert Israel: Yes, as your comment on one of the answers in the linked question says! :)
Answer: One way is to apply the Cauchy-Schwarz inequality to two $n$-dimensional vectors $\mathit{\boldsymbol a}=(x_1,x_2,\ldots,x_n)$ and $\mathit{\boldsymbol b}=(1,1,\ldots,1)$.
From $|\mathit{\boldsymbol a}\cdot\mathit{\boldsymbol b}|\le |\mathit{\boldsymbol a}||\mathit{\boldsymbol b}|$ it follows that $$|x_1+x_2+\cdots+x_n|\le \sqrt{x_1^2+x_2^2+\cdots+x_n^2}\sqrt{1+1+\cdots+1}.$$
Since the left hand side equals $|1|=1$,
$$\frac{1}{n}\le x_1^2+x_2^2+\cdots+x_n^2.$$
The two sides are equal if and only if $\mathit{\boldsymbol a}$ and $\mathit{\boldsymbol b}$ are parallel, that is, $x_1=x_2=\cdots=x_n(=1/n)$.
Comment: The LHS had a small typo (there should be no $\sqrt{\cdot}$ there). I fixed it for you :)
Answer: Let  $S=\sum\limits_i x_i^2$. Define $z_i=x_i-h$ for $h=1/n$. One looks for the vector $(z_i)$ such that $\sum\limits_i z_i=0$ which minimizes
$$
S=\sum_i(z_i+h)^2=\sum_iz_i^2+2h\sum_iz_i+h^2\sum_i1=\sum_iz_i^2+2h\cdot0+h^2\cdot n=\sum_iz_i^2+h.
$$
Since $z_i^2\ge0$ for every $i$, the last expression of $S$ shows simultaneously that $S\ge h$ for every $(x_i)$ and that $S$ is minimal when $z_i=0$ for every $i$, that is, when $x_i=1/n$ for every $i$.


How do I add a patch to patches in composer.json from the command line?

Question: In https://drupal.stackexchange.com/a/297530/69441

Third, add an "extras" section in composer with a patch:

How do I do this without an interactive editor?
Answer: <code>composer config --merge --json extra.patches.drupal/tooltip_ckeditor '{"D10": "https://www.drupal.org/files/issues/2022-08-16/tooltip_ckeditor.4.0.1.rector.patch"}'
</code>


Merging columns with same same using pandas

Question: I have the following data in CSV file:
time   conc   time   conc   time    conc   time   conc
1:00    10    5:00   11     9:00    55     13:00   1
2:00    13    6:00   8      10:00   6      14:00   4
3:00    9     7:00   7      11:00   8      15:00   3
4:00    8     8:00   1      12:00   11     16:00   8

And I just wanted to merge them together as:
time   conc
1:00   10
2:00   13
3:00   9
4:00   8
...
16:00  8

I've got more than 1000 columns, but I'm new to pandas. So just wondering how I can achieve?
Answer: One approach is to cut the dataframe in two-column slices, then re-combine using pd.concat() after renaming.
First load the dataframe normally:
df = pd.read_csv('time_conc.csv')
df

Which looks something like the below. Notice that pd.read_csv() has added a suffix to the duplicate column names:
    time    conc    time.1  conc.1  time.2  conc.2  time.3  conc.3
0   1:00    10      5:00    11      9:00    55      13:00   1
1   2:00    13      6:00    8       10:00   6       14:00   4
2   3:00    9       7:00    7       11:00   8       15:00   3
3   4:00    8       8:00    1       12:00   11      16:00   8

Then slice using pd.DataFrame.iloc:
total_columns = len(df.columns)
columns_per_set = 2

column_sets = [df.iloc[:,set_start:set_start + columns_per_set].copy() for set_start in range(0, total_columns, columns_per_set)]

column_sets is now a list holding each pair of duplicate columns as a separate dataframe. Next, loop through the list to rename the columns back to the original:
for s in column_sets:
    s.columns = ['time', 'conc']

This modifies each two-column dataframe in place so that their column names match.
Finally, use pd.concat() to combine them by matching the column axis:
new_df = pd.concat(column_sets, axis=0, sort=False)
new_df

Which gives you the full two columns:
    time    conc
0   1:00    10
1   2:00    13
2   3:00    9
3   4:00    8
0   5:00    11
1   6:00    8
2   7:00    7
3   8:00    1
0   9:00    55
1   10:00   6
2   11:00   8
3   12:00   11
0   13:00   1
1   14:00   4
2   15:00   3
3   16:00   8

Answer: Since your file has duplicated column names, Pandas will add suffixes. The DataFrame header by default will be like ['time', 'conc', 'time.1', 'conc.1', 'time.2', 'conc.2', 'time.3', 'conc.3' ...]
Assuming that the separator of your CSV file is a comma:
import pandas as pd
df = pd.read_csv('/path/to/your/file.csv', sep=',')
total_n = len(df.columns)

lst = []
for x in range(int(total_n / 2 )):
    if x == 0:
        cols = ['time', 'conc']
    else:
        cols = ['time'+'.'+str(x), 'conc'+'.'+str(x)]
    df_sub = df[cols]  #Slice two columns each time
    df_sub.columns = ['time', 'conc']  #Slices should have the same column names
    lst.append(df_sub)
df = pd.concat(lst)  #Concatenate all the objects

Answer: Assuming that df is a DataFrame with the csv file data you can try the following:
# rename columns if needed
df.columns = ["time", "conc"]*(df.shape[1]//2)
# concatenate pairs of adjacent columns
pd.concat([df.iloc[:, [i, i+1]] for i in range(0, df.shape[1], 2)])

It gives:
     time conc
0    1:00  10
1    2:00  13
2    3:00   9
3    4:00   8
0    5:00  11
..    ...  ..
3   12:00  11
0   13:00   1
1   14:00   4
2   15:00   3
3   16:00   8


Location Stops Updating after App Sent to Background

Question: OK, here's a tough  one (for me anyway)... My app has a button that checks to see if a user is in close proximity to a business. The button works almost perfectly by doing the following when it is pressed:

Gets the user's latitude and longitude coordinates
Passes the user's latitude and longitude coordinates to a PHP script
The PHP script compares the distance between the user and the business. If the user is within 100 feet, the script returns 1, if the user is not within 100 feet, the script returns 0.
Lastly, the app then displays an alert saying that the user is less than 100 feet away, or more than 100 feet away

Like I mentioned, this works almost perfectly. I can walk towards a business continuously clicking the button as I approach the building and when I get close enough, the alert will tell me that I am less than 100 feet away.
My problem is that the alert displays wrong information if I send the app to the background while I am walking. For example, I open the app from very far away, then I send the app to the background and approach the business, then when I am right next to the business, I bring the app to the foreground and click the button and it says I am more than 100 feet away. Anyone have any ideas on why this might be happening?
In my viewDidLoad Method:
<code>[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appReturnsActive) name:UIApplicationDidBecomeActiveNotification
object:nil];
</code>
In appReturnsActive Method:
<code>- (void)appReturnsActive{

    locationManagerProfile.delegate = self;
    locationManagerProfile.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManagerProfile startUpdatingLocation];
    [locationManager startUpdatingLocation];
}
</code>
Answer: To save battery, location updates are stopped when your app goes to background. You can add a value to info.plist to keep your app updated. But you should carefully consider battery usage.
Comment: Thanks, lets say that I want it to start updating right away when I bring it back to the foreground. I've updated my question to show what the appDidWaken might look like...
Comment: Updating location takes time. If no other app or the system updated location info while your app is in background, you can't get current location immediately.


C++ version of MATLAB code that reads raw image bytes from file and reshapes them to image dimensions

Question: I have some simple MATLAB code that reads a RAW file, representing an image, reshapes and transposes the data to image dimensions and then shows the image:
    width = 640;
    height = 480;
    fin = fopen('image.raw','r');
    I = fread(fin, width * height, 'uint8=>uint8');
    img = reshape(I, width, height);
    img = img';
    imgFromRaw = imshow(img)

How do I produce the same code in C++, either using a vector to read the raw file data or a BYTE pointer? I can read the file data into a vector like this:
    ifstream file("image.raw", ios::binary);
    rawData.insert(rawData.begin(),
        std::istream_iterator<BYTE>(file),
        std::istream_iterator<BYTE>());

But I don't know now how to reshape the data manually to be a 640 * 480 matrix. Any ideas?
Comment: Why not generate the C++ code from MATLAB itself and see what it's doing?
Comment: what exactly is a "640 * 480 matrix" ? what type should the data be in the end?
Comment: Sorry, matrix refers to a `Mat` type in OpenCV. The final data type should be unsigned char.
Comment: Looks like the raw data is a 640*480 size vector of bytes that is column major on disk. You want to access it in C++ as row major and probably flip the row index (lower left corner of the image is either 0 or 479). This is pretty easy to do with a short lambda. It would be helpful if you provide what pixel on the image is accessed by say, `pixel(row, col)`  Where on the image would you want `pixel(0,0)` to be? Top left? lower left?
Comment: @G-man, I didn't know that option existed so I;m checking that out.
Comment: @doug, `pixel(0,0)` on the image is top left
Comment: if you know the size in advance you just need two nested loops read the values one by one and set the correct pixel, sorry, but without providing more information on what causes you problems I dont think you will get a better answer than that
Comment: Also, 2D arrays are normally kept in memory as 1D vectors and just accessed appropriately based on whether row or col major. Do not create a `vector>` to access like `v[i][j]` as it's slower.
Answer: You should be able to access with a lambda like this:
auto& pixel=[rawData, width](int row, int col) {
    return rawData[col+width*row];};

Alternately, you can write a function which does the same. Lambdas are short and convenient ways of creating a function.
BYTE& pixel(vector<BYTE>& rawData, int width, int row, int col) {
    return rawData[col+width*row];
};

To use the lambda:
auto value_at_lower_right = pixel(479,639);

To use the function:
BYTE value_at_lower_right = pixel(rawData, width, 479,639);

These can be used on the left side as well to change a value in the image:
pixel(rawData, width, 479,639) = 127;
// or, for the lambda
pixel(479,639) = 127;

Comment: I'm really sorry but I've been out the game for a long while. I haven't come across lamdas in C++ and even reading about them just now, I'm still confused how to implement your answer. I was guessing I'd need two FOR loops to work through the width and height. I'll try to edit my question to make it more appealing to everyone.
Comment: You will get more specific responses if you include a snippet that is compilable since it will include things like the declaration of `rawData`.  That wasn't needed for the lambda since the only operator needed was `[]` For the function you will likely need to change it.


Show the collection of subsets is a basis.

Question: Here is my attempt at showing this collection forms a basis. Have I done all the necessary cases? Is this correct?
Problem:We construct a topological space. Let $\mathbb{R}_{+00}$ be the set consisting of $\mathbb{R}_+$ together with two points called $0'$ and $0''$. Put a topology on it generated by a basis consisting of all intervals in $\mathbb{R}_+$ of the form $(a,b)$ or else of the form $(0,b) \cup \{0'\}$ or $(0,b) \cup \{0''\}$, $a,b \in \mathbb{R}_+$. Show this collection of sets forms a basis for a topology.
Attempt:
Each point in $\mathbb{R}_{+00}$ is in at least one basis element. If $x \in \mathbb{R_+}$,the basis element $(0,x+1) \cup \{0'\}$ certainly contains $x$. $0' \in (0,b) \cup \{0'\}$ for any $b \in \mathbb{R_+}$ and $0'' \in (0,b) \cup \{0''\}$ for any $b \in \mathbb{R_+}$. The intersection of any two open intervals $(a,b),(c,d),a,b,c,d \in \mathbb{R_+},a<b,c<d$  is either $\varnothing$, or a basis element. If  $a<b$ and $x \in ((0,a) \cup \{0'\}) \cap ((0,b) \cup \{0''\})$, choose $\epsilon$ such that $0<\epsilon<x$. Then $x\in (x-\epsilon,a)  \subset ((0,a) \cup \{0'\}) \cap ((0,b) \cup \{0''\})$. The case where $b>a$ is similar. $(c,d) \cap ((0,a) \cup \{0'\})$ is either $\varnothing$ or an open interval of the form  $(e,f)$, a basis element. Similarly for $(c,d) \cap ((0,a) \cup \{0''\}).$
Comment: @ShubhamJohri: No, they are simply two new points not in $\Bbb R_+$. The topology generated by this base makes each of the subsets $\Bbb R_+\cup\{0'\}$ and $\Bbb R_+\cup\{0''\}$ homeomorphic to $\Bbb R_{\ge 0}$ with the usual topology; the space as a whole is the [line with two origins](https://math.stackexchange.com/questions/709777/the-line-with-two-origins) minus the negative reals.
Comment: @DanielWainfleet I do not mean to be rude, but I thought those conditions are what I have shown.Where did I go wrong? At least that is what I have tried to show.
Comment: You aren't wrong. I just wanted to state the general case. Some other students get the mistaken notion that a base must be closed under finite intersections
Comment: Looks nice for me.
Comment: Are we supposed to assume $0',0''$ are distinct negative points?
Comment: @ShubhamJohri I am not sure, it just says two made up points.
Comment: @ScottFrazier If you don't know that $0',0''\le0$, how does your second last line make sense?
Comment: If $B$ is a family of subsets of a set $X$ then $B$ is a base (basis) for a topology on $X$ iff $(i) \,\cup B=X\,$(i.e. every member pf $X$ belongs to at least one $b\in B$), and $(ii)$ whenever $b,b'\in B$ and $x\in b\cap b',$ there exists $b''\in B$ with $x\in b''\subseteq b\cap b'.$ Of course if $b\cap b'\in B$ whenever $b,b'\in B$ then $(ii)$ is satisfied by $b''=b\cap b'$.
Answer: Without knowing the sign of $0',0''$, your assumption that $(c,d)\cap[(0,a)\cup\{0'\}]$ being either empty or an open interval is incorrect. Note that it is equal to$$A=[(c,d)\cap(0,a)]\color{pink}\cup[(c,d)\cap\{0'\}]=(\max\{0,c\},\min\{a,d\})\color{pink}\cup[(c,d)\cap\{0'\}]$$where the former is an open interval (including the empty set) and the latter may give you an isolated point $0'$ in case $0'$ is positive. In this case there is no basis element containing $0'$ which is a subset of $A$ unless $c=0$. For example, $(c,d)=(5,15),(0,a)\cup\{0'\}=(0,6)\cup\{12\}$.
So you must remark that the given set forms a basis iff $0',0''\le0$.

For $a<b$,$$[(0,a) \cup \{0'\}] \cap[(0,b) \cup \{0''\}]=(0,a)\color{pink}\cup[\{0'\}\cap\{0''\}]$$There is a possibility that this intersection contains the point $0'$ iff $0'=0''$, in which case $(0'-\epsilon,a)$ is not be a suitable choice. For $0'$, select the basis element  $(0,a)\cup\{0'\}$ and you are done.
Comment: It says in the book that $0'$ and $0''$ are not points in $\mathbb{R}_{+}$.
Comment: @ScottFrazier Should have mentioned that earlier. Now you know why $0',0''$ must be non-positive ;) The second part of my solution still applies to your answer.


Using comma-formatted numbers for DecimalField in Wagtail page admin

Question: I have a request from a client to have page admin fields that they can add/read numbers into  with commas such as 1,000,000.
The Django model field to store the value would be a django.db.models.fields.DecimalField instance.
From looking at the Django docs, this is something that's supported by the django.forms.fields.DecimalField localized property, but I can't find a way of enforcing it in the Wagtail admin, even when subclassing the Wagtail BaseFieldPanel __init__ function with self.bound_field.field.localize = True.
Answer: Thanks @lb-ben-johnston - also to the Wagtail team who pointed me in a similar direction.
I have it working now in a loosely coupled fashion with this:
from django.forms.fields import DecimalField
from wagtail.wagtailadmin.forms import WagtailAdminPageForm

class ProductPageForm(WagtailAdminPageForm):

    def __init__(self, *args, **kwargs):
        super(ProductPageForm, self).__init__(*args, **kwargs)
        for key, field in self.fields.items():
            if isinstance(field, DecimalField):
                field.localize = True
                field.widget.is_localized = True

# The Page class to localize

class LocalizedPage(Page):

    base_form_class = ProductPageForm

    # Rest of page class

Make sure you explictly pass a TextInput widget to the field handler:
FieldPanel('localized_field', widget=TextInput)

Finally, make sure that the thousand separator flag is explicitly set in your settings.py or base.py:
USE_THOUSAND_SEPARATOR = True

Answer: You can override the fields that Wagtail FieldPanel uses by customising generated forms documented here:
http://docs.wagtail.io/en/v1.13/advanced_topics/customisation/page_editing_interface.html#wagtail.wagtailadmin.forms.WagtailAdminPageForm
Basic example below - myapp/models.py
from django import forms
from django.db import models

from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.forms import WagtailAdminPageForm
from wagtail.wagtailcore.models import Page

class MyCustomPageForm(WagtailAdminPageForm):
    # fields here are django.forms fields
    # when set to localize, renders as a TextInput widget
    total_amount = forms.DecimalField(localize=True)

    # when left with defaults, renders as a NumberInput widget
    # total_amount = forms.DecimalField()

    # can also set any kind of widget here
    # total_amount = forms.DecimalField(widget=MyCustomDecimalWidget)

class MyCustomPage(Page):
    # fields here are django.db.models fields
    total_amount = models.DecimalField()
    content_panels = Page.content_panels + [
        FieldPanel('total_amount'),
    ]
    base_form_class = MyCustomPageForm # important: must set this

When you set the form field to localize=True it appears to follow the intended behaviour as per the Django Docs which is to render a TextInput widget.
You could also set your own widget for any field in your page's form class if you want to do some more complicated functionality.


Are Unions/Intersections of Cartesian Products of Indexed Sets "Distributive"?

Question: In a situation like $\bigcup\limits_{x \in [0,1]} [x,1] \times [0,x^2]$, could one correctly assume that $\bigcup\limits_{x \in [0,1]} [x,1] \times \bigcup\limits_{x \in [0,1]}[0,x^2]$ also holds true? That is to say, is it "distributive" in some sense of the word?
In general, if $\bigcup\limits_{i \in I} A_i \times B_i$ or $\bigcap\limits_{i \in I} A_i \times B_i$ for some indexed sets $A_i, B_i$, does it hold that:
$$\bigcup\limits_{i \in I} A_i \times B_i = \bigcup\limits_{i \in I} A_i \times \bigcup\limits_{i \in I} B_i$$
$$\bigcap\limits_{i \in I} A_i \times B_i = \bigcap\limits_{i \in I} A_i \times \bigcap\limits_{i \in I} B_i$$
in general?
Comment: $(0,1) \notin \bigcup_{x \in [0,1]} [x,1] \times [0,x^2]$ but $(0,1) \in \bigcup_{x\in [0,1]} [x,1] \times \bigcup_{x\in [0,1]} [0,x^2]$.
Comment: Are you sure about this? Because the solution to the first is $[0,1] \times [0,1]$, and $(0,1)$ is definitely an element of that set.
Comment: If you had $(0, 1) \in \bigcup_{x \in [0,1]} [x,1] \times [0, x^2]$ then that would mean $(0, 1) \in [x,1] \times [0,x^2]$ for some $x \in [0,1]$.  But that implies $x \le 0$ since $0 \in [x,1]$ and also $x^2 \ge 1$ since $1 \in [0,x^2]$, giving a contradiction with $x \in [0,1]$.  (In fact, I think $\bigcup_{x \in [0,1]} [x,1] \times [0,x^2] = \{ (x,y) \in \mathbb{R}^2 \mid 0 \le x \le 1, 0 \le y \le x^2 \}$.)
Comment: The union of $[x,1] \times [0,x^2]$ with $x \in [0,1]$ most certainly contains $(0,1)$ since the solution to the union is $[0,1]\times [0,1]$, which clearly contains $(0,1)$. I don't understand what you're trying to say.
Comment: No, what I'm saying is that the first is *not* equal to $[0,1] \times [0,1]$ - whereas $\bigcup_{x \in [0,1]} [x,1] \times \bigcup_{x \in [0,1]} [0,x^2]$ is equal to $[0,1] \times [0,1]$.
Comment: Right, but what I'm saying is that that is incorrect and that the first is indeed equal to $[0,1] \times [0,1]$. You're making the mistake of thinking that x has to be one value, whereas this is the union of a cartesian product. That is to say, the union is the interval which contains all possible intervals given our x in our index set. The union thus is $[0,1] \times [0,1]$, because that cartesian product contains all others.
Answer: It is false for unions. To see why, consider the following Battenberg cake (image from Wikipedia), whose cross-section is identified with the subset $[0,1]^2 \subseteq \mathbb{R}^2$ of the plane:

Let $A_1 = B_1 = [0,\frac{1}{2}]$ and $A_2 = B_2 = [\frac{1}{2},1]$. Then

$\bigcup_{i \in \{ 1,2 \}} (A_i \times B_i) = [0,\frac{1}{2}]^2 \cup [\frac{1}{2},1]^2$ consists only of the white squares in the cake; but
$\left( \bigcup_{i \in \{ 1,2 \}} A_i \right) \times \left( \bigcup_{i \in \{1,2\}} B_i \right) = [0,1]^2$ is the entire cake.

It is true for intersections. To see why, just chase the definitions. Indeed, $\bigcap_{i \in I} (A_i \times B_i)$ consists of those things which are elements of all the sets $A_i \times B_i$. Now:

For each $i \in I$, an element of $A_i \times B_i$ is a pair $(a,b)$;
Such a pair is an element of all the sets $A_i \times B_i$ if and only if $a \in A_i$ for each $i \in I$ and $b \in B_i$ for each $i \in I$;
But this is equivalent to saying that $(a,b) \in \left( \bigcap_{i \in I} A_i \right) \times \left( \bigcap_{i \in I} B_i \right)$.
Comment: P.S. If anyone knows how to scale the image to make it less obnoxiously huge, please feel free to edit my answer accordingly.


Android: Is there any way to detect any user input?

Question: on Android! I need to get user input (touch event, keyboard event). is there any way? In java code, It seems there is no way. What about native code?
Comment: Your question is not clear. Please try explaining further and sharing some code that you tried but not worked.
Comment: can you please tell what is the difference b/w Java Code and native code
Answer: In java code, It seems there is no way.

=> sorry, there is a way to do detect any action user made and play with application.
Some examples:

KeyboardView.OnKeyboardActionListener
Responding to Touch Events
Answer: for touch you can use
mView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    //show dialog here
    return false;
 }
});

Answer: if your YourActivity implements OnTouchListener you can get the event and where the user touched on the screen:
   public class YourActivity extends Activity implements OnTouchListener {

     @Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
     System.out.println("I touched: "+event.getX()+"-"+event.getY());
 }

}

Answer: Actually I don't know what you exactly mean. Do you mean text input on an EditText or in General when something is touched?
If you mean text you can use TextWatcher
http://developer.android.com/reference/android/text/TextWatcher.html
If you mean on a View directly you can use OnTouchListener as mentioned above.
Answer: https://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
Activity
public void onUserInteraction ()

Added in API level 3 Called whenever a key, touch, or trackball event
  is dispatched to the activity. Implement this method if you wish to
  know that the user has interacted with the device in some way while
  your activity is running. This callback and onUserLeaveHint() are
  intended to help activities manage status bar notifications
  intelligently; specifically, for helping activities determine the
  proper time to cancel a notfication.
All calls to your activity's onUserLeaveHint() callback will be
  accompanied by calls to onUserInteraction(). This ensures that your
  activity will be told of relevant user activity such as pulling down
  the notification pane and touching an item there.
Note that this callback will be invoked for the touch down action that
  begins a touch gesture, but may not be invoked for the touch-moved and
  touch-up actions that follow.


Por numero negativo em vermelho

Question: var btnSoma = document.querySelector("#btnSoma")
var btnSubtrai = document.querySelector("#btnSubtrai")
var currentNumberWrapper = document.getElementById('currentNumber');

var currentNumber = 0;

btnSoma.addEventListener("click", function incremento() {
    currentNumber++
    currentNumberWrapper.innerHTML = currentNumber;
    return
})

btnSubtrai.addEventListener("click", function decrement(){
    currentNumber--
    currentNumberWrapper.innerHTML = currentNumber;
    return
})

console.log(currentNumber)

if (currentNumber < 0){
    document.getElementById('currentNumber').style.color="#ca6567";
}

Não estou sabendo como alterar a variável "CurrentNumber"
Comment: A cor vermelha é comumente usada para indicar entrada inválida. As pessoas que têm certos tipos de daltonismo serão incapazes de determinar o estado da entrada, a menos que seja acompanhada por um indicador adicional que não dependa da cor para transmitir significado. Normalmente, texto descritivo e/ou um ícone são usados.
Answer: Algo assim resolveria:
function verify(params) {
  if (currentNumber < 0){
    currentNumberWrapper.style.color="#ca6567";
  } else {
    currentNumberWrapper.style.color="#000";
  }
}

Basta chamar essa função em cada eventListener:
btnSoma.addEventListener("click", () => {
  currentNumber++;
  currentNumberWrapper.innerHTML = currentNumber;
  verify()
})

btnSubtrai.addEventListener("click", () => {
  currentNumber--;
  currentNumberWrapper.innerHTML = currentNumber;
  verify()
})

Nesse caso a Arrow Function nos eventListeners deixa o código mais legível.
() => {}

Por numero negativo em vermelho


Custom launcher.ini in export of Eclipse RCP product

Question: Is it possible to tell the Eclipse Product export wizard to add a custom launcher.ini (the "eclipse.ini" deployed with my RCP application) in the export instead of the generated one (the wizard generates it from the content of the "Launching" tab section "Program Arguments" or "VM Arguments")?
Background of my question: I need different launcher options when starting the RCP application inside of Eclipse IDE during development and when starting it stand-alone outside the IDE. If I put the options needed when starting the application outside of the IDE in the "Launching" section of the product file, then this is fine for the stand-alone RCP application, but since Eclipse IDE generates the launch configuration for debuggging or running the RCP application from the product file these options do not fit during development.
If I change the generated launch configuration then Eclipse IDE overwrites these changes the next time I click "Launch an Eclipse application" in the "Testing" section of the Product Configuration Editor.
So I thought it would be nice if I could specify a custom launcher.ini in the "product export wizard" (the way like specifying the custom config.ini on the "Configuration" tab of the Product Configuration Editor) but unfortunately there isn't such an option in Eclipse Luna SR2.
Answer: You can't customize the ini used in the exported RCP.
You can change the options used when you test your RCP from Eclipse.
Instead of using the 'Launch and Eclipse application' option in the product file use the 'Run > Run Configurations...' menu. An entry from your Eclipse application should already have been created there, you can modify it as you require.
Comment: I already thought about modifying the generated run configuration, but it has the drawback that if I change the product (e.g. remove/add plugins) I have to manually sync the run configuration. But since it is not possible to customize the ini used in the export, I will use this solution. Thanks!


Kernel Smoothing for Time Series data

Question: I have generated a time series data set of measurements that are a bit noisy and I want to apply kernel smoothing to the data. My time series data is not regular however, meaning that the time difference between consecutive observations can be variable so I want to account for that within the weighting of the kernel smoothing.
I give an example dataset below and apply kernel smoothing with a couple different bandwidth sizes as well as a rolling mean with different window sizes for comparison.
My impression was that kernel smoothing worked by taking a weighted average of the adjacent points weighted by how close they are (here in time) to the "focal observation". The bandwidth controls the relative contribution of adjacent points (essentially the weights given to adjacent points given how close they are) where larger bandwidths results in more smoothing (i.e. larger weights to closer observations). In contrast, a rolling mean takes a regular uniform average of observations within a window around the focal observation and so that all observations within the window contribute equally to the mean regardless of how far away they are from the focal observation.
However, when I applied this in practice, I don't see this in my results. Is my understanding wrong? Is my code wrong?
What I see is that when I apply kernel smoothing with a bandwidth of 1/2 or 1, it doesn't change the raw data, when I apply kernel smoothing with a bandwidth of 2 or 3, the results are equivalent, and when I apply a rolling mean of window size +/- 1 or +/- 2 these are equivalent to a kernel smooth with bandwidths of 2 or 4 respectively.
Can anyone explain to me what's going on?
Thanks!
<code>#################
# Simulate data #
#################
# Simulate a time series data set with different underlying processes that
# last a random length with variable sampling frequencies
library(dplyr)
library(ggplot2)
library(tidyverse)
# Set random seed
set.seed(1)
# Total # of process bouts
n_mode = 5
# Average sampling rate
sample_rate = 10 #hz
# Durations can be irregularly long
durs = rgamma(n_mode, shape = 2.5, rate = .5)
# Total length of time collected
times = cumsum(durs) # Ending times
# Random order of modes
order = c(3,1,3,2,1)
# Stick in a data frame
df = data.frame(modes = order,
                duration = durs,
                end_time = times)
# Determine starting timestamp of bout
df$start_time = c(0, times[1:(length(times)-1)])
# Reorder columns
df = df %>% select(modes, duration, start_time, end_time)
# For each mode
for(i in 1:nrow(df)){
  # By each row
  df_sample = df[i,]
  # Generate an idealized sequence of data with perfect really fast sampling
  ts_ideal = seq(df$start_time[i], df$end_time[i], by = 1/10000)
  # Randomly sample observations so that the total sampling rate ends up
  # at an average of observations a second
  time_ss = sample(ts_ideal, size = sample_rate * df_sample$duration, replace = FALSE)
  # Put in order
  time_ss = time_ss[order(time_ss)]
  # Get "time stamp" second
  time_s = floor(time_ss)
  # Extract sub-second info
  ss = time_ss - time_s
  # Put into time df
  times_df = data.frame(index = i, mode = df_sample$mode, time_s, ss, time_ss)
  # If first iteration, generate combined df
  # Otherwise add to combined df
  if(i == 1){comb = times_df}else(comb = rbind(comb, times_df))
}
# Generate variable by process type (mode)
for(i in 1:length(unique(comb$index))){
  # subset by index
  df_index = comb[comb$index == i, ]
  # given the mode
  if(unique(df_index$mode) == 1){
    # signals
    df_index$x_raw = rep(0, length(df_index$time_ss))}
  if(unique(df_index$mode) == 2){
# signals
df_index$x_raw = sin(2 * pi * df_index$time_ss)}
  if(unique(df_index$mode) == 3){
    # signals
    df_index$x_raw = rep(1, length(df_index$time_ss))}
  # Combine
  if(i == 1){df_comb = df_index}else(df_comb = rbind(df_comb, df_index))
}
# Add some error (noise)
df_comb$x_raw = df_comb$x_raw + rnorm(n = nrow(df_comb), mean = 0, sd = .05)
# Define as factor
df_comb$mode = as.factor(df_comb$mode)
# Pull out transition times of x for visualization
trans_times = df_comb$time_ss[df_comb$index!=lag(df_comb$index)]
# Remove NA
trans_times = trans_times[!is.na(trans_times)]

#############
# Visualize #
#############
df_comb %>%
  ggplot(aes(x = time_ss, y = x_raw, color = mode, group = 1))+
  geom_point(aes(color = mode, group = 1))+
  geom_line(aes(color = mode, group = 1))+
  scale_color_manual(values = c("red", "blue","green"))+ #Color by mode
  geom_vline(xintercept = trans_times, linetype = "dashed") # Delineate transitions

####################
# Kernel smoothing #
####################
df_comb$x_ks1_2 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 0.5)$y
# Bandwidth is 1 (does not appear to work)- is same as raw
df_comb$x_ks1 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 1)$y
# Bandwidth is 2 (first that appears to work)
df_comb$x_ks2 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 2)$y
# Bandwidth is 3 (is same as 2)
df_comb$x_ks3 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 3)$y
# Bandwidth is 4 (higher smoothing)
df_comb$x_ks4 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 4)$y

########
# Plot #
########
df_comb %>% pivot_longer(cols = x_raw:x_ks4, names_to = "type", values_to = "x") %>%
  ggplot(aes(x = time_ss, y = x, group = type, color = type))+
  geom_point()+
  geom_line()+
  scale_color_manual(values = c("x_raw" = "black",
                                "x_ks1_2" = "red",
                                "x_ks1" = "orange",
                                "x_ks2" = "green",
                                "x_ks3" = "blue",
                                "x_ks4" = "purple"))+ #color by bandwidth
  geom_vline(xintercept = trans_times, linetype = "dashed") # Delineate transitions

##############################################################
# Why do different bandwidths produce the same numbers ??!! #
#############################################################
# Kernel smoothing bandwidth of 3 same as kernel smoothing bandwidth of 2?
sum(df_comb$x_ks2 == df_comb$x_ks3)/nrow(df_comb) # 100% same
# Kernel smoothing bandwidth of 1 and kernel smoothing bandwidth of 1/2 same as raw?
sum(df_comb$x_ks1 == df_comb$x_raw)/nrow(df_comb) # 100% same
sum(df_comb$x_ks1_2 == df_comb$x_raw)/nrow(df_comb) # 100% same

##################
# Rolling Window #
##################
# Quarter second window (+/- 1 observation)
setDT(df_comb)[, "x_rm1_4" := frollapply(x_raw,
                       n = (floor(sample_rate/4) + 1),
                       FUN = mean,
                       align = "center",
                       adaptive = F,
                       na.rm = T)]
# Half second window (+/- 2 observations)
df_comb[, "x_rm1_2" := frollapply(x_raw,
                       n = sample_rate/2,
                       FUN = mean,
                       align = "center",
                       na.rm = T)]
########
# Plot #
########
df_comb %>% pivot_longer(cols = c(x_raw,
                                  x_rm1_4,
                                  x_rm1_2), names_to = "type", values_to = "x") %>%
  ggplot(aes(x = time_ss, y = x, group = type, color = type))+
  geom_point()+
  geom_line()+
  scale_color_manual(values = c("x_raw" = "black",
                                "x_rm1_4" = "green",
                                "x_rm1_2" = "purple"))+ #color by smoothing window width
  geom_vline(xintercept = trans_times, linetype = "dashed") # Delineate transitions

###################################################
# Plot both Kernel and Rolling Mean on same Graph #
###################################################
df_comb %>% pivot_longer(cols = c(x_raw,
                                  x_rm1_4,
                                  x_ks2,
                                  x_rm1_2,
                                  x_ks4
                                  ), names_to = "type", values_to = "x") %>%
  ggplot(aes(x = time_ss, y = x, group = type, color = type))+
  geom_point()+
  geom_line()+
  scale_color_manual(values = c("x_raw" = "black",
                                "x_rm1_4" = "red",
                                "x_ks2" = "orange",
                                "x_rm1_2" = "green",
                                "x_ks4" = "blue"
                                ))+ #color by smoothing window width
  geom_vline(xintercept = trans_times, linetype = "dashed") # Delineate transitions

# Plot by each mode in case differences are very tiny
df_comb %>% filter(index == 1) %>% pivot_longer(cols = c(x_raw,
                                  x_rm1_4,
                                  x_ks2,
                                  x_rm1_2,
                                  x_ks4
), names_to = "type", values_to = "x") %>%
  ggplot(aes(x = time_ss, y = x, group = type, color = type))+
  geom_point()+
  geom_line()+
  scale_color_manual(values = c("x_raw" = "black",
                                "x_rm1_4" = "red",
                                "x_ks2" = "orange",
                                "x_rm1_2" = "green",
                                "x_ks4" = "blue"
  ))
df_comb %>% filter(index == 2) %>% pivot_longer(cols = c(x_raw,
                                                         x_rm1_4,
                                                         x_ks2,
                                                         x_rm1_2,
                                                         x_ks4
), names_to = "type", values_to = "x") %>%
  ggplot(aes(x = time_ss, y = x, group = type, color = type))+
  geom_point()+
  geom_line()+
  scale_color_manual(values = c("x_raw" = "black",
                                "x_rm1_4" = "red",
                                "x_ks2" = "orange",
                                "x_rm1_2" = "green",
                                "x_ks4" = "blue"
  ))
##########################################################
# Why is kernel smoothing the same as rolling means ??!! #
##########################################################
# Round to same number of decimal places so precision isn't the underlying difference
df_comb$x_rm1_4 = round(df_comb$x_rm1_4, 12)
df_comb$x_rm1_2 = round(df_comb$x_rm1_2, 12)
df_comb$x_ks2 = round(df_comb$x_ks2, 12)
df_comb$x_ks4 = round(df_comb$x_ks4, 12)
# Pull out observations where the rolling mean and kernel smooth is not the same
df_comb[df_comb$x_rm1_4!=df_comb$x_ks2,]
df_comb[df_comb$x_rm1_2!=df_comb$x_ks4,]
# Eyeball the data
cbind(df_comb[1:6, "x_rm1_4"], df_comb[1:6, "x_ks2"], df_comb[1:6, "x_rm1_4"] == df_comb[1:6, "x_ks2"])
```
</code>
Comment: It's very good that the OP solved their own question, but I find it hard to imagine that this is both on-topic and likely to be useful to anyone else. Too much depends on a reader wading through lengthy code -- or even on running it -- to find out exactly what was done.  (R is, I guess, the most commonly used software here, but it's not universal, nor is any other software.)
Answer: So, it turns out that all I needed to do was to remove the time() function within the kernel smoothing function and use my variable by itself (it's already a numeric representation of time, not a posix_ct type object) and it performs as expected. So my code should been:
<code># THIS WORKS
df_comb$x_ks1_2 = ksmooth(df_comb$time_ss, df_comb$x_raw, bandwidth = 0.5)$y
# THIS DOES NOT
df_comb$x_ks4 = ksmooth(time(df_comb$time_ss), df_comb$x_raw, bandwidth = 4)$y
</code>
This is because the time() function converted by numeric time into a sequential time series treating each individual observation as an integer. I think this is why it wouldn't allow me to use an uneven number for my bandwidth or go below 1 for the bandwidth value.
Well, if anyone needs a practice data set (I created it to represent accelerometer data with different behavior types "modes") in which to test out methods and better understand how they work...here you go!
Comment: Assuming this is the right answer -the implication to me is that the thread is about using the right code.

Kernel Smoothing for Time Series data


How to interpret ANOVA output when comparing two nested mixed-effect models?

Question: I've got two models (all variable are count variables):
frm.ct <- glmer(frm ~ age + education + socialrole +
              offset(log(words)) + (1|subkorpus), family=negative.binomial(1),
data=daten.alle.kom)

frm.oage <- glmer(frm ~ education + socialrole +
              offset(log(words)) + (1|subkorpus), family=negative.binomial(1),
data=daten.alle.kom)

I used this to compare them:
anova(frm.ct, frm.oage)

AIC values tell me that frm.oage is the better model, right? but what do 0.0452 and 0.8315 mean?
Comment: The `chisq` is analogous to an $F$-statistic. Your questions suggest you may benefit from some basics. You could try starting here: [How to interpret F- and p-value in ANOVA?](http://stats.stackexchange.com/q/12398/)
Comment: The log-likelihoods of the two model are almost identical (this is also what the p-value tells you) and the AIC of the more complex model is higher by almost exactly two (which is the penalty for each additional parameter). This means that the additional parameter (age) does not improve the fit.
Comment: these are chi-squared test values. http://en.wikipedia.org/wiki/Chi-squared_test
Answer: The Chisq value is the test statistic of the likelihood ratio test (LRT) being applied to the two models. This value is computed as twice the difference in the log-likelihoods of the two models (the log likelihood is in column logLik). Asymptotically, the log-likelihood ratio follows a Chi-square distribution with degrees of freedom equal to the difference in degrees of freedom of the two models; here this is $|6 - 7| = 1$ and is shown in the Chi Df column. As such, the probability of observing a test statistic as extreme as the observed (0.0452) value if the two models were equivalent can be computed from that Chi-square distribution. This probability is the value 0.8315.
You can compute this yourself as
> pchisq(0.0452, df = 1, lower.tail=FALSE)
[1] 0.8316367

(This doesn't quite match as I used the rounded values printed to the console whereas the software will have used higher precision.)
In more practical terms, this just reaffirms you interpretation of the relative merits of the two models you made via AIC. The log-likelihoods of the two models are almost exactly equal indicating the two models do a similar job of fitting the data. The LRT is telling you that you'd be very likely to observe a test statistic (Chisq) as large as the one reported if the two models provided the same fit. Hence you fail to reject the null hypothesis that the likelihoods of the two models are equivalent.
frm.oage is "better" in the sense that it does as well as the more complex model with 1 fewer parameters. The AICs of the two models differ by almost 2 AIC units; which is, from the definition of AIC, what you'd expect if you added a redundant parameter with no additional explanatory power to the model
This is not unexpected; AIC is computed from the log-likelihood of a model. All indicators of the comparison of the "fits" of the two models is that they are essentially the same.


I don't understand what am I doing wrong?

Question: I have eliminated $y$ and have done this question in terms of $x$, then I solved the $x$ terms, collected like terms and did some elimination. After that, I made an auxiliary equation, founded roots and solved $x$ base $c$. The answer I'm getting is totally different from the book. I'm currently using Dennis G. Zill book 9th edition. Following is the book's answer.
\begin{align}x &= A + Bt + Ce^t + te^t \\
y &= -A — B — Bt - Ce^t - te^t + e^t\end{align}
Comment: Can you type out this question using MathJax? This shows your seriousness towards the question. If you can't give time to your question, why would anyone solve it for you?
Comment: If you don't know how to use MathJax, [this tutorial will help you](https://math.meta.stackexchange.com/q/5020/421580)
Answer: You are fine up to $D^3x- D^2x= e^t$.
Immediately after that you have "m^3- m^2= 0".
I presume that you are saying that the "associated homogeneous equation", $D^3x- D^2x= 0$ has "characteristic equation" $m^3- m^2= 0$.
Then you say "$m_1= 1$, $m_2= 0$".  That is true but not the entire story!
$m^3- m^2= m^2(m- 1)= 0$ so m= 0 is a double root!  The general solution to the associated homogeneous equation is $x_C= C_1e^t+ C_2e^{0t}+ C_3te^{0t}= C_1e^t+ C_2+ C_3t$.
Now, because the "non-homogeneous part" of this equation is $e^t$, you tried a "specific solution" of the form $Ae^t$.  That can't possibly work, because you already know that $Ae^t$ will give 0.  Changing the coefficient will still only give 0.  The same is true of $Ate^t$.
So try $x(t)= At^2e^t$.


Creating a Custom Button in React Typescript and add onClick Event

Question: I am trying to create a custom button component in a React Typescript project that use React Hooks and Styled components.
// Button.tsx
import React, { MouseEvent } from "react";
import styled from "styled-components";

export interface IButtonProps {
    children?: React.ReactNode;
    props?: any;
    onClick?:
        | ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
        | undefined;
}

const Button: React.FC<IButtonProps> = ({
    children,
    onClick = () => {},
    ...props
}) => {
    const handleOnClick = (e: MouseEvent<HTMLButtonElement>) => {
        onClick(e);
    };
    return (
        <ButtonStyles onClick={handleOnClick} {...props}>
            {children}
        </ButtonStyles>
    );
};

export default Button;

const ButtonStyles = styled.button``;

This is the component I want to use my custom Button
// Login.tsx
import React from "react";
import Button from "../../components/Generic/Button/Button";

const Login: React.FC = () => {
    const clickMe = () => {
        console.log("Button Clicks");
    };

    return (

            <Button onClick={clickMe}>My Button</Button>

    );
};

export default Login;

I want to click on my custom button and want to print the console log message when I click on it. But I am getting the following error. How to resolve this issue?
Argument of type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to parameter of type 'MouseEvent<HTMLButtonElement, MouseEvent<Element, MouseEvent>>'.
  Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist  TS2345

    16 | }) => {
    17 |    const handleOnClick = (e: MouseEvent<HTMLButtonElement>) => {
  > 18 |        onClick(e);
       |                ^
    19 |    };
    20 |    return (
    21 |        <ButtonStyles onClick={handleOnClick} {...props}>

Comment: I believe your `clickMe` method is missing the event argument. Try chaning it to `clickMe(e)`.
Comment: @kaveh I think you mean this:  clickMe(e)}>My Button , but still getting the error.
Comment: No, I mean where you actually create `clickMe`, so `const clickMe = () => {...}` should be `const clickMe = (e) => {...}`
Comment: nope, it didn't work as well.
Answer: UPDATED:
if you want to include them aria props

new

import React from "react";

export interface ButtonProps extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, React.AriaAttributes  {}

export const ButtonPrimary:React.FC<ButtonProps> = props => {
    const {children, ...rest} = props;

    return (
        <button {...rest}>{children}</button>
    )
}

old
import * as React from "react";

export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {}

/**
 * Button.
 *
 * @param {ButtonProps} props button's props
 * @returns {React.ReactElement<ButtonProps>} Button.
 */
export function Button(props: ButtonProps): React.ReactElement<ButtonProps> {
    const { children, ...rest } = props;
    return (
        <button
            {...rest}
        >
            {children}
        </button>
    );
}

Comment: The useful part for me was `interface Props extends ButtonHTMLAttributes {`
Answer: Your interface IButtonProps defines the expected signature of onClick
    onClick?:
        | ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void)
        | undefined;

However, the e argument to handleClick is defined differently as MouseEvent<HTMLButtonElement>
If you change the onClick signature to match your handleClick definition, that may go some way to fix it?
    onClick?:
        | ((event: React.MouseEvent<HTMLButtonElement>) => void)
        | undefined;

Answer: // Button.tsx
import React from "react";
import styled from "styled-components";

interface IButtonProps {
    children?: React.ReactNode;
    props?: any;
    onClick?: any;
}

const MyButton: React.FC<IButtonProps> = ({ onClick, children, ...props }) => {
    return (
        <ButtonStyles {...props} onClick={onClick}>
            {children}
        </ButtonStyles>
    );
};

export default MyButton;

const ButtonStyles = styled.button``;

// Login.tsx
import React from "react";
import MyButton from "../../components/Generic/Button/Button";

const Login: React.FC = () => {
    const ClickMe = () => {
        console.log("Button Clicked");
    };

    return (

            <MyButton onClick={ClickMe}>Hello MY Button</MyButton>

    );
};

export default Login;

I just able to fix the issue by changing the type of onClick?: any This is not the best solution, but at least it didn't throw any error and I can perform the onClick action in my Login.tsx.
Answer: The code snippet should work fine.

export interface ButtonProps
    extends React.ButtonHTMLAttributes<HTMLButtonElement> {
    // customProps
  }

const Button: React.FC<ButtonProps> = ({ children }) => {
    return <button>{children}</button>;
};

export default Button;


How to bind Radio Buttons In Blazor?

Question: Radio button binding is not happening in blazor. As per the documentation it is suggested to use InputRadio tag but this tag doesn't work in blazor and shows binding issue. Any suggestions on how to bind a radio button
Answer: The below code works for me
<input type="radio" checked="@(User.Gender == GenderEnum.Male)"
    name="Gender" @onchange="@(() => User.Gender = GenderEnum.Male)" />
Male

<input type="radio" checked="@(User.Gender == GenderEnum.Female)"
    name="Gender" @onchange="@(() => User.Gender = GenderEnum.Female)" />
Female

<input type="radio" checked="@(User.Gender == GenderEnum.Other)"
    name="Gender" @onchange="@(() => User.Gender = GenderEnum.Other)" />
Other

We can also have a function called from @onchange like
@onchange="@UpdateGender"
Comment: Sure that can be done! But the question is about binding simple radio buttons. I have chosen a simple Gender enum example. While choosing the gender example itself, I was not sure to go ahead since it might start a gender identity war in the comments as I left many genders in my example.
Comment: I like this, thanks!
Comment: If you're doing this, might as well make a generic component that accepts any Enum type and loops through its values.
Answer: Of course it is, it is described here:
@using System.Globalization
@typeparam TValue
@inherits InputBase<TValue>

<input @attributes="AdditionalAttributes" type="radio" value="@SelectedValue"
       checked="@(SelectedValue.Equals(Value))" @onchange="OnChange" />

@code {
    [Parameter]
    public TValue SelectedValue { get; set; }

    private void OnChange(ChangeEventArgs args)
    {
        CurrentValueAsString = args.Value.ToString();
    }

    protected override bool TryParseValueFromString(string value,
        out TValue result, out string errorMessage)
    {
        var success = BindConverter.TryConvertTo<TValue>(
            value, CultureInfo.CurrentCulture, out var parsedValue);
        if (success)
        {
            result = parsedValue;
            errorMessage = null;

            return true;
        }
        else
        {
            result = default;
            errorMessage = $"{FieldIdentifier.FieldName} field isn't valid.";

            return false;
        }
    }
}

Usage
@page "/RadioButtonExample"
@using System.ComponentModel.DataAnnotations

Radio Button Group Test

<EditForm Model="@model" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    @for (int i = 1; i <= 5; i++)
    {

           <InputRadio name="rate" SelectedValue="i" @bind-Value="model.Rating" />
           @i

    }

    <button type="submit">Submit</button>
</EditForm>

You chose: @model.Rating

@code {
    private Model model = new Model();

    private void HandleValidSubmit()
    {
        ...
    }

    public class Model
    {
        [Range(1, 5)]
        public int Rating { get; set; }
    }
}

Comment: Sure, but how do you do that without using the MS InputRadio inside an EditForm? <input type="text"... can @bind without any problems. How to do that with <input type="radio"...?
Comment: Updated link: https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#radio-buttons
Comment: Unsure whats changed since 2020, but this InputGroup solution taken as is shown above gives stacktrace error of:
InvalidOperationException: Microsoft.AspNetCore.Components.Forms.InputRadio`1[System.String] must have an ancestor Microsoft.AspNetCore.Components.Forms.InputRadioGroup`1[System.String] with a matching 'Name' property, if specified.
Comment: I mean. . . the error message literally says how to solve the error.

How to bind Radio Buttons In Blazor?