Chi-squared vs ANOVA test

Question: My study consists of three treatments. One treatment group has 8 people and the other two 11.
Each person in the treatment group received three questions and I want to compare how many they answered correctly with the other two groups.
How would I do that? Should I calculate the percentage of people that got each question correctly and then do an analysis of variance (ANOVA)? Somehow that doesn't make sense to me.
Comment: So the outcome is essentially whether each person answered zero, one, two or three questions correctly?
Comment: So, each person in each treatment group recieved three questions?
Comment: Each person in each treatment group receive three questions. And the outcome is how many questions each person answered correctly.
Comment: I'm a bit confused with the design. Are you trying to make a one-factor design, where the factor has four levels: control, treatment 1, treatment 2 etc? But it makes no sense because you didn't apply any "treatment" to those groups, you were asking them questions....
Comment: Possibly poisson regression may also be useful here: http://www.theanalysisfactor.com/poisson-regression-analysis-for-count-data/
Comment: Since there are up to 3 questions, I think [Binomial logistic regression] maybe the most appropriate generalized linear model here.
Answer: Since your response is ordinal, doing any ANOVA or chi-squared test will lose the trend of the outputs. Consider doing a Cumulative Logit Model where multiple logits are formed of cumulative probabilities.
$$
\begin{align}
P(Y \le j | x) &= \pi_1(x) + ... +\pi_j(x), \quad j=1, ..., J\\
logit\big[P(Y \le j | x)\big] &= \frac{P(Y \le j | x)}{1-P(Y \le j | x)}\\
&= \frac{\pi_1(x) + ... +\pi_j(x)}{\pi_{j+1}(x) + ... +\pi_J(x)}
\end{align}
$$
Finally we assume the same effect $\beta$ for all models and and look at proportional odds in a single model.
$$
logit\big[P(Y \le j |\textbf{x})\big] = \alpha_j + \beta^T\textbf{x}, \quad j=1,...,J-1
$$
In this case, you would have a reference group and two $x$'s that represent the two other groups
$$
logit\big[P(Y \le j |\textbf{x})\big] = \alpha_j + \beta_1x_1 + \beta_2x_2
$$
Model fit is checked by a "Score Test" and should be outputted by your software. The Score test checks against more complicated models for a better fit.
Finally, interpreting the results is straight forward by moving the logit to the other side
$$
P(Y \le j |\textbf{x}) = \frac{e^{\alpha_j + \beta^T\textbf{x}}}{1+e^{\alpha_j + \beta^T\textbf{x}}}
$$
There are lots of more references on the internet. Agresti's Categorial Data Analysis is a great book for this which contain many alteratives if the this model doesn't fit.
If you want to stay simpler, consider doing a Kruskal-Wallis test, which is a non-parametric version of ANOVA. Like most non-parametric tests, it uses ranks instead of actual values and is not exact if there are ties. Like ANOVA, it will compare all three groups together. While it doesn't require the data to be normally distributed, it does require the data to have approximately the same shape.
If the null hypothesis test is rejected, then Dunn's test will help figure out which pairs of groups are different. It is also based on ranks,
Comment: Maybe I misunderstand, but why would you call these data ordinal? You can meaningfully take differences ("person A got one more answer correct than person B") and also ratios ("person A scored twice as many correct answers than person B").
Comment: I agree with the comment, that these data don't need to be treated as ordinal, but I think using KW and Dunn test (1964) would be a simple and applicable approach.
Answer: I don't think you should use ANOVA because the normality is not satisfied. Furthermore, your dependent variable is not continuous.
Mann-Whitney U test will give you what you want. Your dependent variable can be ordered (ordinal scale). Say, if your first group performs much better than the other group, you might have something like this:
1 1 1 1 1 2 1 1 2 2 2 2
The samples are ranked according to the number of questions answered correctly. In this example, group 1 answers much better than group 2.
Answer: Since it is a count data, poisson regression can also be applied here:
<code>> dd
   grp value
1    x     3
2    x     3
3    x     3
4    x     1
5    x     2
6    x     3
7    x     2
8    x     1
9    y     3
10   y     3
11   y     3
12   y     3
13   y     1
14   y     3
15   y     3
16   y     2
17   y     2
18   y     3
19   y     3
20   z     2
21   z     3
22   z     1
23   z     2
24   z     1
25   z     1
26   z     2
27   z     3
28   z     1
29   z     2
30   z     3

> summary(glm(value~grp, data=dd, family='poisson'))

Call:
glm(formula = value ~ grp, family = "poisson", data = dd)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.1550  -0.4095   0.1422   0.2191   0.7281

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.8109     0.2357   3.440 0.000581 ***
grpy          0.1585     0.3001   0.528 0.597414
grpz         -0.1643     0.3212  -0.512 0.608989
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 9.7656  on 29  degrees of freedom
Residual deviance: 8.4788  on 27  degrees of freedom
AIC: 94.266

Number of Fisher Scoring iterations: 4
</code>
This gives difference of y and z from x. Levels in grp variable can be changed for difference with respect to y or z.
Comment: I don't think Poisson is appropriate; nobody can get 4 or more. If you regarded all three questions as equally hard to answer correctly, you might use a binomial model; alternatively, if data were split by question and question was a factor, you could again use a binomial model. In the absence of either you might use a quasi binomial model.

Chi-squared vs ANOVA test


VBA Before Close

Question: Então o que eu quero fazer é ter uma caixa de mensagem que aparece quando este arquivo do PowerPoint tentam fechar, dizendo "Você enviou os dados?" "Sim ou não".
Se clicarem em "Sim", o Excel fecha, se clicarem em "Não", cancela a operação de fechamento.
Eu sou muito novato com VBA, se você me explicar passo a passo, eu agradeceria. Eu tentei este código, mas não funciona:
Private Sub PPTApp_BeforeClose(Cancel As Boolean)

    If MsgBox("Text", _

            vbQuestion + vbYesNo) = vbNo Then

        Cancel = True

    End If

End Sub

Answer: Boa noite, Leonardo.
Veja se o código abaixo ajuda, por favor:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Cancel = MsgBox("Você enviou os dados?", vbQuestion + vbYesNo) = vbNo
End Sub

VBA Before Close


When editing a node, tab group titles are missing

Question: When editing a node, tab group titles are missing:

The HTML looks like this:

(active tab)

So the titles are already not printed, so it is not a CSS issue.
Is this a known issue? How can I start debugging this?
Comment: Drupal 8 reached end of life in November 2021. Upgrade to Drupal 9.
Comment: @cilefen yes that is unfortunate, we are in the process of a relaunch, still it needs to be fixed for Drupal 8, if possible
Comment: Drupal 8 is directly upgradeable to Drupal 9. I would start by enabling template debugging and work backward from there.
Comment: Thanks, will try. We tried Upgrading to 9 but had issues. The above issue surfaced since we upgraded to the latest 8 version.
Comment: I'm voting to close this question because it's about a bug in a contrib module and needs to be handled in the issue queue on drupal.org
Answer: Updating drupal/field_group to 3.2.0 helped.


Testing survival against frequency of some event

Question: I have the following data for 200 cases/subjects:

time to death over a 15 year period, $t$. A datum with a value of 180 months means that the subject did not die over the 15 year period.
the frequency of three particular types of event associated with each subject $a_{i}$, $b_{i}$ and $c_{i}$,

Apart from the obvious survival statistics and KM curves, how can I test the association between $t$ and each of $a_{i}$, $b_{i}$ and $c_{i}$. I am hypothesizing that a profile of $t$ will be distinct for each of $a_{i}$, $b_{i}$ and $c_{i}$.
One way I was thinking of testing this hypothesis was to simply do Pearson's correlation between $t$ and each of $a_{i}$, $b_{i}$ and $c_{i}$. I could then visualize this with a scatter plot of $t$ vs each of $a_{i}$, $b_{i}$ and $c_{i}$. Any suggestions on a more sophisticated analysis including variations of KM analysis? Code examples with R appreciated.
Comment: Do the events of type $a$,$b$,$c$ occur before the start of the follow-up period, or during it? In the latter case I think you would need their exact timing.
Comment: @Aniko all events have been counted before the follow-up period.
Answer: Here is a good way to start in R.
<code>library(survival)
# Assume your survival data is in the vector time
surv_time <- Surv(time, time < 180)
</code>
With that you can do the popular Cox Proportional Hazard model
<code># a, b, and c are the vectors with frequency data.
summary(coxph(surv_time ~ a+b+c))
</code>
You will get a complete test of the effect of your 3 variables on the survival. The Cox PH model is
$$ \lambda(t|X) = \lambda(t)\exp(X\beta) $$
where $\lambda(t|X)$ is the hazard function, interpreting as the chance of dying at time $t$, and $X$ is a set of measures on the individual. What the model says is that this hazard function can be anything (not necessary exponentially decreasing), but that increase/decrease of the variables in $X$ will increase/decrase the hazard in a proportional way. Variables significant in the test above will tend to multiply or divide the hazard a lot.
For a very didactic introduction to this (and many other) topic, I recommend Frank Harrell's Regression Modeling Strategies.
Comment: Thanks but I suppose I'm looking for something that is alternative to or extends Cox PH
Comment: Why so? Anything wrong with Cox PH, or you are looking for complementary alternatives?
Comment: Looking for complementary alternatives.
Answer: Why not treat this as a competing risks model?  The three types of event could be looked at as different outcomes.  There is literature on this going back to the 1970s.  A lot of recent work has been done by Jason Fine of UNC and Robert Gray.  You can look for the Fine-Gray model.  The cumulative incidence function is the generalization of Kaplan-Meier to competing risks.
Here is a link for a presentation that give background and other information. http://www.stata.com/meeting/australia09/aunz09_gutierrez.pdf


combining array values in looping

Question: i have json data like this:
    {
        "no" : "",
        "hs_code" : "01.05",
        "uraian" : "Unggas hidup, yaitu ayam dari spesies Gallus",
        "description" : "Live poultry, thatis to say, fowls of the ",
        "bm" : ""
    },
    {
        "no" : "",
        "hs_code" : "",
        "uraian" : "domestic us, bebek, an gs a, kalkun dan a yam guinea",
        "description" : "species Gallus domesticus, ducks, geese,",
        "bm" : ""
    },
    {
        "no" : "",
        "hs_code" : "",
        "uraian" : "",
        "description" : "turkeys and guinea fowls",
        "bm" : ""
    },
{
        "no" : "",
        "hs_code" : 0002"",
        "uraian" : "ssss",
        "description" : "ssss",
        "bm" : ""
    },

