Propensity score matching with MatchIt: Question on missing standard mean differences in balance tab on cobalt package

Question: I am using MatchIt to carry out some propensity score matching, and then using the cobalt package to generate the balance diagnostic. The summary() command on MatchIt has a known bug where it does not generate the standard mean differences for the first level of multi-categorical variables. I know that, based on this post:
MatchIt: Explanation of Missing Factors from Summary
the bal.tab in the cobalt package is supposed to print out the standard mean differences for all levels of multi-categorical variables. However, for me, the cobalt package is still missing the first levels. For instance, I have the following multi-categorical variables in the MatchIt formula (number of levels in parenthesis) - RACE (4), PAY1 (4), ZIPINC_QRTL (4), PL_UR_CAT4 (4), CM_ELIX_BIN (5):
set.seed(103)
matched_avgdata <- matchit(SURGERY_SETTING ~
                             AGE + FEMALE + RACE + PAY1 +  ZIPINC_QRTL + PL_UR_CAT4 + STATE + YEAR + CM_ELIX_BIN +
                             CM_CHF +  CM_VALVE +  CM_PULMCIRC +  CM_PERIVASC +  CM_HTN_C +  CM_PARA +  CM_NEURO +  CM_CHRNLUNG +
                             CM_DM +  CM_DMCX +  CM_HYPOTHY +  CM_RENLFAIL +  CM_LIVER +  CM_ULCER +  CM_AIDS +  CM_LYMPH +  CM_METS +  CM_TUMOR +
                             CM_ARTH +  CM_COAG +  CM_OBESE +
                             CM_WGHTLOSS +  CM_LYTES +  CM_BLDLOSS +  CM_ANEMDEF +  CM_ALCOHOL +  CM_DRUG +  CM_PSYCH +
                             CM_DEPRESS,
                        data = avgdata_selected, distance=PS_average$myList, ratio = 1, method = "nearest", caliper = 0.1)

Output with MatchIt summary() formula:
summary(matched_avgdata, standardize=TRUE)

Summary of balance for matched data:
             Means Treated Means Control SD Control Std. Mean Diff. eCDF Med eCDF Mean eCDF Max
distance            0.0736        0.0734     0.0617          0.0032   0.0040    0.0043   0.0182
AGE                64.9960       64.5648     9.5577          0.0397   0.0101    0.0166   0.0668
FEMALE0             0.5587        0.5547     0.4975          0.0082   0.0020    0.0020   0.0040
FEMALE1             0.4413        0.4453     0.4975         -0.0082   0.0020    0.0020   0.0040
RACE2               0.0607        0.0688     0.2534         -0.0321   0.0040    0.0040   0.0081
RACE3               0.0931        0.1073     0.3098         -0.0489   0.0071    0.0071   0.0142
RACE4               0.0344        0.0263     0.1602          0.0446   0.0040    0.0040   0.0081
PAY12               0.0202        0.0202     0.1410          0.0000   0.0000    0.0000   0.0000
PAY13               0.4271        0.4372     0.4965         -0.0204   0.0051    0.0051   0.0101
PAY14               0.1032        0.1032     0.3046          0.0000   0.0000    0.0000   0.0000
ZIPINC_QRTL2        0.3077        0.2976     0.4577          0.0219   0.0051    0.0051   0.0101
ZIPINC_QRTL3        0.2814        0.2672     0.4429          0.0314   0.0071    0.0071   0.0142
ZIPINC_QRTL4        0.1599        0.1761     0.3813         -0.0443   0.0081    0.0081   0.0162
PL_UR_CAT42         0.2632        0.2632     0.4408          0.0000   0.0000    0.0000   0.0000
PL_UR_CAT43         0.0486        0.0425     0.2020          0.0278   0.0030    0.0030   0.0061
PL_UR_CAT44         0.0263        0.0263     0.1602          0.0000   0.0000    0.0000   0.0000
STATE1              0.2834        0.3077     0.4620         -0.0540   0.0121    0.0121   0.0243
YEAR2015            0.3158        0.3482     0.4769         -0.0696   0.0162    0.0162   0.0324
YEAR2016            0.4271        0.4130     0.4929          0.0286   0.0071    0.0071   0.0142
CM_ELIX_BIN1        0.2814        0.3158     0.4653         -0.0767   0.0172    0.0172   0.0344
CM_ELIX_BIN2        0.1842        0.1619     0.3688          0.0576   0.0111    0.0111   0.0223
CM_ELIX_BIN3        0.0506        0.0405     0.1973          0.0463   0.0051    0.0051   0.0101
CM_ELIX_BIN4        0.0364        0.0385     0.1925         -0.0106   0.0010    0.0010   0.0020
CM_CHF1             0.0101        0.0101     0.1002          0.0000   0.0000    0.0000   0.0000
CM_VALVE1           0.0081        0.0121     0.1096         -0.0454   0.0020    0.0020   0.0040
CM_PULMCIRC1        0.0040        0.0020     0.0450          0.0320   0.0010    0.0010   0.0020
CM_PERIVASC1        0.0162        0.0162     0.1264          0.0000   0.0000    0.0000   0.0000
CM_HTN_C1           0.4555        0.4514     0.4981          0.0081   0.0020    0.0020   0.0040
CM_PARA1            0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_NEURO1           0.0061        0.0061     0.0778          0.0000   0.0000    0.0000   0.0000
CM_CHRNLUNG1        0.0891        0.0870     0.2822          0.0071   0.0010    0.0010   0.0020
CM_DM1              0.1154        0.0992     0.2992          0.0509   0.0081    0.0081   0.0162
CM_DMCX1            0.0101        0.0081     0.0897          0.0203   0.0010    0.0010   0.0020
CM_HYPOTHY1         0.0547        0.0466     0.2109          0.0358   0.0040    0.0040   0.0081
CM_RENLFAIL1        0.0040        0.0040     0.0636          0.0000   0.0000    0.0000   0.0000
CM_LIVER1           0.0101        0.0061     0.0778          0.0406   0.0020    0.0020   0.0040
CM_ULCER1           0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_AIDS1            0.0020        0.0000     0.0000          0.0452   0.0010    0.0010   0.0020
CM_LYMPH1           0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_METS1            0.0000        0.0000     0.0000          0.0000   0.0000    0.0000   0.0000
CM_TUMOR1           0.0040        0.0020     0.0450          0.0262   0.0010    0.0010   0.0020
CM_ARTH1            0.0121        0.0061     0.0778          0.0557   0.0030    0.0030   0.0061
CM_COAG1            0.0040        0.0061     0.0778         -0.0320   0.0010    0.0010   0.0020
CM_OBESE1           0.0385        0.0425     0.2020         -0.0211   0.0020    0.0020   0.0040
CM_WGHTLOSS1        0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_LYTES1           0.0081        0.0121     0.1096         -0.0454   0.0020    0.0020   0.0040
CM_BLDLOSS1         0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_ANEMDEF1         0.0061        0.0061     0.0778          0.0000   0.0000    0.0000   0.0000
CM_ALCOHOL1         0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_DRUG1            0.0040        0.0040     0.0636          0.0000   0.0000    0.0000   0.0000
CM_PSYCH1           0.0000        0.0000     0.0000             NaN   0.0000    0.0000   0.0000
CM_DEPRESS1         0.0526        0.0567     0.2315         -0.0182   0.0020    0.0020   0.0040

Notice how RACE (4), PAY1 (4), ZIPINC_QRTL (4), PL_UR_CAT4 (4), CM_ELIX_BIN (5) are all missing a level. Standard mean differences are only calculated for 3 levels in RACE, 3 levels in PAY1, 3 levels in ZIPINC_QRTL, 3 levels in PL_UR_CAT4, and 4 levels in CM_ELIX_BIN.
Here is the implementation with the bal.tab command in the cobalt package:
bal.tab(matched_avgdata, un = TRUE, binary = "std")

Balance Measures
                 Type Diff.Un Diff.Adj
distance     Distance  0.7974   0.0032
AGE           Contin. -0.3945   0.0397
FEMALE0        Binary  0.1482   0.0082
RACE2          Binary  0.1120  -0.0321
RACE3          Binary  0.1484  -0.0489
RACE4          Binary -0.0051   0.0446
PAY12          Binary -0.0177   0.0000
PAY13          Binary  0.4511  -0.0204
PAY14          Binary  0.1471   0.0000
ZIPINC_QRTL2   Binary  0.0261   0.0219
ZIPINC_QRTL3   Binary  0.0949   0.0314
ZIPINC_QRTL4   Binary -0.1916  -0.0443
PL_UR_CAT42    Binary -0.3528   0.0000
PL_UR_CAT43    Binary  0.0209   0.0278
PL_UR_CAT44    Binary -0.0213   0.0000
STATE1         Binary -0.2455  -0.0540
YEAR2015       Binary -0.0462  -0.0696
YEAR2016       Binary  0.1211   0.0286
CM_ELIX_BIN1   Binary  0.0157  -0.0767
CM_ELIX_BIN2   Binary -0.1959   0.0576
CM_ELIX_BIN3   Binary -0.5315   0.0463
CM_ELIX_BIN4   Binary -0.5487  -0.0106
CM_CHF1        Binary -0.1244   0.0000
CM_VALVE1      Binary -0.3693  -0.0454
CM_PULMCIRC1   Binary -0.0274   0.0320
CM_PERIVASC1   Binary -0.0709   0.0000
CM_HTN_C1      Binary -0.4036   0.0081
CM_PARA1       Binary           0.0000
CM_NEURO1      Binary -0.3707   0.0000
CM_CHRNLUNG1   Binary -0.2873   0.0071
CM_DM1         Binary -0.1701   0.0509
CM_DMCX1       Binary -0.1209   0.0203
CM_HYPOTHY1    Binary -0.4758   0.0358
CM_RENLFAIL1   Binary -0.7866   0.0000
CM_LIVER1      Binary -0.0043   0.0406
CM_ULCER1      Binary           0.0000
CM_AIDS1       Binary  0.0381   0.0452
CM_LYMPH1      Binary           0.0000
CM_METS1       Binary  0.0304   0.0000
CM_TUMOR1      Binary  0.0156   0.0262
CM_ARTH1       Binary -0.3621   0.0557
CM_COAG1       Binary -0.2059  -0.0320
CM_OBESE1      Binary -0.7988  -0.0211
CM_WGHTLOSS1   Binary           0.0000
CM_LYTES1      Binary -0.5490  -0.0454
CM_BLDLOSS1    Binary           0.0000
CM_ANEMDEF1    Binary -0.5805   0.0000
CM_ALCOHOL1    Binary           0.0000
CM_DRUG1       Binary -0.0877   0.0000
CM_PSYCH1      Binary           0.0000
CM_DEPRESS1    Binary -0.4093  -0.0182

I get the same standard mean differences as MatchIt (called "Diff.Un" and "Diff.Adj" in the cobalt package), which is good, but still all the multi-categorical variables are missing the first level. Per the author of the package, this was supposed to have been fixed. Am I missing a parameter in the call to the bal.tab function?
Answer: I'm the author of cobalt. In short, it's because you're using your own distance variable. When you do this, matchit() doesn't save the original data set in the matchit output object; it only saves a version of the data set that has had model.matrix() used on it, which automatically separates the factors into dummies and, in MatchIt's implementation, will remove the first level of all but the first factor variable it sees. Unfortunately, there is no reliable way to recover the original factor variables in the original dataset from the output of the matchit object in this case, so cobalt just treats the variables in the matchit output as if they were binary variables unrelated to each other rather than as components of a factor.
One way around this is to use the data frame or formula methods for bal.tab, i.e., (replacing formula with your actual model formula)
bal.tab(formula, avgdata_selected, weights = get.w(matched_avgdata),
        binary = "std", method = "matching")

