Resizing Images to have the same Height with CSS

Question: I'm trying to resize my images to have all the same height but I can't figure out what I'm doing wrong. I tried adding min-height, max-height, having a fixed height(not my goal) but still can't figure out what is wrong. See how the middle flag is shorter than the rest. Also, how can I have the top of the flags image have the round corner? Right now they are hiding the border because they are on top.

Here is my code
<template>

      <div
        class="country_card"
        v-for="country in countries"
        :key="country.name"
        @click="goToPage(`${country.name}`)"
      >

{{country.name}}

              Population:
              {{country.population.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}

</template>

Comment: How do you want the resizing to be done? Cropping or stretching?
Comment: Doesn't matter since some are shorter and some are bigger. As long as they all the same size.
Comment: Some flags will be cut out, is that OK?
Answer: That's because images are inline elements, so first thing would be to display them block.
img{
  display: block;
  width: 100%;
  height: 140px; //whatever you want
}

Now you can style it as you want. As for the rounded corners, you just need to hide the overflow
Comment: I didn't want to add a fixed height, is there any other option?


How do I check if my app is launched by a Siri shortcut on WatchOS?

Question: I am trying to create a custom SiriKit shortcut on WatchOS. I read this question for an iOS problem, but I believe that the solution is different in watchOS.
In order to do this, I followed these steps:

In WatchKit Extension target, I added the Siri capability;
I've created an Intents Extension through: File> New > Target > watchOS > Intents Extension;
In the Intent Extension group, I created a SiriKit Intent Definition file. In this file, I made some custom changes and checked "Intent is eligible for Siri Suggestions" box;
In the Intent Extension group, I also created a file named HandWashIntentHandler.swift that has the following code:

class HandWashIntentHandler: NSObject, HandWashIntentHandling{
    func handle(intent: HandWashIntent, completion: @escaping (HandWashIntentResponse) -> Void) {
        let activity = NSUserActivity(activityType: "HandWashIntent")
        let title = "Hand Wash"
        activity.title = title
        activity.suggestedInvocationPhrase = "Start hand wash"
        activity.isEligibleForPrediction = true
        activity.persistentIdentifier = title

        let response = HandWashIntentResponse(code: .continueInApp,
                                              userActivity: activity)

        completion(response)
    }
}

Then, in IntentHandler.swift, I've added the following code:

class IntentHandler: INExtension {

    override func handler(for intent: INIntent) -> Any {
        guard intent is HandWashIntent else {
             fatalError("Unhandled intent type: \(intent)")
        }

        return HandWashIntentHandler()
    }
}

Finally, in the Info.plist inside the Intent Extension Group, I've added "HandWashIntent" in the IntentsSupported. Similarly, in the Info.plist inside the WatchKit Extension Group, I've added "HandWashIntent" in the NSUserActivityTypes.

So, basically, I want the spoken shortcut "Start hand wash" through. This shortcut would open the application and push a specific controller. I read in question that the WKExtensionDelegate in watchOS is "equivalent" to AppDelegate in iOS. Then, I've tried to manipulate the userActivity in ExtensionDelegate, but there is no function to do so.
Then, I used the function handle(_:) in the ExtensionDelegate:
func handle(_ userActivity: NSUserActivity) {
     if userActivity.activityType == "HandWashIntent"{
         WKExtension.shared().rootInterfaceController?.pushController(withName: "Wash", context: nil)
     }
}

but without success. So, how do I check if my app is launched by a Siri shortcut on WatchOS?
Answer: Check this method on AppDelegate class. The launchOptions dictionary indicating the reason the app was launched. From LaunchOptionsKey you will get the information.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

Comment: Thanks, but this won't do. Since I'm developing a Watch only app, there's no delegate to work around with, as mentioned in the question itself.
Comment: @Mushu did you ever find a way to do this on Apple Watch?
Comment: @CalebBolton Unfortunately, no


Gaussian Mixture Model parameters from density

Question: How do I estimate parameters of subpopulations in a 1D gaussian mixture model when I already have density (measured on a grid) of the mixture?
All the algorithms I can find (like the well-known EM algorithm) assume that only samples from the mixture are available. My experiment directly yields density values, not separate samples. Of course I could sample manually from that density, but I feel there must be a better way
Answer: If you are willing to code a bit, you can implement your own version of the EM algorithm that takes into account the density value of a grid point. So instead of using the usual likelihood function:
$$
\log L(\Theta) = \sum_{t=1}^L\left [{\sum_{i=1}^N \phi(\boldsymbol r_t|\boldsymbol \mu_i,\boldsymbol \Sigma_i)} \right]
$$
where the outer sum is over the data points and the inner sum is over the GMM. You would instead want a density-weighted likelihood function:
$$
\log L(\Theta) = \sum_{t=1}^Lp(\boldsymbol r_t)\left [{\sum_{i=1}^N \phi(\boldsymbol r_t|\boldsymbol \mu_i,\boldsymbol \Sigma_i)} \right]
$$
This would also affect the M-step - you'd have to multiply the responsibilities (that is, the probability of each data point) by the density at that point, and make sure things are still normalized correctly. Something like this was done in this paper:
http://www.ncbi.nlm.nih.gov/pubmed/18708469
Answer: You can use minimum squared errors in order to estimate/fit a mixture density to your data (Note that this method also inherits problems of uniqueness of the estimators, as any other approach in the context of finite mixtures).
Basically, the idea is to minimize the distances between a mixture density (with fixed number of mixture components) and the observed density values, as a function of the parameters of the mixture you want to fit. The following R code shows an example with simulated data. The simulated data is obtained by simulating from a two-component Gaussian mixture and then using the command hist() (which emulates your context where only the density values are observed). As you can see, the estimators are very accurate in this example. The accuracy depends on how "informative" is the grid where you observe the density values.
rm(list=ls())
library(mixtools)

# Simulated data
set.seed(100)
n <- 500
lambda <- rep(1, 2)/2
mu <- c(0, 5)
sigma <- rep(1, 2)
mixnorm.data <- rnormmix(n, lambda, mu, sigma)
##A histogram of the simulated data.
hist(mixnorm.data,breaks=50)

# Binning the data
x.data <- hist(mixnorm.data,breaks=50,plot=FALSE)$mids
    den.data <- hist(mixnorm.data,breaks=50,plot=FALSE)$density

# Sum of squared errors
ld <- function(param){
mu1 = param[1]
mu2 = param[2]
sigma1 = param[3]
sigma2 = param[4]
eps = param[5]
if(sigma1>0 & sigma2>0 & eps >0 & eps<1){
return(sum((eps*dnorm(x.data,mu1,sigma1) + (1-eps)*dnorm(x.data,mu2,sigma2) - den.data)^2))
}
else return(Inf)
}

# Optimization step
optim(c(0,5,1,2,0.5),ld)

# Estimators of the parameters
MSEPAR <- optim(c(0,5,1,2,0.5),ld)$par

# Fitted density
dmix <- Vectorize(function(x){
mu1 = MSEPAR[1]
mu2 = MSEPAR[2]
sigma1 = MSEPAR[3]
sigma2 = MSEPAR[4]
eps = MSEPAR[5]
return(  eps*dnorm(x,mu1,sigma1) + (1-eps)*dnorm(x,mu2,sigma2))
})

hist(mixnorm.data,breaks=50,probability=T)
curve(dmix,add=T,col="red")

Comment: Yeah, I actually feared optimization because of the reasons you mentioned, but it indeed looks like it's working quite well. I'll try this on my real data later. Thank you!


Conditional variance formula and Geometric RV

Question: I'm stumped on the following problem:
"Use the conditional variance formula to determine the variance of a geometric random variable $X$ having parameter $p$."
My original idea was to have a variable $Y$ where $Y = 1$ if the first trial is a success and $Y = 0$ if not, and then to condition $X$ on $Y$:
$$\mathrm{Var}(X) = E\big[ \mathrm{Var}(X|Y) \big] + \mathrm{Var}\big( E[X|Y] \big)$$
So I begin to calculate:
$$ \mathrm{Var}(X|Y = y) = E\big[ (X - E[X|Y = y])^2 | Y = y \big]$$
At which point I'm kind of lost, as I'm not sure how to calculate the conditional probabilities such as E[X | Y=y]. Am I heading in the right direction? If so, how do I calculate these conditional probabilities?
Answer: You are heading in the right direction. If $Y$ is as you've defined, then $E(X\mid Y)$ and $\operatorname{Var}(X\mid Y)$ are both variables that take two possible values. To determine these values, think about the two cases:

$Y=1$, which occurs with probability $p$. Then the first toss is a success so conditional on $Y=1$ we know that $X=1$, i.e. we hit the success on the first trial. Therefore $E(X
\mid Y=1)=1$ and $\operatorname{Var}(X\mid Y=1)=0$.
$Y=0$, which occurs with probability $1-p$. Then the first toss was a failure, so we need to keep tossing. We can write $X=1+X'$ where $X'$, the remaining tosses required to see success, has the same distribution as $X$ but is independent of the first toss. Therefore $E(X\mid Y=0)=1+E(X)=1+\frac1p$ and $\operatorname{Var}(X\mid Y=0)=\operatorname{Var}(X)$.

Now apply the following fact, which you can easily verify:
Fact: If $W$ is a variable taking value $a$ with probability $p$ and $b$ with probability $1-p$, then $E(W)=(a-b)p$ and $\operatorname{Var}(W)=(a-b)^2p(1-p)$.
Using this fact, and plugging into the conditional variance formula, we obtain:
$$\operatorname{Var}(X)= (1-p)\operatorname{Var}(X) + (\textstyle\frac1p)^2p(1-p).$$
Now solve for $\operatorname{Var}(X)$.
Answer: The key is that if the first trial fails you are at the same place you began plus one failure.  However, if the trial succeeds you are done.
$$\begin{align}\mathsf E(\mathsf {Var}(X\mid Y)) ~=~& \mathsf E(\mathsf E(X^2\mid Y)-\mathsf E(X\mid Y)^2))
\\ =~ & \mathsf P(Y{=}0)(\mathsf E(X^2\mid Y{=}0)-\mathsf E(X\mid Y{=}0)^2)+\mathsf P(Y{=}1)(\mathsf E(X^2\mid Y{=}1)-\mathsf E(X\mid Y{=}1)^2)
\\ =~ & \mathsf P(Y{=}0)\big(\mathsf E((X+1)^2)-\mathsf E(X+1)^2\big)+\mathsf P(Y{=}1)(0)
\\ =~ & (1-p)\big(\mathsf E(X^2)+2\mathsf E(X)+1-\mathsf E(X)^2-2\mathsf E(X)-1)\big)
\\ =~ & (1-p)\big(\mathsf E(X^2)-\mathsf E(X)^2)\big)
\\ =~ & (1-p)\mathsf {Var}(X)
\end{align}$$
Can you continue?


The Matrix of linear map

Question: Let $T: P_1(R) → P_2(R)$ be a linear map defined by $T p(t) = tp(t) + p(0)$. Let
$\{t + 1, t − 1\}, \{t^2 + 1, t − 1,t + 1\}$ be bases of $P_1(R)$ and $P_2(R)$ respectively. Find the matrix of the map T.
Here is my attempt:
$\{t^2 + 1, t − 1,t + 1\}$ is a basis of $P_2(R)$, then
$(t^2 +1) = t(t^2 +1) + 0 = t^3 + t + 0 $
$(t - 1) = t(t-1) + 0 = t^2 - t + 0 $
$(t + 1) = t(t+1) + 0 = t^2 + t + 0 $
$\left[\begin{array}{ccc}
1 &  1 & 1 \\
1 & -1 & 1\\
0 & 0 & 0
\end{array}\right]$
I might be wrong, so any inputs are much appreciated.
Thanks in advance!
Comment: Your notation is confusing.  For example, you should write
$$
T[(t^2 +1)] = t(t^2 +1) + 0 = t^3 + t + 0
$$
or perhaps
$$
(t^2 +1) \mapsto t(t^2 +1) + 0 = t^3 + t + 0
$$
Note, however, that neither of these are correct, anyway.  In this case, $p(0) = 1$.
Comment: What about my matrix? is it right or wrong? any opinion?
Comment: It's wrong.  Posting an explanation.
Answer: Your matrix is incorrect.  To get you started on the right road:
$$
T((1,0)_{B_1}) =
T[(t +1)] = t(t + 1) + 1 = t^2 + t + 1
\\= (t^2 + 1) + \frac 12(t-1) + \frac 12 (t+1) = (1,1/2,1/2)_{B_2}
$$
So, the first column of your matrix should be $\pmatrix{1\\1/2\\1/2}$