how can this loop in php with result data like this:
{
        "no" : "",
        "hs_code" : "01.05",
        "uraian" : "Unggas hidup, yaitu ayam dari spesies Gallus domestic us, bebek, an gs a, kalkun dan a yam guinea",
        "description" : "Live poultry, thatis to say, fowls of the species Gallus domesticus, ducks, geese turkeys and guinea fowls",
        "bm" : ""
 },
{
        "no" : "",
        "hs_code" : 0002"",
        "uraian" : "ssss",
        "description" : "ssss",
        "bm" : ""
    },

so if the "hs_code" index has no value, the 'uraian' and 'description' indexes are merged together in the 'uraian' and "description" indexes whose hs_code index has a value, please help...I try this loop
$data =  APPPATH."modules/masterCrud/seeder/hscode_2017_tes.json";
            $sss = json_decode(file_get_contents($data));
            $result = [];
            $x = 0;
            for($i = 0; $i < count($sss); $i++)
            {
                $x--;
                $no = $sss[$i]->no;
                $hs_code = $sss[$i]->hs_code;
                if($sss[$i]->hs_code == '')
                {
                    $sss[$i]->uraian .= $sss[$i]->uraian;
                    $sss[$i]->description .= $sss[$i]->description;
                }
                $uraian = $sss[$i]->uraian;
                $description = $sss[$i]->description;
                $bm = $sss[$i]->bm;
                array_push($result,compact('no','hs_code','uraian','description','bm'));
            }
            print_r($result);

ini tidak berhasil...
Comment: What have you tried up to this point?
Comment: i try this loop and not work,
Answer: Code:
$result = [];
$x= 0;
for($i = 0; $i < count($sss); $i++) {
    if($sss[$i]->hs_code) {
        $x= $i;
        $result[$i] = $sss[$i];
    } else {
        $result[$x]->uraian =  $result[$x]->uraian . ' ' . $sss[$i]->uraian;
        $result[$x]->description =  $result[$x]->description . ' ' . $sss[$i]->description;
    }
 }
array_multisort($result, SORT_ASC);
print_r($result);

Explanation:
Trick: On every hs_code which has value, save that position as $x by $i.
So for empty hs_code,  update uraian and description.
$result will has difference in keys so user **array_multisort**

combining array values in looping


Pattern to check if queued message can still be processed

Question: We're building an application with multiple components that will likely send messages to each other via JMS queues. There may be times when there are significant delays (due to maintenance and the like) across these queues.
It is anticipated that some messages may become stale - i.e. the circumstances for them to exist has suddenly changed and they should be discarded at the next available opportunity.
Is there a software pattern for implementing such "staleness-checks"? Someone mentioned something about a dead snail pattern but I cannot locate any references on Google...
Comment: What about attaching a time-to-live (ttl) to each message, and discard all messages whose ttl has expired?
Comment: Imagine we're sending 2,000 SMS messages through a message broker. 1,000 go by broker 1, 1,000 by broker 2. Now Broker 2 goes down and comes back two hours later. Three of the 1,000 messages now revived on broker 2 are targetting individuals who just opted-out of receiving SMS. That's just one scenario, another might be that the customer cancels the operation. Setting a TTL is inadequeate yet it feels like something a pattern exists for.
Comment: Perhaps this is the dead snail: http://zguide.zeromq.org/page:all#Slow-Subscriber-Detection-Suicidal-Snail-Pattern
Answer: There is not really a pattern here, because the concept is likely too situation specific.
In short, however, you will need to define staleness and check for it any time you read a message off of the queue.
As per @Space_C0wb0y's comment to the OP, this could use a simple time-to-live or other expiration timer, or it could be some other more complex check at the appropriate point in the line.
It cannot realistically, however, be implemented as a separate step in the chain that puts the message back on the queue, because in your scenario, the delay could then happen after the checks have been done.
So to reiterate, any checks of this nature would need to go at the last possible moment, in the actual processing step, after reading from the queue.


Statistical Quality Control p-chart

Question: A company manufactures small metal brackets. They are packaged in containers of 1000 brackets each. At the unloading facility, 10 containers have arrived and 36 brackets are selected at random from each container. The fraction non-confirming in each sample is $0.0,\  0.0,\  0.0,\  0.01,\  0.02,\  0.02, \ 0.06,\ 0.0,\ 0.0 \ and\  0.0$.

(i) Do the data from this shipment indicate statistical control?
(ii) What is the minimum sample size that would give a positive lower control limit for this chart?
I tried to attempt this question by using the p-chart to determine statistical quality control.
(i) Here, $n = 36$ and so, $\overline p  = \frac{{\sum {{p_i}} }}{{10}} = \frac{{0.2}}{{10}} = 0.02$
The $3\sigma$ control limits for the p-chart are given by:
$\overline p  \pm 3\sqrt {\frac{{\overline p (1 - \overline p )}}{n}} $

Hence, we have:
Lower Control Limit (LCL) = -0.05 $\approx$ 0 (as LCL cannot be negative)

Control Line (CL) = 0
Upper Control Limit (UCL) = 0.09
We see that all the points lie within these control limits. So, we can say that the shipment is in statistical control.
For the (ii) part of the question, we need:
$LCL\ > \ 0$
$ \Rightarrow \overline p  > 3\sqrt {\frac{{\overline p (1 - \overline p )}}{n}} $
 Taking $\overline p = 0.02$ and solving the above inequality I finally got:
$n > 441$
So, the minimum sample size should be $442$ for the LCL to be positive.
Can someone please tell me if my approach is correct or not?
Answer: As long as the sample size is consistent, you should be using an $np$ chart instead of a $p$ chart.
The rest of your approach would be appropriate for solving this type of problem.
There is the $ huge $ problem that with 36 samples, the numbers should be $0.00, 0.00, 0.00, 0.03, 0.03, 0.03, 0.06, 0.00, 0.00$ and $0.00$.  $\frac{1}{36}=0.02\overline{7}$ and $\frac{2}{36}=0.0\overline{5}$.  The values provided in the sample problem are impossible.

Statistical Quality Control p-chart


Unable to get to PHP interactive mode

Question: I'm running Debian Squeeze & am trying to get to the PHP interactive mode. (I've installed php5-cli along with the usual php install packages)
 Normally I would do this by running php -a  on this system I get the following, with no usual php prompt:

Interactive mode enabled

Any help much appreciated.
Comment: http://www.php.net/manual/en/features.commandline.interactive.php Some other comments that might be helpful there too
Comment: look in your `php.ini` for `cli.pager`
Comment: I've searched my php.ini for cli.pager & cannot see anything. Can you give me any pointers on what I need to add to the ini file? Much appreciated.
Answer: Unfortunately, this is a Debian-specific bug: #576218.
To summarize the comments from the bug report:
There seems no easy workaround for this. However, Ubuntu and probably other distributions are not affected by this bug because they build PHP against libreadline. Debian does not use libreadline, but libedit due to licensing issues.
Answer: The other answer is missing out on a solution.

If you want a few short commands without a persistent environment, do
 while read -er line; do php -r "$line"; done

Get a different php, (via compiling or other means) which links to readline instead of libedit (this was not done in debian because someone involved in php packaging does not want readline's gpl to apply to php), or a newer version of php which has this bug fixed.
Answer: You can compile readline module yourself. With Debian Wheezy and PHP 5.4 I was able to fix this by doing this (run commands as root):
# apt-get install php5-dev libedit-dev libreadline-dev

# mkdir php && cd php
# apt-get source php5-cli
# cd php5-5.4.4/ext/readline
# phpize
# ln -s ../../sapi/
# ./configure
# make
# cp modules/readline.so /usr/lib/php5/<number like 20100525>/
# chmod -x /usr/lib/php5/20100525/readline.so
# echo 'extension=readline.so' > /etc/php5/mods-available/readline.ini
# cd /etc/php5/cli/conf.d
# ln -s ../mods-available/readline.ini 20-readline.ini

Now the PHP console should work fine.
Answer: I have solved this for Ubuntu 12.04 Precise Pangolin (based on Debian Wheezy) so:
sudo apt-get install php5-readline

Unable to get to PHP interactive mode


Is it possible to sum the divergent series with prime coefficients?

Question: This is a follow-up of this question.
It is known that the divergent series $$ P := \sum_{n=1}^\infty p_n \qquad \text{where } p_n \text{ is the $n$th prime} $$ cannot be summed by means of (prime) zeta function regularization. (The result was originally due to Landau and Walfisz, see this paper. Froberg later showed it as well.)
However, there are loads of other summation methods. I am wondering whether any of the following summation methods can sum the divergent series of primes. For example:

Analytic continuation of power series: Does $\lim_{x \to 1^{-} } \sum_{n=1}^{\infty} p_{n} x^{n} $ exist?
Lindelöf summation: Does $\lim_{x \to 0} \sum_{n=1}^\infty p_n n^{-nx} $ exist?
Analytic continuation of Dirichlet series: Does $\lim_{s \to 0} \sum_{n=1}^\infty \dfrac{p_n}{n^s} $ exist?

Do any of these methods or another summation method for assigning a number to the sum of primes work? If so, please also indicate what the closed form of the corresponding function (for which the limit exists) is.
Answer: As written the answer to all three is no, since
$$
\begin{align}
1.& \quad \lim_{x \to 1^-} \sum_{n=1}^{\infty} p_n x^n \geq \lim_{x \to 1^-} \sum_{n=1}^{m} p_n x^n = \sum_{n=1}^{m} p_n \text{ for all fixed $m$,} \\
2.& \quad \lim_{x \to 0^+} \sum_{n=1}^\infty p_n n^{-nx} \geq \lim_{x \to 0^+} \sum_{n=1}^m p_n n^{-nx} = \sum_{n=1}^{m} p_n \text{ for all fixed $m$, and} \\
3.& \quad \sum_{n=1}^\infty \dfrac{p_n}{n^s} \text{ diverges for $s \leq 2$.}
\end{align}
$$
You could consider the last one only a technicality, since it may still be possible to find an analytic continuation of the Dirichlet series for $s \neq 2$, where it appears to have a pole of order $2$.  I'm not really familiar enough with these things to say.
Comment: $\sum \frac{p_n}{n^s}$ diverges for $\operatorname{Re} s \leqslant 2$ even. I have no idea whether that has an analytic continuation to $0$ either.
Comment: Whoops, right, thanks for the correction :)


Where is name defined in image_effect_info_alter(&$effects)?

Question: function my_module_name_image_effect_info_alter(&$effects) {
    $effects += array(
        'whatever' => array(
            'label' => t('blabla'),
            'help' => t('Everything you need to know about this effect'),
            'effect callback'=> 'function_I_wrote',
            'dimensions callback'=> 'another_function_I_wrote',
            'form callback'=> 'image_resize_form', //This one is sufficient
            'summary theme'=> 'image_resize_summary', //No need for own summary
            'module'=> 'image', //dunno?
            'name'=> 'image_rotate', //this is where my question is about
            'data'=> []
        )
    );
}