I did think of another way to solve this problem, which is by allowing you to enter a data frame of the original covariates. I just updated the development version of cobalt so that you can run
devtools::install_github("ngreifer/cobalt") #Get development version
library(cobalt)
bal.tab(matched_avgdata, data = avgdata_selected, binary = "std")

That should give you the expected results. I'll make this clearer in the documentation.
Comment: Hello Noah. Thanks so much for your incredible package and taking the time out to answer my questions. I just tried both methods - the first method (using the formula) worked, producing the SMDs for all levels. The second method (using the devtools) did not work, and the output was the same as before.
Comment: It works on my end, so maybe you need to restart your R session if you didn't do that. Either way, I'm glad the first method works as intended. Thank you for the kinds words about `cobalt`.


Why is copy constructor called rather than move constructor?

Question: I have the following code:
#include <bits/stdc++.h>

using namespace std;

class A {
public:
    A(const A& a) noexcept { cout << "copy constructor" << endl; }
    A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; }
    A(A&& a) noexcept { cout << "move constructor" << endl; }
    A& operator=(A&& a) noexcept { cout << "move assignment operator" << endl; }
    A() { cout << "default constructor" << endl; }
};

vector aList;

void AddData(const A&& a)
{
    aList.push_back(std::move(a));
}

int main()
{
    AddData(A());
    return 0;
}

The output is default constructor copy constructor. please tell me is the rvalue reference push_back(T&&)called? And when is copy constructor called?
Answer: The issue is with the a parameter in AddData():
void AddData(const A&& a) // <-- const reference!!!
{
    aList.push_back(std::move(a)); // selects push_back(const A&)
}

The a parameter above is a const rvalue reference. You are marking with std::move() a const object.
Marking a const object with std::move() for moving has no effect when it comes to move semantics because you can't move from a const object (i.e., you need to alter the moved-from object, but it is const-qualified).
An rvalue reference doesn't bind to a const object, but a const lvalue reference does. As a result, the push_back(const A&) overload is selected instead of the push_back(A&&) one, and therefore the A object is copy constructed.

Solution
Use a non-const rvalue reference instead:
void AddData(A&& a) // <-- non-const reference
{
    aList.push_back(std::move(a)); // selects push_back(A&&)
}

Comment: Your answer is great as is. I'm just overly pedantic. a `const` rvalue reference parameter function has no defined semantics _for `std::string`_ or any other standard C++ type, but one is free to define their own semantics for `const&&` for their own classes.
Comment: "Marking a const object with std::move() for moving has no effect " Technically, `std::move` just casts to an Rvalue, leaving you with a valid `const&&`.  It's merely that `std::string` doesn't have a constructor that takes a `const&&`, and so falls back on `const&`.  One could theoretically make a class with a `const&&` constructor.
Comment: @MooingDuck Yes, you are right `std::move()` has **always** the effect of performing a cast. However, the point I would like to make is that `std::move()` has no effect on a `const` object regarding *move semantics* because I think a `const` *rvalue reference* parameter function (e.g., of type `const A&&`) has no defined semantics. I hope it's more or less clear why the overload `vector::push_back(const A&)` was being selected – there is no `vector::push_back(const A&&)` overload after all.


Closed Form Solutions To Simple Iterated Polynomial Building Blocks