The Matrix of linear map


Prove that ABCD is a rectangle

Question: From the 2018 Moroccan Mathematics Olympiad:

Let $E,F, $ and $B$ three distinct points on the plane such that: $B \in [EF]$. Let the semi-circles $(C_1), (C_2)$ and $(C_3)$ with diameters, respectively, $[EF], [EB]$ and $[BF]$ and which lie on the same semi-plane defined by [EF]. The common tangent to $(C_2)$ and $(C_3)$, through B, cuts $(C_1)$ in $D$. The other tangent to $(C_2)$ and $(C_3)$, cuts them respectively at $A$ and $C$.

Prove that $ABCD$ is a rectangle.

My Approach:
Let $O=(AC) \cap (BD)$.
We have: $Pow_{(C_2)}(O)=OB^2=OA^2$, and $Pow_{(C_3)}(O)=OB^2=OC^2$.
Thus $\triangle ABC$ is a right triangle ($\angle B=90$), and $O$ is the midpoint of $[AC]$. Now, we only have to show $O$ is the midpoint of $[BD]$, but I wasn't able to do that.
(Here: $Pow_{\omega}(P)$ is the power of point $P$ with respect to the circle $\omega$)
Answer: Let $A':=ED\cap C_2\neq E, C':=FD\cap C_3\neq F$. In virtue of Thales's Theorem, we infer $$\angle EA'B=90^\circ\implies \angle BA'D=90^\circ, \quad \angle EDF=\angle A'DC'=90^\circ, \quad \angle BC'F=90^\circ\implies \angle DC'B=90^\circ$$

Hence, $BC'DA'$ is a rectangle, so we only need to prove that $A'C'$ is tangent to both $C_2,C_3$.

This, however, follows from similarity considerations, i.e. $$\angle A'C'B=\angle A'DB=\angle EDB=\angle DFB=\angle C'FB\implies A'C'\text{ is tangent to }C_3$$
(where we have used that $\triangle EBD\sim \triangle FBD$). A similar reasoning applies to $\angle BA'C'=\angle BEA'$.
Answer: Since you have shown that $\angle{ABC} = 90°$, what remains to prove is that $\angle{ADC} = 90°$. Let $H_A$ and $H_C$ be the feet of the perpendiculars dropped from $A$ and $C$ to $EF$, respectively. As you have proved, we have $AO = OC$, which implies $H_{A}B = BH_C$ since $OB \perp EF$. We can verify that $\triangle{EAB} \sim \triangle{BCF}$ by angle chasing. Therefore, $$\frac{EH_A}{H_{A}B} = \frac{BH_C}{H_{C}F}.$$
Since $$\frac{EB}{BF} = \frac{EH_A + H_{A}B}{BH_C + H_{C}F} = \frac{EH_A + BH_C}{H_{A}B + H_{C}F},$$ we can conclude that $B$ divides the segment $[EF]$ in the same ratio as $A$ in $[EB]$ and $C$ in $[BF]$. This is sufficient to prove the desired result. I would consider a homothety centered at $E$ sending $B$ to $F$ to complete the proof. However, there are various ways to express the same idea and I think it is more constructive to leave it to you to write the finale of the proof.

Prove that ABCD is a rectangle


How are VPS connected directly to WAN?

Question: How is it that a VPS can be connected to WAN (Wide area network) without port forwarding?
Answer: The physical interface of the host machine acts as a virtual switch (a bridge, really) where the virtual interfaces of the VPS are connected to. This way, you can connect multiple virtual interfaces with just one physical one.

How are VPS connected directly to WAN?


Prove that $\min \{a^7,b^3,c^2,1\} \le abc$

Question: If $a,b,c$ are three non-negative real numbers, prove that:
$$\min \{a^7,b^3,c^2,1\} \le abc$$
I tried several ideas with the geometric mean:
$$\min \{a^7,b^3,c^2,1\} \leq \sqrt[4]{a^7b^3c^2}$$
but $\sqrt[4]{a^7b^3c^2} \leq abc$ is not true. I tried with other means but nothing significant. I think these ideas fail because the inequality is not homognenous.
Comment: Split into two cases: 1. $a,b,c \ge 1$ and 2. $\min(a,b,c) <1$. Also, if $x \in [0,1)$ then $x^{n+1} \le x^n$.
Answer: Let our minimum be equal to $k$.
Thus, $$a^{42}\geq k^6,$$
$$b^{42}\geq k^{14},$$ $$c^{42}\geq k^{21}$$ and $$1\geq k.$$
Thus, $$(abc)^{42}\geq k^{6+14+21+1}$$ or
$$abc\geq k.$$
Answer: For the sake of contradiction, assume that:
$$\min\{a^7,b^3,c^2,1\} > abc$$
Then:
$$a^7 > abc \Rightarrow a > (abc)^{\frac{1}{7}}$$
$$b^3 > abc \Rightarrow b > (abc)^{\frac{1}{3}}$$
$$c^2 > abc \Rightarrow c > (abc)^{\frac{1}{2}}$$
Also, because $\frac{1}{2}+\frac{1}{3}+\frac{1}{7} < 1$, we have:
$$1 > abc\Rightarrow 1 > abc^{1-\frac{1}{2}-\frac{1}{3}-\frac{1}{7}}$$
Multiplying these four inequalities, it follows that:
$$abc > (abc)^{\frac{1}{7}} \cdot (abc)^{\frac{1}{3}}\cdot  (abc)^{\frac{1}{2}} \cdot abc^{1-\frac{1}{2}-\frac{1}{3}-\frac{1}{7}} = abc$$
a contradiction.
Comment: can make this a direct proof:  Let $k= \min(a^7,b^3,c^2,1)\le 1$ so $abc = (a^7)^{\frac 17}(b^3)^{\frac 13}(c^2)^{\frac 12}\ge k^{\frac 17}k^{\frac 13}k^{\frac 12}=k^{\frac{41}{42}}\ge k^1$
Comment: @fleablood, I think the proof is sufficiently direct (and natural) as is. It might seem verbose, because I wanted it to be as clear as possible.
Answer: One can also grind through to get an answer:
If $a,b,c \ge 1$ or any of $a,b,c$ is zero then clearly the statement is true.
So we can suppose all are strictly positive and $\min (a,b,c) <1$.
If $a^7$ is the $\min$  then $a^{7 \over 5} \le b$ and $a^{7 \over 2} \le c$ so
$a^7 = a a^{7 \over 5} a^{7 \over 2} a^{11 \over 10} \le a a^{7 \over 5} a^{7 \over 2} \le abc$.
The same analysis mutatis mutandis applies to $b,c$.
Answer: For a positive $a$ and $x>1$,
$$
min(a^x,1) \leq min(a,1) \leq a
$$
Moreover,
$$
[min(a,b,1)]^2 = min(a^2,b^2,1) \leq min(a,1) \, min(b,1) \, .
$$
This result is immediately extended to the case of three or more variables. Apply the two equations above to obtain
$$
min(a^n,b^n,...,h^n,1) \leq a b ... h
$$
for $n>0$ variables $a...h$. The first equation tells you that
$$
min(a^{n_1},b^{n_2},...,h^{n_n},1) \leq a b ... h
$$
when $n_1...n_n\geq n$.
Comment: This is not correct. If you take $a=b={1\over 2}$ then your second formula is false.
Comment: Thank you for pointing out, I corrected the wrong statement. I was trying to generalize the original question but actually my result is rather trivial and does not apply to the case in the original question (because it requires all the exponents to be bigger than 3 for three variables).


Query mysql com join de subquery

Question: Estou precisando criar uma query que eu possa filtrar as vendas que possuem notas emitidas, na minha estrutura existem 2 tabelas: a tabela vendas e a tabela nfe. As duas são relacionadas pelo campo cod_venda.
Como posso fazer?
  SELECT v.cod_venda
  FROM vendas v

  JOIN
     ( SELECT COUNT(num_nfe) AS qnt_notas
            , cod_venda
         FROM nfe
        GROUP
           BY nfe.cod_venda
     ) notas
    ON nota.cod_venda = v.cod_venda
 WHERE  notas.qnt_notas > 0
   AND nfe.status in ('emitida', 'cancelada')

Answer: Só um pouco diferente do que você ja fez,
SELECT v.cod_venda, COALESCE(notas.qnt_notas, 0) qnt_notas
FROM vendas v
LEFT JOIN (SELECT COUNT(num_nfe) qnt_notas, cod_venda
           FROM nfe
           WHERE status IN ('emitida','cancelada')
           GROUP BY cod_venda) notas ON notas.cod_venda = v.cod_venda

Comment: Obrigado pela resposta, mas fazendo o teste notei que dessa forma quando não existir nenhum dado correspondente na tabela de notas a consulta não retorna nenhum registro, ou seja, se a venda não tiver nota ela não será mostrada, teria alguma ideia de como contornar essa situação?-
Comment: No lugar de `JOIN`, coloque `LEFT JOIN`.
Comment: Se bem que, se a venda não tiver notas, não faz sentido contar as notas, não é verdade?
Comment: Editei a resposta.
Comment: Então.. a função desta query seria para listar as vendas com notas e sem notas, para tal eu preciso fazer essa comparação entre as duas tabelas, a dificuldade é que algumas vendas podem ter mais de uma nota, senão daria para fazer um gatilho e gravar o codigo da nota na tabela de vendas... vou continuar tentando aqui, mesmo com o left join não funcionou, o having não obedece ao filtro.
Comment: Obrigado, agora funcionou!

Query mysql com join de subquery


git merge command use

Question: I can't make correct branch merge in git. For example, I have two branches:
         C - D - E  my_branch
       /
A - B -  F - G - K  *master

Now I am on master. After "git merge my_branch" I got at master some like this:
A - B - C - D - F - G - K - E - M  *master

(M - merge commit)
But I except this:
A - B - F - G - K - M

It important, because at my_branch I often make not-compilable commits, for myself only; and I don't want to push them into master. How make merge that I want?
Answer: I think what you're asking for is a way to make a single commit that appears as if you did all the work in your personal branch in one go. Note that this isn't a "merge commit" in git terminology; it's just a normal commit.
Edit: one thing to note here is that doing this means that git doesn't keep any knowledge of the merge, so it starts getting awkward if you want to continue using your personal branch from where you merged it. It's perfect though for experimental branches that don't get used again after your squashed "merge".
You can do exactly what you're after by using git merge --squash (and then commit the result using git commit). This will give you your desired result of:
A - B - F - G - K - M

What I usually do is manipulate my personal branch first (using git rebase -i master) to adjust the commits so that they appear exactly as I want, and then use git merge to bring them into master. This way I can also do:
A - B - F - G - K - M1 - M2 - M3

where M1, M2 and M3 are a rework of all the work in the personal branch, but in a way that also makes sense from the point of view of the master branch. This is useful since keeping individual commits small and logically divided is handy when using the revision history in the future.
Answer: Use the --squash option to git merge: it'll take your branch, squash it into a single commit, and then merge that in.

git merge command use


jquery use of parseFloat and toFixed

Question: This works :
var x = parseFloat($(this).val());
$(this).val(x.toFixed(2));

and not this :
$(this).val(parseFloat($(this).val())).toFixed(2);

I get "toFixed is not a function".
I don't understand why !
Answer: That is because you are applying toFixed on jQuery object and not the value. Just shift it inside one parenthesis.
$(this).val(parseFloat($(this).val()).toFixed(2));