So I was looking at https://api.drupal.org/api/drupal/modules!image!image.api.php/function/hook_image_effect_info/7
They don't even mention name, but without it I get error:

PDOException: SQLSTATE[HY000]: General error: 1364 Field 'name'
  doesn't have a default value

And if I specify my own name it doen't show up under the Image styles effect section after adding. Using an existing one gives it that name. So my guess it's some kind of constant. Where does it come from?
Answer: First of all: I think the alter method should not exist if this is the easier way.
Call hook_image_effect_info() and just pass

label, help, effect callback, dimension callback and form callback

this way it won't ask for

name


Likelihood and estimates for mixed effects Logistic regression

Question: First let's simulate some data for a logistic regression with fixed and random parts:
set.seed(1)
n    <- 100
x    <- runif(n)
z    <- sample(c(0,1), n, replace=TRUE)
b    <- rnorm(2)
beta <- c(0.4, 0.8)
X    <- model.matrix(~x)
Z    <- cbind(z, 1-z)
eta  <- X%*%beta + Z%*%b
pr   <- 1/(1+exp(-eta))
y    <- rbinom(n, 1, pr)

If we just wanted to fit a Logistic regression with no random parts, we could use the glm function:
glm(y~x, family="binomial")

glm(y~x, family="binomial")$coefficients
# (Intercept)           x
#  -0.2992785   2.1429825