Question: I've been doing some work on fractals and simple iterated polynomials lately. I admit, I've only taken classes up through Calc 2, although I've done a decent bit of reading on many topics over the years. But I've been working on finding closed-form solutions to simple polynomial recurrence relations using three basic "building blocks" (the most basic math operations essentially) and then combining them in various ways to see how the solution form changes based on its parts. (Note: In some ways, I am somewhat of a child playing with a loaded gun, so to speak, i.e. fumbling with things I don't fully understand probably.)
Here are the most basic building blocks I started with:
$$\mathbf{x_{n+1}=ax_n}$$
$$\mathbf{x_{n+1}=x_n+b}$$
$$\mathbf{x_{n+1}=x_n^c}$$
And their combinations:
$$\mathbf{x_{n+1}=ax_n+b}$$
$$\mathbf{x_{n+1}=ax_n^c}$$
$$\mathbf{x_{n+1}=x_n^c+b}$$
And the combination of all three:
$$\mathbf{x_{n+1}=ax_n^c+b}$$
The solutions I have come up with so far:
$$\mathbf{x_{n+1}=ax_n \Rightarrow x_n=a^nx_0}$$

$$\begin{eqnarray*}
x_1&=&ax_0\\
x_2=ax_1=a(ax_0)&=&a^2x_0\\
x_3=ax_2=a(a(ax_0))&=&a^3x_0
\end{eqnarray*}$$

$$\mathbf{x_{n+1}=x_n+b \Rightarrow x_n=x_0+nb}$$

$$\begin{eqnarray*}
x_1&=&x_0+b\\
x_2=x_1+b=(x_0+b)+b&=&x_0+2b\\
x_3=x_2+b=((x_0+b)+b)+b&=&x_0+3b
\end{eqnarray*}$$

$$\mathbf{x_{n+1}=x_n^c \Rightarrow x_n=x_0^{c^n}}$$

$$\begin{eqnarray*}
x_1&=&x_0^c\\
x_2=x_1^c=(x_0^c)^c&=&x_0^{c^2}\\
x_3=x_2^c=((x_0^c)^c)^c&=&x_0^{c^3}
\end{eqnarray*}$$

$$\mathbf{x_{n+1}=ax_n+b \Rightarrow x_n=a^nx_0+b\sum_{i=0}^{n-1}a^i=a^nx_0+b\left(\frac{1-a^n}{1-a}\right),(a\neq1)}$$

$$\begin{eqnarray*}
x_1&=&ax_0+b\\
x_2=ax_1+b=a(ax_0+b)+b&=&a^2x_0+ab+b\\
x_3=ax_2+b=a(a(ax_0+b)+b)+b&=&a^3x_0+a^2b+ab+b
\end{eqnarray*}$$

$$\mathbf{x_{n+1}=ax_n^c \Rightarrow x_n=a^{\sum_{i=0}^{n-1}c^i}x_0^{c^n}=a^{\left(\frac{1-c^n}{1-c}\right)}x_0^{c^n},(c\neq1)}$$

$$\begin{eqnarray*}
x_1&=&ax_0^c\\
x_2=ax_1^c=a(ax_0^c)^c=a(a^cx_0^{c^2})&=&a^{c+1}x_0^{c^2}\\
x_3=ax_2^c=a(a(ax_0^c)^c)^c=a(a^{c+1}x_0^{c^2})^c=a(a^{c^2+c}x_0^{c^3})&=&a^{c^2+c+1}x_0^{c^3}
\end{eqnarray*}$$

The solutions that still evade me:
$$\mathbf{x_{n+1}=x_n^c+b \Rightarrow x_n=?}$$
$$\begin{eqnarray*}
x_1&=&x_0^c+b\\
x_2=x_1^c+b=(x_0^c+b)^c+b&=&\sum_{i=0}^c\binom{c}{i}x_0^{ci}b^{c-i}+b\\
x_3=x_2^c+b=\left(\sum_{i=0}^c\binom{c}{i}x_0^{ci}b^{c-i}+b\right)^c+b&=&\sum_{j=0}^c\binom{c}{j}\left[\sum_{i=0}^c\binom{c}{i}x_0^{ci}b^{c-i}\right]^{cj}b^{c-j}+b
\end{eqnarray*}$$
$$\mathbf{x_{n+1}=ax_n^c+b \Rightarrow x_n=?}$$

(Ouch. My head...)

Can anyone give a succinct explanation as to why these last two have such complicated forms compared to the rest? (And sorry for my possibly horrendous algebra, it's been several years since I had any formal math classes...) I read Chaos And Fractals, New Frontiers in Science several years ago (and still have the book). Might the answer be in there? I realize the last two relations are non-linear, but isn't $x_{n+1}=ax_n^c$? I apologize if this has been answered elsewhere. I tried looking around but nothing really seemed to match what I am talking about. Is there a good way to manipulate the nested summations?
Comment: Wow, I just learned that this site is for professional mathematicians only. While I'd like to consider myself one, I'm really not. I apologize if this question is better for math.stackoverflow.
Comment: You can flag this for moderator attention and ask them to migrate it if you like.
Comment: @DavidRoberts Thanks. I will do that.
Answer: Mandelbrot considered a special case of your last one: $z_{n+1}=z_n^2+b$.  There are closed forms in case $b=0$ and in case $b=-2$.  But not for other values of $b$.
For the lower cases, like $z_{n+1}=az_n+b$, you can look for the topic "difference equations".
For $z_{n+1}=az_n^c$ you can try $u_n = \log z_n$ intead.
Comment: Thank you for your answer GEdgar. Where can I find more information about the closed forms for $z_{n+1}=z_n^2+b$? Like why -2? 0 is obvious (the term just vanishes), but -2? And only -2? Does it have to do with the fact that it has the same absolute value as the exponent?
Comment: The hint for $z_{n+1}=z_n^2-2$ is: double angle formula for cosine.


Pooled time series regression in R

Question: I've got data on mail volume sent by household for seven age groups, with 12 years of data for each age group. I originally ran a simple regression on each age group individually and realized I needed to dig deeper. My aim now is to pool the data (giving me 84 observations) and try to identify some period effects (or year effects, whichever you prefer). My pooled data are currently organized like this (PPHPY stands for Pieces per Household Per Year):
Age Group    Year   PPHPY
1            2001   127.62
1            2002   144.47
1            2003   111.70
1            2004   95.96
1            2005   96.46
1            2006   139.91
1            2007   85.52
1            2008   75.43
1            2009   109.34
1            2010   53.16
1            2011   64.09
1            2012   50.94
2            2001   176.48
2            2002   172.86
2            2003   137.79
.              .      .
.              .      .
.              .      .
7            2012   163.39

I first regressed PPHPY on year and year dummies (leaving the intercept as 0 to avoid perfect multicollinearity). This gave me period effects for the aggregated data (ie something like a period effect across all age groups, I think). This looked like the following:
> ## Generate YearDummy using factor()
>
> YearDummy <- factor(YearVar)
>
> ## Check to see that YearDummy is indeed a factor variable
>
> is.factor(YearDummy)
[1] TRUE
>
> ## (...+0) ensures intercept is left out and thus YearDummy1 remains in.
    ## One or the other must be subtracted out to avoid perfect mutlicollinearity
>
> LSDVYear <- lm(PPHPY ~ YearVar + YearDummy + 0, data=maildatapooled)
> summary(LSDVYear)
Call:
lm(formula = PPHPY ~ YearVar + YearDummy + 0, data = maildatapooled)
Residuals:
Min 1Q Median 3Q Max
-99.658 -39.038 8.814 43.670 82.300
Coefficients: (1 not defined because of singularities)
Estimate Std. Error t value Pr(>|t|)
YearVar 5.743e-02 9.851e-03 5.830 1.45e-07 ***
YearDummy2001 1.099e+02 2.795e+01 3.930 0.000193 ***
YearDummy2002 1.209e+02 2.796e+01 4.324 4.85e-05 ***
YearDummy2003 7.791e+01 2.797e+01 2.786 0.006819 **
YearDummy2004 8.053e+01 2.797e+01 2.879 0.005251 **
YearDummy2005 6.887e+01 2.798e+01 2.461 0.016236 *
YearDummy2006 6.572e+01 2.799e+01 2.348 0.021618 *
YearDummy2007 5.975e+01 2.799e+01 2.134 0.036210 *
YearDummy2008 5.836e+01 2.800e+01 2.084 0.040696 *
YearDummy2009 4.119e+01 2.801e+01 1.471 0.145745
YearDummy2010 3.056e+01 2.801e+01 1.091 0.278990
YearDummy2011 1.472e+01 2.802e+01 0.525 0.600951
YearDummy2012 NA NA NA NA
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 52.44 on 72 degrees of freedom
Multiple R-squared: 0.9316, Adjusted R-squared: 0.9202
F-statistic: 81.71 on 12 and 72 DF, p-value: < 2.2e-16

What I want, however, is to tease out period effects for each age group individually. This is what I'm not sure how to set up. I was hoping someone might help me devise some code in R that would kick out those period effects for each of the seven age groups using the pooled data, as well as help me understand the problem conceptually.
EDIT: I forgot to mention that I see I must include an interaction term involving the time dummies to allow the coefficients to vary across age groups. I'm just having difficulty constructing the proper interaction term and resulting regression equation.
EDIT 2: I came up with two models and ran them. I felt like the question had evolved at this point and might merit a new post, which is can be found here.
Comment: Have you checked the [plm](http://cran.r-project.org/web/packages/plm/vignettes/plm.pdf) package in `R`. This is the package designed specifically for running various panel data models (including pooled OLS)in `R`. There is also how to do file [here](http://dss.princeton.edu/training/Panel101R.pdf)
Comment: I think you can specify the interaction terms when specifying the model. There is a recent discussion [here](http://stats.stackexchange.com/questions/51417/issues-when-using-interaction-term-with-a-lagged-variable-in-r)
Comment: I have indeed downloaded and experimented with the plm package and came across that very how-to link (quite well-written!). I found it useful (the plm package) but couldn't find a function with the layer of detail necessary to include the appropriate interaction terms that would give me period effects for individual age groups. I mainly experimented with the plm() and pggls() functions. Is there a function in the package I may have missed which could help me here?
Comment: Ok, that's helpful! My question after that, however, is how do I design the equation I wish to specify? My dependent variable is PPHPY, and the information I've got is Age Group (ranging from 1-7) as well as YearVar (ranging from 2001-2012). I would like to find period effects for each age group using the pooled data. Any idea how I might go about constructing the regression equation?
Comment: Please post what you did (by updating the question with code) and others can then help.
Comment: Done! Hopefully it makes some sense in the context of what I want to do now...
Answer: This doesn't exactly answer what are you looking for. However, I think you need to consider these issues before doing the analysis. In other words, I focus more on the conceptual part (part a) [I thought it to include in comment but this is very long]
With the repeated cross section data, you have here the pseudo panel data (with age group (age cohort) acting as individual effect and year as time effect) and not the true panel data. Theoretical stuffs on this has been discussed here. The good news is that you can use the fixed effect, random effect,and  pooled estimator as being used for the true panel data. The use of different tests to choose one over another estimator has been discussed in the plm package manual. However, it is good to start with Introductory Econometrics by Woolridge if you are beginners in panel data. That being said, consider this Oxford discussion paper as a starting one. Once you understand the concept mentioned in the paper, it won't be difficult to apply in R. Your question doesn't spell out other variables. Is that the case?
Comment: Correct, there are no other variables at play here besides what I've included in the original post. I'll read the Oxford paper and see if that clears things up for me.

Pooled time series regression in R


How can I make Drupal/MySql accept special characters in ANSI (without changing the file's encoding)?

Question: I'm developing a custom module where a user (actually an admin of sorts) can upload a  CSV file. Based on the contents of this file, certain rows are inserted into a table.
I'm now having problems with special characters, like é. These give the following error:
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE9initi...' for column 'remarks' at row 1

I've tried changing the collation of the table and of the specific field, but this didn't help. The only thing that did help is changing the encoding of the file. But this puts the burden of solving the problem in the hands of the (non-technical) admin. Something I don't want.
What's more, this used to work. Before this module, things were done with a (non-Drupal) php script. The difference is that the old php script used mysql_query to insert the records, whereas I am now using db_insert.
How can I make Drupal/MySql accept the special characters in ANSI?
Answer: Found it. I just needed to encode the values with:
$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

Comment: If that's what you are using, and it works, please mark this answer as accepted. It will show people you are not waiting for another answer.
Comment: Oh, OK. I was sure there were plans to lift or at least shorten these limits on less busy sites, but it seems it didn't happened yet. Thanks for caring :)


Finding points that are closest and most far way from origin - using calculus

Question: As the title says i want to find $(x,y,z)\in \mathbb{R}$ that are connected with thse two "equations":
$$z^2-x^2-y^2=0$$
$$x-2z-3=0$$
And are the closest or most far away from origin $(0,0,0)$
So i know i need to use Lagrange multipliers and than find maximums and minimums with a system, but i get lost at trying to get that.
Normally i had a function and then some "sub"functions but now i don't have a main function or i just don't notice how to solve it using calculus.
I think it's solved with Lagrange multiplier, if not i am ope for suggestions.
Any help would be appreciated.
Comment: The "main" function is the one you want to minimize, so in this case, it is the distance from the origin.
Comment: @5xum yeah thank you, it was in the answer down below as well, so it's undestandable now.
Answer: A first remark, if I may : minimizing the distance is the same as minimizing the square of the distance.
So, you want to minimize $$f=x^2+y^2+z^2$$ subject to the constraints $$z^2-x^2-y^2=0\qquad , \qquad x-2z-3=0$$ So, let us define $$F=x^2+y^2+z^2+\lambda(z^2-x^2-y^2)+\mu(x-2z-3)$$ and work as usual. $$F'_x=2x -2 \lambda  x+\mu$$ $$F'_y=2 y-2 \lambda  y$$ $$F'_z=2z+2 \lambda  z-2 \mu $$ $$F'_\lambda=z^2-x^2-y^2$$ $$F'_\mu=x-2z-3$$ At the extremum, all the derivatives must be $0$.
I am sure that you can take it from here.
Answer: When we face such problems, the first reaction (you properly had) is to think about Lagrange multipliers.
However, in some case such as this one, the problem can be extremely simplified.
We want to minimize $$f=x^2+y^2+z^2\tag 1$$subject to the constraints $$z^2-x^2-y^2=0\tag 2$$ $$x-2z-3=0\tag 3$$ The first constraint can rewrite $$z^2=x^2+y^2\implies f=2(x^2+y^2)\tag 4$$ and the second constraint gives $z=\frac{x-3}{2}$. So $$z^2=x^2+y^2\implies \frac{1}{4} (x-3)^2=x^2+y^2\implies y^2=-\frac{3 x^2}{4}-\frac{3 x}{2}+\frac{9}{4}\tag 5$$ and since $(x,y,z)\in \mathbb{R}$, $$y^2 \geq 0 \implies -3\leq x\leq 1\tag 6$$ So, finally, we look for the extrema of the function $$f=\frac{1}{2} (x-3)^2$$ in the above range.
Simpler, isn't it ?
Comment: yeah, that is much simpler,didn't even see it
Comment: @MathIsTheWayOfLife. I made both answers on purpose. The first one to show how to solve it using Lagrange multipliers. In fact, from the very beginning, I noticed what I gave in the second answer. One possible conclusion : before starting solving the problem, have a deep look at what is given. Please notice that if one of the equality constraints is linear with respect to one variable, you can eliminate the variable and the constraint. Cheers :-)


how to hide articles page from home page in drupal

Question: I have added article page in my project and made Views for that, but articles page also display on the front page. How to hide article from home page?
Answer: you have to untick "Promoted to front page " on structure / content types / your content types / publishing options, for every content type you have.
Comment: Or you can change your homepage to a node in Configuration -> System -> Site Information
Comment: I had Crate view of that all news ,I want to add Author details in view as one field how can I ?


Redirect from one module to another

Question: I have form in one module.
<code>  public static function validateForm(array &$form, FormStateInterface $form_state) {
      $url = \Drupal\Core\Url::fromRoute('test.route');
      $form_state->setRedirectUrl($url);
      $form_state->setRedirect('test.route');
  }
</code>
Trying to redirect the route of another module.
It's not redirecting from one module to another.
Answer: An example
<code>    use Drupal\Core\Url;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
</code>
Its not working in Form validate.
Its working un submitform
<code>public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('route.path');
        $form_state->setRedirectUrl($url);
}
</code>
Comment: It's not working. Already tried
Comment: It does not work in the form validation, but in the submit. I updated the code.
Comment: Thanks. Yes it;s not working in Form Validate, but works in Submit

Redirect from one module to another


Prove that $\lim_{n\to \infty} \int_A f_n d\mu = \int_A fd\mu$

Question: Let $(X, \mathcal{F}, \mu)$ be a measure space, $A\in \mathcal{F}$ and $f: A\to \overline{R}$ is a non-negative measurable function. For each $n\ge 1$, we define $f_n: A\to \overline{R}$ as $$f_n(x) = \begin{cases} f(x) &\text{if } f(x)\le n \\ n^2 &\text{if } f(x) > n \end{cases}.$$
Show that $$\lim_{n\to \infty} \int_A  f_n d\mu = \int_A fd\mu.$$
I cannot apply either Monotone Convergence Theorem or Dominated Convergence Theorem here, so I wonder if there exists any counter-example for this problem.
Thank you very much.
Comment: why can't you use monotone convergence?
Comment: Why do you write "show that" if you think it might be false?
Comment: @pwerth Since $(f_n)$ is not a monotone sequence.
Comment: @zhw. It's a problem in my exam.
Comment: A better way to write it would be "here's a problem from my exam, but I am wondering if the result is true." When you write "show that" you can send people off on a wild goose chase.
Comment: @zhw. My mistake. I will write more clearly next time. Also, thanks so much for your answer.
Answer: Hint: Consider $f(x) = 1/\sqrt x$ on $(0,1).$


Como consigo criar uma imagem no docker mas ao invez de utilizar o copy para os arquivos usar clone do git

Question: Tenho um repositorio no github com meu projeto e preciso criar uma imagem pra rodar esse projeto mas não estou conseguindo
FROM python:3.6.7
MAINTAINER RENAN SACCA
CMD ["git","clone","https://github.com/Renan-Sacca/teste-docker.git"]
WORKDIR teste-docker
RUN pip3 install -r requirements.txt
EXPOSE 8000
CMD ["python3", "main.py"]

Ele da erro na hora de instalar o requisito fala que não encontrou então acho q o problema esta em pegar diretorio do git
Answer: O erro está na confusão entre CMD e RUN.
Segundo a documentação do Docker, a instrução CMD serve prioritariamente para indicar os parametros a serem usados pelo entrypoint de um container. E adiciona que o Dockerfile deve conter uma ÚNICA instrução CMD e caso mais de uma seja adicionada, somente a última terá efeito.
Este é justamente o problema do seu Dockerfile. Primeiro que, mesmo que CMD ["git","clone","https://github.com/Renan-Sacca/teste-docker.git"] estivesse correto, seria ignorado porque há outro CMD. Ainda que não existisse outro, o CMD é utilizado somente no momento da inicialização do container. É por isso que ao fazer RUN pip3 install -r requirements.txt não existe o requirements.txt.
Para se executar instruções no build de uma imagem deve-se usar o RUN. Dessa forma, o seu Dockerfile deveria ser algo como
FROM python:3.6.7
LABEL maintainer="RENAN SACCA"
EXPOSE 8000

RUN git clone https://github.com/Renan-Sacca/teste-docker.git
WORKDIR teste-docker
RUN pip3 install -r requirements.txt

CMD ["python3", "main.py"]

Obs:

a instrução MAINTAINER está obsoleta e foi substituída por LABEL;
a instrução EXPOSE foi movida a fim de melhorar a legibilidade do código;
Comment: Entendi, estou aprendendo meio do zero então não sabia disso do cmd, testei o codigo que deixou e funcionou, muito obrigado pela ajuda


How can I calculate the effect of my equipment on my sport's performance?

Question: I'm doing a stationary sport like golf, so the details matter.
I'm recording each of my scores with detailed information about the equipment I'm using, and the weather conditions. So 1 score has 2-3 pieces of equipment attached to it.
I can plot averages for may main piece of equipment, but then how do I isolate the effect of the others(performance accessories/safety equipment)?
Answer: You can apply multiple factor ANOVA with your score as dependant variable and equipment and weather conditions as factors. You would need to meet certain assumptions:
1) scores should be normally distributed under each factor
2) ratios of variance between groups should not exceed 3 or be less then 1/3
3) most importantly: all scores must be independent among and within groups
Comment: +1 The second item isn't actually an assumption of anova. The *assumption* is equality of variance. What you have there is advice about how much heteroskedasticity can be tolerated. I'm curious about how they arrived at those particular numbers. Is there a paper from which this advice comes?
Answer: Depending on your response variable which might be skewed (e.g. distance from tee, distance from hole), or counts (frequency of some event, like 'on the green'), you'd likely use some form of GLM. In some cases, the response might be nearly normal, in which case you might use some form of regression/ANOVA.
But before you worry about analyzing data you need to design your experiment; a good experiment will mix and match your various types of equipment in an appropriate manner (to your assumptions and hypotheses - if you aren't looking for interactions, it's relatively simple), and will likely randomize these combinations to different holes, preferably more than one per combination of equipment. If you want to estimate interactions, you could be in for a lot of holes of golf.


