Why is dh$(k(x))=$dim $X$?

Question: Let $X$ be an integral Noetherian scheme. Let $x\in X$ be a regular closed point of $X$. Then Huybrechts and Lehn in his book, says that dh$(k(x))=$dim $X$. Here dh$(k(x))$ refers to the homological/projective dimension of the $\mathcal{O}_x$-module (vector space in this case) $k(x)$. I have not been able to prove this.
I have tried the following. The Auslander-Buchsbaum formula for a module M over a  regular local ring $A$ is given by : $\mathrm{dh}(M)+\mathrm{depth}(M)=\mathrm{dim}(A)$.
depth($k(x)$)=0 since $k(x)$ is field. Therefore dh$(k(x))$=dim($\mathcal{O}_x)$=height$(\mathcal{m})$, where $\mathcal{m}$ is the maximal ideal corresponding to the point $x$ in an affine say Spec$(A)$ containing $x$. But why is this equal to dim$(X)$. The fact that $x$ is a regular closed point is to be used. But I am not able to proceed.
Any help will be appreciated!
Answer: Your reasoning is correct and gives the first equality in the chain
$$\text{projdim}_{{\mathscr O}_{X,x}}(k(x))=\text{dim}({\mathscr O}_{X,x})=\text{codim}(\{x\},X)\leq\text{dim}(X)$$
in which the second equality can be checked directly for $X$ affine, and in which the third inequality is clear but strict in general: Take $R$ a discrete valuation ring with prime $\pi$, $X=\text{Spec}(R[T])$ and $x=(\pi T - 1)$. Then $X$ is regular integral of dimension $2$ and $x$ is a closed point since $$R[T]/(\pi T - 1) = R_{(\pi)} = \text{Quot}(R)$$ is a field. However, we have $\text{dim}({\mathscr O}_{X,x})=\text{height}_{R[T]}((\pi T-1))=1$ by the principal ideal theorem.
This is taken from Exercise 2.5.3 from Liu's book Algebraic Geometry and Arithmetic Curves.
If $X$ is a integral variety over a field, however, you do have $\text{codim}(\{x\},X)=\text{dim}(X)$ for a closed point $x$.
Comment: +1: this is an excellent answer. However it presupposes that $X$ is an algebraic scheme over some field, as you point out, and this is not part of the hypothesis. I don't know if the result is true for general integral schemes and although I can't find a counterexample, I am not especially convinced it is.
Comment: Dear Georges, thank you! Isn't $\text{Spec}(R[T])$ from the answer a counterexample for the general case?
Comment: Dear Hanno: yes your counterexample is indeed  absolutely correct and is exactly what I had been looking for. I am unforgiveable because I had thought of your counterexample before you posted your answer and had stupidly convinced  myself that it doesn't work. But it works beautifully and it is a pity I can't upvote you again!
Comment: Also, a zany consequence of your answer is that a discrete valuation ring cannot be finitely generated over some subfield!
Comment: @Hanno, thanks for that great answer!
Answer: This is consequence of the following fact : Let $(A,\mathfrak m,k)$ be a noetherian local ring. If $\operatorname{inj dim}_A k$ is finite, then $A$ is regular, where $\operatorname{inj dim}_A k$ is the injective dimension. As far as I remember, one variation on this assertion is called "global dimension theorem", referring to a (JP) Serre's result on the subject.
Comment: Thank you, but I don't understand fully. Global dimension says that a Noetherian local ring $A$ is regular if and only if it has finite global dimension, in which case the global dimension coincides with the Krull dimension of $A$. So here, $gd(\mathcal{O}_x)=dim(\mathcal(O_x)$ since $\mathcal{O}_x$ is regular. But I want to prove that $dim(\mathcal{O}_x)=dim X$. How do I get that?
Comment: See http://www.math.utah.edu/vigre/minicourses/algebra/spiroff2.pdf, more specifically the Auslander-Buchsbaum-Serre theorem. It shows that the height of $\mathfrak{m}$ is the dimension of $X$. If I open EGA today, I'll manage to give you the reference.
Comment: poorna is right: this does not prove that $dh(k(x))=dim (X)$ .
Comment: ...and Hanno provides a counterexample.

Why is dh$(k(x))=$dim $X$?


Markov chains- recurrence and transience

Question: This is an exercise in Durrett's probability book.

$p$ is the transition probability for a markov chain on a countable space. $f$ is said to be superharmonic if $f(x)\geq\sum_y p(x,y)f(y)$, or equivalently $f(X_n)$ is a supermartingale. Suppose $p$ is irreducible. If every nonnegative superharmonic function is constant, show that $p$ is recurrent.

It's not that easy to use the statement "every nonnegative superharmonic function is constant", so I tried 2 ways to reformulate the statement.
1.For all $f\geq 0$ nonconstant, there exists an $x$ s.t. $f(x)<\sum_y p(x,y)f(y)$. Show that $p$ is recurrent.
2.If $p$ is transient, show that there exists a nonnegative superharmonic function which is nonconstant.
But I haven't got a clue about how to prove this.
Answer: I think the easiest way is through strategy 2). Let $X$ be a transient irreducible Markov Chain. Consider an arbitrary $x_{0}$ and define:
$$\tau = \inf\{n \geq 0: X_{n} = x_{0}\}$$
Define
$$f(x) = P(\tau < \infty|X_{0}=x)$$
By construction, $f(x) \in [0,1]$ and $f(x_{0}) = 1$. Since $X$ is transient, there exists $y$  such that $f(y) < 1$. Finally, by Markovianity, for any $x \neq x_{0}$,
$$f(x) = P(\tau < \infty|X_{0}=x) = \sum_{y}{p(x,y)P(\tau < \infty|X_{1}=y)} = \sum_{y}{p(x,y)f(y)}$$
and
$$f(x_{0}) = 1 \geq \sum_{y}{p(x,y)f(y)}$$
Hence, $f$ is super-harmonic and non-constant.
ps: the condition is actually necessary and sufficient. Can you prove the reverse?
Comment: Yes the condition is necessary and sufficient. I have proved the reverse and that's why I only asked the first part. In fact, if $p$ is recurrent and let $f$ be a nonnegative superharmonic function, then $f(X_n)$ is a nonnegative supermartingale thus $f(X_n)\rightarrow Y, a.s.$ As $p$ is recurrent, for all $x, P(f(X_n)=f(x), i.o.)=1$, thus $Y=f(x) a.s.$ As this is true for all $x$, $f$ is constant.
Comment: How do we take the last equality at the line after $x\neq x_0$?
Comment: Could you please explain why there exists $y$ such that $f(y)<1$? I can't see that. Thanks.
Comment: @FengShao We are choosing $y$ transient, which by definition means $f(y)=P_y(T_y<\infty)<1$


Maximise the happiness among children

Question: Given N different candies and  M childrens. Each ith children demands for K[i] different candies and will ONLY BE HAPPY IFF HE GET ALL THOSE DIFFERENT CANDIES WHICH HE DEMANDED.
Now i want that maximum children should be happy.So how should i distribute the candies to do the same?
I need to find maximum children that i can make happy.
EXAMPLE :
Let we have N=4 candies and M=3 children
Now
1st children require 2 (=K[1]) candies which are : 1 and 2
2nd children require 2 (=K[2]) candies which are : 2 and 3
3rd children require 2 (=K[3]) candies which are : 3 and 4
Then here answer will be 2 as i can at max only make 1st and 3rd child happy.
Comment: Spank them all and send the rotten little ingrates to bed *without* any candy.
Comment: @MJD that was soooo rude..:p
Comment: @MJD And eat the candies yourself :P
Comment: I think your question needs clarification. Do you only want an algorithm that calculates that? Then you can just use a brute force algorithm. Or you want an "efficient" one? (where "efficient" must be properly defined).
Comment: @PedroForquesato I want an efficient one.N can go upto 20,000 and M <=20 .So i dont think bruteforce will work
Comment: @user3001932 How often are you running this algorithm?  Checking the 2^20 can be done extremely quickly with a well written program (think C not javascript).  What is the maximum number of candies a child could want?
Comment: @DanielV at worst he can want all of them .And are u talking of ur algorithm being purposed ?
Comment: @user300192 Actually I'm dumb, the number of candies a child could want is irrelevant, it may be infinity and it won't affect your runtime.  Just build a 20x20 table with a 1 when children are exclusive and a 0 when they aren't and run basic exponential search on it.  It will take you longer to write the program than to run it.  20 isn't that much.
Comment: @DanielV means u mean no need of algorithm u purposed down ? thn could u please easy and correct algorithm ?How to check if children are exclusive or not ?
Comment: @user3001932 You need to understand my answer below to solve this problem.  However, once you understand how to build the graph (or adjacency matrix of the graph), then you can use brute force to search all possible valid subsets.  It will take you longer to optimize the algorithm than to actually run it for 20 children.  Given the extreme density of the graph, a smart depth first search of the children will probably finish in a few milliseconds.  Asking for code is considered rude on this site, because it suggests that you are not trying to understand the problem yourself.
Comment: @DanielV i generated adj matrix .What u mean by bruteforce here to search all possible VALID subsets?Can i ask u what u means by SMART DFS ?
Comment: If $C$ is a set of children, and $g(C, x)$ is the subset of $C$ that don't conflict with child $x$, then, and $f(C)$ is the maximum number of children that can be pleased: $f(C) = \max(1 + f(g(cdr\, c, car\, c)), f(cdr\, c))$, this is very fast to compute when $|C|$ is about 20 and your $g(C, x)$ is much smaller than $C$.  (car c is the first child, cdr c is the rest of the children, it's lisp notation)
Answer: Construct a graph as follows:

Each vertex represents a child
Two vertexes share an edge iff the children are exclusive in terms of happiness; that is, if there exists a piece of candy that both children want then they share an edge

Now your problem is to find the maximum number of vertices which do not share an edge.  This is called an "independent set".  Unfortunately, this is NP-Hard.  Solving it exactly is not known in polynomial time, but it is a well studied problem so you have options.
The problem of finding the maximum independent set is the same as the problem as finding the maximum clique in the dual graph, so you may see the problem described that way.
http://en.wikipedia.org/wiki/Maximum_independent_set#Finding_maximum_independent_sets