Or constructing our own function of the log-likelihood
$$ \log\text{L}(\boldsymbol{\beta}) = \sum_{i=1}^n y_i \log \Lambda(\eta_i) + (1-y_i)\log(1-\Lambda(\eta_i)) $$
where $\Lambda(\eta_i)=\frac{1}{1+\exp(-\eta_i)}$ and $\eta_i=\boldsymbol{X_i' \beta}$
and use optim() to estimate the parameters that maximize it, as in the following example code:
ll.no.random <- function(theta,X,y){
  beta <- theta[1:ncol(X)]
  eta  <- X%*%beta
  p    <- 1/(1+exp(-eta))
  ll   <- sum( y*log(p) + (1-y)*log(1-p) )
  -ll
}

optim(c(0,1), ll.no.random, X=X, y=y)

optim(c(0,1), ll.no.random, X=X, y=y)$par
# -0.2992456  2.1427484

which of course gives the same estimates and maximizes the log-likelihood for the same value. For mixed effects, we would want something like
library(lme4)
glmer(y~x + (1|z), family="binomial")

But how can we do the same with our own function? Since the likelihood is
$$ L = \prod_{j=1}^J \int \text{Pr}(y_{1j},...,y_{n_jj}|\boldsymbol{x}, b_j) f(b_j)db_j $$
and the integral has no closed-form expression, we need to use numerical integration like Gaussian Quadrature. We can use the package statmod to get some quadratures, say 10
library(statmod)
gq <- gauss.quad(10)
w  <- gq$weights
g  <- gq$nodes

UPDATE: Using these quadrature locations $g_r$ and weights $w_r$ for the $r=1,...,R$ ($R=10$ here), we can approximate the integral over $b_j$ by a sum of the $R$ terms with $g_r$ substituted for $b_j$ and the whole term multiplied by the respective weights $w_r$. Thus, our likelihood function should be now
$$ L = \prod_{j=1}^J \sum_{r=1}^{R} Pr (y_{1j},...,y_{n_jj} | \boldsymbol{x}, b_j=g_r ) w_r $$
Also, we need to account for the variance of the random part, I read that this can be achieved by replacing the $b_j \sim N(0,\sigma_b^2)$ in our $\eta$ function with $\sigma_j \theta_j$ where $\theta_j \sim N(0,1)$, so in the likelihood function above we actually replace $\theta$'s with $g$'s and not $\beta$'s.
One computational issue I don't get is how to substitute the terms since the vectors won't be of the same length. But probably I don't understand that, because I'm missing something crucial here, or misunderstood how this method works.
Comment: Have you asked this in the R-sig-ME list (email@example.com)? Some people might be able to help you there further. In addition: I would strongly urge you to study the paper [Efficient Laplacian and Adaptive Gaussian Quadrature Algorithms for Multilevel Generalized Linear Mixed Models](http://www.jstor.org/stable/27594165) by Pinheiro and Chao. It contains results regarding AGQ performance as well as the linear algebra behind them. If you want to code them.... well, get ready for some serious sparse matrix decompositions. :D
Comment: I don't have time to take a good look now but this looks like a good use for MCMC.
Comment: @ssdecontrol thanks, MCMC is good alternative. But I would like to apply the classical approach.
Comment: What's non-classical about MCMC to evaluate an integral?
Comment: @ssdecontrol well, I'm not sure... But all the books I checked and the lme4,ordinal R packages, do not use MCMC. So, I would like to stick with that. At least at the beginning.
Comment: You're right that it's not in the "classical statistics" toolkit, but that's for outdated computational reasons rather than conceptual, philosophical, or statistical reasons. In any case if you want to take a further look at it there are decent slides here: http://humis.bmi.utah.edu/humis/docs/organization_1863_1330728239.pdf and a mathoverflow question here: http://mathoverflow.net/q/41855
Comment: Steve, can you make sure that you agree with Randel's edit? You can re-edit or roll-back.
Answer: I did not see how "the vectors won't be of the same length", please clarify your question.
First of all, for the integral with dimension less than 4, the direct numerical methods like quadrature are more efficient than MCMC. I studied these questions for a while, and I would be happy to discuss this problem with you.
For mixed-effects logistic regression, the only explicit R code I have found is from Prof. Demidenko's book, Mixed Models: Theory and Applications, you can download the code via the column of "SOFTWARE AND DATA" on the webpage. The logMLEgh() can be found in \mixed_models_data.zip\MixedModels\Chapter07. He did not use the statmod package to obtain the quadratures, but wrote his own function gauher(). There are some minor errors in the code and I have discussed them with the author, but it is still very helpful to start from his code and book. I can provide the corrected version if needed.
Another issue is that, if you want to get accurate estimates, optim() is not enough, you may need to use methods like Fisher scoring, as in glm().
Comment: the book seems to have rich info on what I'm working on. The code itself doesn't say much - just ordered the book so I have to wait for that. The thing about the vectors is that if we substitute the terms, the 2 `b`'s with the 10 nodes, how we'll be able to multiply the matrices `Z` and `g`? Or I have it completely wrong?
Comment: I know that I should go further to get accurate estimates, but I was hoping to understand first the GQ as a first step.
Comment: You can preview the two editions on [Google Books](https://www.google.com/search?q=Mixed+Models%3A+Theory+and+Applications&oq=Mixed+Models%3A+Theory+and+Applications&aqs=chrome..69i57.461j0j7&sourceid=chrome&es_sm=122&ie=UTF-8#newwindow=1&q=Mixed+Models:+Theory+and+Applications&safe=off&tbm=bks) first. In your code, $Z$ is a $n \times 2$ matrix? But $b$ just a scalar? You can start from the random intercept model `Z = rep(1,n)` first. If the dimension of the random effects is two, you need totally 100 two-dimensional nodes then, 10 nodes on each dimension.
Comment: sorry but the more I'm thinking it the more it confuses me. If I do the `Z=rep(1,n)` then I would get one random intercept for each row, meaning that each individual is a group? In my example I have two groups, thus we have `Z%*%b` $n \times 2$ and $2 \times 1$ to give the $n \times 1$ we need. No?
Comment: Oh, I just noticed that `Z` is used to separate the random intercept for each cluster, not the design matrix for the random effect. Then you are right, but you should evaluate the integral and utilize the quadrature separately for each cluster. You do not need `Z` anymore, just evaluate the integral for each cluster, and then sum them together. The design matrix for the random intercept is just the vector of 1s.
Comment: I think did it (hopefully), as you said. Is this what you had in mind?
Comment: Probably. Each $b_j$ is a random variable, and they are independent with each other, so you can evaluate the integral separately for each cluster. After you read the book, you will find `logMLEgh()` does in this way, i.e., evaluate the integral for each unique id. The number of quadrature points should be at least 5 based on my experience. And the number of cluster in your example seems too small.
Comment: Yes I know, I gave this small example with 3 points and 2 clustests, just to see if I'm on the right track with the way I'm thinking it. I can understand that for tenths of clusters would be much more complex, hence the matrix decompositions?
Comment: Not really, you just time (or sum) the (log) likelihood for each cluster together, like you did for 2 clusters.


FirePHP not returning ajax request queries, yet returns normal page load queries

Question: I am using firePHP(Zend profiler) on on FF 3.6.3(firephp addon installed) and it returns queries, when I do a normal page load.  Ajax requests, however, are not returning the proper queries.  I am using Prototype 220.127.116.11 for ajax requests.  Is there something I am missing?  Most of the write-ups seem to imply that this should work by default.
Answer: I have had similar problems and got through them after a firebug upgrade (check the getFirebug website)
Firefox has been going through several evolutions of how a sniffer should listen to the different network events going on. Attribution of ajax requests to the correct page is among the new difficulties.
For information, I have firebug 1.5.3
It might also be a firephp issue and you may check on their website if someone has already hit the issue.
I hope this will help you
Jerome WAGNER


Would like change Marker icon to little circles

Question: In my Delphi app I use GMlib for the first time and I sucessfully displayed a map with an airline route and all markers.
I use a GMMap, GMMarker, GMPolyline components
However I would like to replace normal marker icons by littles red circles (3-4 pixels radius).
Here is the code I use to plot the map and route:
procedure TfrmWebBrowser.PlotMap;
var
  aList1,
  aList2: TstringList;
  dLatitude,
  dLatitude1,
  dLatD,
  dLonD,
  dLongitude,
  dLongitude1: Single;
  i: Integer;
  Poly: TPolyline;
  begin
    Poly:= TPolyline(GMPolyline1.Add);
    Poly.StrokeColor:= clRed;
    Poly.StrokeWeight:= 1;
    aList1:= TstringList.Create;
    aList1.StrictDelimiter:= True;
    aList1.Delimiter:= ';';
    aList2:= TstringList.Create;
    aList2.StrictDelimiter:= True;
    aList2.Delimiter:= ';';
    GMMarker1.Clear;
    for i := 0  to GstlMapPoints.Count-1 do
    begin
      aList1.DelimitedText:= GstlMapPoints.Strings[i];
      if i > 0 then
      begin
        aList2.DelimitedText:= GstlMapPoints.Strings[i - 1];
        dLatitude:= StrToFloat(aList2[0]);
        dLatitude1:= StrToFloat(aList1[0]);
        dLongitude:= StrToFloat(aList2[1]);
        dLongitude1:= StrToFloat(aList1[1]);
        Poly.AddLinePoint(dLatitude,dLongitude);
        Poly.AddLinePoint(dLatitude1,dLongitude1);
        Poly.Geodesic:= True;
      end
      else
      begin
        dLatD:= StrToFloat(aList1[0]);
        dLonD:= StrToFloat(aList1[1]);
      end;
    dLatitude:= StrToFloat(aList1[0]);
    dLongitude:= StrToFloat(aList1[1]);
    GMMarker1.Add(dLatitude, dLongitude, aList1[2]);
  end;
  GMMarker1.ZoomToPoints;
  aList1.Free;
  aList2.Free;
end;

Would ypu help me to do that?
Thanks
Pierre
Answer: The Add method from TGMMarker class return a TMarker object. This object have a Icon property to set the image to display
var
  Marker: TMarker
begin
  .....
  Marker := GMMarker1.Add(dLatitude, dLongitude, aList1[2]);
  Marker.Icon := 'http://www.cadetill.com/imagenes/gallery/gmlib/marker.png'
  .....

The image must be on the web or in your local PC
Comment: Thanks so much it works fine.

Thank you also for the awesome GMlib.


Approximation in $L^p$ spaces

Question: Let $X$ denotes the span {$x^n:n \ge1 $}. Is it true that $X $ is dense in $L^1([0,1])?.$
I showed that $X$ is dense in the space of continuous functions that vanishes at zero. I also know space of continuous functions with compact support is dense in $L^p$ space.
I guess it not true but my friend told me it is true.
Anybody's help would be appreciated
Comment: Use the Stone-Weierstrass approximation theorem.
Answer: Hint: given any continuous function on $[0,1]$, you can approximate it in the $L^1$ norm by continuous functions that vanish at $0$.
Comment: Thanks for the hint but I am still confused could you please elaborate little bit..
Comment: Given any $f \in L^1$ and $\epsilon > 0$, there is a continuous function $g$ on $[0,1]$ with $\|f - g\|_1 < \epsilon/3$.  There is a continuous function $h$ on $[0,1]$ with $h(0) = 0$ and $\|g - h\|_1 < \epsilon/3$.
There is $p \in X$ with $\|h - p\|_1 \le \|h - p\|_\infty < \epsilon/3$...
Comment: By the help of your hint, i also did exactly same, thank you it helped me to verify my work...

Approximation in $L^p$ spaces


Calcular media de temperaturas em R

Question: Tenho:
     Data Sala.1 Sala.2 Sala.3 Horas
1  02/08/2013   20.5   19.7   21.6 15:00
2  02/08/2013   19.7   18.9   20.2 15:30
3  02/08/2013   19.7   19.1   20.0 16:00
4  02/08/2013   19.7   18.8   19.8 16:30
5  02/08/2013   19.8   18.8   19.9 17:00
6  02/08/2013   19.9   19.2   20.0 17:30
7  02/08/2013   19.9   18.9   20.0 18:00
8  02/08/2013   20.0   19.1   20.1 18:30
9  02/08/2013   20.2   19.4   20.3 19:00
10 02/08/2013   20.3   19.1   20.4 19:30
11 02/08/2013   20.5   19.6   20.6 20:00
12 02/08/2013   20.5   19.2   20.6 20:30
13 02/08/2013   20.8   19.8   20.9 21:00
14 02/08/2013   20.7   19.3   20.8 21:30
15 02/08/2013   21.0   19.9   21.1 22:00
16 02/08/2013   20.9   19.5   21.1 22:30
17 02/08/2013   20.9   19.3   21.1 23:00
18 02/08/2013   21.2   20.1   21.4 23:30

Preciso calcular a média de temperatura por sala durante o horário de permanência (7:00 até as 23:30h)
Alguem sabe como faço em R?
Comment: Possível duplicata de [Como calcular a média de uma coluna em R?](https://pt.stackoverflow.com/questions/43905/como-calcular-a-m%c3%a9dia-de-uma-coluna-em-r)
Comment: `colMeans(dados[2:4])`.
Answer: Você pode usar data.table. Além de facilitar cálculos por grupos e subconjuntos, ele possui funções para lidar com data e hora.
Dupliquei seus dados para conter mais de um dia:
dados <- read.table(text = c('
    Data       Sala.1 Sala.2 Sala.3 Horas
    02/08/2013   20.5   19.7   21.6 15:00
    02/08/2013   19.7   18.9   20.2 15:30
    02/08/2013   19.7   19.1   20.0 16:00
    02/08/2013   19.7   18.8   19.8 16:30
    02/08/2013   19.8   18.8   19.9 17:00
    02/08/2013   19.9   19.2   20.0 17:30
    02/08/2013   19.9   18.9   20.0 18:00
    02/08/2013   20.0   19.1   20.1 18:30
    02/08/2013   20.2   19.4   20.3 19:00
    02/08/2013   20.3   19.1   20.4 19:30
    02/08/2013   20.5   19.6   20.6 20:00
    02/08/2013   20.5   19.2   20.6 20:30
    02/08/2013   20.8   19.8   20.9 21:00
    02/08/2013   20.7   19.3   20.8 21:30
    02/08/2013   21.0   19.9   21.1 22:00
    02/08/2013   20.9   19.5   21.1 22:30
    02/08/2013   20.9   19.3   21.1 23:00
    02/08/2013   21.2   20.1   21.4 23:30
    03/08/2013   20.5   19.7   21.6 15:00
    03/08/2013   19.7   18.9   20.2 15:30
    03/08/2013   19.7   19.1   20.0 16:00
    03/08/2013   19.7   18.8   19.8 16:30
    03/08/2013   19.8   18.8   19.9 17:00
    03/08/2013   19.9   19.2   20.0 17:30
    03/08/2013   19.9   18.9   20.0 18:00
    03/08/2013   20.0   19.1   20.1 18:30
    03/08/2013   20.2   19.4   20.3 19:00
    03/08/2013   20.3   19.1   20.4 19:30
    03/08/2013   20.5   19.6   20.6 20:00
    03/08/2013   20.5   19.2   20.6 20:30
    03/08/2013   20.8   19.8   20.9 21:00
    03/08/2013   20.7   19.3   20.8 21:30
    03/08/2013   21.0   19.9   21.1 22:00
    03/08/2013   20.9   19.5   21.1 22:30
    03/08/2013   20.9   19.3   21.1 23:00
    03/08/2013   21.2   20.1   21.4 23:30'),
    header = TRUE)

library(data.table)

dt <- as.data.table(dados)

dt$Horas <- as.ITime(dt$Horas, format = '%H:%M')

medias <- dt[ Horas >= as.ITime('7:00:00') & Horas <= as.ITime('23:30:00'), lapply(.SD, mean), by = Data ][ , Horas := NULL ]

>     medias
         Data   Sala.1   Sala.2 Sala.3
1: 02/08/2013 20.34444 19.31667  20.55
2: 03/08/2013 20.34444 19.31667  20.55

Answer: A seguir, segue o trecho de codigo que resolve seu problema.
tempo_inicial <- '19:00'
tempo_final <- '23:30'

#Encontrar indice da hora inicial e final
#match retorna o primeiro casamento que encontrar na coluna de horas
indices <- match(c(tempo_inicial, tempo_final), dados[, 5])

#primeiro indice da hora inicial, segundo possui a hora final.
#considerando que o horario esta ordenado em ordem crescente.
inicio <- indices[1]
fim <- indices[2]

#delimita o dataframe nesse intervalo, alem de delimitar as
#colunas 2, 3 e 4 que correspondem a posição das salas.
dados.temp <- dados[inicio:fim, c(2, 3, 4)]

#por fim, calcular suas medias
colMeans(dados.temp)

Answer: Modifiquei uma parte dos seus dados:
# vetores de dados
Data <- rep('02/08/2013', 13) # cria 13 datas iguais
Sala.1 <- c(20.5,19.7,19.7,19.7,19.8,19.9,19.9,20.0,20.2,20.3,20.5,20.5,20.8)
Sala.2 <-c(20.5,19,19.7,19.7,19.9,19.9,19.9,20.0,20.2,20.3,20.5,20.5,20.3)
Horas <- c('15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00',
                   '18:30', '19:00', '19:30', '20:00', '20:30','21:00')

# criando o data frame
dados <- data.frame(Data, Sala.1, Sala.2, Horas)

dados

    Data Sala.1 Sala.2 Horas
1  02/08/2013   20.5   20.5 15:00
2  02/08/2013   19.7   19.0 15:30
3  02/08/2013   19.7   19.7 16:00
4  02/08/2013   19.7   19.7 16:30
5  02/08/2013   19.8   19.9 17:00
6  02/08/2013   19.9   19.9 17:30
7  02/08/2013   19.9   19.9 18:00
8  02/08/2013   20.0   20.0 18:30
9  02/08/2013   20.2   20.2 19:00
10 02/08/2013   20.3   20.3 19:30
11 02/08/2013   20.5   20.5 20:00
12 02/08/2013   20.5   20.5 20:30
13 02/08/2013   20.8   20.3 21:00

Calcular a média de temperatura entre 16h e 18h30 para a sala 1. Vemos nos dados acima as linhas dos dados da sala 1 neste horário correspondem da linha 3 a 8 do dataframe. Então:
# funcao temp media
m.temp <- function(intervalo){
  T <- c()                     # vetor vazio
  for(i in intervalo){         # itera da linha inicial da hora ate a final
    T<- c(T,dados$Sala.1[i])   # adciona valores das T das do intervalo
  }
mean(T)                        # retorna a media das T
}

m.temp(3:8)     # media entre 16h e 18h30 da Sala.1
19.83333

Calcular media de temperaturas em R


$form_state['num_names'] increases differently

Question: I'm implementing ajax add more example in my own module. I am pulling data from an Oracle database and printing children's data. However, when I click Add Person, the 1st child's data is multiplied several times, 2nd child's data is multiplied several times and so on. How can I multiply only the last child's fieldset once?
My code:
function suweb_agi_add_more_callback($form, &$form_state) {
  return $form['c'];
}
function suweb_agi_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}
function suweb_agi_add_more_remove_one($form, &$form_state) {
  $form_state['id']=$form_state['clicked_button']['#attributes']['data-id']+1;
}
..
..
..
function suweb_agi_form(&$form, &$form_state, $form_id) {
  for ($x=0;$x<count($child);$x++) {
    for ($y=0;$y<$form_state['num_names'];$y++) {
      $form['c'][$x][$y]['info'] =  [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Çocukları / Bakmakla Yükümlü Olduğu Kişilerin Durumu':'Status of Children Dependent On or Living With The Taxpayer',
        '#collapsed' => false,
        '#collapsible' => false,
        '#prefix' => '
',
        '#suffix' => '
',
        'info' => [
          '#type' => 'markup',
          '#markup' => ($lang == 'tr')?'Çocuğunuz 18 yaşından büyük ve eğitimine devam ediyorsa; eğitim durumu bilgilerini doldurunuz. Eğitimine devam etmiyor ise, Asgari Geçim İndirimi kapsamında değildir. Çocuğunuz 24 yaşından büyük ise Asgari Geçim İndirimi kapsamında değildir.':'If your other is older than 18 and continuing his/her education, fill out the education status information. If he/she is not continuing his/her education, he/she is not covered in the Minumum Living Allowance. If your other is older than 24, he/she is not covered in the Minumum Living Allowance.',
          '#prefix' => '',
          '#suffix' => ''
        ],
      ];
      $form['c'][$x][$y]['info']['first_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Ad':'Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['middle_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Orta Ad':'Middle Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_MIDDLE_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['last_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Soyad':'Last Name',
        '#default_value' => $person['LASTNAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['tckn'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'T.C. Kimlik No':'T.C. Identity Number',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['TC_KIMLIK_NO'],
        '#attributes' => [
          'class' => ['tckn'],
        ],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['birth_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Doğum Tarihi':'Date of Birth',
        '#default_value' => ($form_state['num_names']>1)?'':date('Y-m-d',strtotime($child[$x]['BIRTH_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-30:+0',
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['father_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Baba Adı':'Father\'s Name',
        '#default_value' => $person['CINSIYET'] == 'M'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['mother_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Anne Adı':'Mother\'s Name',
        '#default_value' => $person['CINSIYET'] == 'F'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['gender'] = [
        '#type' => 'radios',
        '#title' => ($lang == 'tr')?'Cinsiyeti':'Gender',
        '#options' => ($lang == 'tr')?['F'=>'Kız','M'=>'Erkek']:['F' => 'Girl','M' => 'Boy'],
        '#default_value' => ($form_state['num_names']>1)?'':trim($child[$x]['GENDER']),
      ];
      $form['c'][$x][$y]['info']['studying'] = [
        '#type' => 'checkbox',
        '#title' => ($lang == 'tr')?'Çalışıyor mu?':'Studying?',
        '#default_value' => (isset($child[$x]['SCHOOL_NAME']))?1:0,
      ];
      $form['c'][$x][$y]['info']['education'] = [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Eğitim Bilgileri':'Education Details',
        '#collapsed' => false,
        '#collapsible' => false,
        '#states' => [
          'visible' => [
            ':input[name="c['.$x.'][0][info][studying]"]' => ['checked' => TRUE],
          ],
        ],
      ];
      $form['c'][$x][$y]['info']['education']['education_type'] = [
        '#type' => 'select',
        '#title' => ($lang == 'tr')?'Eğitim Tipi':'Education Type',
        '#options' => ($lang == 'tr')?[0=>'İlköğretim',1=>'Lise',2=>'Üniversite']:[0=>'Primary School',1=>'High School',2=>'University'],
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['EDUCATION_TYPE'],
      ];
      $form['c'][$x][$y]['info']['education']['school_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Okulun Adı':'School\'s Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['SCHOOL_NAME'],
      ];
      $form['c'][$x][$y]['info']['education']['school_start_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Başlangıç Tarihi':'School Start Date',
        '#default_value' => (!isset($child[$x]['SCHOOL_START_DATE']))?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_START_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-18:+0'
      ];
      $form['c'][$x][$y]['info']['education']['school_end_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Bitiş Tarihi':'School End Date',
        '#default_value' => (!isset($child[$x]['SCHOOL_END_DATE']))?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_END_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-18:+10'
      ];
      $form['c'][$x][$y]['info']['remove_person'] = [
        '#type' => 'submit',
        '#value' => ($lang == 'tr')?'Kişi Sil':'Remove Person',
        '#submit' => ['suweb_agi_add_more_remove_one'],
        '#attributes' => ['style' => 'float:right', 'data-id' => $x],
        '#ajax' => [
          'callback' => 'suweb_agi_add_more_callback',
          'wrapper' => 'agi-fieldset-wrapper',
        ],
      ];
    }
  }
  $form['add_person'] = [
    '#type' => 'submit',
    '#value' => ($lang == 'tr')?'Kişi Ekle':'Add Person',
    '#submit' => ['suweb_agi_add_more_add_one'],
    '#ajax' => [
      'callback' => 'suweb_agi_add_more_callback',
      'wrapper' => 'agi-fieldset-wrapper',
    ],
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => ($lang == 'tr')?'Bilgileri Güncelle ve Yazdır':'Save Information and Print',
  ];
  return $form;
}

Answer: You have double for-loop in your provided code..
Here is an example how it could be done. The code is not tested but should work and is only the an example for the approach.
function suweb_agi_add_more_add_one($form, &$form_state) {
  // We want to add one more fieldset, so lets signalize that.
  $form_state['add_more'] = TRUE;
  // And build the form with the new form_state again.
  $form_state['rebuild'] = TRUE;
}

function suweb_agi_form(&$form, &$form_state, $form_id) {
  // Don't know where you get $child from.. but let's assume, you have it from somewhere.
  // And it is an array.
  $child = array();
  for ($x=0;$x<count($child);$x++) {
    // First you should create the form for existing data.
    $form['c'][$x]['info'] =  [
      '#type' => 'fieldset',
      // Use the t()-function and do your translations not in your functions!!
      '#title' => t('Status of Children Dependent On or Living With The Taxpayer'),
      '#collapsed' => false,
      '#collapsible' => false,
      '#prefix' => '
',
      '#suffix' => '
',
      'info' => [
        '#type' => 'markup',
        // Use the t()-function and do your translations not in your functions!!
        '#markup' => t('If your other is older than 18 and continuing his/her education, fill out the education status information. If he/she is not continuing his/her education, he/she is not covered in the Minumum Living Allowance. If your other is older than 24, he/she is not covered in the Minumum Living Allowance.'),
        '#prefix' => '',
        '#suffix' => ''
      ],
    ];
    // [...]
  }

  // Now you can check if there is the request for add more..
  if (!empty($form_state['add_more']) && $form_state['add_more']) {
    // Copy the latest form element.
    $latest_form_element = end($form['c']);
    // Change some values, i.e. the id you use for delete functionality.
    $latest_form_element['xyz']['#attributes']['data-id'] += 1;
    // And then add it to the element
    $form['c'][] = $latest_form_element;
    // Reset the form_state add_more
    $form_state['add_more'] = FALSE;
  }

  $form['add_person'] = [
    '#type' => 'submit',
    '#value' => t('Add Person'),
    '#submit' => ['suweb_agi_add_more_add_one'],
    '#ajax' => [
      'callback' => 'suweb_agi_add_more_callback',
      'wrapper' => 'agi-fieldset-wrapper',
    ],
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Save Information and Print'),
  ];
  return $form;
}

Comment: The only problem with this that it duplicates the first child, omitting First Name textfield. I have no clue why. I think it was happening before as well.
Comment: My bad, I should have reset the value, not the textfield itself. Thank you :)
Comment: Hrm, after much trying, I found another issue. If the number of childen aka count($child) is zero, I get `Warning: end() expects parameter 1 to be array, null given`


How to handle features with hierarchy in regression

Question: I'm trying to fit a regression model to predict the total expense of department with predictor variables being the headcount at different levels within the department. Level 1 to level 5 are the different hierarchy levels with 1 being the highest and 5 being the lowest. It is intuitive that the number of people in the higher level is lesser than that in the middle and lower levels. Due to the difference in magnitude, the regression parameters gets biased to the levels with high headcount numbers. I tried regularization but unfortunately couldn't achieve the best fit. I was looking to add weights to the features but unable to get a hold on the right weighing technique. Looking for suggestions on the appropriate models. Attaching the snap of how my data looks.
Comment: This doesn't really make sense. If you assume cost is a function of people hired, then of course it is determined by the number of people at lower levels. Every department presumably has a single head, whether it employs 10 people or 10000. So basically - rethink what you are trying to achieve with this regression. Actually, there's insufficient information here to judge whether you need regression at all.
Comment: It would help if you add more details about the data. For e.g., why do you need statistics as opposed to just calculating it based on salary information? How many different companies do you have data for? What are these levels and what are the ranges of numbers in each, roughly?
Comment: please break down your claims (adding to the question). what do you mean by biased? what do you mean couldn't achieve best fit? in a straight (not regularised) linear regression did you check the uncertainties. I would expect the uncertainties to be higher on the coefficients of level 1/2, which perhaps reflects why managerial salaries can rocket - they have minimal effect on total cost.
Comment: @mkt Thank you very much for your explanation. Let me try to be more clear on the objective.
Objective: To build a predictive model that takes headcount structure at different levels as input to predict/estimate the potential cost associated with them and simulate different headcount scenarios.   An example to this is --  if my level 1 headcount increased by +2 and all other levels remains the same, what would be my cost implication? This can be scaled up by adjusting headcounts in other levels as well.
Comment: @seanv507 Thank you. So it goes like this. By biased I mean, the magnitude of the coefficients of level 3 and 4 and much higher than that of levels 1 and 2 due to its higher numbers relatively. As a result when I simulate adding 1 person to level 4 shows a great increase in the cost whereas adding 1 person to level 1 hardly shows any difference in the cost. Ideally the cost of the VP in an organization is higher than that of a senior engineer and this reality is taking a hit in my model.
Comment: What are these levels and why are you using them?
Comment: please add/update the question/rather than in individual comments.
Answer:
the magnitude of the coefficients of level 3 and 4 and much higher
than that of levels 1 and 2 due to its higher numbers relatively

this is not bias.
as others have noted, one would expect the coefficients to roughly correspond to salary.
So this may be due to your modelling (regularisation) and/or correlations between your levels data.
In particular imagine if your data only consists of level 1 and level 5 employees in fixed proportion 1: 10. ie
company A has 1 level 1, and 10 level 5.
company B has 2 level 1 and 20 level 5.
...
in this case the data is perfectly collinear, and eg a model with only level 5 input can capture all the variation. eg say salary of level 1 is 100 and level 5 is 20. then a coefficient of 30 on level 5 (and 0 on level 1) will still match the total cost. since $100n + 20.10.n =30.10.n$
note that L2 regularisation will prefer this solution (0 salary for level 1, 30 for level 5) to the correct one (30^2 < 100^2 + 20^2),
[I am not saying this is the optimal solution, but hopefully you get the idea, why you are getting lower numbers for your level 1s etc]
This is the problem with observational data. In an experiment, you would create orthogonal columns (varying level 1, independent from level 5 etc), in observational data, you have to consider the correlations between your variables - there is practically no company with a level 1 employee and zero level 5...
Comment: Thank you @seanv507. This is very useful!


How to fix "No module named 'encodings'" in Python3.7.1?

Question: I tried to start uwsgi for myproject(mywords_dict):
uwsgi --http :8000  -H /root/mywords_dict/env --chdir mywords_dict -w mywords_dict.wsgi

But received the following error:
Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

I am so confused that uwsgi can work well if I run it after entering virtual env .Python version of 'mywords_dict' is 3.7.1. I have checked that the there is encoding package in mywords_dic/env. And I can run python  successfully from there. Does anyone can help?
*** Starting uWSGI 2.0.18 (64bit) on [Fri Aug 30 00:15:16 2019] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-36) on 29 August
2019 13:49:55
os: Linux-3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018
nodename: VM_0_17_centos
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /root
detected binary path: /root/.pyenv/versions/3.7.1/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
chdir() to mywords_dict
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3882
your memory page size is 4096 bytes
detected max file descriptor number: 100001
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8000 fd 4
spawned uWSGI http 1 (pid: 22645)
uwsgi socket 0 bound to TCP address 127.0.0.1:42301 (port auto-assigned) fd 3
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
Python version: 3.7.1 (default, Nov 11 2018, 01:35:46)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
Set PythonHome to /root/mywords_dict/env
**Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'**

Comment: Hi guys, I finally solved this problem by 'rm -rf env'  and rebuild it . And I still don't know why it happend.
Comment: You might need to reinstall python or reset virtual env [This might be a duplicate](https://stackoverflow.com/questions/38132755/importerror-no-module-named-encodings)
Comment: @ryanyang , thank u for sharing. But I can run python and import encodings successfully in virtual env without using uwsgi. It's so wired.
Comment: @SyntaxVoid thanks, but it didn't work for me.
Comment: `Set PythonHome to /root/mywords_dict/env` — do you actually have a working installation of Python 3 in that directory? Can you run `python` from there and `import encodings`?
Comment: @9000 yes, I can run python from there and import encoding successfully . That is why I am so confused.
Comment: I occasionally experience this. To fix it I have to do `unset PYTHONHOME` before I call python. In fact, I added it to my `.bashrc` file and the problem went away.
Answer: This is due to wrong python virtual environment path. It is defined in you .ini file under home variable.
What you need to do is assign to this variable path pointing to the root of your venv. So if your venv path is /home/user/project/venv, just assign this path to the home variable. Be sure not to include the trailing / (slash) in the venv path (since it is later concatenated to /bin/python and you'll end up with double slash.
Then save your .ini file and try starting uWSGI again.
Comment: I made this exact mistake: I changed the env path in the conf from `/home/vinzee/.pyenv/versions/envname/bin/` to `/home/vinzee/.pyenv/versions/envname` and it worked.
Answer: I got the same error.
Fixed after trying these steps :

Uninstall python(38) as administrator. Checking all the boxes during custom installation, including install for all user and precompiling standard library.
Downgrading python38 to 37

I still dont know what & where the error came from though haha.


Show that the simple continued fraction of $\sqrt{d^2-1}$ is $[d-1; \overline{1, 2d-1}]$ for $d \geq 2$

Question: Show that the simple continued fraction of $\sqrt{d^2-1}$ is $[d-1; \overline{1, 2d-1}]$ for $d \geq 2$
For some reason I keep getting the wrong answers. I think it's because I am not setting my initial values correctly. What are $q_0, p_0, q_1, p_1$?
Answer: Terms of the Continued Fraction
Since $\left\lfloor\sqrt{d^2-1}\right\rfloor=d-1$, the first term is $d-1$. Subtracting $d-1$ and inverting gives
$$
\frac1{\sqrt{d^2-1}-(d-1)}=\frac{\sqrt{d^2-1}+(d-1)}{2d-2}\tag{1}
$$
The floor of the term on the right is $1$; so the next term is $1$. Subtracting $1$ and inverting gives
$$
\frac{2d-2}{\sqrt{d^2-1}-(d-1)}=\sqrt{d^2-1}+(d-1)\tag{2}
$$
The floor of the term on the right is $2d-2$, so the next term is $2d-2$.  Subtracting $2d-2$ and inverting, we get back to $(1)$. Thus, the continued fraction for $\sqrt{d^2-1}$ is
$$
\left\{d-1;\overline{1,2d-2}\right\}\tag{3}
$$

Approximants Example
To compute the approximants for the continued fraction of $\sqrt{15}$, use $d=4$. As computed above, the continued fraction is $\left\{3;\overline{1,6}\right\}$:
$$
\begin{array}{r|rr|rr}
c_n&&&3&1&6&1&6&1&6\\\hline
p_n&0&1&3&4&27&31&213&244&1677\\
q_n&1&0&1&1&7&8&55&63&433
\end{array}
$$
where $p_n=c_np_{n-1}+p_{n-2}$ and $q_n=c_nq_{n-1}+q_{n-2}$ .
Comment: How is it found what the right hand side expressions in 1) and 2) are approximate to though ? How can one see that $ \tfrac{\sqrt{d^2-1}+(d-1)}{2d-2} \approx\frac{2d-1-\frac1{2d}}{2d-2} $. Is there some Theorem at work here ? I'm just a little confused, I'm only a learner..
Comment: @Voltron: the approximation $\sqrt{d^2-1}\approx d-\frac1{2d}$ is the only approximation used.
Comment: Ah okay, I see now the rest just input that approximation, but how was that original approximation obtained, if you don't mind my asking ?
Comment: There are several ways to get this approximation: Binomial Theorem and Taylor Series are a couple. Probably the easiest is to note that for small $x$, $(1+x)^2=1+2x+x^2\approx1+2x$. Thus, for small $x$, $(1+x)^{1/2}\approx1+\frac x2$. Therefore, $$\sqrt{d^2-1}=d\left(1-\frac1{d^2}\right)^{1/2}\approx d\left(1-\frac1{2d^2}\right)=d-\frac1{2d}$$ This can be checked with $$\left(d-\frac1{2d}\right)^2=d^2-1+\frac1{4d^2}$$
Comment: Since all we really need is $\left\lfloor\sqrt{d^2-1}\right\rfloor=d-1$, I have removed the approximations and replaced with floor expressions.
Comment: Thank you , your explanation was very informative :)
Answer: I think it should be $[d-1;\overline{1,2d-2}],$ in other words replace your $2d-1$ by $2d-2.$ Doing this works in the case of $d=2.$
$1+1/x$ where $x=1+1/(2+x)$ which gives $x=(1-\sqrt{3})/2$ then $1+1/x=\sqrt{3}.$
I believe in the case of any integer squareroot the period starts immediately after the initial integer part of the radical, and that the last term of the repeating part is always twice the integer part.
Comment: (+1) your extrapolation is correct. I've not looked into your last statement, though.
Comment: @robjohn Yes, and would be easy to check as above by finding solution $y$ to $y=1+1/(2d-2+y).$
Comment: @robjohn I saw that last statement about continued fractions for $\sqrt{n}$ in some number theory book, and didn't go through the proof myself.


How to copy values of a Component from object A to the same Component on object B?

Question: I want to make inventory loader, but I don't know I could set component to older component. Of course I would make it with set every variable, but that doesn't have sense for me, because I think that can be done a lot easier.
I have 2 GameObjects with the same components. While I'm loading my second player I want to declare there the same variables as the old GameObject ("Local Player"). I want to make it for network, because one Player Prefab is Network Player and second one is Local Player, for not online lobbies.
The script is on the new Player, which spawn while Player join to server.
gameObject.GetComponent<Inventory>() = GameObject.Find("Local Player").GetComponent<Inventory>();

Error: The left-hand side of an assignment must be a variable, property or indexer
Thanks!
Comment: Can you tell me what problem you are facing right now, because for me it wasn't clear enough from your question alone?
Comment: Left Site must be the variable for change it.
Comment: @Pretzel I think that what Mathew try to say is that your question description, doesn't have a question, or at least is not easy to say what is your problem, what are you trying to achieve and why it doesn't work ^^ (or at least it doesn't say it in a way that Mathew and I can understand :( )
Comment: Ok, I will try to change it for less confusing
Answer: GetComponent<Inventory>() returns a reference ... you cant assign a value to it ... what you are trying to do is probably deep cloning the component with all its current values.

General case
There seems to be a solution for this (didn't test it though) from this thread using Reflection to deep copy the field and property values of one component to another. Only refactored it slightly ;)

So I finally found a solution to copying components at runtime - via
reflection. Thanks to @Jamora who pointed out that I could set values
via reflection too, not just get them.
This extension method gets a copy of a component:
public static class ComponentExtensions
{
     public static T GetCopyOf<T>(this T comp, T other) where T : Component
     {
         Type type = comp.GetType();
         Type othersType = other.GetType();
         if (type != othersType)
         {
             Debug.LogError($"The type \"{type.AssemblyQualifiedName}\" of \"{comp}\" does not match the type \"{othersType.AssemblyQualifiedName}\" of \"{other}\"!");
             return null;
         }

         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default;
         PropertyInfo[] pinfos = type.GetProperties(flags);

         foreach (var pinfo in pinfos)
         {
             if (pinfo.CanWrite)
             {
                 try
                 {
                     pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
                 }
                 catch
                 {
                     /*
                      * In case of NotImplementedException being thrown.
                      * For some reason specifying that exception didn't seem to catch it,
                      * so I didn't catch anything specific.
                      */
                 }
             }
         }

         FieldInfo[] finfos = type.GetFields(flags);

         foreach (var finfo in finfos)
         {
             finfo.SetValue(comp, finfo.GetValue(other));
         }
         return comp as T;
     }
}

Usage:
 var copy = myComp.GetCopyOf(someOtherComponent);

To make things more convenient, I added this GameObject extension
method to add a component directly by just passing it so a copy of it
will get added:
 public static T AddComponent<T>(this GameObject go, T toAdd) where T : Component
 {
     return go.AddComponent<T>().GetCopyOf(toAdd) as T;
 }

Usage:
 Health myHealth = gameObject.AddComponent<Health>(enemy.health);

Specific Component
In general however I think you wouldn't use this just on any component but should rather simply implement such functionality directly in your component and do e.g. something like
public class MyComponent : MonoBehaviour
{
    private int someIntField;
    private string someStringProperty { get; private set; }
    public GameObject someReference;
    // ...

    public void CopyValuesFrom(MyComponent input)
    {
        // Since you are in the same class you have access to all private members ;)
        someIntField = input.someIntField;
        someStringProperty = input.someStringProperty;
        someReference = input.someReference;
        // ...
    }
}

and then do e.g.
objectB.GetComponent<MyComponent>().CopyValuesFrom(objectA.GetComponnet<MyComponent>());

That would be the cleaner solution.

Careful though!!
For both solutions especially for reference types like e.g. List<T> or your custom classes etc. you might rather want to create deep clones instead of just copying the reference e.g.
private List<string> someList;

...

someList = new List<string>(input.someList);

Comment: That is great solution, but I think is minimally complicated. Thanks anyway! I will try to understand it, because that looks more profesionally haha.
Comment: @Pretzel see the update at the bottom for an in my eyes way cleaner solution ;)


How to pass std::move through a templated argument

Question: Often times I will have a templated function where I try to pass a && type. Problem is, if I put std::move as the argument, I get an error such as this one:
error: no matching function for call to 'doThing(void (*)(int&&), std::remove_reference<int&>::type)'

The code that generated that particular error is as following:
#include <utility>

template<typename T>
void doThing(void (*thing)(T), T input)
{
    thing(input);
}

void exampleThing(int&& someData)
{someData++;}

int main()
{
    int x, y = 5;
    exampleThing(std::move(x));             //compiles fine
    doThing(&exampleThing, std::move(y));   //error as shown above
}

So, how would I pass an argument to a template as a move?
Comment: I would try using a separate template parameter to define the first parameter to `doThing()`, and then use enable_if_t to check that it's callable with the 2nd parameter as a value.
Answer: Issue with
template<typename T>
void doThing(void (*thing)(T), T input)
is that T is deduced from 2 places, and should be identical.
Simpler to split in 2 template parameters:
template <typename Arg, typename T>
void doThing(void (*thing)(Arg), T&& input)
{
    thing(std::forward<T>(input));
}

Demo
Another option is to allow deduction only at one place:
I use std::type_identity (C++20) for this, but can be trivially re-implemented for previous version.
template <typename Arg>
void doThing(void (*thing)(Arg), std::type_identity_t<Arg> input)
{
    thing(std::forward<Arg>(input));
}

Demo


Gtkmm3 : wait for css transition to finish

Question: My question does not concern JavaScript, but C++ :
In gtkmm3, application appearance is managed by CSS, so transitions can be set like that :
theme.css :
.purple {
transition: 500ms linear;
background-image: -gtk-gradient (radial,
    center center, 0,
    center center, 1,
    from (#FFB2E8),
    to (#80005A));
 }

main.cc :
   // Create and define the StyleContext
   CssProvider = Gtk::CssProvider::create();
   CssProvider->load_from_path (Glib::build_filename (UI_DIR, "theme.css"));
   Glib::RefPtr<Gtk::StyleContext> ButtonContext = button->get_style_context ();
   ButtonContext->add_provider (CssProvider,
                                GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
   // Assign new color
   ButtonContext->add_class ("purple");
   // Assign an intermediate color
   ButtonContext->remove_class ("purple");
   ButtonContexy->add_class ("green");
   // To something
   // ... ...
   // Change the color again
   ButtonContext->remove_class ("green");
   ButtonContext->add_class ("yellow")

With this code, the user sees only the "yellow" state of the button, and not the previous ones, because transitions are skipped.
How to display all the color changes one after the other?
EDIT :
My application is a game, where buttons are colored accordingly to their label. This label can change multiple times very closely, and I want the user to see these changes, so, to see the transitions between each state. So, it is not just a flash (my example was not perfect, if you want the whole code of the application, you can get it here).
EDIT 2:
I modified the code above and the following sentences to explain my problem better.
Answer: Are you trying to make the button flash purple briefly? If so, you can set a timeout with GLib::SignalTimeout for the correct amount of time that you want the button to flash for.
Comment: I edited my question to be more precise (your answer does not resolve my problem)
Comment: I think it does. If you set the timeout to, for example, 1050 ms, then you get 500 ms of the transition to purple, a 50 ms purple flash, and 500 ms of the transition back to the original color.
Comment: Again, I don't want the button to flash. I want it to wait until the end of the CSS transition before changing its color. It can be multiple successive color changes, in all cases I want the user to see these successive changes (and not just the last color, as it is for the moment). Glib::SignalTimout is not a solution for my problem (I already tested it).
Comment: I have spent a long time learning how to use it, but finally, I managed to do what I wanted with `Glib::signal_timeout ().connect ()`. Thank you and sorry for how long it tool me to accept your answer !


CheckBox gets Checked when its Text is clicked

Question: I have a checkbox and i don't want it be checked when the user click's its text. It should only be checked when the button is clicked.
Is it possible ?
Answer: Dont have much experience about the CheckBox control.
But i think.
You can make checkbox without giving names/text and put a TextView to rightof the checkbox as the name/text of that checkbox.
Ex.
<RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="center_vertical">
<CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
<TextView android:text="TextView" android:layout_toRightOf="@id/checkBox1" android:layout_marginTop="15dp" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</RelativeLayout>

Comment: I am already using this step but i want it to be simple. That's the reason i asked this question.
Comment: simple means? you dont want to use another textview ?
Comment: yes, I don't want to use another textview. I just want the checkbox itself. Current i am using a checkbox with no text value and a textview placed to its right with the text.
Answer: It is by default i think.You can remove text of checkbox and put a textView beside it.This trick may work. :)


Android view over a view

Question: I need to get below result:

I need LinearLayout to appear on MapView
mapview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="0.1"
        android:clickable="true" />

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.9"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnAcceptMyLocation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:text="Onayla" />

        <Button
            android:id="@+id/btnCancelMyLocation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:text="İptal" />
    </LinearLayout>

</LinearLayout>

Comment: u need to over right Map fragment ? or u need one more layout under MAP fragment ?
Comment: Post your map layout xml alone and explain your need.
Answer: Put your LinearLayout and MapView into a RelativeLayout. Align your LinearLayout to parent bottom.
Set MapView to fill parent width and height, set your LinearLayout width to fill parent, and height to something like 50dp (assuming your picture). Then use this option in your LinearLayout:
android:layout_above="@+id/mapView"

Android view over a view


Group_by no Dplyr

Question: Considere o seguinte data frame:
dados <- data.frame(Bairro=c("Bairro1","Bairro2","Bairro3", "Bairro4","Bairro1",
                             "Bairro2","Bairro3", "Bairro4", "Bairro1", "Bairro1"),
                    Piscina=c("sim","sim","sim","sim","não","não","não","não","não","não"),
                    Area=c(300,110,400,130,90,160,200,180,210,140))

Por enquanto meu códido está retornando o total de casas analisadas e o total de casas com piscinas, agrupando tudo por bairro:
library(dplyr)
estatisticas <- dados %>%
  group_by(Bairro) %>%
  summarise(
    Qtd_casas = n(),
    Casas_com_piscina = sum(Piscina=="sim"))

Agora gostaria de acrescentar duas novas colunas nesse novo data frame "estatisticas":

área média das casas com piscina;
área média das casas sem piscina.

Como consigo isso?
Answer: Basta acrescentar mais duas linhas ao summarise da pergunta.
library(dplyr)

dados %>%
  group_by(Bairro) %>%
  summarise(
    Qtd_casas = n(),
    Casas_com_piscina = sum(Piscina == "sim"),
    Area_com_piscina = mean(Area[Piscina == "sim"]),
    Area_sem_piscina = mean(Area[Piscina == "não"])
  )
## A tibble: 4 x 5
#  Bairro  Qtd_casas Casas_com_piscina Area_com_piscina Area_sem_piscina
#  <chr>       <int>             <int>            <dbl>            <dbl>
#1 Bairro1         4                 1              300             147.
#2 Bairro2         2                 1              110             160
#3 Bairro3         2                 1              400             200
#4 Bairro4         2                 1              130             180

Group_by no Dplyr


Running check_plain after t

Question: Will this be correct :
<code>drupal_set_title(check_plain(t("Donation Details for Project: $project->title")))
</code>
I want all of the string to be translated when needed. Should call check_plain first then t or vice versa?
Answer: This would be better:

drupal_set_title(t("Donation Details for Project: @title"),
  array('@title' => $project->title));

Taken from here

Special variables called "placeholders" are used to signal dynamic
  information in a string which should not be translated. Placeholders
  can also be used for text that may change from time to time (such as
  link paths) to be changed without requiring updates to translations.
@variable, which indicates that the text should be run through
  check_plain, to escape HTML characters. Use this for any output that's
  displayed within a Drupal page.
Comment: Can't I myself add html meta chars in typed text by mistake?
Comment: What do you mean? Also, is $project->title a node title?
Comment: I mean inadvertently I can add html meta chars even in this text: Donation Details for Project: ..... Then your example will not take care of it.
Comment: Is all of the data user-supplied then?  I'm not sure I follow.  Maybe you could expand your question with your specific use case.
Answer: Better call check_plain first it will escape the html tags.Then you convert them into whatever the language you want.
Comment: If t() returns an invalid UTF-8 character, the translation is broken and should be fixed.
Comment: If you call t() first may be for some language, it will return **invalid UTF-8 characters**.Then you pass t() result string into check_plain() it will filter all invalid UTF-8 characters.
Answer: Call t() first. t() should be applied to literal strings, not to variables and not to results of function calls. From the manual of t():

Because t() is designed for handling code-based strings, in almost all
  cases, the actual string and not a variable must be passed through
  t().
Extraction of translations is done based on the strings contained in
  t() calls. If a variable is passed through t(), the content of the
  variable cannot be extracted from the file for translation.

Running check_plain after t


XNA Smooth Downward Swoop Motion

Question: (Before you read, I'm very nervous about posting here since my previous question got a lot of negative responses... Please try and be nice. I am a student and can't write "Perfect" code yet)
I'm currently trying to figure out how to make a mosquito (Texture2D) swoop downwards and then come back up to it's original position.
Currently the mosquitoes simply move left and right within the screen bounds, with no Y movement.
I've stepped it through a debugger and observed it's Y coordinate. My mosquitoes are indeed swooping down and then back upwards again... However, they do it so quickly that it isn't visible to the human eye.
Therefore I need a way to smoothly swoop them down so that it's actually visible.
I am currently unable to embed images into my posts, however I have made a GIF demonstrating the effect that I want.
Here's a link to my GIF
Things I've tried:

Copied the first line of my movement code (seen below) and changed it so that it would only affect the Y coordinates.

Result: Mosquitoes were still swooping too fast to see.

Changing my mosquitoe's velocity.Y to include a Y that isn't 0, so that my movement code will also change the Y position instead of just the X position.

Result: Game was stuck in an infinite loop since my movement code is found in the Update() function, and the code never got out of the loop so that it could update the position...

Here's the movement code I have in my Update.
The mosquitoes move all the way to the right, then all the way to the left.
        internal void Update(GameTime GameTime)
        {
           position += velocity * (float)GameTime.ElapsedGameTime.TotalSeconds;

           // Reverses the direction of the mosquito if it hits the bounds
           if (position.X <= gameBoundingBox.Left ||
              position.X + animationSequence.CelWidth > gameBoundingBox.Right)
           {
               velocity.X *= -1;
           }
        }

And here's the actual Swoop() code that I have...
    internal void Swoop(GameTime gameTime)
    {
        float originalYPosition = position.Y;
        bool currentlySwooping = true;

        while (currentlySwooping)
        {
            position.Y++;

            if (this.BoundingBox.Bottom >= gameBoundingBox.Bottom)
            {
                currentlySwooping = false;
            }
        }

        while (!currentlySwooping && position.Y > originalYPosition)
        {
            position.Y--;
        }
    }

I don't ask questions on here too often, so I'm sorry if I'm using an incorrect format or if I've given too little information.
If you need to know anything else then please let me know.
Comment: Where are you calling `Swoop`?
Comment: In my main game code (MosquitoAttackGame.cs). I have a random number generator that calls the swoop method if a specific number is generated.

I still have yet to try your solution, as I'm currently at school. However I will try it when I get home :)
Answer: There are many ways of implementing this, but this should do it.
float originalYPosition = position.Y;
int swoopDirection = 0;
internal void Update(GameTime GameTime)
{
    /* Same update code */

    if (swoopDirection != 0)
    {
        position.Y += swoopDirection;

        if (swoopDirection == 1 && this.BoundingBox.Bottom >= gameBoundingBox.Bottom)
        {
            swoopDirection = -1;
        }
        else if (swoopDirection == -1 && position.Y <= originalYPosition)
        {
            swoopDirection = 0;
        }
    }
}
internal void Swoop()
{
    swoopDirection = 1;
}

Basically, we have a variable swoopDirection that changes depending on the state of the swoop (1 when going down and -1 when going up). In the update method we check that swoopDirection != 0 (we are swooping). If we are swooping we add the direction to the Y axis and check that we aren't out of bounds. If we touch the bottom we set swoopDirection to -1 so we go up. If we are at the original position swoopDirection is set to 0 and we stop swooping.
Comment: Thank you! I had to tweak and modify your code so that it would work with my game, but overall your method did work! :)

Thanks again!

XNA Smooth Downward Swoop Motion


Como converter esse código da versão 2 para 3.4 do Python?

Question: Estou tendo dificuldades para converter o código abaixo para a versão 3.4 do Python, a finalidade deste código é codificar e decodificar hexadecimais, afim de criar shellcodes.
import binascii, sys, time

RED = '\033[31m'
WHITE = '\033[37m'
RESET = '\033[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)
    q = raw_input("=> ")

    if q == "encode":
        inputtype = raw_input("Please input data : ")
        print "shellcode => ",
        for encoded in inputtype:
            print "\b\\x"+encoded.encode("hex"),
            sys.stdout.flush()
            time.sleep(0.5)
            print RESET

    elif q == "decode":
        inputtype = raw_input("Please input data : ")
        cleaninput = inputtype.replace("\\x","")
        print "hex       => ",cleaninput
        print "plaintext => ",
        print "\b"+cleaninput.decode("hex")

    else:
        print "wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET)
        sys.exit(1)

if __name__ == '__main__':
    main()

Essa parte não entendi:
print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)

Ta certo ele definiu as cores lé em cima, e o %sencode%s / %sdecode%s como funciona isto? Pelo que entendi ele fez um %s, no começo e no final das palavras encode e decode e chamo com as cores.
q = raw_input("=> ")

Ele definiu a variável e este => serial algo em específico no Python 2?
Neste parte abaixo entendi umas partes porém nem todas se alguém me explicar melhor fico grato.
inputtype = raw_input("Please input data : ")
print "shellcode => ",
for encoded in inputtype:
    print "\b\\x"+encoded.encode("hex"),
    sys.stdout.flush()
    time.sleep(0.5)

Obrigado pessoal.
Comment: @qmechanik Estava apenas dando uma dica rápida que *talvez* resolvesse os problemas sem precisar pensar muito. Mas na realidade, uma resposta como a sua que explica as diferenças entre as versões é bem mais útil. O `2to3`, pelo que eu li (nunca o usei de fato), seria apenas uma ajuda para converter códigos grandes, mas não garante que o resultado seja um código correto e funcional (i.e. não dispensa a revisão cuidadosa do código convertido).
Comment: Já experimentou o [`2to3`](https://docs.python.org/2/library/2to3.html)? Se isso não resolver, diga *quais são* esses "probleminhas", o que você já tentou fazer para resolvê-los, e no que quer que a gente ajude. À primeira vista, uns parênteses após os `print`s resolveriam a maior parte dos problemas...
Comment: @mgibsonbr Por que não cria uma resposta? acho que deve ser interessante mostrar esse processo de tradução.
Answer: Deverá ser feita algumas mudanças no código para que funcione do modo esperado no Python 3.

Em versões anteriores ao Python 3 o print era uma instrução (statement), a partir do Python 3, ele é considerado uma função, e por isso alguns detalhes da sintaxe mudaram, como o uso obrigatório de parênteses, ().

A partir do Python 3, a função built-in raw_input() foi renomeada para input().

No Python 3 não é necessário usar a vírgula no final para suprimir uma nova linha.

A partir do Python 3.4 os métodos que tratavam sobre a codificação e decodificação foram substituídos pelas funções do módulo codecs.
Python 3.4, modo errado:
b"hello".decode("hex")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

Python 3.4, modo correto:
>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'

Essa parte não entendi:

print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)

As quatro ocorrências do formato %s serão substituídas pelos valores de RED, RESET, WHITE e RESET. O print imprimirá:
print "what do you want to do ? \033[31mencode\033[0;0m / \033[37mdecode\033[0;0m"

Isso imprimirá na tela palavras com uma cor diferente, outras combinações de cores podem ser vistas aqui.

q = raw_input("=> ") --> ele definiu a variável e este => serial algo em específico no python 2

O => é o texto que será apresentado e que irá receber a entrada do usuário.

Neste parte abaixo entendi umas partes porém nem todas se alguém me explicar melhor fico grato.

inputtype = raw_input("Please input data : ") # Recebe a entrada do usuário
print "shellcode => ",                        # Imprime "shellcode =>" e elimina a nova linha
for encoded in inputtype:                     # Percorre cada letra da variável "inputtype"
    print "\b\\x"+encoded.encode("hex"),
    sys.stdout.flush()                        # Imprime diretamente na saída padrão "stdout"
    time.sleep(0.5)                           # Espera 30s

O código convertido para Python 3 deve ficar assim:
import sys, time, binascii
# -*- coding: utf-8 -*-

RED = '\033[31m'
WHITE = '\033[37m'
RESET = '\033[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print("what do you want to do ? {0}encode{1} / {2}decode{3}".format(RED, RESET, WHITE, RESET))
    q = input("=> ")

    if q == "encode":
        inputtype = input("Please input data : ")
        print ("shellcode => ")
        for encoded in inputtype:
            print ("\\x{0}".format(binascii.hexlify(bytes(encoded, 'utf-8')).decode()))
            sys.stdout.flush()
            time.sleep(0.5)
            print (RESET)

    elif q == "decode":
        inputtype = input("Please input data : ")
        cleaninput = inputtype.replace("\\x","")
        print ("hex       => {0}".format(inputtype))
        print ("plaintext => {0}".format(binascii.unhexlify(cleaninput).decode('utf-8')))
    else:
        print ("wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET))
        sys.exit(1)

if __name__ == '__main__':
    main()

Uma versão mais limpa e com algumas modificações:
# -*- coding: utf-8 -*-
import sys, binascii

cor = {'vermelho': '\033[1;31m', 'branco': '\033[1;34m', 'sem_cor': '\033[0;0m'}

def shellcode(opcao, texto):
    resultado = ""
    if opcao == 'e':
        resultado += ''.join("\\x{0}".format(binascii.hexlify(bytes(s, 'utf-8')).decode()) for s in texto)
    elif opcao == 'd':
        texto = texto.replace('\\x', '')
        resultado = binascii.unhexlify(texto).decode()
    return resultado

def main():
    opcoes = "{0}encode{1} / {2}decode{3} ou sair".format(cor['vermelho'], cor['sem_cor'], cor['branco'], cor['sem_cor'])
    print("O que quer fazer? {0}".format(opcoes))
    while True:
        try:
            questao = input("Opcao: ").lower()
            dados = input("Dados: ")
            codigo = ""

            if questao in ['encode', 'enc', 'e']:
                codigo = shellcode('e', dados)
            elif questao in ['decode', 'dec', 'd']:
                codigo = shellcode('d', dados)
            elif questao in ['sair', 's']:
                sys.exit()
            else:
                sys.exit("Opcao inválida! Opcoes: {0}".format(opcoes))

            print("{0}: {1}".format(questao, codigo))
        except KeyboardInterrupt:
            sys.exit()

if __name__ == '__main__':
    main()

Comment: @GlaucioFonseca Entendi, em todo caso postei uma versão mais limpa e corrigi um erro na parte do *decode*, se tiver algo a mais que eu possa ajudar, diga. =)
Comment: @GlaucioFonseca Se possível marque a resposta como aceita. =)
Comment: @GlaucioFonseca Para marcar como aceita clique sobre o ✔ depois ela fica verde. Uma outra coisa, se quiser usar `codecs.encode/decode` ao invés de `binascii.hexlify/unhexlify` também da certo.
Comment: Feito mano obrigado.
Comment: Pó amigo me ajudo muitos nas minhas dúvidas, eu vi tu colocou o código nos formatados novos, porém queria que você não tive-se colocado. E que eu gosto de colocar a cabeça pra funcionar, se eu tive-se dúvida perguntaria aqui de novo. Como sou novato em python e bom pra colocar a cabeça funcionar, mais vou fazer do meu jeito aqui o código e depois posto aqui como ficou. Muito obrigado.
Comment: Valeu mano obrigado.
Comment: Já marquei como resposta aceita @qmechanik