2 HTML forms with same submit - POST through values from both

Question: Ok , maybe a hard one to explain. I have a form that is built using PHP Form Builder Class
Which looks like:
$form = new form("firstForm");
    $form->setAttributes(array(
             "width" => 600,
             "noAutoFocus" => 1,
             "jsIncludesPath" => "lib/php-form-builder-class/includes",
             "action" => "uploader.php"
    ));

    $form->addTextbox("Enter a Title:", 'title' , $row['title']);
    $form->addTextbox("Enter a Promo Code:", "promo" , $row['promo']);
    $form->addWebEditor("Description", "description", $row['description'], array("basic" => 1));
    $form->addWebEditor("Terms and Conditions", "terms", $row['terms'], array("basic" => 1));
    $form->addHidden("img_urls", $row['img_urls']);
    $form->addHidden("destination", $row['destination']);
    $form->addHidden("header", $row['headerimg']);
    $form->addHidden("cmd", "submit_0");
    $form->addButton();
    $form->render();

I want to add some jQuery to one of the elements to allow drag and drop,  so I've made another form element:
?>
    <form id="firstForm"  action="uploader.php" method="post" >

    Mags Select:
    <?
    foreach ($profiles as $mag) {
    ?>

<input type="checkbox" name="units" value="<? echo $mag ?>" /><? echo $mag ?>

    <? }  ?>

    </form>

How can I make the jQuery part post through its values 'units' when the PHP Form Builder Class is submitted?
Ive had a look at adding a method to the class, but wondered if there was an easier way?
EDIT:
The PHP Form Builder Class form is self contained, so wherever the jQuery form is in the page, it will always be outside the other.
Comment: Why make another form? Just add your elements to the original form so they submit the values along with it.
Comment: Ah, didnt explain that when the PHP Form is generated, it is self contained.
Answer: You could use javascript and transfer the values from the second form INTO (hidden fields in) the first form?
Or similarly you could just build the form and copy the HTML (view source) and use that instead of the raw php, then slot your jQuery drag and drop thing into it that way.
Comment: an inelegant solution ,(I mean that in no way disrespectfully!) but I did your second answer, thanks!
Answer: Just change your second "firstForm" id to secondForm then do something like this:
$('#firstForm').submit(function(event) {
    event.preventDefault();

    var postData = $(this).add('#secondForm').serialize();

    $.post($(this).attr('action'), postData, function() {
     // Complete....
    }
});

As your units input has multiple elements, you can change this to an array like so (take note of change from units to units[]):

   <? foreach ($profiles as $mag) { ?>
      <input type="checkbox" name="units[]" value="<? echo $mag ?>" />
      <? echo $mag ?>

   <? } ?>

Then you'll receive this just like an array in PHP:
 foreach ($_POST['units'] as $key => $value)
 {

 }

Comment: I tried this :   but the window redirect never gets called.
Answer: Could you not have your jQuery drag-and-drop form field in the same <form> tag as all the other fields? That's the natural way to do it.
Comment: I'm guessing he can't put custom HTML/jQuery into forms made using the php form class?
Comment: Without adding another custom method to the class, I cannot think how to add the 'jQuery' form to the PHP one.
Comment: @BobFlemming: the jQuery field is just made up of checkboxes and that ``, right? Could you not add the checkboxes to the form via PHP Form Builder, then put the `` after the form? (I'm not familiar with PHP Form Builder, so apologies if this isn't possible.)


Create a layout 3 column with 2-1-2 teasers

Question: I would like to create a layout like in this image.

It's all the same content type, and I am displaying images.
The columns have all the same width, the first columns -left- contains 2 teasers ( one below the other), the second one -center- contains 1 teaser, the last column -right- contains 2 teasers ( one below the other).
The image teaser on the center column has the same width of the other but it has the double of height, so I will need another image style or another field.
I can't achieve this just with css otherwise the images will look stretched/cropped.
I don't know how to approach to this issue. How to say that each two nodes, I need to display one with a different image style or another field image, using views.
Any help, suggestion, idea would be appreciate!
Comment: it's do able, but first you should tell us if this is Drupal 7 or 8?
Comment: @NoSssweat at the title says Drupal 7 ;)
Comment: @ЕлинЙ. oh geeze for some reason I was only looking at the tags field.
Comment: Yes is Drupal 7, any idea how to approach to this issue?
Answer: This solution is not perfect, but will most likely be the fastest to achieve:

In hook_node_preprocess() render the image field twice, once with small and once with large image style.
Edit your node--YOUR-CTYPE.tpl.php file and display both images.
Use CSS to display the correct one. You can basically do this:
.views-row-1 .your-large-image-selector,
.views-row-2 .your-large-image-selector,
.views-row-4 .your-large-image-selector,
.views-row-5 .your-large-image-selector {
  /* Hide large image. */
}
.views-row-3 .your-small-image-selector {
  /* Hide small image. */
}

Other than that, you could try doing this in a custom module, unless you really need Views for something. I think doing this through a custom module makes more sense if you have to display a larger number of images on the page (e.g. 20-30), because with the approach above you will end up with twice as much images.
Here's what you would need to do in a custom module:

Add hook_theme() implementation and declare your own custom template. Here you would display the first two items on the left, third in the middle and the last two in the right column. The arguments for the template would be just an array called items for example.
Get all nodes you want to display, prepare the output and split them into groups of 5. Every third item would use the larger image style.
Loop through the groups and theme the output based on your custom theme.
Put everything together and display on the page.

This way you won't have 2 images for each node, but you will have to write custom code.
There are other ways to achieve this, but I believe developer sanity should not be overlooked. The ways I suggested above are more or less easy to do.
Hope this helps.


make taxonomy terms more human friendly

Question: I work on a  news site that has hundreds of articles and all the article urls are written by hand. eg. example.com/world-news-today-28-march-2018
The site has various news categories like: business, economy, technology, etc
but they are named taxonomy/term/1 and so on.
Is it too late now to activate pathauto module on a live production site that has tons of content?
All I want to do is change the urls of the news categories and make them more human friendly, so example.com/taxonomy/term/1 becomes example.com/business
without touching the article urls which are in each category.
Any ideas how can I do this and if it's safe at this stage?
Comment: You can add Pathauto and Redirect module so it creates redirects from URLs when new ones are generated.
Comment: Why you are considering Pathauto? You've written the url aliases for the nodes by hand, why not do the same for the taxonomy terms? As soon as you enter a url alias in the term edit form the internal path taxonomy/term/1 will be replaced.
Comment: Thank you, I entered a url alias in the term edit form the internal path like you said and it worked like a charm. A million thanks again, and I wish you Happy Holiday.
Answer: You can use Pathauto module and follow these steps:

Enable pathauto module
Go to admin/config/search/path/patterns and set the patterns for specific taxonomy using Token module and save the form
Go to admin/config/search/path/update_bulk and generate URLs for taxonomy

Don't worry about the existing URLs (no matter wherever you added it) it will remain same, Pathauto will not effect anything. Now, visitors can access by both URLs (default and newly generated).
I hope this will help you.
Comment: Thank you very much for your reply. I chose the manual way to avoid installing extra modules, because the site has too many already. Thanks again.

make taxonomy terms more human friendly


Autofill Bootstrap select dropdown

Question: I have a form which has the option of an 'autofill' button. I've got the autofill button working correctly using jQuery formautofill.
The problem I'm having is that I'm using Bootstrap select and I have a title field which isn't changing - is there something specific to Bootstrap select that I have to do in order to change the field when the button is clicked?
My jQuery currently looks like:
var data = {
    "title": "1",
    "forename": "John",
    "surname": "Doe",
    "email": "",
    "tel": ""
}
$(".autofill.btn").bind("click", function() {
    $(".autofillForm").autofill(data, {
        //findbyname: false
    });
});

Answer: I think I've managed to figure it out. For those ever in need you have to re-render the select box.
This is my finished jQuery
var data = {
    "title": "1",
    "forename": "John",
    "surname": "Doe",
    "email": "",
    "tel": ""
}
$(".autofill.btn").bind("click", function() {
    $(".autofillForm").autofill(data, {
        //findbyname: false
    });
    $('select').selectpicker('render');
});

Autofill Bootstrap select dropdown


Laravel 7 add React.js to project without composer require laravel/ui?

Question: I need to connect React.js to Laravel 7.23 project with UIkit.css framework.
Standard solution
composer require laravel/ui
php artisan ui react
php artisan ui react --auth
npm install

But, this solution includes bootstrap.css framework which I do not need.
I also found
php artisan preset react

But on execution I get "Command "preset" is not defined."
Comment: i'm looking for this same question, did you found a solution?
Answer: laravel-ui is the new laravel frontend Scaffolding library. php artisan preset is no longer supported.
php artisan ui react will give you the react Scaffolding. There is no default option for UIkit.css If you do not need bootstrap just remove it and add something you want.
Hope that answers all your concerns.
Answer: For installing react in laravel 7, refer to documentation
Install laravel ui composer package
composer require laravel/ui

Install react
 php artisan ui react

Install react with auth
 php artisan ui react --auth

Make sure you run npm install and npm run dev


How to create digital persona FMD from byte[] in Android?