Splitting up code to simpler and more understandable syntax is always a great idea though. Use a code minifier to take care of the build size.
Answer: Another way to write this is with val(function)
$(this).val(function(_, currVal){
    return parseFloat(currVal).toFixed(2);
});

Your problem in second version is the chaining is incorrect
Comment: $(this).val(parseFloat($(this).val()).toFixed(2));
runs. If I well understand your answer, it's better to write this code on two lines ?

jquery use of parseFloat and toFixed


Trying to run different functions based on user input

Question: def teamEnter():
    for x in range (4):
        tnames.append(input("Please enter a team name:"))
    print(tnames)
    tevent1()
#This loops 4 times and asks you to enter 4 team names

def individualEnter():
    for x in range (20):
        inames.append(input("Please enter an individuals name:"))
    print(inames)
    ievent1()
#This loops 20 times and asks you to enter 20 individual names

def intro():
    inp = input("Would you like to hold a tournament for teams or individuals: ")
    # Asks the user to enter as a team or individual
    print (' ')
    TeamOrIndividual = str(inp)
    if inp == "Individuals":
        individualEnter()
    elif inp =="Teams":
        teamEnter()
#This is the initial home page where you choose between teams or individuals
intro()

def tevent1():
    print("This is the relay race event")

def ievent1():
    print("This is the tug of war event")