This is the example from your question.  The 3 vertexes are the circles which represent the 3 children.  The red edge represents that the first and second child both want candy number 2.  The blue edge represents that the second and third child both want candy 3.
The maximum independent set is 1st and 3rd since they do not share an edge.
Comment: Could u please explain how u constructed graph through some example..i didnt get u
Comment: @user3001932 Ok hopefully that helps.
Comment: What would be answer according to u if we have 2 candies and 4 children each demanding for candy no. 1 ?
Comment: Only 1 child can be pleased.  Please don't deliberately misspell words on this website.  It is spelled "you".  Not everyone is a native English speaker, but you should do the best you can.  You aren't the only user here.
Comment: Ohk..Am sorry for mistake .Actually am not able to develop algorithm to do it..:(
Answer: This is a greedy algorithm: you have give the candy that they demand in the order of the amounts that they require to be happy (i.e. K[i]). In other words, you should only give candy to a child if you have made happy all the children that demand less, and every time you give candy to one of them you have to give them the whole amount that they require.
Comment: whats the correctness proof of ur algorithm?
Comment: The actual number of candies they demand is completely irrelevant. What matters is how many (and which) other children they demand.  You could have 50 children demanding 1000 different candies (50000 candies) and 2 children that demand 25 candies each, one from each of the other 50 children.  Obviously you would want to pick the 50 children not the 2.
Comment: @DanielV is it going to be correct always ? Could u please provide some algorithm to do the same
Comment: @user3001932 This approach is not always correct, unfortunately.  My above comment is to provide a counter example.
Comment: @DanielV, this is not a counter example. If you apply the algorithm that I propose, if you have N=50000 candies you would give 25 to each of the 2 children that demand 25 and 1000 to each 49 kids that demand 1000. This would cost you 49050 candies, which you have, and you would make 51 kids happy. Only one of them will be unhappy. If you choose to give the 50000 candies to the 50 kids that demand 1000, you make 50 kids happy and 2 unhappy.
Comment: @jordix I think you are misunderstanding the question.  The candies are unique; they are all different.  You did correctly answer the problem for when the candies are all the same, but that is not what the poster wants unfortunately.

Maximise the happiness among children


Correlations between explanatory variables in regression

Question: I'm just starting to learn about linear regression models and time series analysis and came upon the following doubt.
Suppose we have a variable $Y$ that we're trying to model using $p$ explanatory variables $X_i$, maybe using a simple linear model such as:
$$Y = a_0 + a_1X_1 +...+a_pX_p$$
My question is the following: what happens if the explanatory variables are correlated with each other. In the assumptions for this model, I see no mention of this fact, but clearly there has to be some kind of qualitative difference depending on the degree to which the variables are correlated with each other. For example if $X_1 = X_3 ^2$, then what is the point of including both $X_1$ and $X_3$ in the model, intuitively it seems like the other one carries no additional 'information'?
Perhaps depending on how correlated the variables are one would use a different model or approach?
Comment: Possible duplicate of [What is the effect of having correlated predictors in a multiple regression model?](https://stats.stackexchange.com/questions/86269/what-is-the-effect-of-having-correlated-predictors-in-a-multiple-regression-mode)
Comment: Do not see the relationship to the link as being clear, the question is a bit muddled but colinearity investigation alone is not enough; it is only a starting point, and many other steps are needed and I put in the `ancova` tag to provide some hints on this.
Answer: If $$Y = a_0 + a_1X_1 + a_2X_2 +a_3X_3 +...+a_pX_p\;\&$$ $$X_1=X_3^2$$ then eliminate $X_1$ as it is unnecessary and regress $$Y = a_0 +a_3X_3 + a_1X_3^2 + a_2X_2 +...+a_pX_p$$
However, the example used for the question of how to treat correlated variables was not relevant as the answer to the example is based on the assumption of a perfect correlation, i.e., an equality, that lets us eliminate $X_1$ entirely as perfectly redundant.
Covariates in the analysis of covariance context, i.e., as per the ANCOVA procedure is as follows, assuming that a linear relationship between the response (DV) and covariate (CV) exists:
$$y_{ij} = \mu + \tau_i + \beta (x_{ij} - \overline{x_i}) + \epsilon_{ij}.$$
In this equation, the DV, $y_{ij}$ is the $j^{th}$ observation under the $i^{th}$ categorical group; the CV, $x_{ij}$ is the $j^{th}$ observation of the covariate under the $i^{th}$ group. Variables in the model that are derived from the observed data are $\mu$ (the grand mean) and $\overline{x_i}$ (the $i^{th}$ group mean). The variables to be fitted are $\tau_i$ (the effect of the $i^{th}$ level of the IV), $\beta$ (the slope of the line) and $\epsilon_{ij}$ (the associated unobserved error term for the $j^{th}$ observation in the $i^{th}$ group).
This answer is only partial in the sense that the variations on the theme are numerous, and each circumstance requires special treatment.
Answer: Regressions are pretty good at handling correlations between predictors. In fact that is WHY we use multiple regression instead of doing many many simple correlations.
However. If the correlation is REALLY high, you get something called collinearity. Which means that the two predictors are so correlated that they are essentially the same thing. A real life example of collinearity might be something like waist circumference in inches and jean-size. These are so similar to each other that they are basically measuring the same thing (but not quite).
In the case of collinearity it's preferable to remove one of them. Usually you remove the one with less theoretical reasons to be included.
Answer: In the linear regression, it's preferable to remove correlated variables, otherwise your model would have a very high variance. adding by the correlated variable (X3 in your exemple) will result of opposite estimates forcing your predictions to highly vary : the absolute value of the parameters a1 and a3 would be very close but the signs of these two paramter would be opposite.
Many ways are possible to remove these correlation :

Keep the variable having the most meaning (in the studied subject)
Create a third variable : which represent a linear combination of the two first variables ...
Comment: I am afraid that is not true. There is no "must remove" here. What to do with correlated predictors depends on the underlying scientific question.
Comment: Yes, you're right, there is no "indicated rule" for this (otherwide it would be too easy :p). I think i meant "it's preferable"!
Comment: I think you need to clarify a bit exactly what has high variance in this situation.  It's the estimated parameters, while the predictions do not inherit any variance from correlations.  If the predicted values are of primary importance, correlations are not much of an issue, if the parameters themselves are of interest, then correlations are worth considering.
Comment: +1 for effort. However, the answer is neither correct nor incorrect. It is relevant to the example given in the question, but not to the question itself. To clarify the Q&A confusions I have provided an answer myself.


How can I use tab_parent/tab_root in hook_menu to have one router item appear as a local task for another router item with a different path?

Question: Say I have the path widget/123 to view a widget, and have another path to edit some properties of this widget at admin/acme/widget/123/edit. In hook_menu it looks like I can still have the admin path appear as a local task (tab) by setting the tab_parent and tab_root properties in hook_menu(), but I can't seem to get it to work. I know how to setup widget/%/edit as a local task, but in this case I'm only interested in setting a different "root" path as a local task.
Here's my code:
<?php

function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  // Edit a widget.
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'tab_parent' => 'widget/%',
    'tab_root' => 'widget/%',
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

?>

Am I misunderstanding tab_parent/root, or can this be done?
Update: I was missing a MENU_DEFAULT_LOCAK_TASK. Adding
$items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
);

allows the tabs to appear. However, they don't share the same argument position and so the argument (the widget ID) isn't passed between the two. The 'Edit' tab, for example, links to admin/acme/widget//edit. Is there a way to have different routes like this and pass the argument position around?
Comment: That looks right - but in order to invoke tabs, you need more than one in the parent path. Usually you'd have something like `$items['widget/%/view']` as well, which is a `MENU_DEFAULT_LOCAL_TASK`, and becomes a sibling of the other `MENU_LOCAL_TASK`s under the same parent. At the moment I think the fact you've only got a single local task under the parent means that none will show
Comment: @Clive I wanted to post something similar as an answer, but you are first... only why as a mere comment?
Comment: @Mołot It's just a theory, I haven't had time to check if it's true (sounds logical but this is Drupal, you never know!) Do feel free to put the answer in
Comment: @Clive now when you said that... will need to test :P I'll try to test it tomorrow, no way I'll be able to do this today.
Comment: That's it, Clive! Adding this item solved it: `$items['widget/%/view'] = array('type' => MENU_DEFAULT_LOCAL_TASK, 'title' => 'View');`. If you post your comment as an answer I'll accept it.
Comment: Actually, Clive, the argument isn't available to the 'edit' tab – it just links to admin/acme/widget//edit. Any thoughts there?
Comment: I would add that if you have a loader wildcard (ex. `/admin/%node/view`) in the parent path, you should replace it with normal wildcard (ex.  `'parent_tab' => '/admin/%/view'`)
Answer: If I'm not mistaken the tab_root and tab_parent properties need to point to a path prefix of the router item in question - at least if there are wildcards on the path. The code responsible for this restriction is somewhat convoluted, but what you find when stepping through it is the following:
When generating the tab-links, the _menu_translate function is responsible for replacing the %-wildcards with actual values (node-id, etc). However the replacement values are not computed from the actual object-ids but are derived from the current URL. For example when accessing widget/5, the object-id is on position 1 and therefore when generating tab-links, the value 5 is only injected into paths having the %-wildcard at position 1.
This also leads to another consequence. When navigating to admin/acme/widget/5/edit, you will find that there are no tabs on this page - even if widget number 5 actually exists. This is because when generating the URLs for the other tabs, they will start with widget/acme instead of widget/5 because the value acme is at position 1 in the current path.
If you like to provide tabs on your widget page as well as have it in the backend, then simply duplicate the router item. E.g:
function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  $items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
  );

  // Edit a widget - frontend
  $items['widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  // Edit a widget - backend
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(3, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

If you like to move around stuff from a third-party module, you still can implement additional router-items on behalf of it in a custom module - or even move them using hook_menu_alter.
Comment: Thanks znerol. I ended up doing something similar to this, i.e. duplicating the `widget/%` item, and leaving all other items at the admin path. I think I'll use a `user_access`/`drupal_goto` to send proper users to `admin/acme/widget/%` if they visit `widget/%`.


Using lm for 2-sample proportion test

Question: I have been using linear models to perform 2-sample proportion tests for a while, but have realized that might not be completely correct. It appears that using a generalized linear model with a binomial family + identity link gives exactly the unpooled 2-sample proportion test results. However, using a linear model (or glm with gaussian family) gives a slightly different result. I'm rationalizing that this might be due to how R solves glm for binomial vs. gaussian families, but could there be another cause?
## prop.test gives pooled 2-sample proportion result
## glm w/ binomial family gives unpooled 2-sample proportion result
## lm and glm w/ gaussian family give unknown result

library(dplyr)
library(broom)
set.seed(12345)

## set up dataframe -------------------------
n_A <- 5000
n_B <- 5000

outcome <- rbinom(
  n = n_A + n_B,
  size = 1,
  prob = 0.5
)
treatment <- c(
  rep("A", n_A),
  rep("B", n_B)
)

df <- tbl_df(data.frame(outcome = outcome, treatment = treatment))

## by hand, 2-sample prop tests ---------------------------------------------
p_A <- sum(df$outcome[df$treatment == "A"])/n_A
p_B <- sum(df$outcome[df$treatment == "B"])/n_B

p_pooled <- sum(df$outcome)/(n_A + n_B)
z_pooled <- (p_B - p_A) / sqrt( p_pooled * (1 - p_pooled) * (1/n_A + 1/n_B) )
pvalue_pooled <- 2*(1-pnorm(abs(z_pooled)))

z_unpooled <- (p_B - p_A) / sqrt( (p_A * (1 - p_A))/n_A + (p_B * (1 - p_B))/n_B )
pvalue_unpooled <- 2*(1-pnorm(abs(z_unpooled)))

## using prop.test --------------------------------------
res_prop_test <- tidy(prop.test(
  x = c(sum(df$outcome[df$treatment == "A"]),
        sum(df$outcome[df$treatment == "B"])),
  n = c(n_A, n_B),
  correct = FALSE
))
res_prop_test # same as pvalue_pooled
all.equal(res_prop_test$p.value, pvalue_pooled)
# [1] TRUE

# using glm with identity link -----------------------------------
res_glm_binomial <- df %>%
  do(tidy(glm(outcome ~ treatment, family = binomial(link = "identity")))) %>%
  filter(term == "treatmentB")
res_glm_binomial # same as p_unpooled
all.equal(res_glm_binomial$p.value, pvalue_unpooled)
# [1] TRUE

## glm and lm gaussian --------------------------------

res_glm <- df %>%
  do(tidy(glm(outcome ~ treatment))) %>%
  filter(term == "treatmentB")
res_glm
all.equal(res_glm$p.value, pvalue_unpooled)
all.equal(res_glm$p.value, pvalue_pooled)

res_lm <- df %>%
  do(tidy(lm(outcome ~ treatment))) %>%
  filter(term == "treatmentB")
res_lm
all.equal(res_lm$p.value, pvalue_unpooled)
all.equal(res_lm$p.value, pvalue_pooled)

all.equal(res_lm$p.value, res_glm$p.value)
# [1] TRUE

Answer: It's not to do with how they solve the optimization problems that correspond to fitting the models, it's to do with the actual optimization problems the models pose.
Specifically, in large samples, you can effectively consider it as comparing two weighted least squares problems
The linear model (lm) one assumes (when unweighted) that the variance of the proportions is constant. The glm assumes that the variance of the proportions comes from the binomial assumption $\text{Var}(\hat{p})=\text{Var}(X/n) = p(1-p)/n$. This weights the data points differently, and so comes to somewhat different estimates* and different variance of differences.
* at least in some situations, though not necessarily in a straight comparison of proportions
Answer: In terms of calculation, compare the standard error of the treatmentB coefficient for lm vs. binomial glm.  You have the formula for the standard error of the treatmentB coefficient in the binomial glm (the denominator of z_unpooled). The standard error of the treatmentB coefficient in the standard lm is (SE_lm):
    test = lm(outcome ~ treatment, data = df)
    treat_B =  as.numeric(df$treatment == "B")
    SE_lm = sqrt( sum(test$residuals^2)/(n_A+n_B-2) /
              sum((treat_B - mean(treat_B))^2))

See this post for a derivation, the only difference being that here the sample error is found instead of $\sigma^2$ (i.e. subtract 2 from $n_A+n_B$ for lost degrees of freedom). Without that $-2$, the lm and binomial glm standard errors actually seem to match when $n_A = n_B$.

Using lm for 2-sample proportion test


Rhythmic values don't add up in a variant of Chopin's Nocturne op. 9 no 2?

Question: In the book Chopin: Pianist and Teacher: As Seen by his Pupils I found a fragment which shows 2 variants (at least that's what it looks like to me) of bar 24 of Nocturne op. 9 no 2, presented by Chopin to one of his pupils:

[Here is] a variant [bar 24] often added by Chopin and indicated to me by
Mr Makomaski, a pupil of Tellefsen:

But the problem I'm having is that it seems to me the rhythmical values don't add up in these variants.
For comparison, this is the original bar 24 from the 1st edition of the music score:

You can see it's much shorter than either of the variants and the rhythmic values add up perfectly.
In this book there are also some other modifications/variants of Nocturne op. 9 no 2, but they all look fine, it's only these 2 that I'm having problems with.
Can this be a mistake? Or can it actually happen that the bar is too long (and maybe you're suppose to "squeeze" the notes to fit)?
Comment: I have another question. In the French first edition, why is there an extra note squeezed in beat 5?
Answer: In a cadenza-like passage, the notes are not given in exact rhythm. Instead, one "squeezes them in" or prolongs the measure via rubato. Such passages are often notated with smaller note heads, as is the case in the two variants shown.
Passages like this are common in Chopin. Here's another example from his C# minor Nocturne:

The runs in measures 58 – 60 are indicated as tuplets, but they are not intended to be played in strict metrical cohesion with the left hand. They are played more freely than that. The scales themselves should be more-or-less even, but the musical goal is just that the start and end points should align. In between, the scale itself can increase and decrease in speed, and the left hand, which is the "metronome", can stretch or contract the meter. The specific pacing and alignment is determined by the interpreter.


How can I control the root element namespace and name when serializing an IXmlSerializable object with the data contract serializer?

Question: I have a type that implements IXmlSerializable which I am serializing with DataContractSerializer.  How can I control the root element namespace and name when serializing it as the root element of an XML document?
Say I have the following type:
public partial class PersonDTO : IXmlSerializable
{
    public string Name { get; set; }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        Name = reader["name"];
        if (!reader.IsEmptyElement)
            reader.Skip();
        reader.Read();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteAttributeString("name", Name);
    }

    #endregion
}

If I serialize this with DataContractSerializer as my root object I get:
<PersonDTO name="John Doe" xmlns="http://schemas.datacontract.org/2004/07/MyClrNamespace" />

I want the root name to be <Person> and the root namespace to be "http://www.MyCompany.com", so I tried adding [DataContract] like so:
[DataContract(Name = "Person", Namespace = "http://www.MyCompany.com")]
public partial class PersonDTO : IXmlSerializable
{
}

But when I do, DataContractSerializer throws an exception stating Type 'PersonDTO' cannot be IXmlSerializable and have DataContractAttribute attribute:
System.Runtime.Serialization.InvalidDataContractException occurred
  Message="Type 'PersonDTO' cannot be IXmlSerializable and have DataContractAttribute attribute."
  Source="System.Runtime.Serialization"
  StackTrace:
       at System.Runtime.Serialization.XmlDataContract.XmlDataContractCriticalHelper..ctor(Type type)
       at System.Runtime.Serialization.XmlDataContract..ctor(Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
       at System.Runtime.Serialization.DataContractSerializer.get_RootContract()

I know it is possible to modify the root name and namespace by using the DataContractSerializer(Type type, String rootName, String rootNamespace) constructor when serializing manually:
var person = new PersonDTO { Name = "John Doe", };

var serializer = new DataContractSerializer(typeof(PersonDTO), "Person", @"http://www.MyCompany.com");
var sb = new StringBuilder();
using (var textWriter = new StringWriter(sb))
using (var xmlWriter = XmlWriter.Create(textWriter))
{
    serializer.WriteObject(xmlWriter, person);
}
Console.WriteLine(sb);
// Outputs <Person name="John Doe" xmlns="http://www.MyCompany.com" />

But is there any way to do this automatically via attributes?
Answer: This can be done using attributes in one of two ways.
Firstly (and surprisingly) if you apply the [XmlRoot] attribute for the old XmlSerializer to the type, DataContractSerializer will use the namespace and name specified therein as the root data contract namespace and name:
[XmlRoot("Person", Namespace = "http://www.MyCompany.com")]
public partial class PersonDTO : IXmlSerializable
{
}

Which generates the following XML:
<Person name="John Doe" xmlns="http://www.MyCompany.com" />

However, this solution only applies to the root element name.  If you try to serialize an array or generic list of such objects the unmodified namespace and name are used:
<ArrayOfPersonDTO xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyClrNamespace">
  <PersonDTO name="John Doe" />
</ArrayOfPersonDTO>

Secondly and more powerfully, the [XmlSchemaProvider] attribute can be used to specify a static method that returns a data contract name, namespace and schema for the type:
[XmlSchemaProvider("GetSchemaMethod")]
public partial class PersonDTO : IXmlSerializable
{
    // This is the method named by the XmlSchemaProviderAttribute applied to the type.
    public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
    {
        // Fill in a plausible schema for the type if necessary.
        //
        // While DataContractSerializer will not use the returned schema set,
        // svcutil.exe will use it to generate schemas.  XmlSerializer also
        // seems to require it to be initialized to something plausible if you
        // are serializing your types with both serializers.
        string personSchema = @"<xs:schema xmlns:tns=""http://www.MyCompany.com"" elementFormDefault=""qualified"" targetNamespace=""http://www.MyCompany.com"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
  <xs:element name=""Person"" nillable=""true"" type=""tns:Person"" />
  <xs:complexType name=""Person"">
    <xs:attribute name=""name"" type=""xs:string"" />
  </xs:complexType>
</xs:schema>";
        using (var textReader = new StringReader(personSchema))
        using (var schemaSetReader = System.Xml.XmlReader.Create(textReader))
        {
            xs.Add("http://www.MyCompany.com", schemaSetReader);
        }
        // Return back the namespace and name to be used for this type.
        return new XmlQualifiedName("Person", "http://www.MyCompany.com");
    }
}

This has the advantage that not only will the root name and namespace be modified, but also the data contract name used in arrays, generic collections, and other generics will be as well:
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.MyCompany.com">
  <Person name="John Doe" />
</ArrayOfPerson>

Notes:

DataContractSerializer uses only the XmlQualifiedName returned by the schema provider method.  However, if you plan to generate an XSD for your type using svcutil.exe or also serialize your type with XmlSerializer, you will need to fill in the XmlSchemaSet xs with something plausible.  (And when you do, the XSD generated will reflect the returned schema.)


Tensor product of finite group with group of rational number.

Question: The tensor product of the finitely generated abelian group G with a rational number is zero if and only if G is finite. is it true for any finite group? For example, we take the tensor product of the symmetric group with a rational number. This group is zero or not.
Answer: If $A$ is an Abelian group (written additively), then $A\otimes\Bbb Q=0$
iff $A$ is torsion. Of course, all finite groups are torsion. But if $A$ is non-Abelian, then I'm not sure that $A\otimes \Bbb Q$ makes sense.


Update window every time image gets received

Question: I'm getting images through sockets. Now, I'm actually getting it, but only once as I expected.
I have checked out some classes you can add events to, such as the ImageReader but it wont communicate with my JFrame. When I finalize my frame, it doesn't seem to update at all.
Server:
public static void main(String[] args) {
    try {
        DefaultWindow window = new DefaultWindow();
        window.frame.setVisible(true);

        ServerSocket ss = new ServerSocket(4305);
        Socket cs = ss.accept(); // only 1 client is assumed

        // this bit should be in some sort of complete event
        BufferedImage bi = ImageIO.read(cs.getInputStream());

        window.image.setIcon(new ImageIcon(bi));
        window.frame.validate();
        window.frame.repaint();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

What should I do? What's the best practice?

EDIT 11-11-11 16:19
I have followed mKorbel's answer and it seems to work better, but I'm still getting errors.
My client script:
public static void main(String[] args) {
    try {
        Socket cs = new Socket(InetAddress.getByName("localhost"), 4305);
        OutputStream os = cs.getOutputStream();

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        BufferedImage[] screenshots = new BufferedImage[gs.length];

        DisplayMode mode;
        Rectangle bounds;

        while(true) {
            try {
                for(int i = 0; i < gs.length; i++)
                {
                    mode = gs[i].getDisplayMode();
                    bounds = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
                    screenshots[i] = new Robot(gs[i]).createScreenCapture(bounds);
                }

                if(screenshots[0] != null) {
                    ImageIO.write(screenshots[0], "png", os);
                }
                os.flush();

                Thread.sleep(500);
            } catch (AWTException e) {
            } catch (InterruptedException e) {}
        }
    } catch(IOException e) {}
}

I'm getting an IndexOutOfBoundsException at this line: ImageIO.write(screenshots[0], "png", os); where I write the output to the outputstream.
It seems that the while loop just run 3 times. Why just 3 times? And why does it gives an IndexOutOfBoundsException?

EDIT 11-11-11 16:38
It seems I've sorted it, however, my label won't update. Any idea's?
Server:
public static void main(String[] args) {
    try {
        final DefaultWindow window = new DefaultWindow();
        window.frame.setVisible(true);

        ServerSocket ss = new ServerSocket(4305);
        final Socket cs = ss.accept();

        SwingWorker<ImageIcon, Void> sw = new SwingWorker<ImageIcon, Void>() {
            BufferedImage bi = ImageIO.read(cs.getInputStream());

            BufferedImage bis;
            Graphics2D graphics2D;
            ImageIcon icon = null;

            @Override
            protected ImageIcon doInBackground() throws Exception {
                bis = new BufferedImage(window.image.getWidth(), window.image.getHeight(), BufferedImage.TYPE_INT_ARGB);

                graphics2D = bis.createGraphics();
                graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                graphics2D.drawImage(bi, 0, 0, window.image.getWidth(), window.image.getHeight(), null);
                graphics2D.dispose();

                if(icon != null) {
                    icon.getImage().flush();
                }

                icon = new ImageIcon(bis);
                return icon;
            }

            protected void done() {
                window.image.setIcon(icon);
                window.frame.validate();
                window.frame.repaint();
            }
        };

        sw.execute();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Comment: Is this the client or server?
Comment: This is the server. Notice the `ServerSocket` and the `InputStream` objects. I'll add it anyway
Comment: I see a server accepting connections on port 4035, but I don't see the image being written. Are you getting a valid image in `bi`? Is `window` built on the [event dispatch thread](http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)? An [sscce](http://sscce.org/) might help.
Comment: @trashgod I'm displaying the image in a label (see `window.image.setIcon(icon)`) so there's no need to write anything anywhere. Yeah, the image is valid, because it does show the (first) image (read the question and edit). Finally no, the window is not built on an event dispatch thread.
Comment: `DefaultWindow` is not shown. Swing GUI objects should be constructed and manuipulated _only_ on the [event dispatch thread](http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html).
Answer: because you have some issues with Concurency in Swing, put that to the Background Task

SwingWorker, similair example in the tutorial, in this case is GUI still accesible and doesn't waiting for end of Task(s)
Runnable#Thread, but output to the GUI must be wrapped into invokeLater(), in this case is GUI still accesible and doesn't waiting for end of Task(s)
simple wrap that to the invokeLater(), but in this case is GUI freeze isn't accesible and  waiting for end of Task(s), but this way is wrong, simply don't do that

put your BufferedImage as Icon to the JLabel
Comment: Thanks for your answer, but unfortunately I don't see how this is helping me. Sorry
Comment: @Tim S. hmmm http://stackoverflow.com/questions/8084115/use-of-seticon-on-jlabel-repeats-old-image/8084657#8084657
Comment: I think it's my icon cache. Any solutions for that?
Comment: +1 This definitely needs a separate thread for reading; `SwingWorker` is convenient.
Comment: Okay I tried what you said and so far it works, but now I'm getting IndexOutOfBoundsException on my `ImageIO.write()`, although I'm not sure why... See my updated post


Connecting with local server machine from the internet

Question: I have a MikroTik router with dynamic IP. I also have one of PCs connected to that router via cable. That machine has a TCP socket server program running on it. Previously I was testing the server by connecting from another machine in the same LAN. Now I want to connect with the server from any PC via internet. I tried this and this tutorials. I still can't connect to the server. I currently try to set it all up on Windows 10. I double checked firewalls on both client and server machines.
When the client is trying to connect (via Wi-Fi), the socket fails with an error:

No connection could be made because the target machine actively
  refused it.

The error is API specific (using boost.asio in this case) so probably every other netwokring API would issue some different error.
What I have done:

Login into my router.
IP -> Firewall -> Nat-> Add New:

General:

Action:

The IP in the 'Action' panel comes from ipconfig -> Default Gateway. But I also tried the IP from IPv4 Address line as I am not completely sure which of those should be used.
That's basically it. The client uses the internet IP of the router, which I put into the "Dst.Address" field. And here I also tried to substitute with WAN IP (via http://wanip.info/), which is different from router's internet IP. Again, I am not sure which one should be used. My reason tells me that the WAN IP is not what I should use on the client program as it doesn't take me to the router. Maybe I am wrong. Any help to get this setup working will be highly appreciated.
Answer: First of all, the main reason is that your WAN address is still a private address in the 10.0.0.0/8 subnet which is not routable on the public internet - the reason is that there is a carrier-grade NAT going on, and basically the clients get private IP addresses with the ISP doing the NAT, just like your router, just on a much larger scale. If you want it publicly accessible, maybe you can talk to your ISP about getting a static public IP address, though if they are open to it, they'll probably want you to pay for it.
Secondly, when doing dst-nat, you have to put the target computer (the PC with the server software) address in the "To addresses" field - the idea is that in the "General" section you define what connections to match, and in the "Action" section you define what to do with them (where to send them, in this case.)


How to prove using Ferrer's diagrams?

Question: Using Ferrer's diagrams, show that the number of partitions of $n$ into parts of size 1 or 2 is equal to the number of partitions of $n$ into two parts.
Answer: It isn't: it's equal to the number of partitions of $n$ into at most two parts. The concept that you want is the conjugate of a partition.
Added: Here's the Ferrers diagram of a partition whose parts all have sizes $1$ or $2$:
$$\begin{align*}
&\bullet\bullet\\
&\bullet\bullet\\
&\bullet\\
&\bullet\\
&\bullet
\end{align*}$$
And here is the Ferrers diagram of its conjugate partition:
$$\begin{align*}
&\bullet\bullet\bullet\bullet\bullet\\
&\bullet\bullet
\end{align*}$$
Notice that it has two parts. Here's another example:
$$\begin{align*}
&\bullet\bullet\\
&\bullet\bullet\\
&\bullet\bullet\\
&\bullet\bullet\\
&\bullet\bullet
\end{align*}$$
And its conjugate:
$$\begin{align*}
&\bullet\bullet\bullet\bullet\bullet\\
&\bullet\bullet\bullet\bullet\bullet\end{align*}$$
And one more example:
$$\begin{align*}
&\bullet\\
&\bullet\\
&\bullet\\
&\bullet\\
&\bullet
\end{align*}$$
And its conjugate
$$\bullet\bullet\bullet\bullet\bullet$$
Comment: @aaaaa: Do you see that the conjugate of a partition whose parts have sizes $1$ or $2$ is always a partition with $1$ or $2$ parts, and *vice versa*? Use that relation to define a bijection between the set of partitions with parts of size $1$ or $2$ and the set of partitions into at most two parts.
Comment: And how can I do this?
Comment: @aaaaa: Did you read the material at the link? What does the conjugate of a partition of $n$ into parts of size $1$ and $2$ look like?
Comment: I did, but I don't know how to prove it. I don't have any idea.
Answer: Hint: Change your direction of viewing the diagram.

How to prove using Ferrer's diagrams?


JMSTemplate and recipient list

Question: I've read the documentation and I've seen a similiar question (from late 2005) but it seems no one got an answer. ( http://forum.spring.io/forum/spring-projects/integration/jms/9152-jmstemplate-oracle-jms )
I'm trying to send a message to a Topic using JmsTemplate while specifying the subscriber but either I'm not able to find the correct documentation or I can't find the correct API.
Is it possible to achieve something like this with JmsTemplate?
If you need any additional information please let me know.
Answer: The JMSTemplate high-level methods only support the JMS Standard.
This is an extension to JMS...

Adds Oracle Streams Advanced Queuing specific extensions to javax.jms.TopicPublisher

Sometimes you can handle such extensions with JmsTemplate.execute with a session callback but I think, in this case, you need to create a specific type of session. So, I think you are stuck with rolling your own code.
You could subclass JmsTemplate and override createSession to create the right kind of session; then you can use...
    Boolean result = template.execute(new SessionCallback<Boolean>() {

        @Override
        public Boolean doInJms(Session session) throws JMSException {
            Topic topic = ((AQjmsSession) session).getTopic(...);
            ((AQjmsTopicPublisher) publisher).publish(topic, topicSession.createTextMessage(message),recipientL ist1);
            return true;
        }
    });

JMSTemplate and recipient list


How to calculate the cost of Cholesky decomposition?

Question: The cost of Cholesky decomposition is $n^3/3$ flops (A is a $n \times n$ matrix). Could anyone show me some steps to get this number? Thank you very much.
Answer: Taken from http://www.cs.utexas.edu/users/flame/Notes/NotesOnCholReal.pdf
To analyze complexity for Cholesky decomposition of $n \times n$ matrix,
let $f(n)$ be the cost of decomposition of $n \times n$ matrix
Then,
$f(n) =  2(n-1)^2 + (n-1) + 1 + f(n-1)$ ,  if we use rank 1 update for $A_{22} - L_{12}L_{12}^T$.
But, since we are only interested in lower triangular matrix, only lower triangular part need to be updated which requires approximately $\frac{n}{2} flops$.
So,
$f(n) =  (n-1)^2 + (n-1) + 1 + f(n-1)$
$f(1) = 1$
After solving this you get
$f(n) = \frac{1}{3}n^3 + \frac{2}{3}n$ , which is approximately the total cost of Cholesky decomposition.
Answer: We want to factor $A$ into $R^TR$ where $R$ is upper triangular. The algorithm proceeds as follows.
<code>R = A
for k=1 to m
   for j=k+1 to m
      R_{j,j:m} = R_{j,j:m} - R_{k,j:m} \bar{R}_{kj}/R_{kk}
   R_{k,k:m} = R_{k,k:m}/\sqrt{R_{kk}}
</code>
The line inside the innermost for-loop
<code>      R_{j,j:m} = R_{j,j:m} - R_{k,j:m} \bar{R}_{kj}/R_{kk}
</code>
requires $1$ division, $m-j+1$ multiplications and $m-j+1$ subtractions. Since $j$ runs from $k+1$ to $m$, the cost will be
$m-k$ divisions,
$\left(\displaystyle (m+1)(m-k) - \sum_{j=k+1}^m j \right) = \dfrac{(m-k)(m+k+1)}2$ multiplications and
$\left(\displaystyle (m+1)(m-k) - \sum_{j=k+1}^m j \right) = \dfrac{(m-k)(m+k+1)}2$ subtractions.
Now in the outer loop $k$ runs from $1$ to $m$ costing $(m-1)$ divisions, $\dfrac13m(m^2-1)$ multiplications and $\dfrac13m(m^2-1)$ subtractions.
Hence, the total cost for Cholesky is

$(m-1)$ divisions
$\dfrac13m(m^2-1)$ multiplications
$\dfrac13m(m^2-1)$ subtractions
Comment: R_{j,j:m} = R_{j,j:m} - R_{k,j:m} \bar{R}_{kj}/R_{kk} part is not clear, can you write it in mathematical way instead of programming?
Comment: the total cost you calculated gives us ~ 2m^3/3 not m^3/3
Comment: @ASROMA Usually the multiplications dominate subtraction or addition. So $m^3/3$ multiplications is what is reported usually.
Comment: Since you answered to this question, can you also answer to mine with less programming formulas, try to explain this from mathematical point of view. And you know where is my question asked, thanks... i would really appreciate it. YOU MENTIONED IT AS DUPLICATE
Answer: I found Section 1.6 ("Serial complexity of the algorithm") of the following webpage to be useful for this topic: https://algowiki-project.org/en/Cholesky_decomposition
Edit: Here's the info from that page.

1.6 Serial complexity of the algorithm
The following number of operations should be performed to decompose a matrix of order $n$ using a serial version of the Cholesky algorithm:

$n$ square roots
$\frac{n(n-1)}{2}$ divisions
$\frac{n^3-n}{6}$ multiplications and $\frac{n^3-n}{6}$ additions (subtractions): the main amount of computational work.

In the accumulation mode, the multiplication and subtraction operations should be made in double precision (or by using the corresponding function, like the DPROD function in Fortran), which increases the overall computation time of the Cholesky algorithm.
Thus, a serial version of the Cholesky algorithm is of cubic complexity.


How do I set an image to display from a dropdown menu option?

Question: I'm trying to make a form that displays a movie poster when you select which movie you'd like to see. I wrote a function but I'm new to javascript and something isn't working correctly.
Thanks for any help provided.
JS
function setMovie() {
  var img = document.getElementById("movimg");
  var value = img.options[img.selectedIndex].value;
  var selected = document.getElementById("selectedMovie");
  selected.src = this.value;
  return false;
}
document.getElementById("movieList").onChange = setMovie();

HTML
<select id="movimg" onChange="setMovie(this)">
  <option value="null.png">Select a movie!</option>
  <option value="bvs.jpg">Batman vs. Superman</option>
  <option value="tjb.jpg">The Jungle Book</option>
  <option value="tgf.jpg">The Godfather</option>
  <option value="tpb.jpg">The Princess Bride</option>

</select>

Answer: You were referencing movieList, an id that wasn't there. You also did not need to return false in your function.

var select_box = document.getElementById("movimg"),
    image_box = document.getElementById("selectedMovie");

function setMovie() {
  var value = select_box.options[select_box.selectedIndex].value;
  image_box.src = this.value;
}

select_box.addEventListener("change", setMovie);
<select id="movimg">
        <option value="null.png">Select a movie!</option>
        <option value="bvs.jpg">Batman vs. Superman</option>
        <option value="tjb.jpg">The Jungle Book</option>
        <option value="tgf.jpg">The Godfather</option>
        <option value="tpb.jpg">The Princess Bride</option>
</select>

Comment: Thanks man. movieList existed at one point but i must have missed it :/ thank you though!
Comment: If you're satisfied with my answer, can you accept it?
Answer: You can just change your function to this:
 function setMovie(){
    document.getElementById("selectedMovie").src = document.getElementById("movimg").value;
    }


Why pass a query parameter to an image file (/img/button.png?123456789) from inside a HTML page?

Question: I saw this in a HTML template for a web app:

What I didn't understand was why the ?123456789 would be passed to the image file? (in the actual app, the number that was actually passed seemed to be customized to the user's session or unique id perhaps)
Answer: It forces the browser to skip its cache, and retrieve a fresh copy from the server.
Comment: Yes. That's useful when a website gets a new design for example.
Comment: It forces the browser not to use its own cache?
Comment: But if they change the number at each session, for example, the browser has to load new images every time, which seems like a loss of efficiency for the user and puts more bandwidth strain on the servers.
Comment: That's true. If an image has to be regenerated every time, it should be done in this way. But if it doesn't have to be regenerated every time, then it's an error from the web developer.


use of undeclared identifier 'temp'

Question: The below c++ code gives me error use of undeclared identifier 'temp'
/home/test/include/memory.h
#ifndef MEMORY_H
#define MEMORY_H

#if __ENABLE_MEMORY

__device__ int temp = 50;
extern "C" inline __device__ void* memory(){
     ...
     temp =  temp + 100;
     ...
}

#endif
#endif

/home/test/include/internal_memory.h
#ifndef INTERNAL_MEMORY_H
#define INTERNAL_MEMORY_H

#ifndef __ENABLE_MEMORY
#define __ENABLE_MEMORY 1
#endif

#if __ENABLE_MEMORY
extern "C" __device__ void* memory();
static inline __device__ void* call_memory(){ return memory();}
#endif

#include <memory.h>
#endif

/home/test/main.cpp
 #include "internal_memory.h"
 ..
 .
 .
 void show(){
    std::cout << "temp is: " << temp << std::endl;
 }
 .
 .
 .

I m compiling the code with clang++  version 11.0.0.
clang --version looks as follows:
  clang version 11.0.0
  Target: x86_64-unknown-linux-gnu
  Thread model: posix
  InstalledDir: /opt/rocm/llvm/bin

Im compiling the code as below.
  /opt/rocm/llvm/bin/clang++ -DDEBUG -D__x86_64__ -I/home/test/include -I/home/test -g -fPIC -std=c++14 -o main.o -c main.cpp

what am i missing here.
Answer: Function memory has the __device__ qualifier (I suppose you are compiling a CUDA program).
memory refers to temp, which is a global variable in host memory. You probably want __device__ int temp = 50;
To query temp, you would need to copy its value back to the host. Along the lines of
int host;
cudaMemcpy(&host, &temp, sizeof(int), cudaMemcpyDeviceToHost);

Comment: That's because `temp` is not declared in `internal_memory.h`. You are including a standard C include `memory.h`, when your intention is to probably `#include "memory.h"`. There is a subtle yet very important search path difference between `` and `"memory.h"`
Comment: sorry. i missed that __ device __ part.. edited the question. it gives me the error still.
Comment: You cannot directly read `__device__` variable from a host function `show`. The compiler is right to complain about this. For all intents and purposes, think that `__device__` part and non-`__device__` parts are on different machines entirely.
Comment: Added querying.
Comment: you mean the querying part should be in the host function show.  This part I can understand as host and device parts are different. But even if i add non device variable int temp1 in the same header, and try to access it in show, still i get the error. This is weird.

use of undeclared identifier 'temp'


Proving that $2^{2018}-2^{2016}+2^{2013}$ is divisible by $5$.

Question:
Prove that $2^{2018}-2^{2016}+2^{2013}$ is divisible by $5$.

I'm not sure how do I even start, so may I get help please?
Comment: You mention in a comment to [this answer](https://math.stackexchange.com/a/3641562/409) that "I must not use mod". Information about what you can and cannot use should be included in the body of your question, so that people don't waste time (theirs or yours) on solutions beyond the intended scope of the problem. Also, even when you don't know how to start, you can —and should— provide context to the problem. For instance, if this is a textbook exercise, what specific results were discussed in the current or preceding chapters that you think might be helpful here? etc
Answer: Simply factorise:
$2^{2018}-2^{2016}+2^{2013}=2^{2013}(2^5-2^3+1)=2^{2013}(25)$
Clearly $5 \mid 25$, so you are done.
Answer: Hint
$$2^2\equiv -1\mod 5$$
so, raise it to suitable powers to conclude the result.
Comment: I must not use mod.
Comment: You might also use $$a-b|a^n-b^n$$which yields $$5=4-(-1)|4^n-(-1)^n$$which is essentially the same of the answer.


C++ contiguous memory operation

Question: I have c++ program in which I am calculating determinant of a matrix using normal array which is as follows:
/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

int** generateStandardMatrix(int dimension);
void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column);
int determinant(int *matrix[], int size);

void ijMinor(int *matrix[], int *minorMatrix[], int size, int row, int column) {
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      if (i < row) {
        if (j < column)minorMatrix[i][j] = matrix[i][j];
        else if (j == column)continue;
        else minorMatrix[i][j - 1] = matrix[i][j];
      }
      else if (i == row)continue;
      else {
        if (j < column)minorMatrix[i - 1][j] = matrix[i][j];
        else if (j == column)continue;
        else minorMatrix[i - 1][j - 1] = matrix[i][j];
      }
    }
  }
}

int determinant(int *matrix[], int size) {
  if (size == 1)return matrix[0][0];
  else {
    int result = 0, sign = -1;
    for (int j = 0; j < size; j++) {

      int **minorMatrix;
      minorMatrix = new int*[size - 1];
      for (int k = 0 ; k < size - 1 ; k++)
        minorMatrix[k] = new int[size - 1];

      ijMinor(matrix, minorMatrix, size, 0, j);

      sign *= -1;
      result += sign * matrix[0][j] * determinant(minorMatrix, size - 1);
      for (int i = 0; i < size - 1; i++) {
        delete minorMatrix[i];
      }
    }

    return result;
  }
}

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

  /* initialize random seed: */
  srand (time(NULL));
  // int iSecret, iGuess;
  int dimension = atoi(argv[1]);

  int rowCount = dimension , colCount = dimension;
  //2d array storing the integer values
  int** ary = new int*[dimension];

  //vector of vector storing the indices across the array for the threads to pick up from
  vector<vector<int> > vec;

  ary = generateStandardMatrix(dimension);

  printf("Array value : %d\n", ary[0][0]);
  int detVal = determinant(ary, dimension);
  printf("determinant value : %d\n", detVal);

  return 0;
}

int** generateStandardMatrix(int dimension) {
  int** ary = new int*[dimension];
  int counter = 0;
  for (int i = 0; i < dimension; ++i) {
    ary[i] = new int[dimension];
    counter = counter + 1;
    for (int j = 0; j < dimension; ++j)
    {
      ary[i][j] = counter;
      std::cout << ary[i][j] << "\t" << std::flush;
    }
    std::cout << std::endl;
  }

  return ary;
}

I want to replace it with code in which I allocate memory for the array before the start of the algorithm and then change the determinant and the ijMonor functions so that they don't create new array's but use the same array only.
The determinant will take parameter like: determinant(int *matrix, int *startOfMyWorkspace, int size) so that it knows where to start.
I am not good at c++ and so far I was not able to do it.
Can someone please provide some sample code.
I allocated some memory for array and created and array but was unable to change the ijMinor and determinant functions for that.
This is how I am allocating memory:
int main (int argc, char* argv[])
{

  /* initialize random seed: */
  srand (time(NULL));
  // int iSecret, iGuess;
  int dimension = atoi(argv[1]);

  int *a;
  size_t const N_BYTES = dimension * dimension * sizeof(int);

  a   = (int*)malloc(N_BYTES);

  createData(dimension,a);

  return 0;
}

void createData(int const dimension, int* const a)
{
    int row, col;

    srand((unsigned)time(NULL));
    int counter;
    for(int row = 0; row < dimension; row++) {
      counter = counter + 1;
       for(int col = 0; col < dimension; col++) {
           int i = col + row * dimension;
           a[i] = counter;
          std::cout << a[i] << "\t" << std::flush;
        }
        std::cout << std::endl;
    }
}

Comment: In `createData` function you're not initialising `counter`.
Answer: Try this.
Note if you use new to allocate an array, you need to use delete[] to free all of it. You'll get away with delete (i.e. it won't crash) but this will only free the first element. Your other functions are the same as you posted.
You're dynamically allocating space for minorMatrix in determinant function, but it's hard to see how that could be preallocated. I've modified determinant function to use allocate_arr and deallocate_arr.
int ** allocate_arr(int dimension)
{
    int** a = new int*[dimension];
    for (int i = 0; i < dimension; ++i)
        a[i] = new int[dimension];
    return a;
}

void deallocate_arr(int dimension, int **a)
{
    for (int i = 0; i < dimension; ++i)
        delete[] a[i];
    delete[] a;
}

int determinant(int *matrix[], int size) {
    if (size == 1)return matrix[0][0];
    else {
        int result = 0, sign = -1;
        for (int j = 0; j < size; j++) {

            int **minorMatrix = allocate_arr(size - 1);
            ijMinor(matrix, minorMatrix, size, 0, j);

            sign *= -1;
            result += sign * matrix[0][j] * determinant(minorMatrix, size - 1);
            deallocate_arr(size - 1, minorMatrix);
        }
        return result;
    }
}

void generateStandardMatrix(int dimension, int**ary) {
    int counter = 0;
    for (int i = 0; i < dimension; ++i) {
        counter = counter + 1;
        for (int j = 0; j < dimension; ++j)
        {
            ary[i][j] = counter;
            std::cout << ary[i][j] << "\t" << std::flush;
        }
        std::cout << std::endl;
    }
}

int main(int argc, char* argv[])
{
    srand(time(NULL));

    int dimension = atoi(argv[1]);
    int** a = allocate_arr(dimension);

    generateStandardMatrix(dimension, a);
    printf("Array value : %d\n", a[0][0]);
    int detVal = determinant(a, dimension);
    printf("determinant value : %d\n", detVal);

    // ... do more computations here, reusing `a` ...

    deallocate_arr(dimension, a);
    return 0;
}

C++ contiguous memory operation


How can we use Django property decorator in Django rest framework?

Question: Hello I trying to use Django property decorator in Django rest framework here my code
Model.py
class TempCalculate(models.Model):
    items = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    create_at = models.DateField(auto_now_add=True)
    create_by = models.ForeignKey(User, on_delete=models.CASCADE)

    @property
    def Price(self):
        self.price = (PriceMaster.objects.get(items = self.items)) * self.quantity

Serializer.py
from rest_framework import serializers
from base.models import TempCalculate

class TempCalSerializer(serializers.ModelSerializer):
    class Meta:
        model = TempCalculate
        fields = "__all__"

api/view.py
@api_view(['GET'])
def TempItem(request):
    queryset = TempCalculate.objects.all()
    serializer_class = TempCalSerializer(queryset, many=True)
    return Response(serializer_class.data)

**I trying to access self.price (which I have make property decorator in models.py) in rest api **
Answer: Update your property method in your TempCal model. return self.price from Price property method. Use name of the property method as a serializer Meta fields like this.
class TempCalculate(models.Model):
    items = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    create_at = models.DateField(auto_now_add=True)
    create_by = models.ForeignKey(User, on_delete=models.CASCADE)

    @property
    def Price(self):
        self.price = (PriceMaster.objects.get(items = self.items)) * self.quantity
        return self.price

from rest_framework import serializers
from base.models import TempCalculate

class TempCalSerializer(serializers.ModelSerializer):
    class Meta:
        model = TempCalculate
        fields = ['id', 'item', 'quantity', 'create_at', 'create_by', 'Price']

Also this is not a code breaking mistake but function and variable name should be in lowercase as stated in pep8 naming convension


Deleteing record from MySQL Database after 1 Week

Question: I want to know how to delete records from a MySQL Database after 1 week
This is the code I have for inserting the record and date of when it was added
INSERT INTO moviesdone VALUES ('" . $id2 . "', NOW())

Where $id is the name of what I am insterting and wanting to delete after 1 week.
I would also like to do this automatically, which I can set up from in phpMyAdmin
So, I only need to know: How do I write the date correctly (if needed) and how do I delete the record one week later?
Answer: Run this code at regular intervals, for example once per day:
DELETE FROM moviesdone
WHERE datetimecol < NOW() - INTERVAL 7 DAY

You can use the  event scheduler.
Comment: That will not do it automatically
Comment: @MarkByers: yes there is, you can use an event
Comment: @MarkByers: you just wrote a delete query, he wants to know how to run a delete query automatically, I think that is very different
Comment: @nico And i am also using phpMyAdmin and creating the event, i just needed to know, what i need to execute to do it

MarkByers, Thanks
Answer: If you are using MySQL 5.1.6 or greater you can use CREATE EVENT
Something like
CREATE EVENT del_entries
ON SCHEDULE EVERY 1 DAY
DO
   DELETE FROM table WHERE DATEDIFF(NOW(), creation_date) >= 7;

Comment: good point, although running it once a day on a normal-sized table won't really make a difference.


How to setup a flagging system

Question: I was wondering if someone could point me to the right direction in setting up a flagging/notification system.  I'd say very similar to a tagging system.  If anyone knows of any tutorial or example setups, that would be great.
Purpose
Basically, the flags are to attach to data items including customers, properties, contractors, applications, etc with the role of notifying users of an important piece of info regarding that item.  The flags should come from a predetermined list of items where users can add or remove.
Database
I was thinking about going with a 3 table setup.

flags table: the list of available flags, along with settings determining what those
flags are applicable to (customers, properties, etc).
linking tables indicating a given item has a given flag attached.
the appropriate entities tables

User Interface
I would like some of the functionalities be similar to that of stack overflow's such as the add and removing of tags.  Maybe use jquery tag-it for this?  Mainly, I would like the user to be able to select the flag from a drop down list and a flag icon display when one or more flags have been selected. Mousing over the flag should show a tooltip listing the flags attached to that item. Not sure if this setup of the one flag show all be good for querying purposes as opposed to displaying multiple flags.
Sample visual: http://i232.photobucket.com/albums/ee2/nismomatic97/flag.png
Answer: Your main problem is that you have a flag record for any number of possible different entities, and not a single entity (like "customers.").
In the past, I have solved this problem by providing an additional Foreign Key field in each table ("FlagID") that is unique across the entire database. A GUID is suitable.  Then you can simply JOIN the table that applies to your particular context to the FlagID in your Flags table, and you will get only the flags that apply to that particular entity.
For example, when you JOIN FlagID in the Flags table to the FlagID in your Customers table, you get only those flags that pertain to Customers.
Note that Stack Overflow doesn't have the "Multiple Entities" problem; all flags are cast to Posts.
Comment: used this to design the tables.
Answer: Basically, you need a table with flags and a table with customers/users.
Those table should look like this:
Flags table:

a unique ID of a flag (the easiest way is to set an "ID" field to AUTO_INCREMENT).
flag name
flag description
something more you want

Users table:

a field to store flags (I suggest to store serialized array of flags)
other data you need for other purposes

Other than storing a serialized array, you can make another table where you'd store users' unique ID and flag ID. One row per flag. However, I think the first method is better and more efficient.
Selecting and displaying flags:

select a field that contains serialized array of flags
unserialize the array and use JOIN to select name and description of flags.

Examples
Storing flags to users' profiles:
Let's assume you want to store flags with ID 1, 3, 5 and 7:
$flags = serialize(array(1, 3, 5, 7));
mysql_query("UPDATE `users` SET `flags` = '$flags'") or die(mysql_error());

If you want to edit flags, select the field, unserialize the array and edit it by using Array functions.
Selecting and displaying:
So, you have the array with values of 1, 3, 5 and 7.
Here's an example of creating a SELECT query:
$flags = array(1, 3, 5, 7); // selected from 'users' table and unserialized
$query = "SELECT u.name, f.name, f.description FROM users u INNER JOIN flags f ON ";
$conditions = null;
for($i = 0; $i < count($flags); $i++)
{
    $conditions .= "f.id = $flags[$i] OR ";
}
$conditions = substr($conditions , 0, -4); // removing the last " OR "

$query = $query . $conditions . " WHERE u.name = 'Nikola'";

This is the query we got from the code:
SELECT u.name, f.name, f.description
    FROM users u
    INNER JOIN flags f
    ON f.id = 1 OR f.id = 3 OR f.id = 5 OR f.id = 7
    WHERE u.name = 'Nikola'

It will return all flags along with their names, descriptions and user's name.
All you have to do is to now display the results.

EDIT 1: User Interface
I'm not sure if I understood what you exactly want, but if you want to allow multiple flags per user, I suggest you to make a checkbox for every flag or a select menu with multiple choices rather than drop-down. I think the drop-down is not a good idea, since you can select only one item.
EDIT 2:
You can use the jQuery Autocomplete which is very similar to Stack Overflow's tagging and probably the best choice.
Another idea is that you actually can use the drop-down menus and still allow multiple flags.
Here's the thing: when a user select a flag from drop-down, store a flag in PHP array via AJAX, and store the array in $_SESSION.Example: send request to a PHP file via AJAX, in PHP file read your $_SESSION variable where flags should be stored. If it's empty (no flags yet) - add an array of 1 key. If it isn't empty, read its value (whole array), add new flag to the array and return it to the session variable.
session_start();

if(isset($_POST['id'])) $flagid = $_POST['id']; // previously sent request via AJAX that contains this ID.
if(empty($_SESSION['flags'])) $_SESSION['flags'] = array($flagid); // this is the first selected flag
else
{
    // other tags was selected earlier
    $flags = $_SESSION['flags'];
    $flags[] = $flagid;
    $_SESSION['flags'] = $flags;
}
die("ok");

Now, back in your JS file, check for the returned result. If it's "ok", then proceed, and if it's different than "ok", display an error.
To prevent selecting the same tag multiple times, you can delete it from drop-down by using jQuery (see this question) when user selects it. On some other place on the page, you can display selected flags.
EDIT 3:
You also can use a <select> with "multiple" attribute.
Comment: very helpful answers so far. i'm now working on getting the table designs down!  Will update with results then will be thinking about the UI.
Comment: @ Nikola K. thanks, saw your edit.  Yeh, I agree on the issue with dropdown.  My concern is that if there ends up being a lot of flags for a given entity, checkboxes or menus with multiple choices could clutter the UI.  Still looking into this.
Comment: @sammich Added another method + suggestion about dropdown menus

How to setup a flagging system


React-native: Is there way to listen to Color Scheme (Dark Mode) change?

Question: The official guideline suggests checking if Dark Theme is enabled on each component render. This seems grossly wrong. Is there better way of keeping the dark mode up to date?
Answer: https://github.com/codemotionapps/react-native-dark-mode
This is a library for tracking dark mode.
You can use context in order to pass a theme to all components and adjusting the theme to the mode


Every locally finite collection is also point finite

Question: We are given the following two definitions for a collection $\mathscr{U} = \{U_\alpha\}_{\alpha \in A}$ of subsets of a topological space $X$.

$\mathscr{U}$ is locally finite if every point $x\in X$ has neighborhood that meets finitely many $U_\alpha$

and

$\mathscr{U}$ is point finite if every point $x\in X$ lies in only finitely many $U_\alpha$

My textbook claims that it's apparent that every locally finite collection is also point finite without proof.
However, let's consider the collection of open intervals $\{(n, n+1) : n\in \mathbb{Z}\}$ in $\mathbb{R}$ under the usual topology.
Is this set not locally finite? For any any $r \in \mathbb{R}$, we consider the the neighborhood $U_r = (r-\frac{1}{4}, r+\frac{1}{4})$. Then clearly $U_r$ can only meet at most $2$ of those open intervals. However, this collection is not point finite since $n \in \mathbb{Z}$ is not contained in any of those open intervals.
Where am I going wrong here?
Comment: Your collection **is** point-finite: each real number is contained in either $0$ or $1$ of them, and $0$ and $1$ are both finite.
Comment: @BrianM.Scott Ahhhh, thanks so much.
Comment: You're welcome!
Answer: Your collection is point finite. Each $n\in\mathbb Z$ belongs to zero of those intervals, and therefore the set of intervals to which $n$ belongs is emtpy. And $\emptyset$ is a finite set.
Answer: The omitted prooflet:
Let $\mathcal{U}$ be a locally finite collection.
Let $x \in X$. Then by local finiteness we have $O(x)$,an open neighbourhood of $x$, such that $$\{U \in \mathcal{U}\mid U \cap O(x) \neq \emptyset \}\text{ is finite. }$$
But as $$\{U \in \mathcal{U}: x \in U\} \subseteq \{U \in \mathcal{U}\mid U \cap O(x)\neq \emptyset \}$$ because if $x \in U$ for sure $O(x) \cap U \neq \emptyset$, the former set is also finite and so $\mathcal{U}$ is point-finite. Your example shows that the inclusion can be strict: for $n \in \Bbb N$ the left hand set is finite and the right hand one has 2 elements. Both finite sets. No contraction..
You example family is both locally finite and point finite.


MySQL: Update Record with only one FK record

Question: I have two tables.
Table A has the following:
UserID | ActiveFlag
000001 |    1
000002 |    1
000003 |    1
000004 |    1

Table B:
ID      | UserID    |   CustomerId
1       | 000001    |  10
2       | 000002    |  10
3       | 000002    |  11
4       | 000003    |  11

I want to update the ActiveFlag column in Table A to 0 where users in table B has a CustomerID of 10 and only 10. Meaning that since, in the example, UserID 000002 has two records in Table B: CustomerID 10 and 11. I don't want to update 00002 in table A.
Answer: 10 and only 10
update table a set activeflag = o where a.userid in
(
select b.userid from table b group by b.userid
having min(b.customerid) = max(b.customerid)
and min(b.customerid) = 10
)

Comment: `min(b.customerid) = max(b.customerid)` and min(b.customerid) = 10` is a better mechanism than using `count(distinct)`.  The latter is generally more expensive than other aggregation functions.
Comment: I'll try to remember that @GordonLinoff  I've changed it to be less expensive.  I'm was thinking readability  for answer count(distinct b.customerid) = 1
Answer: exists comes to mind:
update tablea a
     set activeflag = 0
     where a.activeflag <> 0 and
           exists (select 1 from b where b.userid = a.userid and b.customerid = 10) and
           not exists (select 1 from b where b.userid = a.userid and b.customerid <> 10);

Comment: This doesn't exclude the users who have multiple customer IDs.
Comment: @Barmar . . . Thank you for pointing that out.  I've fixed the answer.
Comment: Unfortunately when I tried this it affect 0 rows. Can you explain "select 1" please?
Comment: @slaskwroclaw18 . . . That is used with `exists`, which only counts rows, not columns.  "1" is easy to type.
Answer: Try this:
UPDATE tableA
SET ActiveFlag = 0
WHERE UserID IN (
   SELECT UserID
   FROM tableB
   WHERE CustomerId = 10);

The principle is:

It filters out all UserID with CustomerId = 10 in Table B, i.e. 000001 (ID=1)    and 000002 (ID=2)
Check each UserID  from step 1, set ActiveFlag = 0. i.e. the first two rows in Table A are updated
Comment: Thank you, but would this not update UserID 00002 as well since they have a record in Table B with CustomerID 10? I do not want to update users with multiple CustomerIds even one of them happens to be 10.
Comment: Update only those with `CustomerID` = 10, not the one with `CustomerID` = 11
Comment: But some users have more than one customer ID. It's supposed to update only the users with just one customer ID that's = 10.
Comment: Sure but in table B two records have the same FK of 00002, one each with CustomerID 10 and 11 respectively. So since there is a record in table b with a FK of 00002 and CustomerId 11, UserID 000002 would still be update in table A.
Comment: This will not work.  In OP's example, this will also update UserID 000002.
Comment: Read the question carefully before comment.


Filling a ruby array with a default object

Question: Let's say I have a class Counter in ruby, defined as
class Counter
    attr_accessor :starting_value
    def initialize(starting_value)
        @starting_value = starting_value
    end

    def tick
        @starting_value = @starting_value + 1
    end
end

and I want to fill an array with that object, using a default parameter, like this:
counter_arr = Array.new(5, Counter.new(0))
This is almost what I want, except that I now have an array that contains the same instance of a counter 5 times, instead of an array of 5 new counters. IE when I run the code
counter_arr = Array.new(5, Counter.new(0))
counter_arr[0].tick
counter_arr.each do |c|
    puts(c.starting_value)
end

I output
1
1
1
1
1

instead of
1
0
0
0
0

I was wondering, what is the "ruby-esque" way to initialize an array with multiple new instances of an object?
Comment: Don't forget syntax features like `@starting_value += 1`. That's usually less verbose and avoids typographical errors.
Comment: This code is pretty much line-for-line identical to the example in the ["Common gotchas"  section of the docs for `Array::new`](http://ruby-doc.org/core/Array.html#method-c-new-label-Common+gotchas) which answer this very question.
Answer: One of the first major stumbling blocks people encounter when learning Ruby if they're unfamiliar with a language that uses object reverences pervasively is how these work.
An array is a collection of references to zero or more other objects. These objects are not necessarily unique, and in some cases they are all identical. You are creating such an object here:
counters = Array.new(5, Counter.new(0))

This creates a singular Counter object and populates all 5 slots of the array with it. This comes about because arguments to methods are evaluated once before the method is called. You can test this:
counters.map(&:object_id)

That returns the unique object ID for each object in the array. They'll be random values, each process is different, but they will be identical.
The way to fix this is to use the block initializer:
counters = Array.new(5) do
  Counter.new(0)
end

That doesn't insert the same object, but the result of evaluating that block each time, and since that initializes a new Counter object, the objects will be unique.
One way to tidy this up is to adjust your Counter object to have a sane default:
class Counter
  def initialize(initial = nil)
    @value = initial.to_i
  end

  def tick
    @value += 0
  end
end

This has the advantage of accepting arbitrary values, even those that aren't necessarily the right type. Now Counter.new('2') will work with that value being converted automatically. This is the fundamental principle of Duck Typing. If it can give you a number, it's as good as a number.
Comment: thanks! That code was literally the first 21 lines of ruby I've ever written, so I appreciate all improvements.
Comment: Hope that works out for you. Seems like you're already off and running, which is good to see.
Comment: Very clear answer. Perhaps `def initialize(initial=0); @value = initial; end`.
Comment: @CarySwoveland I try to default to `nil` as sometimes values of that sort sneak through inadvertently. `= 0` gives a sort of false confidence that it will be forced to `0` by default, but it's only `0` if the argument is not specified, a subtle but important distinction.
Comment: You don't want an "inadvertent" `nil` to raise an exception?
Comment: In this case `nil.to_i` produces the desired results, it's acceptable. Likewise for `options = nil` where it expects a Hash if populated. In other cases `nil` could be harmful and you do want it to do that. Depends on the situation.
Answer: Try
counter_arr = Array.new(5) { Counter.new(0) }

Answer: counter_arr = ([-> { Counter.new(0) }] * 5).map &:call

Comment: That's a pretty crazy solution, but it is at least novel.
Comment: Well, first of all I upvoted @tadman's answer, and then I recalled that I'm the "just-out-of-curiosity-clown" here. So: the `Counter` constructor is wrapped withing a `proc` to delay it's execution, than an array of size 1 is created out of this `proc`, then this array is being spread to have 5 elements using `Array#*` and finally it's mapped to actual counters by invoking `proc`s.
Comment: I think the other answers provide cleaner solutions, but I am still curious as to what is going on here
Comment: It is Ursus's answer expressed inside-out.


Ordenar matriz de n linhas tendo como critério o valor da coluna em C

Question: Tenho o seguinte código :
int** ordena(int **v, int tam)
{
   int i, j,aux;
   int swap[3];
   for (i = 0; i > (tam-1); i++){
      aux = i;
      for (j = (i+1); j > tam; j++) {
         if(v[j][1] > v[aux][1]) {
            aux = j;
         }
      }
      if (i != aux) {
         swap[0] = v[i][0];
         swap[1] = v[i][1];
         swap[2] = v[i][2];
         v[i][0] = v[aux][0];
         v[i][1] = v[aux][1];
         v[i][2] = v[aux][2];
         v[aux][0] = swap[0];
         v[aux][1] = swap[1];
         v[aux][2] = swap[2];
     }
  }
return v;

}

Nao estou a perceber porque é que não esta a ordenar pela segunda coluna da matriz. Executo o código e devolve a mesma matriz inicial desordenada pela 2 coluna. A matriz é de 3 colunas por n linhas. E quero ordenar a matriz trocando a linha que esta desordenada em relação a seguinte tendo em conta o valor da coluna 2 de cada linha.
Exemplo
2 3 4
3 7 9
1 1 1
5 2 4
Saída
1 1 1
5 2 4
2 3 4
3 7 9
Answer: O que se passa é que tem erros pequenos nos fors e ifs, que eu suspeito que sejam distrações:
for (i = 0; i > (tam-1); i++){
//------------^ aqui tem de ser <
  aux = i;
  for (j = (i+1); j > tam; j++) {
  //----------------^ e aqui também <
     if(v[j][1] > v[aux][1]) {
     //---------^ aqui também < para ter a ordenação do menor para o maior
        aux = j;
     }
  }

Com essas alterações já funciona como pretende.
Veja no Ideone
Deixo no entanto a nota de que o retorno de int** que tem não faz sentido pois a função altera o array recebido diretamente, e retornar o array de entrada em nada adianta. Por este motivo o tipo de retorno devia ser void.


GIT merge develop into feature branch -- after the same branch was merged and reverted

Question: I am in a pretty sticky situation with a merge, I hope someone can help me.
A feature branch was merged into develop some time ago, all good.
Because that feature was not required for a release, the merge was reverted.
In the meantime some more feature branches were merged into develop.
Now, it is time to re-merge the same feature branch into develop.
As expected, when I try to do that, git will notice that my changes were deleted, so it automatically deletes those files/changes that were part of the original merge in my local feature branch.
Is there a way to fix this: merge/rebase develop into my feature branch, but keeping all my changes?
Answer: Ok, it was easier than I thought:

updated local develop with git pull
found the ref of the revert commit with git log, copied
reverted that with git revert <ref_here>, my local develop is pre-revert now
git checkout to my feature branch, and finally git merge develop.


Two sample t-test to show equality of the two means

Question: Given two (numeric) samples I would like to show that there is not a significant difference between the two means $\mu_{1}$ and $\mu_{2}$.
If my goal was to show a significant difference I would formulate the $t$-test as follows:
(1) $H_{0}: \mu_{1} = \mu_{2}$ vs $H_{1}: \mu_{1} \neq \mu_{2}$
I learned in school that the null hypothesis should always represent the "common" belief and the alternative hypothesis should represent the change that I would like to show.
So then if my goal is to show that there is not a significant difference between both means, should I formulate the test like this?
(2) $H_{0}: \mu_{1} \neq \mu_{2}$ vs $H_{1}: \mu_{1} = \mu_{2}$
Or can I use the first test (1) and when I am not able to reject the null hypothesis say that there is not a significant difference?
Comment: The alternative hypothesis indicates what an extreme result might look like.  The problem with your (2) formulation is that this would be a difference in means close to $0$; so if you took a commonly used significance level of $5\%$ then the power of the test (its ability to reject the null hypothesis when it is false) would never be above $5\%$ no matter how large the sample size.  This is not good
Comment: "I learned in school that the null hypothesis should always represent the "common" belief and the alternative hypothesis should represent the change that I would like to show." Then you were taught to commit to [confirmation bias](https://en.wikipedia.org/wiki/Confirmation_bias) as a mode of scientific inquiry.
Answer: You cannot use the first test in the way you describe, because failure to reject in the first test only says that you were unable to reject $H_0$ nothing more than that. It is like only being given the information that "the prosecutor was unable to provide the jury with enough evidence to secure a conviction" - that does not tell you that the suspect is innocent.
The second test is not usable in practice, because no matter how much data you have, you cannot exclude the possibility of very small differences.
What you can do is to look at
$$H_{0}: |\mu_{1} - \mu_{2}|>\delta \text{ vs  }H_{1}: |\mu_{1} - \mu_{2}| \leq \delta,$$
i.e. try to reject the null hypothesis that the absolute size of the difference is greater than some difference $\delta>0$. $\delta$ would be chosen e.g. so that any difference smaller than that is for all (or your specific) practical purposes irrelevant.
Comment: Not quite, you look in both directions, i.e. do two one-sided tests (https://en.wikipedia.org/wiki/Equivalence_test). Formulae for these are given e.g. here http://ncss.wpengine.netdna-cdn.com/wp-content/themes/ncss/pdf/Procedures/PASS/Non-Inferiority_Tests_for_Two_Means_using_Differences.pdf.
Comment: Thanks! How would I then go about computing the test statistic? t = (x1 - x1 - delta) / sqrt(s1^2/n1 + s2^2/n2) ?
Comment: Note that we have a considerably informative tag on [two one-sided tests](https://stats.stackexchange.com/tags/tost/info) here. That's what the **[tost]** tag is for. :)
Answer:
I learned in school that the null hypothesis should always represent the "common" belief and the alternative hypothesis should represent the change that I would like to show.

That is not accurate explanation of the null hypothesis. The null hypothesis is simply a hypothesis that consists of a specific distribution from which probabilities can be calculated. The reason we use $\mu_1=\mu_2$ as the null hypothesis has nothing to do with whether this is the "common" belief. It's used as the null hypothesis because if we hypothesize that the mean is a specific value, then given a particular set of data we can calculate the probability of seeing that data. We can't use $\mu \neq \mu_2$ as our null hypothesis because there's no way to calculate p-values based simply on the hypothesis that the means aren't equal to a particular value. Consider the following problem:

The weights of apples have a standard deviation of 5 grams. The mean is not equal to 100. What is the probability of seeing an apple with a weight of 110 grams?

There's no way to answer that, because simply being told what the mean isn't is not enough to calculate probabilities.
Björn suggests testing the hypothesis that the difference in means is greater than some $\delta_0$. How that would work is to take the null hypothesis as that the difference is equal to exactly $\delta_0$. Then once you have the data, you can calculate the p-value given that $\delta_0$. Call that $p_{\delta_0}$. If the difference in sample means is less than $\delta_0$, then the the p-value would have been even smaller than $p_{\delta_0}$ if we had chosen $\delta$ to be larger than $\delta_0$. We reject the null if the p-value is less than $\alpha$, so if we're rejecting under that null, that means that $p_{\delta_0} < \alpha$. And since $p_{\delta}<p_{\delta_0}$ for any $\delta>\delta_0$, we can conclude that $p_{\delta}<\alpha$ for any $\delta>\delta_0$. Thus, we can not only reject this null of $\delta_0$, but we can reject any null with a larger $\delta$. It is only because of this ability to get an upper bound on p that we don't need a specific value for $\delta$. If we just take "$\delta$ is larger than zero" as our null hypothesis, without any lower bound for $\delta$, then there is no upper bound for p, and so we cannot conclude that it is lower than $\alpha$.
Comment: You seem quite confused about how two one-sided tests for equivalence work: "How that would work is to take the null hypothesis as that the difference is equal to exactly $\delta_{0}$." is not remotely close to these procedures.
Comment: @Alexis That is the rigorous mathematical theoretical foundation of the process. Certainly, there are people doing statistics in the field that are not engaging in full rigor.


Mostrar atributo específico no Select usando Python e Django

Question: Em models.py criei as seguintes tabelas:
class UsuarioAdicionalPlano(models.Model):
    quantidade = models.PositiveIntegerField(primary_key=True)
    preco = models.DecimalField(decimal_places=2, max_digits=13)

class ConfiguracoesDoPlano(models.Model):
    plano = models.ForeignKey('login.Plano', related_name='plano', on_delete=models.CASCADE)
    usuarios_adicional = models.ForeignKey('login.UsuarioAdicionalPlano', related_name='usuario_adicional', on_delete=models.CASCADE)

Em forms.py
class ConfiguracoesDoPlanoForm(forms.ModelForm):
    class Meta:
        model = ConfiguracoesDoPlano
        fields = ('plano', 'notas_adicional', 'usuarios_adicional')
        widgets = {
            'plano': forms.Select(attrs={'class': 'form-control'}),
            'usuarios_adicional': forms.Select(attrs={'class': 'form-control'}),
    }
        labels = {
            'plano': 'Plano escolhido',
            'usuarios_adicional': 'Usuários adicionais',
    }

E no arquivo .html tenho o seguinte Select
O form vem de ConfiguracoesDoPlanoForm da tabela ConfiguracoesDoPlano

    {{form.usuarios_adicional.label}} *
       {% if form.usuarios_adicional.errors %}{% for error in form.usuarios_adicional.errors %}{{error}}{% endfor %}{% endif %}

           {{form.usuarios_adicional}}

Porém o meu select está aparecendo com os valores 'UsuarioAdicionalPlano object (0)' , 'UsuarioAdicionalPlano object (1)', e assim por diante.

Como eu faço para que os valores do Select sejam o valor do atributo quantidade?
Answer: isso não esta relacionado a função __str__ da classe? Tente declarar a função __str__ retornando a saída que você quer no modelo UsuarioAdicionalPlano, algo parecido com isso:
def __str__():
   return this.quantidade

Comment: Funcionou usando a função `def __str__(self): return str(self.quantidade)`


Attachment_fu: how can I selectively prevent thumbnail creation?

Question: I'm happily using attachment_fu to handle file uploads and thumbnail creation.  However, for some (but not all!) cases I would like to suppress the creation of thumbnails.
How would I hack attachment_fu to do this?
Specifics: I have a traditional attachment_fu model
class Pic < ActiveRecord::Base
  has_attachment :content_type => :image, :storage => :s3, :resize_to => '200x600>',
                 :thumbnails => { :thumb48 => [48,48],
                                  :thumb32 => [32,32],
                                  :thumb22 => [22,22] }
  validates_as_attachment
end

The user specifies the file to be uploaded in a form using a file input, and submits the form to an action where the pic is created using
@pic = Pic.new(params[:pic])

In certain cases I'd like to be able to do something like
@pic = Pic.new(params[:pic], {:generate_thumbnails => false})

and prevent the thumbnails from being generated.
Answer: interesting question.
have you thought about just not displaying the thumbnails for certain pics?   or is storage a concern?
another option would be to create two models - one called Pic which doesn't define any thumbnails and then one called PicWithThumbs, which extends the Pic class, and does define thumbnails.
Then in your controller you could do an 'if' statement that checked the params for a value called 'create_thumbs' (boolean) - if :create_thumbs is true, then create an instance of PicWithThumb, else create a Pic
I know, it smells a little, and I'm a bit of a noob, so feel free to shoot me down.  I'm interested in seeing what the best solution is though...
Comment: Totally reasonable suggestion, but it doesn't work for my particular application -- I'm trying to supply the thumbnails from another source for certain pics rather than creating them first using the default method and then having to overwrite them.
Answer: I'm not sure about attachment fu, but in paperclip you can stop thumbnail generation by returning false in before_post_process, in attachment fu perhaps you could do a similar thing in the process_attachment callback?