Question: I am able to save FMD to SQLite in Android. However when I am trying to recreate FMD it is not working properly.
Saving FMD in database.
try {
                        Fmd m_enrollmant_fmd = m_engine.CreateEnrollmentFmd(Fmd.Format.ANSI_378_2004, enrollThread);
                        if (m_success = (m_enrollmant_fmd != null)) {
                            byte[] fingerprintData = m_enrollmant_fmd.getData();
                            int fingerprintImageHeight = m_enrollmant_fmd.getHeight();
                            int fingerprintImageWidth = m_enrollmant_fmd.getWidth();
                            int fingerprintResolution = m_enrollmant_fmd.getResolution();
                            int fingerPosition = m_enrollmant_fmd.getViews()[0].getFingerPosition();
                            int cbeffId = m_enrollmant_fmd.getCbeffId();
                            int m_templateSize = m_enrollmant_fmd.getData().length;
                            m_current_fmds_count = 0; // reset count on success
                            // Save above values in database and this is working fine.
                        }
                    } catch (Exception e) {
                        m_current_fmds_count = 0;
                    }

Recreating FMD Code:
Fmd temp_fmd = m_engine.CreateFmd(
                                user.fingerPrint,  // byte[]
                                user.width,  // width
                                user.height, // height
                                user.resolution, // resolution
                                user.fingerPrint, //Finger position,
                                user.cbeffId, // Cbeff Id
                                Fmd.Format.ANSI_378_2004); // Format algorithm

                        if (temp_fmd != null) {
                            // m_fmd is FMD that we generate after taking fingerprint
                            int m_score = m_engine.Compare(m_fmd, 0, temp_fmd, 0);
                            if (m_score < (0x7FFFFFFF / 100000)) {
                                userFound = user;
                                break;
                            }
                        }

This gives me UareUException saying FID is invalid. However when I try to give fix values in m_engine.CreateFmd(...) except byte[] parameter, it works fine but its dissimilarity is 100%, meaning it doesn't match at all. Any help will be appreciated. I am using UareU SDK 3.1 from Crossmatch (previously known as Digital Persona).
Note that values from Database are correct there is no issue in that. Only I am unable to create correct FMD.
Answer: Try using the following to recreate the Fmds from a byte array:
Fmd print = UareUGlobal.GetImporter().ImportFmd(prints, Fmd.Format.ANSI_378_2004, Fmd.Format.ANSI_378_2004);

Where prints here is your byte array.


Mostrar resultado de uma consulta sql by group na página PHP

Question: Boa noite, esse código funciona exatamente da forma que preciso executando direto no sql, porém como eu faço para ele aparecer em uma página php, tentei diversas coisas, até consegui fazer imprimir porém não aparece certo.
SELECT estado, COUNT(*) As Total FROM emailc WHERE status = 1 GROUP BY estado

Resultado no SQL:

O mais próximo que cheguei do resultado igual ao da imagem foi com esse código:
$estados = mysqli_query($conexao,"SELECT * FROM `emailc` where status = 1");