I want to be able to run the tevent1 when the user inputs 'Teams' at the start and the ievent1 when the user inputs 'Individuals' at the start.
How do i do this?
Should i use an IF statement in the intro function or is there a better way to do it?
Comment: 1. Post your code as text, not as an image.  2. What's the problem with your code ?
Comment: Please, [provide a minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: Is `firstTeamPlace` a `list`?
Comment: You wrote "firstTeamPlace" array (I imagine you mean list), but then you check if it is a string. Do you want to compare the last element? Also, why don't you pass any variable to your function?
Please, provide more details about your code.
Comment: At first glance, this code seems like it will do what you want.  So, what is the problem?
Comment: Mixing strings like `"1"` with ints like `4` isn't good design. Why not have all your arrays be arrays of ints? You could use `int(input(...` rather than just `input(...`
Comment: `firstTeamPlace == "1"` (or any other condition) will never be true because it's a _list_, not a string
Answer: Simplify your logic:
def firstTeamPoints():
    firstTeamTotal.append(5 - int(firstTeamPlace))

If it turns out to be more complicated, you can use a map:
m = {
    "1": 4,
    "2": 3,
    "3": 2,
    "4": 1,
}
def firstTeamPoints():
    firstTeamTotal.append(m[firstTeamPlace])

Comment: The firstTeamTotal array still isnt being appended
Answer: You can have what you want to do in a faster and more flexible way:
#Some preparation. You can do it manually or with another function

tnames = ['team 1', 'team 2', 'team 3', 'team 4', 'team 5']
teamsPlaces = [] # This is for where the teams placed for each event, 1st, 2nd, 3rd etc
teamsTotals = [] # This is where the scores are added to make a final score for each team

#Here we prepare the final scores, with everyone starting from 0
for team in range(len(tnames)):
    teamsTotals.append(0)

def tevent1():
    print("This is the relay race event")
    print("Please enter the where each team placed next to their name (1-4)")
    eventTeamsPlaces = []
    for i in range(len(tnames)):
        teamPos = input(tnames[i])
        eventTeamsPlaces.append(teamPos) #for each event, you will have a list of places
        teamsTotals[i] = teamsTotals[i] + (len(tnames) - int(teamPos))

    teamsPlaces.append(eventTeamsPlaces) #and the list of places is appended to the list of places for all the events
    print(teamsTotals)
tevent1()

so that at the end, after two events, your outputs are:
teamsPlaces = [['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
teamsTotals = [4, 4, 4, 4, 4]

end if you want to have the list of the places for the event number 2 you can just use teamsPlaces[1] which is ['5', '4', '3', '2', '1']
With this approach, you can use this simple function for all the events, without any limit for the number of teams and the number of events.


Possible to run views_embed_view() for a specific role

Question: Without having to user_load(SOME_UID_THAT_HAS_MY_INTENED_ROLES); and swap the current $user object and then replace it.
Is it possible to say,
views_embed_view('view_of_articles');

But tell it to respect the permissions of a certain array of roles like,
views_embed_view('view_of_articles', array(SOME_RID));

I know the above wont work since the function isn't defined in such a way, but could this be possible with theme() functions, or something else I'm missing?
Answer: In view check the option of "Access" and select roles. Now even if you call the view with views_embed_view() It wont display if the user is not part of the role that have access.
Comment: Nope that's not what I'm trying to accomplish. For example, when your an admin and you've got contextual links turned on and you look at a view, you see the extra markup and the hovering states. Or imagine a field that is permissioned for certain roles, but you print the view as an admin while you want the view to look like it was for a certain role.
Comment: Have you check this module : http://drupal.org/project/roleswitcher It might help.
Comment: Yea I'm also aware of those types of modules, but I don't want to see the whole experience as the other role, just the view in question.


ServerSocket e Socket

Question: Estou tentando criar um ServerSocket:

public class RunServer {

public static void main(String[] args) {
    try {

        byte[] buffer = new byte[1024];
        String passwordCript;

        ServerSocket socketRecepcao = new ServerSocket(22300);
        System.out.println("Servidor esperando conexão na porta 22300");

        while (true) {

            Socket socketConexao = socketRecepcao.accept();
            System.out.println("Conexão estabelecida na porta "
                    + socketConexao.getPort());

            InputStream is = socketConexao.getInputStream();
            OutputStream os = socketConexao.getOutputStream();

            is.read(buffer);

            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(buffer, 0, buffer.length);

            BigInteger hash = new BigInteger(1, md.digest());
            passwordCript = hash.toString(16);

            buffer = passwordCript.getBytes();
            os.write(buffer);

            socketConexao.close();
        }

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

NOTA: É um código simples para criar ServerSocket,

Mas recebo essa exceção:
java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.PlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at com.iamExport.RunServer.main(RunServer.java:20)

Por que essa exceção está sendo lançada?
Que cuidados devo tomar depois que o ServerSocket funcionar?

NOTA: Sei que existem outros tipos de conexão como API HttpClient, etc., mas estou estudando socket...
Comment: Está usando Eclipse? Verifica no Console se não há várias instâncias do programa executando.
Comment: @utluiz, Verifiquei, na verdade está certo. Acabei executando o ServerSocket ele entrou em background... Obrigado pessoal. Estou errado em acreditar que preciso de um método para verificar se uma determinada porta pode ser usada?
Comment: Eduardo, coloque um bloco `try/catch` para tratar as exceções ao retor da chamada ao método `accept()` e, no caso de cair num `catch` com `BindException`, mostra uma mensagem mais específica como "porta em uso".
Comment: @utluiz, vou fazer isso.
Answer: Basicamente, já tem algo ouvindo nessa porta (22300). Possivelmente o seu próprio programa, rodando em background -- dê uma olhada nos processos java, certifique-se de matar todos, e tente de novo.

ServerSocket e Socket


Fourier series of $f(x)=\pi-x$

Question: $$f(x)=\pi-x \qquad x \in [0,2 \pi[$$

$$a_0=\frac{1}{\pi} \ \int_0^{2 \pi}f(x) \ dx=\frac{1}{\pi} \ \int_0^{2 \pi} (\pi-x) \ dx=0$$

$$a_n=\frac{1}{\pi} \ \int_0^{2 \pi} \cos(nx) \ dx=\frac{1}{\pi} \ \int_0^{2 \pi}(\pi \ \cos(nx)-x \ \cos(nx)) \ dx=$$
$$\frac{1}{\pi} \ \Big( \ \Big[\frac{\pi}{n} \ \sin(nx) \Big]_0^{2 \pi}-\Big[\frac{x}{n} \ \sin(nx)+\frac{1}{n^2} \ \cos(nx) \Big]_0^{2 \pi} \Big)=0 $$

$$b_n=\frac{1}{\pi} \ \Big( \ \Big[\ -\frac{\pi}{n} \ \cos(nx) \Big]_0^{2 \pi}-\Big[-\frac{x}{n} \ \cos(nx)+\frac{1}{n^2} \ \sin(nx) \Big]_0^{2 \pi} \Big)=\frac{2}{n}$$

$$f(x)=2 \sum_{n=1}^{+\infty} \frac{1}{n} \ \sin(nx)$$
Is it correct?
Comment: That is the correct approach. A plot of your answer also shows that the approximation is tending to the desired function http://www.wolframalpha.com/input/?i=plot+sum_%7Bn%3D1%7D%5E%7B20%7D+2sin(nx)%2Fn+for+x+in+(0,2pi)
Answer: Slight errors:
$$
\begin{align}
%
  a_{0} &= \frac{1}{\pi} \int_{-\pi }^{\pi } f(x) \, dx = 2\pi \\[5pt]
%
  b_{k} &= \frac{1}{\pi } \int_{-\pi }^{\pi } f(x) \sin (k x) \, dx = (-1)^k \frac{2}{k \pi}
%
\end{align}
$$
The decay of the amplitudes is linear:

The series expansion looks like
$$
 \pi - x = \pi - 2 \sin (x) + \sin (2x) - \frac{2}{3} \sin (3x) + \frac{1}{2} \sin \left( 4x \right) - \dots
$$
Convergence sequence:
Comment: Nice illustration of the Gibbs Phenomenon in this answer, too.
Answer: Any function $F(x)$ defined on $[0,2\pi]$ expands as the Fourier series
$$ F(x) = \dfrac{A_0}2 + \sum^\infty_{n=1}A_n\cos(nx) + \sum^\infty_{n=1} B_n \sin(nx),$$
$$\text{where} \qquad A_0 = \frac1\pi\!\int_0^{2\pi}\!\!\!\!\!F(x)dx, \quad
   A_n = \frac1\pi\!\int_0^{2\pi}\!\!\!\!\!F(x)\cos(nx)dx, \quad
   B_n = \frac1\pi\!\int_0^{2\pi}\!\!\!\!\!F(x)\sin(nx)dx. $$
Thus, for $f(x) = \pi-x$, these coefficients are computed as follows:
$$\begin{split}
a_0 &= \frac1\pi\!\int_0^{2\pi}\!\!\!(\pi-x)dx = 0, \\
a_n &= \frac1\pi\!\int_0^{2\pi}\!\!\!(\pi-x)\cos(nx)dx
     = \frac{1-\cos(2n\pi)-n\pi\sin(2n\pi)}{n^2\pi}, \\
b_n &= \frac1\pi\!\int_0^{2\pi}\!\!\!(\pi-x)\sin(nx)dx
     = \frac{2\cos(n\pi)\big[n\pi\cos(n\pi)-\sin(n\pi)\big]}{n^2\pi}.
\end{split}$$
Therefore, its Fourier series is given by
$$\sum_{n=1}^\infty \frac1{n^2\pi} \Big\{ \big[ 1 -\cos(2n\pi) -n\pi\sin(2n\pi) \big] \cos(nx) + 2\cos(n\pi) \big[ n\pi\cos(n\pi) -\sin(n\pi) \big] \sin(nx) \Big\}.$$

Fourier series of $f(x)=\pi-x$


Por que o atributo gravity do objeto LinearLayout.LayoutParams não funciona como o método setGravity() da View?

Question: Problema
Estou trabalhando em uma biblioteca UI para android, onde seto os parâmetros de layout (height, width, weight e gravity) dinamicamente via código, em um objeto LinearLayout.LayoutParams mas o atributo gravity não parece ter o mesmo efeito de setGravity(gravity) direto na View.

Obs: não seto diretamente a View por que na codificação do componente não pretendo ter  acesso a View diretamente.

O que faço resumidamente é algo similar a isso:
// width = 0, height = LinearLayout.LayoutParams.WRAP_CONTENT, weight = 1000
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1000);
params.gravity = Gravity.RIGHT;
textView1.setLayoutParams(params);

Mas o textview1 não fica alinhado a direita como deveria.
Já se eu faço o seguinte código dai funciona:
// width = 0, height = LinearLayout.LayoutParams.WRAP_CONTENT, weight = 1000
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1000);
textView1.setLayoutParams(params);
textView1.setGravity(Gravity.RIGHT);

Pergunta?

Por que isso acontece?
gravity do objeto LinearLayout.LayoutParams e setGravity da View são atribitos diferentes?
Qual a diferença entre as duas abordagens?
Há alguma maneira de obter o mesmo resultado do setGravity da View no gravity do objeto LinearLayout.LayoutParams?

Obs: A View que me refiro na questão, no caso é o TextView.
Para ficar mais claro, fiz um exemplo em HTML do efeito que quero no layout do meu TextView android, através do LinearLayout.LayoutParams.
Comment: São atributos diferentes, não? Um me parece ser a gravidade do `LinearLayout`, e o outro a gravidade da `TextView` que fica dentro do `LinearLayout`.
Comment: Na verdade não sei, no inicio acreditei que era a mesma coisa, mais não deve ser, e se assim for, há como setar a gravidade do `TextView` através do `LinearLayout.LayoutParams`?
Comment: O que significa o `textview1` ficar alinhado à direita? É o próprio `TextView` que fica alinhado em relação ao `LinearLayout` que o contém, ou é o texto dentro do `TextView` que fica alinhado à direita?
Comment: @Piovezan, é o texto alinhado a direita, é tipo um grid que estou fazendo, então valores numéricos quero deixar alinhados a direita e strings a esquerda.
Comment: Então creio que não tenha jeito. Porque o `gravity` de `LinearLayout.LayoutParams` se refere ao layout dentro do qual está a `TextView`. Para alinhar o texto contido na `TextView`, você tem que alterar a gravity da própria `TextView` como está fazendo no segundo exemplo. Por que esse segundo exemplo não é viável para você?
Comment: @Piovezan, é que a estrutura atual, não está disponibilizando a `View` para ser setada diretamente, somente o `LinearLayout.LayoutParams`, que é setado a ele. Achei que talvez poderia conseguir o resultado esperado sem ter que setar diretamente a `View`. Mais é possível sim, com alguma mudança de estrutura no componente, se a unica solução for essa e farei.
Answer:

Por que isso acontece?
gravity do objeto LinearLayout.LayoutParams e setGravity da View são
  atribitos diferentes?
Qual a diferença entre as duas abordagens?

Porque na classe LinearLayout.LayoutParams o parâmetro public int gravity refere-se a gravidade para a View em que o objeto (no seu caso um TextView) está associado , diferente da gravidade interna do objeto TextView que, no seu segundo exemplo, você utilizou o método setGravity(Gravity.RIGHT) que fará com que o texto do TextView se alinhe a direita.

Há alguma maneira de obter o mesmo resultado do setGravity da View no gravity do objeto LinearLayout.LayoutParams?

Não, se essa "View" que você se refere seja o TextView e o resultado que você necessita seja o alinhamento do texto do TextView para esquerda ou direita. Já que o LinearLayout.LayoutParams é responsável pela informação por layout filho do esquema associado com ViewLinearLayout e não a gravidade interna desses filhos.
Fontes consultadas: LinearLayout.LayoutParams e TextView
Comment: Sua resposta, parece ser interessante e coerente, andei pesquisando sobre o assunto e parece que `gravity` do `LinearLayout.LayoutParams` é equivalente a `layout_gravity` do [tag:xml], e `setGravity()` seria equivalente ao `gravity` do [tag:xml], fazendo sentido em relação ao que você citou.
Comment: Seria mais preciso dizer que o parâmetro `gravity` de `LinearLayout.LayoutParams` se refere à gravidade do layout dentro do qual se encontra o `TextView`, afetando portanto o posicionamento do `TextView` dentro desse layout e não do que existe dentro do `TextView`.
Answer: Mas eu não percebi se queres alinhar o texto a direita dentro da textview  ou se queres alinhar a própria texview a direita.
Desculpa a resposta mas não tenho reputação para comentar...
Posso te responder a isso dependendo do que queres, se puderes explicar melhor...
Resposta

Não dá para fazer isso através do LinearLayout.LayoutParams. Podes é fazer outra coisa, defines 2 tipos de TextView no xml, um com texto alinhado a direita outra com o texto alinhado a esquerda, assim quando quiseres usar é só utilizar a que te der mais jeito.
Comment: Alinhar o texto a direita. Fiz um [exemplo](http://jsfiddle.net/fernandoleal/CP7jK/1/) em [tag:html] do efeito que quero no `layout` do meu `TextView` [tag:android], da maneira que citei na questão, através do `LinearLayout.LayoutParams`
Comment: Não dá para fazer isso através do `LinearLayout.LayoutParams`.
Podes é fazer outra coisa, defines 2 tipos de `TextView` no xml, um com texto alinhado a direita outra com o texto alinhado a esquerda, assim quando quiseres usar é só utilizar a que te der mais jeito.


plm::purtest: Error in object[1:(length(object) - x)] : only 0's may be mixed with negative subscripts

Question: I am trying to conduct a Im-Pesaran-Shin panel unit root test and R keeps throwing me this error:
<code>Error in object[1:(length(object) - x)] : only 0's may be mixed with negative subscripts
</code>
I have looked up what the error means, but it is unclear what is throwing it here within plm::purtest().
Specifically, I am working with this dataset:
<code>> dput(wdi)
structure(list(countrycode = c("BRA", "BRA", "BRA", "BRA", "BRA",
"BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA",
"BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA",
"BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA",
"BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "BRA",
"BRA", "BRA", "BRA", "BRA", "BRA", "BRA", "GHA", "GHA", "GHA",
"GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA",
"GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA",
"GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA",
"GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA",
"GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "GHA", "IRL",
"IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL",
"IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL",
"IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL",
"IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL",
"IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL", "IRL",
"IRL", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX",
"MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX",
"MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX",
"MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX",
"MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX", "MEX",
"MEX", "MEX", "MEX", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL",
"NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL",
"NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL",
"NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL",
"NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL", "NZL",
"NZL", "NZL", "NZL", "NZL", "NZL", "PER", "PER", "PER", "PER",
"PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER",
"PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER",
"PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER",
"PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER", "PER",
"PER", "PER", "PER", "PER", "PER", "PER", "PER", "ZAF", "ZAF",
"ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF",
"ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF",
"ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF",
"ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF",
"ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF", "ZAF",
"SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE",
"SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE",
"SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE",
"SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE",
"SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE", "SWE",
"SWE", "SWE", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR",
"TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR",
"TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR",
"TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR",
"TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR", "TUR",
"TUR", "TUR", "TUR", "TUR", "GBR", "GBR", "GBR", "GBR", "GBR",
"GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR",
"GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR",
"GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR",
"GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR", "GBR",
"GBR", "GBR", "GBR", "GBR", "GBR", "GBR"), year = c(1971L, 1972L,
1973L, 1974L, 1975L, 1976L, 1977L, 1978L, 1979L, 1980L, 1981L,
1982L, 1983L, 1984L, 1985L, 1986L, 1987L, 1988L, 1989L, 1990L,
1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L,
2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L,
2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L,
1971L, 1972L, 1973L, 1974L, 1975L, 1976L, 1977L, 1978L, 1979L,
1980L, 1981L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L, 1988L,
1989L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L,
1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L,
2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 2015L,
2016L, 2017L, 1971L, 1972L, 1973L, 1974L, 1975L, 1976L, 1977L,
1978L, 1979L, 1980L, 1981L, 1982L, 1983L, 1984L, 1985L, 1986L,
1987L, 1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L,
1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L,
2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L,
2014L, 2015L, 2016L, 2017L, 1971L, 1972L, 1973L, 1974L, 1975L,
1976L, 1977L, 1978L, 1979L, 1980L, 1981L, 1982L, 1983L, 1984L,
1985L, 1986L, 1987L, 1988L, 1989L, 1990L, 1991L, 1992L, 1993L,
1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L,
2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L,
2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 1971L, 1972L, 1973L,
1974L, 1975L, 1976L, 1977L, 1978L, 1979L, 1980L, 1981L, 1982L,
1983L, 1984L, 1985L, 1986L, 1987L, 1988L, 1989L, 1990L, 1991L,
1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L,
2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L,
2010L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 1971L,
1972L, 1973L, 1974L, 1975L, 1976L, 1977L, 1978L, 1979L, 1980L,
1981L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L, 1988L, 1989L,
1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L,
1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L,
2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L,
2017L, 1971L, 1972L, 1973L, 1974L, 1975L, 1976L, 1977L, 1978L,
1979L, 1980L, 1981L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L,
1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L,
1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L,
2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 1971L, 1972L, 1973L, 1974L, 1975L, 1976L,
1977L, 1978L, 1979L, 1980L, 1981L, 1982L, 1983L, 1984L, 1985L,
1986L, 1987L, 1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L,
1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L,
2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L,
2013L, 2014L, 2015L, 2016L, 2017L, 1971L, 1972L, 1973L, 1974L,
1975L, 1976L, 1977L, 1978L, 1979L, 1980L, 1981L, 1982L, 1983L,
1984L, 1985L, 1986L, 1987L, 1988L, 1989L, 1990L, 1991L, 1992L,
1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L,
2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L,
2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 1971L, 1972L,
1973L, 1974L, 1975L, 1976L, 1977L, 1978L, 1979L, 1980L, 1981L,
1982L, 1983L, 1984L, 1985L, 1986L, 1987L, 1988L, 1989L, 1990L,
1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L,
2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L,
2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L
), expenditures_pcgdp = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
18.57386, 18.751022, 19.390184, 19.359026, 19.554941, 24.42634,
25.987106, 23.572901, 30.126379, 36.56868, 34.187275, 23.47085,
28.483221, 36.510372, 32.207279, NA, NA, 21.815582, 21.894501,
21.709864, 21.368114, 22.58164, 22.627327, 24.688396, 22.700518,
25.369011, 27.834694, 26.809689, 27.305458, 26.337072, 30.267986,
30.754955, 30.177795, 30.206541, 31.378775, 36.158054, 35.687759,
34.928814, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 20.510181, NA, NA, NA,
NA, NA, NA, NA, NA, 28.624834, 28.618805, 31.492687, 34.782394,
35.274593, 34.061157, 35.314377, 36.87944, 40.241753, 42.121765,
45.52338, 46.444908, 44.971764, 45.809807, 44.980827, 44.660767,
41.026974, 35.127625, 35.699303, 37.080471, 37.537243, 37.584755,
37.071335, 37.157104, 35.310028, 33.080204, 31.131033, 30.537609,
27.688242, 28.981302, 29.453209, 29.697298, 29.707375, 30.413275,
30.615002, 31.872538, 36.937172, 43.849823, 62.190903, 43.830479,
39.411423, 37.782665, 34.756107, 27.055733, 25.42186, 24.40394,
NA, 10.088495, 10.419682, 11.666667, 12.545455, 13.129103, 12.979989,
12.665811, 13.168188, 10.872793, 12.571509, 21.955528, 21.040037,
18.658382, 20.529604, 24.904715, 27.330492, 23.800133, 19.341707,
16.918575, 13.772678, 13.362055, 10.87185, 10.913582, 11.91382,
11.684354, 12.217944, 11.161502, 11.962865, 12.680059, NA, NA,
NA, NA, NA, NA, NA, 22.104532, 21.570011, 21.403656, 21.732147,
21.873823, 21.551323, 21.794832, 21.630699, 20.977993, 20.551291,
NA, 25.247524, 25.61692, 27.413506, 31.096819, 28.485542, 31.339758,
34.008984, 34.089359, 35.096714, 36.595699, 36.98917, 36.324593,
36.764984, 35.748989, 37.47002, 41.12204, 38.913746, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 31.551292, 30.72579,
31.217342, 30.436657, 30.986078, 31.365622, 31.281376, 32.600452,
34.353168, 34.30434, 40.076042, 35.023129, 33.09127, 32.513466,
31.866594, 30.841063, 30.244081, NA, 12.65359, 13.161526, 11.746681,
13.605937, 14.230906, 13.222456, 15.667478, 13.332707, 18.763405,
17.391436, 16.437389, 18.305017, 17.419443, 17.033836, 16.936241,
15.852185, 13.212941, 12.977591, 19.457102, 14.430077, 17.072933,
15.167376, 15.430264, 17.501808, 17.04991, 16.625416, 16.924335,
17.818132, 18.421289, 18.243986, 17.613434, 17.770838, 17.383371,
18.020134, 17.077677, 18.1434, 17.823631, 18.483582, 17.82234,
17.627886, 17.917788, 18.954376, 20.703936, 20.914022, 19.512623,
20.281525, NA, 17.748812, 17.127398, 18.040783, 19.832541, 20.830061,
21.021811, 21.012228, 21.069654, 19.035093, 20.42724, 22.72263,
24.704796, 24.815081, 26.215103, 27.421268, 27.714472, 28.065773,
27.272587, 27.711384, 27.200689, 30.498302, 31.950811, 28.351601,
28.823311, 29.879169, 28.582968, 28.511471, 28.059881, 27.193941,
27.128674, 26.470325, 27.846453, 28.650305, 28.690125, 28.907198,
29.012487, 29.959778, 32.244446, 31.783628, 32.320011, 33.081799,
34.701942, 34.321373, 35.853924, 34.535339, 34.430107, NA, 23.336748,
23.277695, 24.514791, 24.874428, 27.027029, 30.131639, 32.333992,
33.955139, 34.16431, 36.955612, 37.631519, 39.449322, 38.222195,
39.360039, 37.851521, 36.252819, 35.028114, 34.473179, 35.676899,
37.151897, 40.275459, 44.848915, 42.49633, 42.860813, 40.371529,
38.588623, 37.811268, 36.588802, 34.654915, 33.300312, 33.733418,
33.769047, 32.526688, 33.026478, 31.778162, 31.087246, 31.113777,
33.444366, 32.788441, 32.056057, 32.552181, 33.305042, 32.819454,
31.870672, 31.485804, 31.337461, NA, 14.908337, 15.137362, 12.283178,
14.225877, 14.079203, 15.923507, 16.056641, 18.721428, 18.240738,
15.725858, NA, 16.752722, 17.537312, 16.726931, 13.669138, 14.443557,
14.439909, 14.98505, 15.295647, 19.233305, 18.86739, 22.93519,
21.935106, 20.955494, 25.173187, 27.570986, 21.864641, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 29.87928, 35.954453, 33.555801, 30.999722,
30.320856, 29.989727, 29.894615, 29.03376, 30.836208, 31.929678,
NA, 29.511858, 28.838079, 33.253574, 36.48901, 36.444958, 34.528168,
34.489017, 33.979923, 35.559879, 37.48444, 37.671547, 36.881618,
36.819561, 35.932758, 34.977859, 33.137413, 30.972441, 29.654623,
32.583042, 34.784077, 37.640625, 37.368984, 37.079777, 35.231194,
34.015076, 32.878323, 32.278214, 32.064007, 32.444122, 32.996822,
34.117905, 35.44413, 36.025055, 36.509747, 36.590897, 36.796555,
39.736668, 42.173836, 42.668694, 41.397018, 42.063259, 39.776093,
38.965351, 38.110355, 37.0849, 36.419762), agedepratio = c(82.931709,
81.901657, 80.82663, 79.637421, 78.337425, 77.244598, 76.109596,
74.954445, 73.816582, 72.726616, 72.077133, 71.35627, 70.61274,
69.867432, 69.105843, 68.545952, 67.852531, 67.060593, 66.204407,
65.295174, 64.290749, 63.323193, 62.320408, 61.20837, 59.980881,
58.887756, 57.723915, 56.534389, 55.379333, 54.28643, 53.446384,
52.571552, 51.697498, 50.853268, 50.044228, 49.188732, 48.407051,
47.675579, 46.965405, 46.276161, 45.668896, 45.118832, 44.623783,
44.189659, 43.824265, 43.644318, 43.471035, 93.654572, 94.303688,
94.668945, 94.771027, 94.571213, 94.825691, 94.772957, 94.445572,
93.964439, 93.488815, 93.210777, 92.718567, 92.107185, 91.398659,
90.569069, 90.162369, 89.594406, 88.886932, 88.077095, 87.204109,
86.790482, 86.233612, 85.578415, 84.864082, 84.106422, 83.627251,
83.11528, 82.54203, 81.870735, 81.1036, 80.802834, 80.310379,
79.713921, 79.115265, 78.548485, 78.051186, 77.563339, 77.030861,
76.408806, 75.709976, 75.248726, 74.719223, 74.150696, 73.56472,
72.958336, 72.608185, 72.136475, 71.195663, 71.192047, 71.456429,
71.559555, 71.312447, 71.693222, 71.417168, 70.746895, 70.075005,
69.555946, 69.264709, 69.229332, 69.25042, 69.006073, 68.33709,
67.792969, 66.873779, 65.62571, 64.232254, 62.823437, 60.877613,
59.083473, 57.38168, 55.709702, 54.075077, 52.297222, 50.665005,
49.20039, 47.958763, 46.968361, 46.094597, 45.387348, 44.874535,
44.579624, 44.508358, 44.698906, 45.049824, 45.563839, 46.181278,
46.832077, 48.227726, 49.643017, 51.041523, 52.416599, 53.763546,
54.516586, 55.195694, 100.97634, 101.12232, 101.30132, 101.24901,
100.81917, 100.78103, 100.04939, 98.896317, 97.660126, 96.457138,
94.581139, 93.02182, 91.529411, 89.788124, 87.709747, 85.48317,
83.093506, 80.666954, 78.411591, 76.426743, 74.705933, 73.094383,
71.61937, 70.282234, 69.068718, 68.024612, 67.136322, 66.344002,
65.561371, 64.740204, 63.884403, 62.995811, 62.100426, 61.244801,
60.448498, 59.409908, 58.415142, 57.44503, 56.47892, 55.519535,
54.587555, 53.694649, 52.855999, 52.090576, 51.410007, 50.912548,
50.432297, 66.547775, 65.872124, 65.119904, 64.190498, 63.025288,
62.610508, 61.818306, 60.745243, 59.628761, 58.640125, 57.317196,
56.291706, 55.442329, 54.613243, 53.771111, 53.362682, 52.959312,
52.591366, 52.362022, 52.332661, 52.379318, 52.492287, 52.640377,
52.764015, 52.818283, 53.011585, 53.113224, 53.080429, 52.938091,
52.745636, 52.266438, 51.843834, 51.443302, 51.034573, 50.620441,
50.453308, 50.329483, 50.274757, 50.322002, 50.489616, 51.022743,
51.491615, 51.939129, 52.416862, 52.947323, 53.422169, 54.0536,
91.579765, 91.171135, 90.589897, 89.861389, 89.014755, 88.488884,
87.882889, 87.148468, 86.19709, 84.999428, 84.187119, 82.963264,
81.524696, 80.121834, 78.867966, 77.739166, 76.825897, 75.994583,
75.045448, 73.903, 73.09256, 72.033272, 70.839844, 69.671562,
68.594772, 67.769997, 66.993668, 66.236053, 65.441063, 64.579468,
63.614025, 62.652561, 61.666943, 60.651684, 59.63414, 58.694168,
57.723747, 56.771221, 55.909172, 55.183006, 54.612026, 54.165955,
53.814392, 53.499001, 53.188076, 52.991005, 52.757019, 82.567154,
82.405235, 82.232109, 81.952477, 81.522667, 81.619049, 81.472397,
81.162491, 80.796036, 80.421066, 80.230362, 80.002632, 79.682411,
79.173851, 78.433952, 78.021675, 77.336739, 76.440521, 75.412346,
74.290337, 72.828934, 71.309128, 69.74424, 68.142059, 66.521072,
65.339455, 64.130157, 62.890823, 61.62302, 60.342697, 59.58894,
58.758904, 57.893974, 57.049004, 56.254921, 55.786282, 55.341854,
54.920479, 54.511227, 54.115749, 53.745983, 53.394096, 53.070511,
52.774303, 52.500668, 52.408577, 52.2752, 53.490852, 54.19722,
54.847065, 55.399555, 55.831303, 56.139889, 56.28994, 56.305786,
56.214592, 56.032066, 55.816753, 55.548401, 55.257935, 55.00798,
54.862591, 54.886204, 54.998989, 55.188595, 55.412621, 55.638783,
56.106255, 56.495178, 56.820328, 57.044559, 57.108734, 57.164944,
56.937592, 56.507263, 56.022076, 55.583862, 54.776466, 54.256596,
53.902184, 53.549721, 53.165596, 53.233356, 53.063549, 52.837097,
52.834866, 53.201508, 53.873688, 54.871342, 56.118649, 57.378799,
58.465595, 59.32048, 60.051353, 83.235596, 82.958832, 82.671089,
82.334625, 81.943512, 81.820663, 81.538429, 81.100784, 80.497345,
79.725449, 78.801147, 77.71624, 76.512993, 75.223877, 73.87291,
72.845505, 71.671928, 70.400024, 69.091164, 67.784149, 66.549622,
65.335007, 64.145271, 62.997074, 61.917458, 61.028004, 60.230892,
59.489128, 58.744022, 57.966362, 57.364075, 56.638317, 55.869118,
55.147713, 54.506332, 53.841915, 53.274231, 52.76305, 52.26244,
51.776344, 51.391968, 51.030239, 50.701637, 50.403507, 50.116802,
49.849239, 49.498661, 59.805176, 60.250923, 60.48938, 60.453823,
60.128387, 59.745125, 59.134285, 58.303833, 57.303909, 56.207214,
55.320984, 54.383408, 53.492805, 52.754951, 52.228966, 52.27507,
52.409393, 52.63274, 52.917061, 53.224442, 53.579063, 53.954037,
54.312584, 54.579739, 54.707645, 54.718445, 54.586754, 54.342087,
54.029263, 53.675674, 53.321774, 52.882805, 52.407959, 51.954433,
51.571106, 51.410065, 51.329597, 51.358742, 51.511276, 51.791718,
52.523602, 53.26041, 54.015648, 54.782848, 55.535969, 56.174866,
56.809673), birthrateper1000 = c(34.653999, 34.112, 33.674999,
33.337002, 33.083, 32.894001, 32.734001, 32.563, 32.351002, 32.058998,
31.655001, 31.135, 30.507999, 29.783001, 28.982, 28.134001, 27.278,
26.452, 25.677, 24.979, 24.370001, 23.837999, 23.365, 22.940001,
22.540001, 22.139, 21.716, 21.256001, 20.753, 20.204, 19.618,
19.016001, 18.42, 17.844999, 17.309999, 16.832001, 16.413, 16.052999,
15.749, 15.492, 15.269, 15.06, 14.852, 14.635, 14.405, 14.163,
13.918, 46.403, 46.071999, 45.717999, 45.351002, 44.979, 44.609001,
44.243, 43.881001, 43.521, 43.164001, 42.805, 42.438, 42.057999,
41.661999, 41.244999, 40.799999, 40.332001, 39.846001, 39.353001,
38.867001, 38.408001, 37.987999, 37.612, 37.280998, 36.980999,
36.696999, 36.408001, 36.102001, 35.778999, 35.445999, 35.117001,
34.811001, 34.539001, 34.303001, 34.104, 33.941002, 33.799, 33.660999,
33.513, 33.333, 33.099998, 32.806, 32.448002, 32.028999, 31.556999,
31.047001, 30.52, 22.6, 22.6, 22.299999, 22, 21.1, 20.9, 21,
21.1, 21.5, 21.700001, 20.9, 20.299999, 19.1, 18.1, 17.6, 17.4,
16.5, 15.5, 14.8, 15.1, 14.9, 14.4, 13.8, 13.4, 13.5, 13.9, 14.4,
14.5, 14.4, 14.4, 15, 15.4, 15.4, 15.2, 14.8, 15.3, 16.200001,
16.700001, 16.700001, 16.5, 16.200001, 15.6, 14.9, 14.4, 13.9,
13.4, 12.9, 43.935001, 43.555, 42.903, 41.98, 40.824001, 39.505001,
38.130001, 36.793999, 35.554001, 34.453999, 33.511002, 32.695999,
31.979, 31.354, 30.805, 30.313999, 29.860001, 29.423, 28.989,
28.548, 28.101, 27.653999, 27.212, 26.774, 26.336, 25.899, 25.461,
25.021999, 24.58, 24.132, 23.673, 23.205, 22.731001, 22.259001,
21.799, 21.365999, 20.968, 20.608999, 20.287001, 19.992001, 19.714001,
19.434999, 19.145, 18.837, 18.511999, 18.173, 17.83, 22.6, 21.799999,
20.5, 19.6, 18.299999, 17.700001, 17.299999, 16.299999, 16.799999,
16.200001, 16.200001, 15.8, 15.8, 16, 15.9, 16.299999, 16.799999,
17.299999, 17.5, 17.5, 17.4, 17.280001, 16.530001, 15.95, 15.77,
15.34, 15.23, 14.51, 14.87, 14.66, 14.36, 13.67, 13.94, 14.2,
13.96, 14.14, 15.15, 15.1, 14.53, 14.68, 14, 13.87, 13.2, 12.68,
13.27, 12.65, 12.43, 41.612999, 40.952999, 40.365002, 39.845001,
39.361, 38.862999, 38.306, 37.661999, 36.933998, 36.147999, 35.347,
34.582001, 33.889999, 33.278999, 32.743, 32.261002, 31.794001,
31.311001, 30.798, 30.243, 29.643, 29.011, 28.360001, 27.700001,
27.040001, 26.392, 25.767, 25.172001, 24.615, 24.1, 23.627001,
23.190001, 22.785, 22.41, 22.07, 21.768999, 21.507, 21.278, 21.072001,
20.875999, 20.673, 20.452, 20.202999, 19.924, 19.615, 19.281,
18.936001, 37.632999, 37.471001, 37.282001, 37.061001, 36.806,
36.527, 36.233002, 35.926998, 35.605999, 35.257999, 34.872002,
34.436001, 33.944, 33.393002, 32.780998, 32.104, 31.375999, 30.615999,
29.841, 29.075001, 28.337999, 27.646999, 27.013, 26.448, 25.957001,
25.538, 25.177, 24.861, 24.580999, 24.329, 24.101, 23.892, 23.698,
23.511, 23.330999, 23.159, 22.995001, 22.836, 22.677999, 22.51,
22.322001, 22.108, 21.865, 21.594, 21.297001, 20.981001, 20.655001,
14.1, 13.8, 13.5, 13.5, 12.6, 12, 11.6, 11.3, 11.6, 11.7, 11.3,
11.1, 11, 11.3, 11.8, 12.2, 12.5, 13.3, 13.7, 14.5, 14.4, 14.2,
13.5, 12.8, 11.7, 10.8, 10.2, 10.1, 10, 10.2, 10.3, 10.7, 11.1,
11.2, 11.2, 11.7, 11.7, 11.9, 12, 12.3, 11.8, 11.9, 11.8, 11.9,
11.7, 11.8, 11.5, 39.632, 39.233002, 38.775002, 38.251999, 37.669998,
37.051998, 36.422001, 35.794998, 35.167999, 34.521999, 33.823002,
33.049999, 32.195, 31.27, 30.295, 29.304001, 28.334999, 27.424,
26.594, 25.865, 25.249001, 24.728001, 24.283001, 23.9, 23.552999,
23.219, 22.874001, 22.506001, 22.105, 21.672001, 21.218, 20.763,
20.323999, 19.908001, 19.521, 19.166, 18.837, 18.528999, 18.237,
17.955999, 17.677999, 17.399, 17.115, 16.826, 16.533001, 16.240999,
15.954, 16.1, 14.9, 13.9, 13.1, 12.4, 12, 11.7, 12.2, 13.1, 13.4,
13, 12.8, 12.8, 12.9, 13.3, 13.3, 13.7, 13.8, 13.6, 13.9, 13.8,
13.6, 13.2, 13, 12.6, 12.6, 12.5, 12.3, 11.9, 11.5, 11.3, 11.3,
11.7, 11.9, 12, 12.3, 12.6, 12.9, 12.7, 12.9, 12.8, 12.8, 12.1,
12, 11.9, 11.8, 11.4)), class = "data.frame", row.names = c(NA,
-470L))
</code>
and am trying to perform the ips test on the expenditures_pcgdp column:
<code>purtest(expenditures_pcgdp ~ 0, data = wdi, test = 'ips', index = c('countrycode', 'year'), lags = 'SIC', pmax = 10)

</code>
Anyone more familiar with how this package works know what I am doing wrong and how to fix it?
EDIT: adjusted some language for clarity
Answer: You should have received in addition to the error a warning about NA dropping:
<code>In addition: Warning message:
In purtest(expenditures_pcgdp ~ 0, data = wdi, test = "ips", index = c("countrycode",  :
  NA value(s) encountered and dropped, results may not be reliable
</code>
If not, update your version of package <code>plm</code>. This warning hinted me to look closer at the data after NA dropping: for observational unit "GHA", there is only one observation left and that is the root cause  for the error. Lagging this, will leave no observation left for this invidual and the code errors. The package should give a better error message in this case...
Once you remove this individual, the code will run. However, note that the IPS test is not meant to be executed without exogeneous variables. Thus, in the code below, I introduced intercepts (<code>~ 1</code> instead of <code>~ 0</code>).
<code>pwdi <- pdata.frame(wdi)
pdim <- pdim(pwdi)
pdim$Tint # balanced panel 47 obs per unit

pwdi2 <- pdata.frame(na.omit(wdi[ , c('countrycode', 'year', 'expenditures_pcgdp')]))
pdim2 <- pdim(pwdi2)
pdim2$Tint # after NA dropping: GHA has only 1 observation

pwdi3 <- pwdi2[pwdi2$countrycode != "GHA", ] # remove offending unit completely

# run IPS test with intercepts as exogeneous variables
purtest(expenditures_pcgdp ~ 1, data = pwdi3, test = 'ips', lags = 'SIC', pmax = 10)
# Im-Pesaran-Shin Unit-Root Test (ex. var.: Individual Intercepts)
#
# data:  expenditures_pcgdp ~ 1
# Wtbar = -1.7792, p-value = 0.03761
# alternative hypothesis: stationarity
</code>


como deixar express asincrono?

Question: estou tendo um problema com esse codigo:
const express = require("express")

const app = express()

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms)
    })
}

async function teste() {
    await sleep(10000)
    return "teste"
}

app.get("/teste", async (_, res) => {
    const t = await teste()
    res.send(t)
})

app.listen(80)

se eu deixar sem o await ele retorna uma pagina em branco, e se eu der await ele bloqueia o codigo pros outros requests
por ex:
ele só vai fazer o request 2 quando terminar o 1
Answer: Não há nada o que fazer, o Express já gerencia requisições de forma assíncrona.

O que eu vou fazer aqui é apenas uma suposição: o seu problema não está no servidor, mas sim no seu cliente.
Uma das formas que eu imagino que você possa estar tendo problemas, é no seu front-end, onde você está fazendo duas requisições idênticas, e a segunda só começa a processar depois que a primeira termina.
Por exemplo, se você rodar o seguinte na sua página (ou no console do navegador):
fetch('/teste').then(res => res.text()).then(payload => console.log(payload));
fetch('/teste').then(res => res.text()).then(payload => console.log(payload));

Você poderá observar que terá um intervalo de 10 segundos entre a resolução de uma requisição e a outra. Esse é o intervalo programado no servidor. Mas na verdade o que está acontecendo é que o seu navegador está esperando a primeira requisição terminar para começar a outra, não é o seu servidor quem está esperando. Como as requisições são idênticas, o navegador está tentando fazer o que ele acha mais otimizado.
Se por outro lado você "enganar" o navegador, tentando parecer que duas chamadas terão resultados diferentes, como por exemplo:
fetch('/teste?a').then(res => res.text()).then(payload => console.log(payload));
fetch('/teste?b').then(res => res.text()).then(payload => console.log(payload));

Nesse caso não haverá otimização, e ele fará as duas requisições simultaneamente, e você receberá as respostas simultaneamente.
Comment: o problema não é no frontend, eu abri 2 abas no navegador mesmo e dei enter, um só inicia quando o outro termina
Comment: Ana, mesmo que você fizer as requisições em abas diferentes você ainda vai ter o problema. Faça o teste enviando um parâmetro como eu coloquei no exemplo e verifique o resultado.

como deixar express asincrono?


How do I stop (not kill) an Activity to trigger an onRestart()?

Question: I'm working on an Android application. Our problems manifest when the user runs our app, navigates away via the home or back button, and comes back later. From the official Android activity lifecycle documentation and Eric Burke's helpful reformatting of the lifecycle diagram, I suspect that our activity is begin killed while stopped, but (critically) not destroyed.
In other words, from running, the functions called are onPause(), onStop(), onRestart(), onStart(), and onResume(). Note, importantly, that this means that onRestart() is being called in the middle instead of onCreate(), which would happen if the app were just killed and removed from memory. This, I think, is the problem.
That's the setup. Here's the question: is there any way that I can reliably force the application to be stopped so that I can reproduce this condition. I don't want to kill the app, and I don't want it to just be paused.
Is there an ADB command? DDMS? Something in the phone?
I've tried faking it by running other memory-hungry apps, but that always just leads it getting killed outright, which means the app gets started all over and onCreate is run and I don't learn anything.
Answer:
is there any way that I can reliably force the application to be stopped so that I can reproduce this condition. I don't want to kill the app, and I don't want it to just be paused.

Press the HOME button.
Comment: And then restart it again by holding the HOME button and switching back to your app.
Comment: Won't this cause it to simply be paused? From reading the documentation, it won't be stopped until some of its memory is needed. This is consistent with our problems that some of our program data is being garbage collected, as though the program were being stopped. The problem only manifests after navigating away from the app for a while (that's as precise as I know to be) and come back.
Comment: @Hober: "Won't this cause it to simply be paused?" -- no, it will be stopped. "it won't be stopped until some of its memory is needed" -- no, that is when it is destroyed.


Understanding why a $p$-value is too small

Question: I have a data set with counts of particles, and I want to test if they follow a distribution. For a certain species, I make the $\chi^2$-test, and everything seems reasonable, finding a $p$-value of $p=0.75$, which I interpret as meaning that my null hypothesis (in this case, that the data follows a Skellam distribution) is not rejected. In the plot below, the histogram is the binned data and the curve is the expected distribution.

However, when I do the same for another type of particle, I find the $p$-value of $p=2\times 10^{-13}$, but the plot suggests to me that the data does follow the Skellam distribution:

I read in some places that a large sample may cause this, but my sample size is $3\times10^4$, and as it didn't affect the first type of particles, I'm assuming that is not the problem. What am I misunderstanding here? Does it really mean that I should reject the null hypothesis?
A follow-up question: which test should I use to check the goodness-of-fit, in this case? For completeness, the statistic is $\chi^2=19.8$ and $\chi^2=220$, respectively.
Comment: 3 x 10^5 is a very large sample in most contexts.
Comment: Related but specific to normal distributions: https://stats.stackexchange.com/questions/2492/is-normality-testing-essentially-useless?noredirect=1&lq=1
Comment: @RenanNobuyukiHirayama these are SIMULATED events? So you can guarantee that the null hypothesis is actually true (assuming you haven't got a bug in your code)?
Comment: Low p-values are indicators for anomalies. But you shouldn't forget that the test to which the p-value relates entails the *entire* experiment. It can be that your hypothesis is wrong, it can also be that your experiment is wrong. The p-value is just testing an idealistic probability distribution, and it does not include the fluctuations in measurements that may occur due to systematic errors (e.g. think of the "discovery" of superluminal neutrinos).
Comment: If you have a large sample size then you can significantly measure tiny fluctuations.
Comment: @SextusEmpiricus, I understand, but these are simulated events, so I don't think that's the case
Comment: Could you provide a table of your data based on which you did the chi-squared test. Possibly your plots are not accurate (I find the apparent shift of the curve in the first plot strange).
Comment: As others said, low p values for seemingly small effects can be due to large samples (and 3000 is large in this context). But, rather than a density plot and histogram, you could look at a QQ plot to get a better idea of any deviations.
Comment: @HongOoi, I'm actually trying to check if the hypothesis is true for different decay configurations on a freeze-out (this data is only one configuration, but the low $p$-value is common to all of them). In non-physics terms, I'm checking that a  certain process doesn't introduce correlations between particles, which has the consequence of making the net-X be Skellam-distributed, and I can't check it directly from the code (which I also hopefully assume has no bugs).
Answer: A few general thoughts:

It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A model doesn't have to be perfect, but good enough for the purpose.
With such a huge sample size, even tiny deviations from a Skellam distribution will result in very small p-values. This is just a result of the consistency of the tests. The power to detect smaller and smaller deviations increases with increasing sample size (see also here). In the second case, a p-value of $2\times 10^{-13}$ means that there is a lot of evidence against the null hypothesis that the data come from a Skellam distribution. Specifically, there are $-\log_{2}(2\times 10^{-13})\approx 42.19$ bits of information agains the test hypothesis (this is called the $S$-value).
A failure to reject the null hypothesis does not mean that it is true. It means that there is not enough evidence to reject the notion that your data are compatible with a Skellam distribution with a high enough confidence. There may be infinitely many distributions other than the Skellam distribution that are compatible with your data.
Histograms are suboptimal to check the agreement between the data and a specified distribution. I recommend to use Q-Q-plots instead (more information here). Another very useful visualization tool is the hanging rootogram. A good paper on this can be found here. I show how to apply a hanging rootogram to check the fit to a Poisson distribution in this answer.

In the light of the points above, here are some questions that you might find useful to ask yourself:

What's your specific goal? Why do you want to show that the data are following a Skellam distribution?
How large do the deviations from a Skellam distribution have to be in order for you to deem the model of a Skellam distribution unsuitable for the task?

Both of these questions require subject matter knowledge which I don't have.
Comment: excellent answer! @RenanNobuyukiHirayama chi square test is very appropriate, you may favour g-test, which is a bit more solid in its convergence, but it's almost the same thing. Since Skellam distribution is almost gaussian, another good option could be Anderson-Darling, which is not specifical for gaussianity, but known to perform well in that case.
Comment: Though general, these thoughts clarified some misconceptions I had (Thanks!). A follow-up question that doesn't seem to deserve its own post: Which test to check the goodness-of-fit should I use?

And to answer your questions:
1. This data is the net-proton (proton minus antiprotons) and net-pion ($\pi^+ - \pi^-$) number after a heavy-ion collision, which should be Skellam-distributed if the particles are emitted independently.
2. I'm not sure, at least yet.
Comment: For reference, I made the suggested QQ plot, posted it here: https://imgur.com/a/6SzmPmX

The Skellam distribution agrees with the data very well, but I'm still curious about a quantification of this agreement (something like reduced residuals)
Comment: @RenanNobuyukiHirayama A $\chi^{2}$-test seems fine to me but I don't have a lot of experience regarding goodness-of-fit tests. I hope someone more knowledgable can make a more informed recommendation.
Comment: I should add that AD test is fairly different from chi square test, but most of the times they give the same result, as they test the same hypothesis.


Is it possible to replicate the _users database in CouchDB?

Question: Is it possible to configure replication between the "_users" database on two instances of CouchDB? (currently using 1.4)
Answer: Yes, you can replicate the _users database in Couch, in this respect, it's no different than any other database.


Como implementar um algoritmo de ordenação MergeSort genérico?

Question: Como implementar um algoritmo de ordenação MergeSort genérico (com ponteiro de função e ponteiro void) nessa função?
#include<stdio.h>
typedef struct{
    inta;
    intb;
}XPTO;

void criaVetor(XPTO∗v, int n){
    int i;
    for(i=0;i<n;i++){
    v[i].a=i%3;
    v[i].b=100−i%5;
    }
}

void imprimeVetor(XPTO∗v, int n){
    int i;
    for(i=0;i<n;i++){
    printf("a=%d b=%d\n",v[i].a,v[i].b);
    }
}

int porA(void ∗p1,void ∗p2){
    XPTO∗pp1=p1;
    XPTO∗pp2=p2;
    return pp1−>a < pp2−>a;
}

int porB(void ∗p1,void ∗p2){
    XPTO∗pp1=p1;
    1XPTO∗pp2=p2;
        returnpp1−>b < pp2−>b;
}

int main(int argc,char∗ argv[]){

XPTO v[10];
criaVetor(v,10);

ordena(v,sizeof(XPTO),10,porA);//<−exemplo de chamada da funcao ordena

imprimeVetor(v,10);

return 0;
}

Comment: Sugiro que comece pelo mais simples mesmo. Comece por implementar um que funcione para inteiros por exemplo e depois então converta-o para genérico. Comece também por ler como o algoritmo funciona e fazer a sua tentativa de resolução. A maior parte das literaturas incluem exemplos do algoritmo em pseudo código que facilitam-lhe a implementação.
Comment: *Have you tried turning it off and on again?*
Answer: Fiz uma solução abaixo.

Utilizei um ponteiro de função para ser o comparador (int (*comparador)(void *, void *)). Esse comparado pode retornar um número negativo se o primeiro parâmetro (o primeiro void *) for menor que o segundo, positivo se for maior, ou zero se forem iguais.
O mergesort necessita de uma memória auxiliar. Por esse motivo, que há um malloc e um free na implementação do mergesort abaixo. Esse malloc só é efetuado uma vez e a mesma memória auxiliar é usada em todas as recursões do mergesort_aux. A função mergesort_aux é a que realiza o mergesort de fato, apenas recebendo como parâmetro, a memória auxiliar.
A função memcpy é utilizada para copiar do array para a memória auxiliar e de volta também. Isso é usado no processo de intercalação das duas metades do array. A intercalação ocorre ao copiar-se os elementos de cada metade do array na memória auxiliar, na ordem dos elementos dada pelo comparador tal como determina o algoritmo de mergesort. Assim, a função intercalar vai colocar no array aux a intercalação de array1 e array2, usando memcpy para copiar os elementos. Com um outro memcpy o array intercalado é copiado de volta por cima dos dois arrays originais sobreescrevendo-os.
Embora a função mergesort e o comparador trabalhem com elementos do tipo void *, internamente o char * é usado. O motivo disso é que não é possível realizar-se aritmética de ponteiros com void *. Por outro lado, com char *, é possível endereçar-se qualquer byte individualmente no array a ser ordenado.
Também coloquei um campo c no seu XPTO com a posição original no array. Isso serve para evidenciar que a ordenação do mergesort é estável. Ou seja, elementos que o comparador diz que são iguais são mantidos na mesma ordem em que estavam no array original.

Eis o código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // Para a função memcpy

// Código do mergesort:

void intercalar(
    char *array1,
    char *array2,
    size_t tamanho_array1,
    size_t tamanho_array2,
    char *aux,
    size_t tamanho_elemento,
    int (* comparador)(void *, void *)
) {
    int a = 0, b = 0, c = 0;
    while (a < tamanho_array1 || b < tamanho_array2) {
        int ain = a < tamanho_array1;
        int bin = b < tamanho_array2;
        char *e1 = ain ? &array1[a * tamanho_elemento] : NULL;
        char *e2 = bin ? &array2[b * tamanho_elemento] : NULL;
        char *e3 = &aux[c * tamanho_elemento];
        char *comp = (e2 == NULL || (e1 != NULL && comparador(e1, e2) <= 0)) ? e1 : e2;
        memcpy(e3, comp, tamanho_elemento);
        if (comp == e1) a++; else b++;
        c++;
    }
}

void mergesort_aux(
    char *array,
    char *aux,
    size_t tamanho_elemento,
    size_t tamanho_array,
    int (* comparador)(void *, void *)
) {
    if (tamanho_array < 2) return;
    int metade1 = tamanho_array / 2;
    int metade2 = tamanho_array - metade1;
    mergesort_aux(array, aux, tamanho_elemento, metade1, comparador);
    char *temp = &array[metade1 * tamanho_elemento];
    mergesort_aux(temp, aux, tamanho_elemento, metade2, comparador);
    intercalar(array, temp, metade1, metade2, aux, tamanho_elemento, comparador);
    memcpy(array, aux, tamanho_elemento * tamanho_array);
}

void mergesort(
    void *array,
    size_t tamanho_elemento,
    size_t tamanho_array,
    int (* comparador)(void *, void *)
) {
    void *aux = malloc(tamanho_elemento * tamanho_array);
    mergesort_aux((char *) array, (char *) aux, tamanho_elemento, tamanho_array, comparador);
    free(aux);
}

// Seu código de teste:

typedef struct {
    int a;
    int b;
    int c;
} XPTO;

void criar_vetor(XPTO *v, int n) {
    for (int i = 0; i < n; i++) {
        v[i].a = (i % 3) + 4;
        v[i].b = 100 - i % 5;
        v[i].c = i;
    }
}

void imprimir_vetor(XPTO *v, int n) {
    for (int i = 0; i < n; i++) {
        printf("(a=%d b=%d c=%d) ", v[i].a, v[i].b, v[i].c);
    }
    printf("\n");
}

int por_a(void *p1, void *p2) {
    XPTO *pp1 = (XPTO *) p1;
    XPTO *pp2 = (XPTO *) p2;
    return pp1->a - pp2->a;
}

int por_b(void *p1, void *p2) {
    XPTO *pp1 = (XPTO *) p1;
    XPTO *pp2 = (XPTO *) p2;
    return pp1->b - pp2->b;
}

#define T 20

int main(int argc, char* argv[]) {
    XPTO v[T];
    criar_vetor(v, T);

    printf("Antes:\n");
    imprimir_vetor(v, T);

    printf("\nPor A:\n");
    mergesort(v, sizeof(XPTO), T, por_a);
    imprimir_vetor(v, T);

    criar_vetor(v, T); // Recria o vetor.
    printf("\nPor B:\n");
    mergesort(v, sizeof(XPTO), T, por_b);
    imprimir_vetor(v, T);

    return 0;
}

Veja aqui funcionando no ideone.


How to find location of wifi packet floods

Question: We've seen ongoing wireless packet floods (beacon, probe requests, and probe response floods) that are reported in the event log of our office firewall appliance. These are being sent continuously and has been on for weeks. We're in a multi-tenant tower so I have no idea if it's originating from our office or from somewhere adjacent to us.
The mac addresses used in the source and/or destination of these packets is constantly changing (cycling through ranges it looks like) so I assume this is the work on one of those tools like air-crack that's forging packets to execute a DoS. It's not actually fully denying usage of our network but it causes slow downs from time to time.
I understand that you can't block these packets because they have no distinguishable characteristic. But is there any way to determine the physical area that these packets are being sent from? I'm wondering about tools that can triangulate the location based on timing of packets.
Comment: You said it cycles through ranges, so first identify the traffic that looks legit and filter it out.  Also, invest in a directional antenna if you are going fox-hunting.  If nothing else in the packet is constant; such as TTL, then it will be a hunting exercise.  You could also move your users to another band and see if the attack follows, accepting this may prevent some folks from using wireless. i.e. 2 ghz vs 5 ghz
Answer: You can use Aerodump-ng to monitor all wireless traffic for signal strength. If you know the temporary MAC of the source, start a capture by issuing "airodump-ng [interface]" where [interface] if the name of your wireless device. As you get closer to the source, the "PWR" will increase.
Comment: The problem is it seems to vary the mac address on each burst so constantly changing. But maybe your suggestion would still work if I can isolate the packets themselves by a filter...


Solving for f(t) in presence of f'(t)

Question: Here's the situation: I have a function
$$e(t) = \frac{a~d(t)}{b + d(t)}$$
with first derivative
$$e'(t) = \frac{a~b~d'(t)}{[b+d(t)]^2}$$
where $a$ and $b$ are constants.
For a given constant $K$ I wish to find some $d(t)$ such that $e'(t) = K$, or at least such that $\epsilon \equiv |K-e'(t)|$ is minimized.
The exact approach gives
$$abd'(t) = K[b+d(t)]^2$$
But try as I might I've been unable to manipulate this algebraically to get an expression for $d(t)$ that doesn't include $d'(t)$ (which would defeat the purpose).
Is there some analytical solution I'm just not seeing? Or could anybody get me started on an optimization-based approach minimizing $\epsilon$?
Answer: I am probably missing a part of the problem; so, please, forgive me if this is off-topic.
If the equation is $$ab d'(t) = K\Big(b+d(t)\Big)^2$$ you can rewrite is as $$\frac{d'(t)}{\Big(b+d(t)\Big)^2}=\frac{K}{ab}$$ (which is moreover separable) and classical integration then leads to $$d(t)=-b \left(1+\frac{a}{a b c_1+K t}\right)=-b \left(1+\frac{a}{ c_2+K t}\right)$$ which gives for $e(t)$ a linear equation in $t$ (which was the basic assumption when saying that $e'(t)=K$).
Another approach does not require the derivatives since $e'(t)=K$ implies $e(t)=Kt+c$ and then you can solve your first equation for $d(t)$. Similarly, saying that $e'(t)$ is almost a constant could be translated as $e(t)=K t +\epsilon t^2 + c$; solve again for $d(t)$.
Is this what you are looking for ?

Solving for f(t) in presence of f'(t)


Como adicionar 100% de altura a uma coluna do Bootstrap 4

Question: Estou utilizando o bootstrap 4.1, anteriormente tentei utilizar a classe h-100, e sem sucesso, mesmo o chrome developer tools indicando que height:100% foi aplicado aos elementos. Resolvi utilizar uma classe como os atributos min-height e height e também acaba no mesmo erro.
A classe css é esta
.maximo{
    min-height:100%;
    height:100%;
}

O código html é este

                Planejar Melhor
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                                Info

                                Simulações

                                Contas

Ínicio

                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle">
                            Periodo
                        </button>

Imagem
[![inserir a descrição da imagem aqui][1]][1]

  [1]: https://i.stack.imgur.com/rBjJm.png

Edit:

            Planejar Melhor
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                            Info

                            Simulações

                            Contas

Ínicio

                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle">
                        Periodo
                    </button>

Resultado (utlizando cores para ver o tamanho real)
Comment: a  coluna continua igual
Comment: apenas o
Comment: coloca position relative nessa classe pra ver
Comment: tem outro elemento antes desses? ou só o body?
Comment: achei algo pra te ajudar
Answer: O seu problema é que seu HTML e o BODY não tem um valor de altura definido, então mesmo colocando height de 100% o browser não entende, pois seria 100% de que?
Então primeiro vc define height:100% no HTML e BODY, agora esses valores valem como referencia e os filhos pode ter 100% de altura referentes aos pais.
OBS1: Repare também que agora que foi definido altura para o HTML e Body o classe default h-100 funciona corretamente, vc não precisa usar a classe .maximo
OBS2: Tive que tirar uma margem de uma div dentro do MAIN para não dar barra de rolagem na tela sem precisar.
OBS3: Vc não precisa coloca o CSS na mão no HTML e Body :D , vc pode usar a classe h-100 neles, mas fiz na mão para te ajudar a entender pq não estava funcionando.
Exiba em "Página toda" para ter um resultado melhor já que ainda não foi feita a parte responsiva.

html, body {
    height: 100%;
}
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"/>

                Planejar Melhor
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                                Info

                                Simulações

                                Contas

Ínicio

                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle">
                            Periodo
                        </button>

Veja como fica seu código funcionando.
Answer: Usando Bootstrap 4.0, tem as classes h-:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Height 25%

Height 50%

Height 75%

Height 100%

Referência do sizing
Comment: Amigo, a classe define height, se aplicado a todos elementos necessários, funciona perfeitamente


How to mount and recover data after succesfully building the raid again?

Question: We have a synology nas and one of the 2 disks crashed although smart was passed and the data was intact.
Note that although the disks are not in a raid, years ago we chose SHR and apparently synology considers a 1 disk raid.
We took out the crashed disk preemptively and replaced it and now we want to recover the data.We placed the disk in a debian 10 box.
Following many guides we managed to recreate a one disk raid but still we cant mount it cause debian cant recognize the fs.
Placing the disk on windows pc first we found that synology formats it into three parts,the first is ext4 with the metadata i suppose since we could see the folder structure,the 2nd and 3rd which holds all the data is RAW.
Actions taken on debian:
lsblk
sdc                            8:32   0   2.7T  0 disk
├─sdc1                         8:33   0   2.4G  0 part
├─sdc2                         8:34   0     2G  0 part
├─sdc3                         8:35   0   2.7T  0 part

cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md127 : inactive sdc3[0](S)
      2925444560 blocks super 1.2

unused devices: <none>

no point to mount if we dont make it active i guess:
mdadm -Asf
   mdadm: No arrays found in config file or automatically

mdadm -A /dev/md127
mdadm: /dev/md127 not identified in config file.

something's missing from /etc/mdadm/mdadm.conf:
mdadm --detail --scan
INACTIVE-ARRAY /dev/md127 metadata=1.2 name=DiskStation:2 UUID=51fe32e5:d1a74bf2:7c07fbd0:ce554944

and
mdadm --examine --scan >> /etc/mdadm/mdadm.conf
ARRAY /dev/md/2  metadata=1.2 UUID=51fe32e5:d1a74bf2:7c07fbd0:ce554944 name=DiskStation:2

I dont know why the second command outputs /dev/md/2 which does not exist but i went into the mdadm.conf and replaced it with md127.So the config now is:
# This configuration was auto-generated on Sat, 02 Nov 2019 20:42:28 +0200 by mkconf
ARRAY /dev/md127  metadata=1.2 UUID=51fe32e5:d1a74bf2:7c07fbd0:ce554944 name=DiskStation:2

I rebooted the machine and then do a :
mdadm --stop /dev/md127
mdadm: stopped /dev/md127

otherwise obviously if you try to build/assemble the raid it says sdc3 is busy.
then i did a :
mdadm --build /dev/md127 --force --level=1 --raid-devices=1 /dev/sdc
mdadm: array /dev/md127 built and started.

cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md127 : active raid1 sdc[0]
      2930266584 blocks super non-persistent [1/1] [U]

unused devices: <none>

so thats progress.But still it cant recognise the fs to mount the disk.
new lsblk:
sdc                            8:32   0   2.7T  0 disk
├─sdc1                         8:33   0   2.4G  0 part
├─sdc2                         8:34   0     2G  0 part
├─sdc3                         8:35   0   2.7T  0 part
└─md127                        9:127  0   2.7T  0 raid1
  ├─md127p1                  259:0    0   2.4G  0 part
  ├─md127p2                  259:1    0     2G  0 part
  └─md127p3                  259:2    0   2.7T  0 part

and now my attempts to mount to a dir:
mount /dev/md127 /mnt/oldsynology/ -o ro
mount: /mnt/oldsynology: wrong fs type, bad option, bad superblock on /dev/md127, missing codepage or helper program, or other error.

mount /dev/md127p3 /mnt/oldsynology/ -o ro
mount: /mnt/oldsynology: unknown filesystem type 'linux_raid_member'.

mount /dev/sdc /mnt/oldsynology/ -o ro
mount: /mnt/oldsynology: /dev/sdc already mounted or mount point busy.

mount /dev/sdc3 /mnt/oldsynology/ -o ro
mount: /mnt/oldsynology: unknown filesystem type 'linux_raid_member'.

Also i tried the above mount commands with mount -t ext4,same results.
My smartctl although when i remounted the drive into synology it read the data without issue.
smartctl -a /dev/sdc3
smartctl 7.1 2019-12-30 r5022 [x86_64-linux-5.3.13-1-pve] (local build)
Copyright (C) 2002-19, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Family:     Western Digital Red
Device Model:     WDC WD30EFRX-68EUZN0
Serial Number:    WD-WCC4N2ELDDTF
LU WWN Device Id: 5 0014ee 20cc90c0c
Firmware Version: 82.00A82
User Capacity:    3,000,592,982,016 bytes [3.00 TB]
Sector Sizes:     512 bytes logical, 4096 bytes physical
Rotation Rate:    5400 rpm
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   ACS-2 (minor revision not indicated)
SATA Version is:  SATA 3.0, 6.0 Gb/s (current: 3.0 Gb/s)
Local Time is:    Tue Jun 30 23:53:12 2020 EEST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x00) Offline data collection activity
                    was never started.
                    Auto Offline Data Collection: Disabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        (38880) seconds.
Offline data collection
capabilities:            (0x7b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    ( 390) minutes.
Conveyance self-test routine
recommended polling time:    (   5) minutes.
SCT capabilities:          (0x703d) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   200   200   051    Pre-fail  Always       -       37389
  3 Spin_Up_Time            0x0027   170   170   021    Pre-fail  Always       -       6466
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       33
  5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       16
  7 Seek_Error_Rate         0x002e   200   200   000    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   050   050   000    Old_age   Always       -       36983
 10 Spin_Retry_Count        0x0032   100   253   000    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   100   253   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       32
192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       22
193 Load_Cycle_Count        0x0032   200   200   000    Old_age   Always       -       670
194 Temperature_Celsius     0x0022   105   104   000    Old_age   Always       -       45
196 Reallocated_Event_Count 0x0032   186   186   000    Old_age   Always       -       14
197 Current_Pending_Sector  0x0032   199   199   000    Old_age   Always       -       529
198 Offline_Uncorrectable   0x0030   100   253   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       0
200 Multi_Zone_Error_Rate   0x0008   200   200   000    Old_age   Offline      -       1

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Extended offline    Interrupted (host reset)      90%     36677         -
# 2  Short offline       Interrupted (host reset)      10%     36671         -
# 3  Extended offline    Interrupted (host reset)      10%     36626         -
# 4  Extended offline    Completed: read failure       10%     35995         30655688
# 5  Extended offline    Interrupted (host reset)      10%     35289         -
# 6  Extended offline    Interrupted (host reset)      10%     34262         -
# 7  Extended offline    Interrupted (host reset)      10%     33403         -
# 8  Extended offline    Interrupted (host reset)      90%     33174         -
# 9  Extended offline    Interrupted (host reset)      10%     33097         -
#10  Extended offline    Interrupted (host reset)      10%     33000         -
#11  Extended offline    Interrupted (host reset)      10%     32792         -
#12  Extended offline    Interrupted (host reset)      10%     32593         -
#13  Extended offline    Completed: read failure       10%     32350         30655688
#14  Extended offline    Completed: read failure       10%     28883         30655688
#15  Extended offline    Interrupted (host reset)      60%     27995         -
#16  Extended offline    Completed without error       00%     27835         -
#17  Extended offline    Completed without error       00%     27676         -
#18  Extended offline    Completed without error       00%     27508         -
#19  Extended offline    Completed without error       00%     27334         -
#20  Extended offline    Completed without error       00%     27167         -
#21  Extended offline    Completed without error       00%     26999         -

SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

i'm hoping there is someone that can shed some light into this puzzle.Haven't found a solution in any similar posts up to now,there was always a slightly different variable into each case.
Answer: This is telling:
mount /dev/md127p3 /mnt/oldsynology/ -o ro
mount: /mnt/oldsynology: unknown filesystem type 'linux_raid_member'.

It seems that /dev/md127p3 contains itself another array, which you may discover using mdadm -E /dev/md127p3.
That said, before messing with SHR on a linux box I would simply try to clone the disk and insert it into the original DiskStation.
Comment: unfortunately the disk died this morning so we'll never know.
Comment: I'm sorry... This was one of the reasons why I suggested to clone the disk in the first place.