while($res = mysqli_fetch_assoc($estados)){

    $nomeEstado = $res['estado'];

    $estadoConta = mysqli_query($conexao,"SELECT COUNT(estado) AS TOTAL FROM emailc WHERE estado LIKE '%$nomeEstado%'");

    while($row = mysqli_fetch_assoc($estadoConta)){

            echo '
'.utf8_encode($nomeEstado).' '.$row['TOTAL'].'
'.PHP_EOL;

Porém repete o estado, mas faz a contagem certa como mostra a imagem abaixo:

Desde já fico agradecido pela ajuda.
Comment: obviamente  na ultima query é que falta o `status`, isso vai dar difença obviamente. Além disso, em ai um `LIKE` na query, pq não usa o `=` ?
Comment: Adicionando o status o resultado permanece igual, e se eu colocar o = no lugar do like, o resultado fica 0, ele não conta quantas vezes tem a sigla RJ por ex.
Answer: ---RESOLVIDO---
Vou deixar aqui a solução que encontrei pode dar a luz para alguém.
$estados = mysqli_query($conexao,"SELECT * FROM `emailc` where status = 1");

$nomeEstado = array();
while($row = $estados->fetch_assoc()) {
$nomeEstado[$row['estado']][] = $row;
}
foreach($nomeEstado as $estado => $values){
$estadoConta = mysqli_query($conexao,"SELECT COUNT(estado) AS TOTAL FROM emailc WHERE estado = '$estado'");
while($row = mysqli_fetch_assoc($estadoConta)){

        echo '
'.utf8_encode($estado).' '.$row['TOTAL'].'
'.PHP_EOL;

}}
Resultado:


How can I consistently see the "renderable" version of a views field?

Question: I created a custom views style plugin. I currently use:
<code>$value = $view->field[$label_column]->getValue($row);
</code>
to get the value of the field. However, I was recently informed that this does not work for list fields(like 0=>'yes'=, 1=>'no'). This original line displays 0 and 1 instead of 'yes' and 'no'. This user suggested I use:
<code>$items = $view->field[$label_column]->getItems($row);
$value = $view->field[$label_column]->render_item(1, $items[0]);
</code>
It seems like this solution does not work on standard fields. I also recently found that the original line does not respect field rewrites. Is there a universal way to see the field value after rewrites, while also respecting lists?
Answer: Use advancedRender(), this is a method in the base class of views fields, which renders an entity field respecting field rewrites and other settings:
<code>$value = $field->advancedRender($row);
</code>


Putting limit inside an integral to calculate $\int_0^\infty \frac{\sin x}{x}dx = \frac{\pi}{2}$

Question: I'm trying to prove: $$\int_0^\infty \frac{\sin x}{x}dx = \frac{\pi}{2}$$
I have defined $\; I(a)= \int_0^\infty\frac{\sin x}{x}e^{-ax}dx\;$ for $a>0$, and I'm trying to show that: $$\frac{dI}{da}(a)=-\int_0^\infty \sin(x)  e^{-ax}dx$$
I started like this: $$\frac{dI}{da}(a)= \lim_{h \to 0} \frac{I(a+h)-I(a)}{h}=\lim_{h \to 0} \int_0^\infty \frac{\sin x}{x}\biggl(\frac{e^{-(a+h)x}-e^{-ax}}{h}\biggr)dx$$
Next I would like to put the limit inside the integral, and then I get what I want, but how can I justify this? Thanks
Comment: [This](https://math.stackexchange.com/questions/253696/can-a-limit-of-an-integral-be-moved-inside-the-integral) might help.
Comment: have you tried the Leibniz integral rule, to derivate under the integral sign ?
Comment: I haven't learned the Leibniz integral rule. The only case I know I am allowed to put limits inside an integral is when I have uniform convergence, which in this case I'm not sure how to prove
Comment: One thing that you can do is just to copy the proof of the Leibniz rule for this specific case. The proof I know uses the DCT.
Comment: Your caution deserves praise, especially since even after showing $\displaystyle I(a)=\arctan\frac1a$, you'll still have to justify $\displaystyle\lim_{a\to0+}\int^\infty_0\frac{\sin x}x\,e^{-ax}\,dx=\int^\infty_0\frac{\sin x}x\,\lim_{a\to0+}e^{-ax}\,dx$.
Comment: Is there a way to justify putting the limit inside the integeral with Fubini's theorem?
Comment: @user401516 that might be an option!!
Comment: @Shashi can you point me on how to do it? I'v tried for a while and couldn't find a way.
Comment: @user401516 I think some use it to find the Dirichlet integral, just searching a bit in MSE will give results. Tell me your opinion on the things that you will find!
Answer: You can use Fubini to calculate $I(a)$:
\begin{align}
\int^\infty_0 e^{-ax}\frac{\sin x}x\,dx&=\int^\infty_0 e^{-ax}\int^1_0\cos tx\,dt\,dx
\\&=\int^1_0\int^\infty_0 e^{-ax}\cos tx\,dx\,dt
\\&=\int^1_0\frac{a}{a^2+t^2}\,dt=\arctan\frac1a
\end{align}
Since $|\cos tx|\le1$, the double integral is absolutely convergent for any $a>0$.
As I said, this is not enough, we have to justify $\displaystyle I(0)=\lim_{a\to0+}I(a)$. We have
$$I(0)-I(a)=\int^\infty_0\sin x\,\frac{1-e^{-ax}}x\,dx=\int^\infty_0\cos x\,\frac{1-(1+ax)\,e^{-ax}}{x^2}\,dx$$ by partial integration. Now, we can use the dominated convergence theorem, because $|\cos x|\le1$, and the fraction is $\ge0$ and $\le$ the minimum of $a^2$ and $x^{-2}$, i.e. dominated by an integrable function on $[0,\infty)$.
Comment: How can I use it to push to limit inside the integral?
Comment: @user401516 I've just added the necessary details.
Answer: What you have done is possible only if the function is itegrable. Then because of linearity of derivation, integral and limit you can substitute them. This is possible since ${sinx\over x}{e^-ax}$ is integrable and bounded for $x\in [0,\infty)$ when $a\ge0$
Comment: When $a=0$, this function is not absolutely integrable over $[0,\infty)$
Comment: It doesn't require for absolute integrability. It suffices only to be integrable....
Comment: In the sense of an Improper Riemann integrable? Do you have a reference for your claim? Now I am curious.
Comment: Sure! Please refer two "Real Mathematical Analysis" written by Charles C. Pugh


how to override module's theme function in a custom module?

Question: I'm a Drupal8 newbie. I installed a third party module simplelogin, and I attempted to change the {{site_name}} value in page--simplelogin.html.twig but can not find a right way.
I noticed that the variable is defined in simplelogin.module:
function simplelogin_preprocess_simplelogin(&$variables) {
  $path = \Drupal::service('path.current')->getPath();
  $module_path = drupal_get_path('module', 'simplelogin');

  $variables['#attached']['library'][] = 'simplelogin/simplelogin-library';

  // Able to use custom variables
  $variables['path'] = $path;
  $variables['base_path'] = base_path();
  $variables['logo'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));
  $variables['background_class'] = simple_login_settings('active');
  $variables['background_opacity'] = simple_login_settings('opacity');
  $variables['wrapper_width'] = simple_login_settings('width');
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
  $variables['site_register'] = \Drupal::config('user.settings')->get('register');
}

I guess the second "simplelogin" presented in the hook function is a form element in the theme (I'm not quite clear although), as I found $form['simplelogin'] appears in the buildForm function of form controller.
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

    $form_state->disableCache();

    $simplelogin_config = $this->config('simplelogin.settings');

    $imageid = $simplelogin_config->get('background_image');
    if ($imageid) {
      $file = \Drupal\file\Entity\File::load($imageid[0]);  // File Load
      $fileUrl = $file->getFileUri();

      // check if image is valid.
      $image = \Drupal::service('image.factory')->get($fileUrl);
      if ($image->isValid()) {
        $image_render = array(
          '#theme' => 'image_style',
          '#width' => $image->getWidth(),
          '#height' => $image->getHeight(),
          '#style_name' => 'medium',
          '#uri' => $fileUrl,
        );
      }
    }
    //$renderer = \Drupal::service('renderer');
    //$renderer->addCacheableDependency($image_render, $file);

    $form['simplelogin'] = array(
      '#type'            => 'details',
      '#title'           => $this->t('Configuration'),
      '#open'            => TRUE,

      'background_active' => array(

WHAT I HAVE DONE:
                                                                                1. created a custom module named "mylogin", this is the info.yml:
name: myLogin
description: my login module
type: module

version: '8.x-1.0'
package: 8.x
core: '8.x'
project: 'mylogin'

dependencies:
  - simplelogin

2. override hook_preprocess_page in mylogin.module:
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\Core\Controller\ControllerBase;
use Drupal\simplelogin\Controller;

function mylogin_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'user.login') {
    $variables['site_name']= 'test';
  }
}

But it cannot work, and I believe the preprocess is not triggered. Is there a simple way to override the needed variable while keep the others in the module's preprocess function? Any help will be very appreciated.
Answer: You can create a new module use hook_theme_registry_alter like module simplelogin
like this:
/**
 * Implements hook_theme_registry_alter
 *
 * {@inheritdoc}
 */
function YOUR_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['page__simplelogin'][preprocess functions] = [
    0 => 'simplelogin_preprocess_simplelogin',
    1 => 'YOUR_MODULE_preprocess_function'
  ];
}

Comment: I tried this, but it still not triggered the preprocess function...
Comment: Did you try clear cache? If doesn' working try create module start with string t (u, v .. string after S).
Comment: Yes, I did clear cache. What do you mean by "create module start with string...", rename the module?
Comment: Yes, the list hooks is array.  I guess this array order by module name. So may be your hook run before simplelogin's hook.
Comment: Do I need to declare the function path somewhere? The two functions locate in different place.
Comment: I think, you don't need. Because your hook  just alter **preprocess functions**.
Comment: Oh yes! You're right. After I create a new module named xylogin, it triggers the preprocess function. This seems weird, what if I have no name to use after the predefined fucntion? Anyway, thank you very much!
Comment: You can try research with key word "module weight".
Comment: :D and don't missing accept my answer.


Estimating the cardinality of the union of the conjugates of a proper subgroup.

Question: If $G$ is a finite group and $H$ is a nontrivial subgroup of $G$ such that $H^{a}\cap H=\{e\}$ for all $a\in G-H$, where $H^{a}=aHa^{-1}$ and $e$ is the neutral element of $G$, show that $$\left\lvert\bigcup_{a\in G}H^{a}\right\rvert\geq\frac{1}{2}|G|+1.$$ Conclude that if $H$ is a proper subgroup of $G$, then $$\bigcup_{a\in G}H^{a}\neq G.$$
Comment: Second conclusion is again  true when $H$ is a proper subgroup of finite group $G$.
Comment: For a more accurate statement of the previous comment by @mesel see Finite Group Theory by Martin Isaacs, Problem 1A.7.
Comment: https://math.stackexchange.com/q/121526/269050
Answer: The different conjugates $H^{a}$ all have $|H|$ elements exactly. Moreover, if $x\in H^{a}\cap H^b$ with $x\neq e$, then $x=bhb^{-1}=ah'a^{-1} $ for some $h,h'\in H\setminus\{e\}$. Then
$$h=b^{-1}ah'a^{-1}b=(b^{-1}a)h'(b^{-1}a)^{-1}\in H\cap H^{b^{-1}a}.$$
Thus $b^{-1}a\in H$, and we have $a=b\hat{h}$ for some $\hat{h}\in H$. Then
$$H^{a}=aHa^{-1}=b\hat{h}H\hat{h}^{-1}b^{-1}=bHb^{-1}=H^b.$$
So two distincts conjugate only have $\{e\}$ as a common element. This means their union contains $e$ and $|H|-1$ distincts elements for each $H^{a}$. Hence, if we denote $m$ the number of these distincts conjugate of $H$,
$$\left\lvert\bigcup_{a\in G}H^{a}\right\rvert=1+m(|H|-1).$$
Now to find $m$ we will use the orbit-stabilizer property. Indeed, conjugation define an action of $G$ on the set of its subgroups; thus the set of conjugates $H^{a}$ is simply the orbit $H^G$, which is in bijection with the set of left cosets of the stabilizer. But the condition that $H^{a}\cap H=\{e\}$ for $a\notin H$ means that $H$ is its own stabilizer, and it follows that $m=\frac{|G|}{|H|}$. Thus
$$\left\lvert\bigcup_{a\in G}H^{a}\right\rvert=1+\frac{|G|}{|H|}(|H|-1)=1+|G|-\frac{|G|}{|H|}.\label{1}\tag{1}$$
Because $H$ is non-trivial $|H|\geq 2$, and thus $\frac{|G|}{|H|}\leq \frac{|G|}{2}$. It follows that
$$\left\lvert\bigcup_{a\in G}H^{a}\right\rvert\geq 1+|G|-\frac{|G|}{2}=1+\frac{|G|}{2}.$$
Moreover $\bigcup_{a\in G}H^{a}=G$ implies that $\left|\bigcup_{a\in G}H^{a}\right|=|G|$. Comparing this to \eqref{1} shows that we must then have $\frac{|G|}{|H|}=1$, and thus $H=G$.
Comment: Why two distincts such conjugates only have $e$ as a common element?
Comment: This was slightly less obvious than I thought. I've edited my answer to add this part (and the second question).


Formatting First and Second Repetitions

Question: Anytime I'm formatting a score with first and second repetitions I struggle on how should I write them in the score. I tend to do 4 bars for each staff (not counting pick up bars) unless the melody's phrasing is different. In those cases I tend to follow the melody which results in a clearer score.
My issue is when I have two different endings (1st and 2nd ending) for my melody and each different ending is 2 bars only. If I keep my 4 bars for each staff, I'll end up with two extra measures (the second ending) that are difficult to fit and make it look good.
Here I'll show you the 4 approaches I've been using so far and the inconveniences that I've found:

Fit 1st and 2nd repetition in the same staff, making a 6 bar in one staff. In this case, it tends to get quite difficult to read, specially if the melody has a lot of notes. However, if the melody doesn't have that much notes, I still find it difficult to read and jump to the second ending.

Add the two previous bars of each ending (which are the same) in order to keep 4 measures on each repetition. This one looks better for me than the first one but also has one big problem: musicians after playing first ending will tend to read again the first repetition amd then realise they should be playing second bar which will make them jump to the second ending, which is confusing for them. This problem could be solved the following way:

I found that on some scores they tend to make a 3-bars system with the first measure of the first ending, and then fit the end of the first ending, and the full second ending within the same system. This way, musicians are aware that they have to jump to the second ending althoug sometimes is difficult to find that second ending since it is in the middle of the staff.

Keep the second ending in a different system with only two bars, but move it so it fits under the first repetition bar making a blank space in front of the second ending. This one is the one I think looks more clear for me and it's easy to read. However, I think I've been so used to staves everywhere in my scores that having that blank space still looks weird to me.

What are your approaches on this?
Thank you so much for your help!
Answer: If your music always has four-bar phrases you need to find a way to compensate for the two extra measures (and without adding ugly blank space). You have three possibilities:

have two systems with 5 measures each (either before or after the repeat).
have two systems with 3 measures each.
leave your music with the phrase ends in the middle of the system until the next repeat.

Which of these solutions works best will depend on how 'full' your measures are. Either way your music will be most easily readable if the repeat sign is either at the end of the system or in the middle.
Answer: The only option I'd definitely advise against is the one you prefer, the cutaway stave on its own system.*
Apart from that, it's a juggling act. It's good to fit both voltas on the same system.  If this is too cramped, it's good to put the end repeat barline on a line break.  And, if the music does run in 4-bar phrases, it's good to have 4 bars to a line.  I'd prioritise in that order.
*But, though the question doesn't mention this, I see you've tagged #lead-sheets.  In 'real book' style, where musicians may be as much interested in the chord sequence as the melody, 4-bar lines take higher priority.  This is why in real books you DO sometimes see the cutaway method.  (But you really DON'T have to follow the other real book convention of omitting clef and key signature after the first line.)

Formatting First and Second Repetitions


Let $\beta$ be a subset of a discrete metric space (IR, $\rho$). Find the boundary points.

Question: Let $β$ be a subset of a discrete metric space $(\mathbb R, ρ)$. Find the boundary points.
In the case of a discrete metric space, we know that $B(x,0.5)={x}$, because every distinct point from $x$ is 1 unit away from it. In this scenario, if I make an open ball around $x$, it is part of $\beta^c$. So, the intersection of open ball and $\beta^c$ is nonempty, right? Therefore, I can say $\{x\}$ is a boundary point of a discrete metric space. Could anyone please confirm if I am on the right track?
Also, the definition of boundary point we have to use is that the intersection of open ball and $\beta^c$ should be nonempty.
Comment: Welcome to MSE. A question should be written in such a way that it can be understood even by someone who did not read its title.
Answer: I'm a bit confused by your question, but in a discrete metric space $X$, there is no boundary point whatsoever. The discrete metric induces the discrete topology in which every subset is open. The boundary of the subset $A$ is defined as
$$\partial A=\overline A\cap\overline{X\setminus A}$$
Since the space $X$ is discrete, $\overline A=A$ and $\overline{X\setminus A}=X\setminus A$, so $$\partial A=\overline A\cap\overline{X\setminus A}=A\cap (X\setminus A)=\emptyset$$
Another equivalent definition is
$\partial A=\overline A\setminus A^\circ$, and again $$\partial A=\overline A\setminus A^\circ=A\setminus A=\emptyset$$
Comment: I am sorry but I don't understand how in a discrete metric A intersection A complement (X\A) is nonempty


Should a cancel button ask for confirmation?

Question: If a user clicks a cancel button should it pop up a dialogue asking for confirmation?
If so, should this be all the time, or only when there are unsaved changes on a form?
Answer: No unless it's something that is very vital/potentially harmful. Having popups followed by popups is annoying.
Answer: If canceling the action will destroy data or a device, yes. For instance, canceling in the middle of upgrading the firmware of some device.
If the action being performed takes a long time and an accidental cancelation will require starting over, yes.
For instance, I don't find the pop-up here on StackOverflow annoying when I decide to close a tab rather than making an edit I started on one of my questions.
Comment: +1 for the case of time taking operations. Though I don't agree about "Cancelling the action will destroy the data". Almost all forms take some inputs from user, if "Cancel" is pressed, let it be "Cancel"!
Answer: "Cancel" means to give up on an action before it begins. If the action has already started, the command should be named "Stop" instead. That makes it clear to the user that the button might interrupt something in mid-stream.
A real Cancel action doesn't need confirmation because it doesn't cause any problems. A Stop action might, but only if stopping partway through could leave things in a messed-up state. (And in that case, you should consider finding a way to have the stop back out all the already-made changes so that the state reverts back to what it was before the action began. This isn't always possible, of course, like if you're deleting files.)
Answer: Make the action easy to do without confirmation (don't annoy your users!). But, also make it easy to undo. Read Alan Cooper's About Face for lots of good UI advice.
Comment: Is it just me or does SO's link insertion mechanism stink?
Comment: It is just you. Not everyone throws junk into links.
Answer: It really depends on the situation.
Encoding a video for example, a process that may take hours, should have a confirmation, just because you may accidentally hit the button at 99%.
The initialization process of an installer or other app, on the other hand, doesn't need a confirmation since it can typically be restarted quickly enough and doesn't take long to begin with.
If clicking Cancel starts a process that will potentially take a long time (let's say it needs to reverse changes), the user should be informed about that, possibly with a popup, but some text next to the button might suffice as well.
The general rule is to minimize Confirmation Dialogs as much as possible, if for example it could be replaced with an Undo action. I don't think this applies to most Cancel buttons though.
Answer: Use the following algorithm to determine the answer to your question:
<code>if (1-p)*w > p*a then ask for confirmation
</code>
where

p is the probability that the user really wanted to cancel (0.7 or so)
w is the amount of lost (work-) time due to inadvertent cancelling
a is the time lost due to an anoying confirmation (5 seconds or so)

Of course you have to estimate p, w and a. Using my default values, you should ask for confirmation when unintentional canceling would cost the user more than 10.5 seconds of time.
So, in the case of a long-time operation, e.g. encoding a video, you shouldn't ask if the user clicks cancel within 10 seconds after starting that task. In the case of data entry, don't ask if the form is still completely empty, but ask if the user has already entered data.
Answer: Basically, if undo-ing a cancel is difficult, time-consuming, or impossible, you should prompt the user. Those are usually the case when the user has done some actions that they might wish to preserve (e.g. writing a blog post and closing a tab, updating firmware on a hardware device, running system updates, installing large pieces of software) instead of just deleting the current state. After all, sometimes the cancel button may be clicked accidentally. You just need to use common sense to determine whether it would be a really bad experience for the user if an operation was accidentally cancelled (which would call for a cancel prompt), or whether they could easily restart whatever operation was accidentally cancelled without much loss. The strategy I use for solving such problems is by putting myself in the user's shoes, i.e. imagining myself as a user of this program. How would I feel if I accidentally clicked cancel??? If that mentality is grim, add a prompt in case.
Answer: It would be better to not prompt, but make it easy to undo the cancellation once it is done, if possible.  GMail does this well.  You click 'Delete', it deletes, but you get a link at the top to say 'Undo delete'.
Answer: I think the answer in terms of data.
If user made changes on data , not talking about clicking somewhere on interface, user should be asked to confirm exiting.
But if no change happenned, no reason for confirmation. Because confirmation is an effort for user.


Is it possible to clean some code using gtk2hs?

Question: I'm starting a GUI with haskell and gtk2hs.
I've got a notebook widget and I want to switch pages with "F1, F2 ... F11" keys.
My working code is:
import Control.Monad.Trans (liftIO)
import Graphics.UI.Gtk

main = do
  initGUI

  builder <- builderNew
  builderAddFromFile builder "M62.glade"

  window <- builderGetObject builder castToWindow "window1"
  notebook <- builderGetObject builder castToNotebook "notebook1"

  window `on` keyPressEvent $ tryEvent $ do "F1" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 0
  window `on` keyPressEvent $ tryEvent $ do "F2" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 1
  window `on` keyPressEvent $ tryEvent $ do "F3" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 2
  window `on` keyPressEvent $ tryEvent $ do "F4" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 3
  window `on` keyPressEvent $ tryEvent $ do "F5" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 4
  window `on` keyPressEvent $ tryEvent $ do "F6" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 5
  window `on` keyPressEvent $ tryEvent $ do "F7" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 6
  window `on` keyPressEvent $ tryEvent $ do "F8" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 7
  window `on` keyPressEvent $ tryEvent $ do "F9" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 8
  window `on` keyPressEvent $ tryEvent $ do "F10" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 9
  window `on` keyPressEvent $ tryEvent $ do "F11" <- eventKeyName
                                            liftIO $ notebookSetCurrentPage notebook 10

  onDestroy window mainQuit
  widgetShowAll window
  mainGUI

Is there betters and/or concises ways to do it?
I've tried to handle it out of the 'main' but then only "F1" works.
I don't see how to manage this boilerplate.
Answer: I don't know much about gtk2hs, but using forM_ to loop over the key indices should go a long way. Also, it seems events are a MonadPlus, so pattern match failure can be favorably replaced with guard.
forM_ [0..10] $ \i -> do
    let key = "F" ++ show (i + 1)
    window `on` keyPressEvent $ tryEvent $ do
        pressed <- eventKeyName
        guard (pressed == key)
        liftIO $ notebookSetCurrentPage notebook i

Comment: Thank you very much, this is the solution I was trying to do! That works very much!
Answer: How about this:
window `on` keyPressEvent $ tryEvent $ do
    'F':n_ <- eventKeyName
    let (n, ""):_ = reads n_
    liftIO . notebookSetCurrentPage notebook $ n - 1

This is hopelessly partial: there are two partial pattern matches that can throw an exception. But that's okay, because that's what tryEvent is for. At time of writing, all other answers involve registering many event handlers, whereas this one registers only one. This should have a (slight) performance advantage.
Comment: Thanks a lot! I choose to use this solution for the registering fact, but can you give some documentation about the partial pattern matches? I don't understand them yet... :)
Comment: @grwp For sure. What would you like to know? Maybe you want to know what things they will *not* match, or...?
Answer: Try splitting the repeated part into a function, like this:
import Control.Monad
import Graphics.UI.Gtk

main = do
  initGUI

  builder <- builderNew
  builderAddFromFile builder "M62.glade"

  window <- builderGetObject builder castToWindow "window1"
  notebook <- builderGetObject builder castToNotebook "notebook1"

  -- Split the repeated code into a reusable function, like this
  let registerKeyPressEvent n =
    window `on` keyPressEvent $ tryEvent $ do
      pressed <- eventKeyName
      guard (pressed == ("F" ++ show (n + 1)))
      liftIO $ notebookSetCurrentPage notebook n
  -- Thanks to Tarmil for catching a bug in the code that used to be above.
  -- Tarmil got it right, so I'm borrowing his/her version.

  -- Then you can call it more than once
  registerKeyPressEvent  0
  registerKeyPressEvent  1
  registerKeyPressEvent  2
  registerKeyPressEvent  3
  registerKeyPressEvent  4
  registerKeyPressEvent  5
  registerKeyPressEvent  6
  registerKeyPressEvent  7
  registerKeyPressEvent  8
  registerKeyPressEvent  9
  registerKeyPressEvent 10

  -- But even that is too verbose.
  -- You can shorten it even further like this:
  mapM_ registerKeyPressEvent [0..10]

mapM is like map, except for monads. The type of map is:
map :: (a -> b) -> [a] -> [b]

meaning that it takes a function and applies it to every element of a list, returning the result. The type of mapM is:
mapM :: Monad m => (a -> m b) -> [a] -> m [b]

meaning that it takes a monadic function (such as registerKeyPressEvent, function in the IO monad that creates the side effect of registering a key press event). mapM then executes this function once for every element in the list, and not only collects the results into a list, but collects the monadic actions into the resulting monad, meaning that the side effects from running registerKeyPressEvent 11 times are performed in order.
The final piece of the puzzle is that you might get a type error if you use mapM, because it assumes you care about the resulting list, and therefore returns m [b]. However, in this case, the type of main is IO (), and () is not going to match up to [b]. You therefore want a slight variation on mapM that throws away the resulting list, only collecting the monadic actions:
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()

This has the return type you're looking for.
Comment: Good explanation, a mistake though: `("F" ++ show (n + 1))` is not a pattern, you can't put it on the left-hand side of `<-`.
Comment: Oops! Give me a minute.
Comment: Fixed, thanks. I took the liberty of borrowing your version. I hope you don't mind.
Comment: If I minded my code being borrowed, I wouldn't put it on StackOverflow :)
Comment: Thank you very much! Explanations are very clear, I forget about the mapM_ magic, used once, sometimes... :)
But the 'window' and 'notebook' need to be parameters of the registerKeyPressEvent function as they are just in the the main.
Comment: Thanks for pointing that out. I've moved registerKeyPressEvent inside main where it belongs.


GCC no longer implements

Question: I have to change this code fragment from varargs.h to stdarg.h, but I do not know exactly how to:
#ifndef lint
int ll_log (va_alist)
va_dcl
{
    int event, result;
    LLog   *lp;
    va_list ap;

    va_start (ap);

    lp = va_arg (ap, LLog *);
    event = va_arg (ap, int);

    result = _ll_log (lp, event, ap);

    va_end (ap);

    return result;
}

When I try build this, compiler says:
error "GCC no longer implements <varargs.h>."
error "Revise your code to use <stdarg.h>."

The program, which I need to compile and run, has a few similar fragments and I need to know how to change them. If you can write some example, I'll be content.
Answer: <varargs.h> is a pre-standard C header; use <stdarg.h> instead. The differences:

The function must take at least one named argument.
The function must be prototyped (using the ellipsis terminator).
The va_start macro works differently: it takes two arguments, the first being the va_list to be initialized and the second the name of the last named argument.

Example:
int ll_log (LLog *llog, ...) {
    int event, result;
    LLog   *lp;
    va_list ap;

    va_start (ap, llog);

    lp = llog;
    event = va_arg (ap, int);

    result = _ll_log (lp, event, ap);

    va_end (ap);
    return result;
}

Regarding va_start: gcc ignores the second argument, but not giving the correct one is not portable.
Answer: You have to include
#include <stdarg.h>

va_ Macro syntax stays the same.
Comment: Wikipedia actually [has a nice description of the change](http://en.wikipedia.org/wiki/Stdarg.h#varargs.h)
Comment: The macro syntax is not the same.  Even ignoring the non-appearance of `va_dcl` in the `` system, the `va_start()` macro is different, taking one argument in the old `` system and two in the new(er) `` system.
Comment: This is correct. I'd also add that you can now use the `int ll_log (...) {` syntax, which wasn't available with ``

GCC no longer implements


Algebraic Proof that $\sum\limits_{k=0}^m \binom{r}{k} \binom{m+n-r}{m-k} = \binom{m+n}{m}$

Question: How do I prove that:
$$\sum\limits_{k=0}^m \binom{r}{k} \binom{m+n-r}{m-k} = \binom{m+n}{m} ~~~~~~~~~ (r <= m + n) $$
by using an algebraic identity?
My Attempt:
I know of the generating functions:
$$ (1 + x)^n = \sum\limits_{k=0}^n \binom{r}{k} x^k ~~~~~  and ~~~~~~
 \frac {1}{(1 + x)^{n + 1}} = \sum\limits_{k=0}^{\infty} \binom{n + k}{k} x^k $$
and after a bit of trial and error I came up with the algebraic identity:
$$(1 - x)^r  \frac {1}{(1 - x)^{n + r + 1}} = \frac {1}{(1 - x)^{n + 1}} ~~~~~~~~~~~~~~~~~ (a)$$
The right hand side of (a) clearly matches the 2nd generating function. So:
$$ \frac {1}{(1 + x)^{n + 1}} = \sum\limits_{m=0}^{\infty} \binom{n + m}{m} x^m  $$
The left hand side of (a) can be expressed as product of summations:
$$\begin{align*}
\displaystyle{
(1 - x)^r  \frac {1}{(1 - x)^{n + r + 1}} }

&=\displaystyle{
\sum\limits_{m=0}^{\infty} \binom{r}{m} (-x)^m \sum\limits_{k=0}^{\infty} \binom{n + r + k}{k} x^k
} \\
&=\displaystyle{
\sum\limits_{m=0}^{\infty} \sum\limits_{k=0}^{m} \binom{r}{k} (-x)^k \binom{n + r + m - k}{m - k} x^{m-k}
} \\
&=\displaystyle{
\sum\limits_{m=0}^{\infty} \sum\limits_{k=0}^{m} \binom{r}{k} \binom{n + r + m - k}{m - k} (-1)^k x^m
}
\end{align*}$$
But now I am stuck since I don't know how to make:
$$ \binom{n + r + m - k}{m - k} (-1)^k ~~~~ equal ~~~~  \binom{m+n-r}{m-k} ~~~~~ ?????  $$
to complete the proof.
Will my method work or should I be using another algebraic identity? I am quite new to combinatorics so please keep concepts understandable by a beginner. Thanks :)
EDIT
The answer
It turns out that my equation wasn't taking me anywhere close to the answer - LOL! Here is the answer with the new algebraic identity:
$$\begin{align*}

(1 + x)^r  (1 + x)^{m+n-r} &= (1 + x)^{m + n} \\

\sum\limits_{m=0}^r \binom{r}{m} x^m
\sum\limits_{k=0}^{m + n-r} \binom{n+m-r}{k} x^k &=
\sum\limits_{m=0}^{n + m} \binom{n+m}{m} x^m
 \\

\sum\limits_{m=0}^{r + (m+n-r)} \sum\limits_{k=0}^m
\binom{r}{m} \binom{n+m-r}{m-k} x^m &=
\sum\limits_{m=0}^{n + m} \binom{n+m}{m} x^m
 \\

\sum\limits_{m=0}^{m+n} \sum\limits_{k=0}^m
\binom{r}{m} \binom{n+m-r}{m-k} x^m &=
\sum\limits_{m=0}^{n + m} \binom{n+m}{m} x^m
 \\

\end{align*}$$
Equating coefficients gives:
$$\sum\limits_{k=0}^m \binom{r}{m} \binom{n+m-r}{m-k}  =
\binom{n+m}{m} ~~~~~~~~~~~~~~~~ QED!!! $$
Comment: Your work looks good, and you do get a nice identity for binomial coefficients that way.  Unfortunately, it's not the one you want to prove, and I don't think it's very close to the one you want to prove.  If you follow Broskiana's suggestion, you'll see that the problem is a bit simpler than what you were attempting.  (One other comment-- when you list the two generating functions you know, the second one should be $\frac{1}{(1-x)^{n+1}}$, not $\frac{1}{(1+x)^{n+1}}$.  Obviously, you realize this, since all your work is correct!)
Comment: @jonas-kibelbek Thanks for reviewing though my work even though it was way off. I am new to combinatorics so it is good to know my manipulations are ok :)
Answer: Since you know binomial series i think you can compare the coefficient of $ x^m $ in $ (1+x)^r(1+x)^{m+n-r} $ and $ (1+x)^{n+m} $. It should be very straight forward from here.
Comment: @Johann: By the way, the combinatorial proof and algebraic proof are related.  The combinatorial proof is this: We want to count the ways to choose $m$ marbles from a set of $m+n$ marbles (which is $\binom{m+n}{m}$).  Suppose $r$ of the marbles are red-- then when we choose $m$ marbles, we will get $k$ red ones, where $k$ could be any number from 0 to $r$, and $m-k$ ordinary marbles (that is, $\sum_{k=0}^r \binom{r}{k} \binom{m+n-r}{m-k}$).  In the algebraic proof, pulling out the factor $(1+x)^r$ is kind of like painting those $r$ copies of $x$ red.
Comment: @Jonas Thanks a lot! I am sure I will to need to be able to understand and do combinatorial proofs somewhere in the course so your combinatorial approach is most appreciated...Cheers
Comment: LOL - It takes 3 lines using your method. Thanks! My method was "not very close" as mentioned by Jonas. Why didn't I think of that equation before? Sometimes my brain just seems to get stuck..... O_O


how to obfuscate react component or jsx file

Question: i have to share a github repository with others but don't wanna expose my react component
i want to obfuscate a jsx files containing react functional component, styled-components, axios...
nonetheless, still "npm start" or "npm run dev" works in react/next.js
how should i do? is there a solution for this?
or can it be a solution to transform jsx file into obfuscated node moudle?
"how to obfuscate" i searched are focused on build time, full project.
i want it to work for dev time, partially
Comment: What's the use case? Usually, front end code is not interesting enough to steal so this is often a waste of effort. You probably already know this but even obfuscated code can be reverse engineered.
Answer: Obfuscating it within the project will be a nightmare.
My suggestion would be to simply extract the component out into a separate library, build it, publish it, and then add it in your shared project as a dependency.
Then it will only exist as a compiled react component in the node_modules folder.
Comment: thanks for answering. Can the created react component module be obfuscated? For obfuscating library, what tool or library do i have to use?


Spree - cannot override js.coffee file

Question: Simply followed instructions from http://guides.spreecommerce.com/developer/asset.html but it just doesn't work. New js files are included and loaded, but if I create file with the same name say product.js.coffee original file is loaded anyway. Any suggestions?
All.js
//= require jquery
//= require jquery_ujs
//= require spree/frontend
//= require_tree .

Answer: I've been tearing my hair out over this problem all morning.
In the end what worked for me is to specify every single file I wanted to overwrite in /app/assets/javascripts/spree/frontend/all.js.
E.g., if you want to overwrite cart.js.coffee and checkout/address.js.coffee, your all.js should look like:
//= require jquery
//= require jquery_ujs
//
//= require spree/frontend
//= require spree/frontend/cart
//= require spree/frontend/checkout/address
//
//= require_tree .

Don't ask me why that's necessary. My understanding is that //= require_tree . should do that automatically, but it my case, well, it wasn't.
After creating an all.js file and redundantly specifying each file, this finally worked for me. But I'm a spree/rails noob, so there's quite probably a better solution.
Edit:
Actually, to get this working I had to put the above in /vendor/assets/javascripts/spree/frontend/all.js and remove /app/assets/javascripts/spree/frontend/all.js. Still confused why this is necessary and why require_tree doesn't pick these up automatically, but happy to finally get it working.
Comment: In my scenario, I was trying to overwrite `app/assets/javascripts/spree/backend/flash.coffee` in Solidus.
 Defining `vendor/assets/javascripts/spree/backend/flash.coffee` in my project and adding `//= require spree/backend/flash` to `vendor/assets/javascripts/spree/backend/all.js` did not overwrite the original JS code, it only added the new JS code. To remove the old JS code, had to also override the `//= require spree/backend` call by defining `vendor/assets/javascripts/spree/backend.js` in my project.
Answer: Backporting this patch for Solidus 2.1.0 solved my issue of replacing/overwriting JS assets [1].
The problem appeared to be that there was an issue with Sprockets where using require_tree or relative require prevented JS assets in the pipeline from being overridden.
In summary

Create a new file under your project's vendor/assets with the same filename as the JS file you're going to replace in Solidus. For example, to overwrite the file solidus_backend/app/assets/javascripts/spree/backend/flash.coffee, create a replacement file in your project at your_project/{app,vendor}/assets/javascripts/spree/backend/flash.coffee. [2]

Create the files your_project/{app,vendor}/assets/javascripts/spree/backend.js and your_project/{app,vendor}/assets/javascripts/spree/backend/templates/index.js in your project.

Copy the contents for the backend.js and index.js files from solidusio/solidus#1613 into your project.

Remove any requires for files that do not exist in your Solidus version, and keep any custom requires if you already had backend.js and index.js defined. [3]

Footnotes

Includes .js, .coffee, .hbs, and any other files that compile to JavaScript during the asset pipeline compilation.

Either directory between {app,vendor}/assets in your project will work since they should both be in the asset pipeline loadpath. It's a matter of preference how you want to organise Solidus extensions and overrides.

I had to remove spree/backend/images/upload from backend.js
and spree/backend/templates/products/upload_progress from index.js since I was using an older version of Solidus and those files didn't exist yet, so I would get an FileNotFound error from Sprockets.

Spree - cannot override js.coffee file


React Router: Wrapping some Routes with a component and not directly inside Switch

Question: I'm trying to do something like this
<Switch>
    <SomeNavBar>
        <Route path="page1">Page 1</Route>
        <Route path="page2">Page 2</Route>
        <Route path="page3">Page 3</Route>
    </SomeNavBar>
    <OtherNavBar>
        <Route path="admin">Admin Page</Route>
    </OtherNavBar>
</Switch>

Where I have wrapper component for a routes that are not the admin page.
However the admin route does not render Admin Page it just renders a blank page. The other routes work fine.
Is there a way to achieve this behavior?
Answer: There's a couple of issues with your example not related to the question which you should rectify before anything else.
The first is that the direct children of a Switch must always be a Route or Redirect - it doesn't know what to do with any other element and will just render the first thing it sees (in your case, the SomeNavBar component). The second is that path declarations must be prepended with a slash for the router to build them correctly, so /page1 and /admin for example.
With that out the way, here is a somewhat contrived example of how to get the behaviour you are after. For the pages, we are checking from a list of possible fragments before rendering SomeNavBar and the correct route. Notice also the exact parameter - this is so we don't also match paths that only begin with the specificed fragment, like /page1foo:
<Switch>
  <Route exact path={['/page1', '/page2', '/page3']}>
    <SomeNavBar>
        <Route path="/page1">Page 1</Route>
        <Route path="/page2">Page 2</Route>
        <Route path="/page3">Page 3</Route>
    </SomeNavBar>
  </Route>
  <Route path="/admin">
    <OtherNavBar>
      Admin Page
    </OtherNavBar>
  </Route>
</Switch>

Comment: Thank you, I didn't knew you can pass an array to `path`


Issue with EditText doesn't get Focus in fragment

Question: I have a fragment which is called from a main activity, in the fragment I have an EditText that listens for a scanned barcode.
private void InputListener() {
    etInput.requestFocus();
    etInput.setOnEditorActionListener((v, actionId, event) -> {
        if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
            String scanned;
            scanned = etInput.getText().toString().replace("\n", "").trim();

            if (scanned.length() != 8) {
                globals.PlayFile(Globals.Sounds.Bell);
                Snackbar snackbar = Snackbar.make(rootView, "Not an 8 Digit Barcode!", Snackbar.LENGTH_LONG);
                ColouredSnackbar.alert(snackbar).show();
            } else if (!scanned.substring(0, 2).equals("00") && !scanned.substring(0, 2).equals("01")) {
                globals.PlayFile(Globals.Sounds.Bell);
                Snackbar snackbar = Snackbar.make(rootView, "Please Check barcode!", Snackbar.LENGTH_LONG);
                ColouredSnackbar.alert(snackbar).show();
            } else {
                //Barcode Good
                AddPoscode(scanned);
            }
            etInput.setText("");
            scanned = "";
            etInput.requestFocus();
        }

        return false;
    });
}

This works as it should and focus is regained on the edittext to await the next scan.
However, if I run this code from a fragment which has been called from another fragment instead of the main activity, then focus is not regained on the EditText.
Does anyone know why this is?
I am using
compileSdkVersion 24
buildToolsVersion '24.0.2'

The xml for both edittexts is the same
  <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/etInput"
/>

My second fragment (called from another fragment) is called by this:
Bundle b = new Bundle();
                b.putInt("PickListID", h.getPickListID());
                MySecondFrag = new  MySecondFrag();
                FragmentTransaction t = getFragmentManager().beginTransaction();
                p.setArguments(b);
                t.replace(R.id.frame_container, p);
                Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
                toolbar.setTitle("Frag2");
                t.addToBackStack(null);
                t.commit();

Update - I don't think the issue is because it is called from another fragment, even calling it from my main activity ends in the same result. Think I may just delete my class and start again!
Answer: Well I solved it, if you have an RecyclerView with a height of match_parent, this steals the focus from the edittext and doesn't allow it to be set. Changing the height to wrap_content solved the issue.


Best transformation for a heavy tailed distribution

Question: I am anaylsing a data set, which displays a heavy-tailed distribution when examined on a Quantile-Quantile plot. What is (or are) the best transformation(s) to use to correct a dataset with a heavy-tailed distribution?
Comment: Some distributions are just heavy tailed, like the mass distribution in a cat.  My cat would be pretty unhappy if I attempted to "correct" this.
Comment: What do you want to correct? What makes you think there's something that needs to be corrected?
Comment: Do you have data to share, or at least some plots? What do you want to achieve with your analysis,  why do you care about normality?
Comment: I'm with kodiologist -- what's the problem with a heavy tailed distribution? Even if there is a problem, why would you transform rather than do something else?
Comment: What do you want to acheive for this data? What is your model? Why do you think tails is wrong then you would like to correct it? Did you have any ideas about transformation? It is good idea to ask yourself many questions before asking this will help you to answer your question.
Answer: You could transform the series with the natural logarithm. Alternatively, some of the literature looking at the determinants of net worth have used the inverse hyperbolic sine transformation. (See Pence 2006) It has the advantage of accommodating zero and negative values.