Exercise 1.1.7 of Dummit and foote . Is $G$ a group?

Question: This question is from "Abstract Algebra" by Dummit and Foote , third edition , page 21 , exercise 1.1.7 .

Let $G = \{ x \in \mathbb R | 0 \leq x < 1 \}$ and for $x,y \in G$ let $x*y$ be the fractional part of $x + y$. (i.e, $x*y = x + y - [x + y]$ where  $[a]$ is the greatest integer less than or equal to $a$).Prove that $*$ is a well defined binary operation on $G$ and that $G$ is an abelian group under $*$ (called the real number mod $1$)

In that exercise , I am asked to prove that $G$ is a group . However , I could not find the identity of the group at all . $0$ seems to not be the identity , because .
If $x \in G$ then $x*0 = 0*x = x + 0 - [x + 0] = x - [x] = x - x = 0$
Can someone tell me what I am doing wrong?
Comment: Please type the question. Everybody does not have access to the book
Comment: @Clayton ok I will do it .
Comment: Thank you for writing out the question, Prithu!
Answer: Note that $[x]$ is the greatest integer function. So $[x] = 0$ for all $x \in G$ as in question. Note that $G$ was the interval $[0, 1)$.
Comment: can you also show me that "all the elements of $G$ has inverses"?
Comment: @Prithubiswas: You want to show that given any $x \in G$, there's some $y$ such that $x + y - [x + y] = 0$ or $$x + y = [x + y].$$ Do you know when a real number (here $x + y$) is equal to the greatest integer below it?
Comment: @Prithubiswas Another hint, Which are the integers you can get with the sum of $x+y$?


int cannot be dereferenced. Databinding binary operators

Question: I have "int cannot be dereferenced" error when I try setup flag using binary operator inside layout using databinding.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/tools">

    <data>
        <variable
            name="textState"
            type="java.lang.Integer"/>
    </data>
        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/checkbox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Text"
            app:paintFlags="@{checkbox.getPaintFlags() | textState.intValue()}"/>
</layout>

Answer: This order checkbox.getPaintFlags() | textState.intValue() of binary operands is interpreted as ((int)checkbox).getPaintFlags() and it's cause of the error.
But! If your invert order of operands it interpreted properly. And it works!
I was wondered when I find out this feature


Adding more disks to Storage Spaces Direct didn't give me the capacity increase I was expecting

Question: I have S2D setup using 2 Azure VMs in a mirror. When I originally set it up, I did so following the instructions here: https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/rds-storage-spaces-direct-deployment
This worked great with no problems. When I set it up, I chose to use 128GB datadisks. With 2 disks on each vm, I had 252GB of capacity in my volume.
Now I'm coming back to this set up and I wanted to add more capacity. I added a 1023GB datadisk to each vm. Waited for the storage pool to automatically add them, which it did. Then I tried to Resize my virtual disk using the information here: https://docs.microsoft.com/en-us/windows-server/storage/storage-spaces/resize-volumes
When looking at my Storage pool in the "Failover Cluster Manager" it indicated that I had 2.00 TB of free space. I assumed I could only use half of that, so my new capacity should be approximately 1.2 TB when combined with my original capacity.
When I ran the "Resize-VirtualDisk" powershell command it told me there wasn't enough available capacity. So then I started just reducing the size and finally got it to work if I resized to 500GB.
So adding 2 x 1TB disks only gave me an extra 250GB of capacity. Why is this? I've been trying to figure out and understand how this all works, but I can't find a definitive answer.
Answer: TLDR: try adding disks of the of the initial size.

It sounds like you are stranding your data. Storage Spaces Direct (S2D) is intelligent and can reclaim the data if with the right combination of extra nodes, for example, it has this sort of cleverness:

It acts playfully depending on its nodes/constraints. Simply adding a fourth node would seem to strand space, but actually allow for a mass reshuffling.
Related, you are creating reserve capacity (whatever you find unusable on your new 1 TiB disks). S2D has some extra intelligence here in that it will use this unclaimed space to reallocate bad sectors on the same disk(s).
Since you are doing this in the cloud though, I wouldn't worry about this stuff if you have read your SLA; just follow the docs and let Azure worry about bitrot. But if you are doing this on premises, it's definitely worth considering.


Logging into Drupal from an external application

Question: I am currently using the services module and some custom code to delete, login and edit drupal users from an external application. I can currently login as a user on the external application but I am only logged on in the code and not the actual browser. Meaning that I can perform actions with the authenticated account in the code but when I visit my drupal website through the browser, I am not logged in. I want my users to be logged into drupal when they log into my external application. How can I do this?
Answer: You can use the form API to write a custom function for validating authentication. Something like this (this is from Drupal 7, but for 6 you have the same logic and the API is not very different). The code here is from a module I've wrote to authenticate users from an IP.Board (a forum software) database:
<code><?php
/**
 * @file
 * Allow Drupal 7 to use IP.Board members table for authentication
 *
 * Some code is based on this nice tutorial http://www.touchnoc.com/node/86
 */

/**
 * Alter the user login block form
 */
function ipbridge_form_user_login_block_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Alter the user login page
 */
function ipbridge_form_user_login_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Change the validate callback
 */
function _ipbridge_user_login_form_alter(&$form, &$form_state) {
  $k = array_search('user_login_authenticate_validate', $form['#validate']);
  $form['#validate'][$k] = 'ipbridge_authenticate_validate';
}

/**
 * Custom validation
 */
function ipbridge_authenticate_validate($form, &$form_state) {

  // try normal validation first
  user_login_authenticate_validate($form, $form_state);
  if ($form_state['uid'] !== FALSE)
    return;

  // still here? Try to find the user in IP.Board
  $name = $form_state['values']['name'];
  $pass = $form_state['values']['pass'];

  $records = db_select('ibf_members', 'u', array('target' => 'ipb'))
  ->fields('u', array('member_id', 'name', 'members_pass_hash', 'members_pass_salt', 'email'))
  ->condition('u.name', $name, '=')
  ->execute();

  if ($records->rowCount() == 1) {

    $ipbUser = $records->fetchObject();

    // this is how IPB generates the pasword hash
    $hash = md5(md5($ipbUser->members_pass_salt) . md5($pass));

    if ($hash == $ipbUser->members_pass_hash) {

      // based on Drupal's user_external_login_register (that function doesn't set the email address)
      $account = user_external_load($name);
      if (!$account) {

        $userinfo = array(
          'name' => $name,
          'mail' => $ipbUser->email,
          'pass' => user_password(),
          'init' => $name,
          'status' => 1,
          'access' => REQUEST_TIME,
        );

        try {
          $account = user_save(drupal_anonymous_user(), $userinfo);
        } catch (Exception $e) {
          drupal_set_message(t('Are you trying to login using an IP.Board username that was previously registered in Drupal? Caught exception: ' . $e->getMessage()), 'error');
        }

        if (!$account) {
          drupal_set_message(t("Error saving IPB account."), 'error');
          $form_state['uid'] = FALSE;
          return;
        }
        user_set_authmaps($account, array("authname_ipbridge" => $name));
      }

      $form_state['uid'] = $account->uid;
    }
  }
}
?>
</code>
Comment: This is part of what I want to do but the other part is logging into drupal whenever someone logs into the external app
Comment: If you want to handle this in a Drupal module you need to have the user registered in Drupal (the code I've sent you does this) and then check if the user is logged in your application and call user_external_load() and user_external_login(). Check http://api.drupal.org/api/drupal/modules--openid--openid.module/6/source for an example. If you don't have any way to check in a Drupal module if the user is authenticated in your external application, then this is another approach that can be used on your application side: http://www.mugginsoft.com/content/automatically-log-authenticated-drupal-user
Comment: I tried the second option but it only authenticates for 1 page


Is there a way to use the covariance matrix to find coefficients for multiple regression?

Question: For simple linear regression, the regression coefficient is calculable directly from the variance-covariance matrix $C$, by
$$
C_{d, e}\over C_{e,e}
$$
where $d$ is the dependent variable's index, and $e$ is the explanatory variable's index.
If one only has the covariance matrix, is it possible to calculate the coefficients for a model with multiple explanatory variables?
ETA:
For two explanatory variables, it appears that $$\beta_1 = \frac{Cov(y,x_1)var(x_2) - Cov(y,x_2)Cov(x_1,x_2)}{var(x_1)var(x_2) - Cov(x_1,x_2)^2} $$
and analogously for $\beta_2$. I'm not immediately seeing how to extend this to three or more variables.
Comment: The coefficient vector $\hat{\beta}$ is the solution to $X'Y=(X'X)^{-1}\beta$. Some algebraic manipulation reveals that this is in fact the same as the formula you give in the 2-coefficient case. Laid out nicely here: http://www.stat.purdue.edu/~jennings/stat514/stat512notes/topic3.pdf. Not sure if that helps at all. But I'd venture to guess that this is impossible in general based on that formula.
Comment: @JaneWayne I'm not sure I understand your question: whuber gave the solution below in matrix form, $C^{-1}(\text{Cov}(X_i, y))^\prime$
Comment: yup I studied it and he's right.
Comment: @David Did you figure out how to extend this to an arbitrary number of explanatory variables (beyond 2)? I need the expression.
Answer: Yes, the covariance matrix of all the variables--explanatory and response--contains the information needed to find all the coefficients, provided an intercept (constant) term is included in the model.  (Although the covariances provide no information about the constant term, it can be found from the means of the data.)

Analysis
Let the data for the explanatory variables be arranged as $n$-dimensional column vectors $x_1, x_2, \ldots, x_p$ with covariance matrix $C_X$ and the response variable be the column vector $y$, considered to be a realization of a random variable $Y$.  The ordinary least squares estimates $\hat\beta$ of the coefficients in the model
$$\mathbb{E}(Y) = \alpha + X\beta$$
are obtained by assembling the $p+1$ column vectors $X_0 = (1, 1, \ldots, 1)^\prime, X_1, \ldots, X_p$ into an $n \times p+1$ array $X$ and solving the system of linear equations
$$X^\prime X \hat\beta = X^\prime y.$$
It is equivalent to the system
$$\frac{1}{n}X^\prime X \hat\beta = \frac{1}{n}X^\prime y.$$
Gaussian elimination will solve this system.  It proceeds by adjoining the $p+1\times p+1$ matrix $\frac{1}{n}X^\prime X$ and the $p+1$-vector $\frac{1}{n}X^\prime y$ into a $p+1 \times p+2$ array $A$ and row-reducing it.
The first step will inspect $\frac{1}{n}(X^\prime X)_{11} = \frac{1}{n}X_0^\prime X_0 = 1$.  Finding this to be nonzero, it proceeds to subtract appropriate multiples of the first row of $A$ from the remaining rows in order to zero out the remaining entries in its first column.  These multiples will be $\frac{1}{n}X_0^\prime X_i = \overline X_i$ and the number subtracted from the entry $A_{i+1,j+1} = X_i^\prime X_j$ will equal $\overline X_i \overline X_j$.  This is just the formula for the covariance of $X_i$ and $X_j$.  Moreover, the number left in the $i+1, p+2$ position equals $\frac{1}{n}X_i^\prime y - \overline{X_i}\overline{y}$, the covariance of $X_i$ with $y$.
Thus, after the first step of Gaussian elimination the system is reduced to solving
$$C_X\hat{\beta} = (\text{Cov}(X_i, y))^\prime$$
and obviously--since all the coefficients are covariances--that solution can be found from the covariance matrix of all the variables.
(When $C_X$ is invertible the solution can be written $C_X^{-1}(\text{Cov}(X_i, y))^\prime$.  The formulas given in the question are special cases of this when $p=1$ and $p=2$. Writing out such formulas explicitly will become more and more complex as $p$ grows. Moreover, they are inferior for numerical computation, which is best carried out by solving the system of equations rather than by inverting the matrix $C_X$.)
The constant term will be the difference between the mean of $y$ and the mean values predicted from the estimates, $X\hat{\beta}$.

Example
To illustrate, the following R code creates some data, computes their covariances, and obtains the least squares coefficient estimates solely from that information.  It compares them to the estimates obtained from the least-squares estimator lm.
#
# 1. Generate some data.
#
n <- 10        # Data set size
p <- 2         # Number of regressors
set.seed(17)
z <- matrix(rnorm(n*(p+1)), nrow=n, dimnames=list(NULL, paste0("x", 1:(p+1))))
y <- z[, p+1]
x <- z[, -(p+1), drop=FALSE];
#
# 2. Find the OLS coefficients from the covariances only.
#
a <- cov(x)
b <- cov(x,y)
beta.hat <- solve(a, b)[, 1]  # Coefficients from the covariance matrix
#
# 2a. Find the intercept from the means and coefficients.
#
y.bar <- mean(y)
x.bar <- colMeans(x)
intercept <- y.bar - x.bar %*% beta.hat

The output shows agreement between the two methods:
(rbind(`From covariances` = c(`(Intercept)`=intercept, beta.hat),
       `From data via OLS` = coef(lm(y ~ x))))

                  (Intercept)        x1        x2
From covariances     0.946155 -0.424551 -1.006675
From data via OLS    0.946155 -0.424551 -1.006675

Comment: Answers like this raise the bar of this Cross Validated
Comment: Thanks, @whuber!  This is exactly what I was looking for, and my atrophied brain was unable to get to. As an aside, the motivation for the question is that for various reasons we essentially do not have the full $X$ available, but have `cov(z)` from previous calculations.
Comment: @Migwell On the contrary, Gaussian elimination is a perfectly legitimate mathematical argument, albeit a little unusual in this context.  Plenty of proofs--especially in discrete mathematics, combinatorics, optimization, and computational geometry (to name a few areas of mathematics important in statistical applications)--amount to applying "just one method" of solving numerical problems.  There is no inherent distinction between "mathematical" and "computational" forms of reasoning.
Comment: @whuber In your example, you computed the intercept from `y` and `x` and `beta.hat`. The `y` and `x` are part of the original data. Is it possible to derive the intercept from the covariance matrix and means alone? Could you please provide the notation?
Comment: @Jane Given only the means $\bar X$, apply $\hat \beta$ to them:  $$\overline X \hat\beta = \overline{X \hat\beta}.$$ I have changed the code to reflect this.
Comment: very helpful +1 for the code
Comment: I think some confusion is caused (it was certainly the case for me) by the use of the full covariance matrix $C$ which (as far as I can tell) the OP is using to indicate the co-variance matrix $Cov([\textbf{X,y}],[\textbf{X,y}])$, while here $C$ seems to represent covarinace matrix for Xs only, i.e. $Cov(\textbf{X},\textbf{X})$.
Comment: @Confounded Could you suggest any way to improve the first sentence of my answer, then, which was intended to resolve that potential for confusion?
Comment: The first sentence is fine as it is; perhaps you might want to change the notation in the main part from $C$ to $C_{e,e}$ as used in the OP to indicate that it is a covariance matrix of the "explanatory" variables.
Comment: @Confounded That's an excellent idea, thank you.  I see I didn't even define my "$C.$"  I have elected to call it $C_X,$ though, because that seems a better mnemonic for connecting it to the variables $X.$
Comment: I wonder if the paragraph about subtracting the mean terms $\bar{X}\bar{X}$ could be written in such a way that it explains *mathematically* rather than *computationally* how the first expression is equivalent to the covariance expression. Gaussian elimination isn't a good argument because that's just one method of solving linear equations.
Answer: The answer above is complete and great. The following aims to complement the answer with a different perspective. I also want to bring attention to the fact that using covariances to estimate coefficients you are implicitly assuming there exists a constant factor on you regression, even if you don't calculate it.
Consider the model:
$$
Y = 1\alpha + X^T\beta + e
$$
Where $1$ is a vector of ones and $X^T$ is a matrix of observable variables. There are $N$ rows.
We can use Frisch-Waugh-Lovell theorem. Consider the projection matrix:
$$
M = I - 1(1^T1)^{-1}1^T
$$
Then, by FWL, $\beta$ vector can then be retrieved by estimating with the orthogonal components:
$$
MY = MX^T \beta + Me
$$
$$
(I - 1(1^T1)^{-1}1^T)Y = (I - 1(1^T1)^{-1}1^T)X^T \beta + Me
$$
Now you need to realize that $(1^T 1)^{-1} = 1/N$ and $1^T Y$ just sums all values, for example:
$$
(1^T 1)^{-1} 1^T Y = \frac{1}{N} \sum_i^N y_i = E(Y)
$$
The above expression can be rewritten as:
$$
(Y - 1E(Y)) = (X^T - 1 E(X^T)) \beta + Me
$$
That is, this projection matrix $M$ is demeaning $Y$ and $X$. Consider writing the above expression as:
$$
\tilde{Y} = \tilde{X}^T \beta + \tilde{e}
$$
And we know that OLS estimates are calculated with:
$$
\beta = (\tilde{X}'\tilde{X})^{-1} \tilde{X}' \tilde{Y}
$$
$$
\beta = [(X^T - 1 E(X^T))' (X^T - 1 E(X^T)]^{-1} (X^T - 1 E(X^T))' (Y - 1E(Y))
$$
$$
\beta = Cov(X)^{-1} Cov(X,Y)
$$


study objects of convex analysis and optimization

Question: In the area of convex analysis and the area of optimization in their general sense, are convex subsets assumed to be in vector spaces or topological vector spaces? Are convex functions defined to be from convex subsets in vector spaces or topological vector spaces to general field or some special field such as $\mathbb{R}$ or $\mathbb{C}$?
Now instead of considering the general sense, what are the special cases that have been extensively studied and have significance in application?
Thanks and regards!
Answer: Q1: Are convex subsets assumed to be in vector spaces or topological vector spaces?
Convex sets are easily defined in topological vector spaces over a subfield of $\mathbb{C}$, following the usual definition: $A$ is a convex set if $\forall x,y\in A$ we have $tx+(1-t)y\in A$ for $t\in[0,1]$. Basically means we can draw a line between any two points and the line segment is contained in $A$.
For non-euclidean spaces convexity generalises to geodesically convex set see "Convex functions and optimization methods on Riemannian manifolds" by Constantin.  There are a few other generalisations. For the most abstract there are Convexity spaces which is an axiomatic description but I can't remember much about this.
Q2: Are convex functions defined to be from convex subsets in vector spaces or topological vector spaces to general field or some special field such as R or C?
Firstly I have seen a convex function defined without the need for its domain to be a convex set at all! It required the function to only be convex on any convex subset of its domain. (I don't think is standard though.)
Secondly, let $f:I\rightarrow K$ be a convex function where $I$ is a convex subset.
If $K=\mathbb{R}$ then $f$ is convex iff $f(tx+(1-t)y)\leq tf(x)+(1-t)f(y)$, $t\in[0,1]$. Is suspect this could be generalised to any ordered field.
If $K=\mathbb{C}$ then we can't use this definition as $\mathbb{C}$ is not a totally ordered field. Instead we have $\mathbb{C}\sim\mathbb{R}^2$ and use the hessian: $f$ is convex iff $\nabla^2f$ is positive semi-definite. However this requires $f\in\mathcal{C}^2$.
Q3: What are the special cases that have been extensively studied and have significance in application?
The majority of the applications in convex optimisation are with a real vector space and a convex real-valued function. There are so many applications for this the mind boggles. A short memory dump is:

Least squares problems
Linear programming: network flow problems, mircoeconomics.
Quadratic programming: This forms the basis of so many optimization algorithms
Entropy maximisation
Comment: Regarding Q1: You don't need any topology to define or discuss convexity. A vector space setting is sufficient. Vector spaces over the real field are the most reasonable, by far. If $t$ is a complex number, then saying that something is true for all $t \in [0,1]$ is a bit odd. If $t$ belongs to some other field (neither the real nor the complex field), then it's not at all clear what $t \in [0,1]$ means.


Raise a matrix to a fractional power

Question: I am trying to achieve A^k in R with further assumption that k is not an integer (and possibly less than 1).
It seems like %^% command does not do the right job. Namely -- A %^% (1.3) == A %^% 1 while using this command.
Answer: Presumably you're talking about the %^% operator from the expm package:

Compute the k-th power of a matrix. Whereas 'x^k' computes
  element wise powers, 'x %^% k' corresponds to k - 1 matrix
  multiplications, 'x %*% x %*% ... %*% x'.

Note the definition of k:

k: an integer, k >= 0.

I believe that if you want fractional powers you can do something like:
z <- matrix(c(3,1,1,3),2,2)
expm(1.3*logm(z))
## Note ...

##              [,1]     [,2]
##     [1,] 4.262578 1.800289
##     [2,] 1.800289 4.262578

I think this may only work for positive-definite matrices, though.
Comment: Your mind reading skills are indeed impressive. This one was even more confusing as OP asked for `k` smaller than 1... I guess `%^%` was the clue, though I never saw this operator before.
Answer: In case it is still relevant to you, and as already pointed out, my own package called 'powerplus' has a function called 'Matpow' that enables you to raise any diagonalizable matrix to any power (even complex powers after the recent update).
Edit: Version 3.0 extends capabilities to (some) non-diagonalizable matrices too.
Answer: This morning I had the same problem (unfortunately logm only works for matrices for which its log exists... not my case apparently) and after some research I found package matlib (function mpower) and package powerplus (function Matpow). Both accept non-integer powers but matlib has the restriction that the input matrix must be symmetric. So I ended up using Matpow from package powerplus and it did the trick. Hope it helps!

Raise a matrix to a fractional power


Question regarding cointegration and superconsistency

Question: I am reading this PDF:
https://warwick.ac.uk/fac/soc/economics/staff/gboero/personal/hand2_cointeg.pdf
where on pages 4 and 5 it says that if the residuals are stationary, the OLS regression is superconsistent even if the Y and X variables are non-stationary.
My question then is why is it necessary to estimate the Error Correction Model (Second step)? Isn't the stationarity of residuals a sufficient condition?
Answer: A rejection of the null of the Engle-Granger test indeed establishes cointegration (up to a type I error, of course).
But estimating the error correction model tells you interesting things about the economic question of interest. E.g., which variable adjusts to deviations from the equilibrium relationship in the previous period so as to restore convergenve towards the long-run cointegration vector.
Why negative $\alpha$? Suppose the error-correction equation is $\Delta y_t=\alpha(y_{t-1}-\beta x_{t-1})+e_t$. When $y_{t-1}-\beta x_{t-1}>0$, it means that the lagged value $y_{t-1}$ is "too large" relative to the cointegrating relationship, so that if $y_t$ is to contribute to restoring the equilibrium relationship, its change in $t$ must be negative, whence $\alpha<0$ is required.
Comment: @adrCoder, here are some answers regarding signs of the adjustment coefficient: [1](https://stats.stackexchange.com/questions/134628), [2](https://stats.stackexchange.com/questions/203649), [3](https://stats.stackexchange.com/questions/217424).
Comment: I made an edit which hopefully helps.
Comment: I would recomment to have a look for Granger representation theorem, which tells us about the relationship between cointegration and existence of an error-correction relationship.
Comment: Thank you Christoph. Also, on page 5 it says that the adjustment coefficient α must be negative. What happens if it is not negative?
Comment: Is it possible to have stationary residuals but α>0? What happens in this case? Does it mean there is no cointegration i.e. the OLS is not superconsistent? Or the fact that the residuals are stationary imply that α will be >0?
Comment: Ok I will do thank you.


Alternating series test question

Question: $$\sum\limits_{n=1}^\infty\dfrac{(-1)^{n}}{n^{2/n}}$$
I applied alternating series test. I tried to check if it fulfills the condition that it goes to zero. $\frac{2}{n}$ goes to $0$ . However $n^0$ goes to $1$ despite $n$ being infinity. Am I doing something wrong here?
Comment: You're wrong in the manner of calculus:
$$n^{2/n}=e^{\frac2n\log n}$$
but the series still divergent.
Comment: okay based on the above and apply l'hopital rule i would get 1, which means alternating series test fails right? But if it's 1, the test of divergence also fails so how do i actually proof it?
Comment: Since the sequence
$$\left(\dfrac{(-1)^{n}}{n^{2/n}}\right)$$ doesn't converge to $0$ then the series is divergent.
Comment: For the limit of the denominator, see here: http://math.stackexchange.com/questions/115822/how-to-show-that-lim-n-to-infty-n-frac1n-1 and http://math.stackexchange.com/questions/28348/proof-that-lim-n-rightarrow-infty-sqrtnn-1/
Answer: Note that
$$\lim_{n \to \infty} \frac{1}{n^{2/n}} = \lim_{n \to \infty} e^{\ln n^{-2/n}} = \lim_{n \to \infty} e^{(-2/n)\ln n} = 1$$
because
$$\lim_{n \to \infty} \frac{\ln n}{n} = 0.$$
But
$$\lim_{n \to \infty} \frac{(-1)^n}{n^{2/n}} = \lim_{n \to \infty} (-1)^n e^{(-2/n)\ln n}$$
does not converge to zero. In fact, it does not converge at all. Therefore
$$\sum_{n = 1}^\infty \frac{1}{n^{2/n}}$$
diverges.

Alternating series test question


Binomial distribution for number of family members

Question: The question below is a part of a more complex question in probability theory. I can't get my head around why is my solution incorrect...
So here it goes. Distribution of number of boys in a family with $n$ children is binomial with parameters $n$, $\frac{1}{2}$ (my guess is that it means $\mathbb{P}(X=k)=\binom{n}{k}(\frac{1}{2})^k(\frac{1}{2})^{n-k}=\binom{n}{k}(\frac{1}{2})^n$). What is $\mathbb{P}(X=2)$?
I thought it would be $$\sum_{n=2}^{\infty}\binom{n}{2}\left(\frac{1}{2}\right)^n=\frac{1}{2}\sum_{n=2}^{\infty}n(n-1)\left(\frac{1}{2}\right)^n=\frac{1}{8}\left(\sum_{n=2}^{\infty}\left(\frac{1}{2}\right)^n\right)''=\frac{1}{8}\left(\frac{2}{(1-\frac{1}{2})^3}\right)$$
But it definitely is not true, since the above-mentioned sum is $2$...
Comment: $\mathbb{P}(X=2|N=n)=\binom{n}{k}(\frac{1}{2})^n$ as you say. You also need a distribution for $N$ to find $\displaystyle \mathbb{P}(X=2)=\sum_{n=2}^{\infty} \mathbb{P}(X=2|N=n)\mathbb{P}(N=n)$.
Answer: There is no reason to sum.  For families with $n$ children, the probability, as you observed, is $\binom{n}{2}\cdot\frac{1}{2^n}$.
In order to find the probability that a randomly chosen family has exactly $2$ boys, you would have to know the distribution of family sizes.
If the probability that a family has $n$ children is $p_n$, then the probability a randomly chosen family has $2$ boys is
$$\sum_0^\infty p_n \binom{n}{2}\frac{1}{2^n}.\tag{1}$$
Without knowing the $p_n$, we cannot go beyond (1).
Remark: We have used some assumptions that are in fact false. The probability of a boy is not exactly $\frac{1}{2}$. And the implicit assumption of independence is quite dubious.
Comment: You are welcome. Yes, sleep (or coffee) are quite useful.
Comment: Dang it, you're totally right, I think I need more sleep. Thank you.


Redirect an url to another url with apache

Question: I've a simple question, so here it is.
I was wondering how to make a simple redirection, I've wamp installed on my computer and I wish I could do that:
When I go to abc.com it redirect to xyz.com.
I did this in the httpd.conf file .. But it isn't working
<code>   <VirtualHost *:80 >

    ServerName abc.com
    Redirect permanent / http://www.xyz.com/

    </VirtualHost>
</code>
Thank you!
Comment: Did your Apache load mod_alias? And, did you reload/restart your Apache after making these changes?
Answer: Enable loggin (CustomLog,ErrorLog) and provide that output information. I'm using same kind of redirect and it works for me no problem.
Comment: Thank you for your answer, it seems to work, but only when I go to http://localhost/ . However, what I want is that when I go to abc.com it goes to xyz.com.. And I can't do that..


typo3 flux select multiple pages suggest wizard

Question: <flux:field.input name="pages">
  <flux:wizard.link label="Select link" activeTab="pages" />
</flux:field.input>
with this I can select ONE page. But how can I select MULTIPLE pages, like it is done at the Menu-Content-Items.
tryed: field.select -needs an item-propery.
field.relation I did not succeed, too.
Thank you for your help,
Christian.
Edit: This is what I'm currently trying:
<flux:field.relation
    name="settings.relationtest"
    label="relationtest"
    multiple="true"
    size="6"
    minItems="0"
    maxItems="30"
    renderMode="singlebox"
    foreignTableField="pages"
>
    <flux:wizard.suggest
        label="NULL"
        hideParent="0"
        pidDepth=""
        minimumCharacters="1"
        searchWholePhrase="0"
        table="pages"/>
</flux:field.relation>

Comment: I'm not entirely sure, thus not an answer: I'd use a [relation field](https://fluidtypo3.org/viewhelpers/flux/master/Field/RelationViewHelper.html), and a [suggest wizard](https://fluidtypo3.org/viewhelpers/flux/master/Wizard/SuggestViewHelper.html) instead of the ones you used - what went wrong when trying that?
Comment: I am not sure about the parameters for the relation abs the wizard never finds anything...
Do you have a working example?
Comment:
Comment: I've added that code into the question, so it is better readable. Hope I got it right. I can't answer your question though.
Comment: `

`
Finds nothing. The ApacheLog says this:
`"POST /typo3/ajax.php?..."http://###element-tt_content-181`

Why tt_content?
Comment: confused aboute the comment function.....
Answer: Had the same problem and tried a lot with different viewhelpers. flux:field.relation seems the right solution for this one. I use a quite simple snippet:
<flux:field.relation label="Auswahl der Seiten" table="pages" size="6" multiple="true" minItems="0" maxItems="30" name="parentpages">
     <flux:wizard.suggest />
</flux:field.relation>

Selecting multiple pages works fine.
Perhaps your problem came from setting the 'table' parameter on flux.wizard.suggest (Link).


Is it safe to use embedded database (RocksDB, BoltDB, BadgerDB) on DigitalOcean block storage?

Question: DigitalOcean block storage uses ceph which means that volume attached to the droplet would be physically located on a different machine. So a database file written to this volume would be using network, not the local disk.
BoltDB specifically mentions that it's not safe to use over network file system, but I'm not sure if that also applies to DO block storage (it's not NFS, but it does use network).
Is it safe to use DO block storage for embedded databases? Yes, performance would be not as good, but that is not relevant if it's entirely not safe.
If the answer is "no, embdeeded databases should only use local disk", then what are the simple ways to replicate the database (e.g. just once a day or few hours)?
Answer:
Is it safe to use embedded database (RocksDB, BoltDB, BadgerDB) on DigitalOcean block storage?

Yes, it is safe to use

then what are the simple ways to replicate the database (e.g. just once a day or few hours)?

Put a timer thread in your app that creates a checkpoint/backup and uploads it to s3 and also snapshot the instance


Why is it easier to remember a melody as opposed to a simple interval?

Question: There's already a question similar to this here, but most of the answers raise questions like, "If you can throw an object a certain distance but not tell precisely how far you threw it, how do you expect to know the quality of an interval when you can only simply recall a melody?"
I'm NOT asking why we can't tell the exact frequency difference between two notes (as if we had pitch identification superpowers) or why we can't magically name the quality of intervals without learning a little bit about intervals first.
I'm asking why it's very easy to remember the SOUND of the melody "Twinkle, Twinkle, Little Star" (without giving ANY thought to pitch or intervals or quality or music theory or any of that other stuff) and why it seems so much harder to remember the SOUND of the tritone or other interval (also without giving any thought to pitch/intervals/quality/music theory/etc.)—especially when the latter only consists of two notes.
For example, I can quickly recognize and identify the melody of "Twinkle, Twinkle, Little Star" in any key after a few seconds of hearing it, but I can't do the same for a simple melodic interval without diligent practice. Why is that the case?
Again, I'm not asking why we don't "understand" intervals at some sort of "intellectual" level or something even though we can recall the melodies to our favorite songs (like so many answers in the aforementioned question brought up).
I'm asking why can't we remember the SOUND of an interval just like we remember the SOUND (and, perhaps, feeling) of the melody of a song we are familiar with.
Comment: Does this answer your question? [If someone can sing a melody, why can they not also recognize the intervals within that melody?](https://music.stackexchange.com/questions/100647/if-someone-can-sing-a-melody-why-can-they-not-also-recognize-the-intervals-with)
Comment: Compare trigonometry. Two points of reference, can't tell where the far point is, even in 2D space. Three points & you can. More points & you can also get elevation….
Comment: Say by yourself. OP. I learned intervals and perception on totally abstract means, sight-singing these topics, not using melodies as mnemonic devices. When you learn how to feel in your body/larynx the difference between intervals, you begin to automatically identifying them.
Comment: If I had a pound for every time I've heard someone mispitch the octave leap in "Happy Birthday to You"… A melody _is_ a sequence of intervals; you can't reproduce a melody without recognising and reproducing its intervals.
Comment: The question calls to mind those puzzles that show an extreme close-up of a familiar object, or a portion of a familiar object but out of context. I wonder if the (in)ability to recognize one or the other involves similar cognitive processes as with individual intervals versus melodies..
Answer: A melody is way more remarkable than an isolated interval.
A melody like Twinkle, Twinkle Little Star you listen to it even before you're born. So, it's ingrained in your ear. It's one of the principles that keep alive systems like The Suzuki Method.
Often time when doing ear training we use melodies as a reference for recognizing intervals. A complete melody awakes many sensations in our body. Thus, it's easier to remember.
You can listen/play a song once and once again, each time you listen to it it it further ingrains in your mind, this repetition process is what gives you the capacity of recalling the correct intervals that shape the melody
Comment: Melodies are made of notes with intervals between them. Therefore, you also listen to intervals before you're born.
Comment: Great point and complements very well what I've said. Yet intervals aren't as remarkable as melodies are.
Answer: It would be easier to remember intervals if they let us remember intervals like we remember melodies: we don't need to immediately generalize them in all keys, they mentioned their names in tight association with their musical appearances more often, we didn't get subjected to stressful practice drills with no sheet music by teachers trying to get us to remember them, we were allowed to make mistakes remembering them and improvise on top of them, we were allowed to make fun of their appearance in any piece other than the original compositions they were found in, we did not have to continually dissociate them from their instrumentation and recordings, and we were allowed to associate them with having a really pleasurable time instead of being forced to remove them from any emotional context.
But at least in the Royal Conservatory of Music syllabus, intervals are expected to be remembered in any key, they appear in the ear testing portions of piano exams in a format similar to a practice drill, you are expected to name the interval in a timely fashion and do not get several minutes to figure out the name (let alone the help of Music Fans Stack Exchange), and one identification mistake or semitone slip suddenly turns the interval into a different interval.
It's very possible that trying to remember an interval the same way that you remember a melody actually does help you recall it better and faster. It's also very possible that the popular method (and one successfully used on me) of using the beginnings of popular melodies to help remember intervals better taps into just that.
Answer: Unlike intervals, which just describe ratio of pitches, melodies have also rhythm. Rhythm is a very important component of music.
A melody played with a different rhythm might be completely unrecognizable. You may even have trouble to recognize the original harmony, since if strong and weak beats change, the melody may suggest different chords.
On the contrary if you play a melody with the right rhythm and right melody shape (up and down movement) but incorrect interval values, there's a good chance you will still recognize it.
Answer: I have a simple answer: Repetition. Melodies usually contain repeated elements and are usually repeated themselves. Bare intervals are more atomic structures that do not inherently contain any repetition or content.
And that leads to another difference: Emotion. Famous melodies are famous because of the mood and/or emotion they evoke. Cognitive research tells us that our brains are better at remembering emotions than data (perhaps it would be more accurate to say the context of an emotion is recalled, more than the emotion itself, but perhaps the two go hand in hand).
"Twinkle Twinkle" is a pretty good example. Each note is repeated and the pattern of note repetition is repeated. The second melodic figure is repeated, then the introductory melody is repeated at the end.
Another way that we remember some melodies like "Twinkle Twinkle" is remembering the words. Even melodies without words have some alternate sounds we can make with our mouths beyond the notes. For example, if I write: duuuuh-dut duuuuuh-dut duh-dut duh-dut duh-dut... many reading that will recall the shark theme from Jaws (or perhaps an excerpt from Dvořák's 9th symphony). That is a much more evocative way to recall that than writing "imagine a repeated ascending minor second played by the celli and basses".
Answer: As @Brian THOMAS alludes to in a note, you do recognize intervals - in the case he mentions, the octave leap in Happy Birthday. Or consider the famous third in the opening of Beethoven's Fifth Symphony. Or in fact the fifth in the opening notes of Twinkle.
Perhaps the issue here is not so much recognition as nomenclature - we use user-friendly names for tunes (like HB and Twinkle) but notions of fifth, octave, minor second, etc.  take a bit of explaining (i.e. basic interval theory).
Answer: I think the issue may be about idiom versus "correct" but unnatural grammar.
A language metaphor may help.
"Put your toys away" would be an idiomatic expression.
"Reposition the toys you played with to the toy storage container" is grammatically correct and has the same meaning, but is unnatural.
If you listened to and were asked to repeat back a series of phrases like those, the idiomatic ones would be much easier to repeat, because the idioms are familiar to you from constant use. In part the idiomatic memory is already there, you just recall it. The unnatural sentence would require new memorization with very little supporting idiomatic patterns.
Twinkle, Twinkle Little Star uses melodic "idioms:" tonic to dominant, dominant to neighbor submediant, descending scale dominant to tonic. Those three short units can be found in lots of other melodies. Importantly when a few of those units are combined it will quickly establish the tonality.
In other words you aren't hearing and remembering - ascend P5 ascend M2 descend M2 descend M2 descend m2 descend M2 descend M2, which is the abstract order of intervals - but rather - ascend tonic to dominant, ascend to submediant, descend scale - which are "idioms" of a major key.

...much harder to remember the SOUND of the tritone or other interval...especially when the latter only consists of two notes.

This sounds like the typical ear training test. I'm suggesting it's difficult, because there is no real musical context, you cannot recognize the interval "idiomatically."

...I'm not asking why we don't "understand" intervals at some sort of "intellectual" level...

Right. People can do this without understanding anything technical about music. Play an ascending major triad and it's easy for a person to sing it back. Ask them to sing an ascending major third and then an ascending minor third and they probably won't understand those terms, even though they understand them with their ears as a musical "idiom."

I'm asking why can't we remember the SOUND of an interval just like we remember the SOUND (and, perhaps, feeling) of the melody of a song we are familiar with.

It's interesting your choice of words "sound" and "feeling." If you consider my suggestion about idiom and context, then "sound" and "feeling" are not fixed abstract qualities. The tritone is a good example. The abstract interval is d5 or A4, but that isn't a "sound" or "feeling." You need context for that. In one context, like diminished seventh chords in a major key, the tritone is discordant. But, in another context like a half diminished chord in an Impressionistic or jazz setting, it's mellow. Or in the dominant seventh chords of blues the tritone is "earthy." Abstract intervals aren't musically expressive until they are put into context. Clearly you would like to "remember" by feeling, but in a ear training test they are usually presented abstractly without context.
Another thing to consider is the memory interaction between word and melody. The two reinforce memorization. In part a song melody is more easily recalled using the words that go with the melody.
This presents a possible strategy for ear training: put intervals into context and use solfege syllables to sing them in lieu of song lyrics. So, don't just sing a tritone, sing the syllables "TI", "FA." Also, play with some extra context. Start with "DO", "MI" and then connect those tones/syllables to those of the tritone "DO", "TI" and "MI", "FA." Then maybe try "DO", "MI" followed by "TI", "FA" and vice versa before finally just singing "TI", "FA" in isolation.
Comment: I don't think it's *that* hard to detect instances of the BACH motif or the DSCH motif just by listening to a piece (after listening to these motives). Given how easily these motives change harmonic contexts or can be placed in (relatively) atonal pieces, this means that people either remember actual notes or raw intervals--not scale degrees.
Comment: or, you are describing something that comes after a lot of practice, probably more practice than the OP has put in.
Comment: I don't even practice motif detection that much - all I need to improve my ability to detect any motif by listening is to be warned that the motif could be present. I've ended up detecting "the lick" and a certain note-minor 2nd above-minor 3rd below motif in a similar fashion (the latter motif, while part of the DSCH motif, is also prominent in Ridley's theme from the Metroid series and certain Kirby-series boss themes).
Comment: Are you talking about video games?
Comment: Yes, for the last part, I am talking about video games.


Equivalent conditions for the ramification group(s) in a finite Galois extension

Question: Let $L|K$ be a finite Galois extension and $v$ a discrete normalized valuation on $L$ such that its restriction to $K$ extends uniquely to $L$.
(1) Why is $G_1=\{\sigma\in G(L|K)\mid v(\sigma(x)-x)\ge 2\ \ \forall x\in\mathcal{O}\}$ equal to the ramification group $R(L|K)=\{\sigma\in G(L|K)\mid v\left(\frac{\sigma(x)}{x}-1\right)>0\ \ \forall x\in L^*\}$? (Here $\mathcal{O}$ is the valuation ring of $L$).
(2) Is it true that in general $G_s$ equals $\{\sigma\in G(L|K)\mid v(\sigma(\pi)-\pi)\ge s+1\}$, where $\pi$ is any element of $L^*$ such that $v(\pi)=1$? (The $G_s$'s are the higher ramification groups, that is $G_s=\{\sigma\in G(L|K)\mid v(\sigma(x)-x)\ge s+1\ \ \forall x\in\mathcal{O}\}$).
This question arises from Chapter II, $\S 10$ of Neukirch's Algebraic Number Theory.
Comment: So here $K$ is not necessarily an algebraic number-field, as its characteristic might not be $0$? And notice that [here in wiki](http://en.wikipedia.org/wiki/Hasse-Arf_theorem) the higher ramification groups are defined by your desired equality.
Comment: And [in the article by Zev Chonoles](http://math.uchicago.edu/~chonoles/expository-notes/ramificationgroups.pdf) these groups are also defined in this way. So I wonder what your definition is. Perhaps you could mention that in the post? Thanks.
Comment: Yes, $K$ is arbitrary (but the residue class field is assumed to have positive characteristic). I added the definition of the higher ramification groups, but note the difference with the other sets in (2)..
Answer: For (1): In $\S$ II.9 Neukirch shows that $R(L/K)$ is the (normal, hence unique) Sylow $p$-subgroup of the inertia group $I(L/K)$.  But (Proposition II.10.2) the quotient $G_0/G_1$ is cyclic of order prime to $p$, while for each $i \geq 1$, $G_i/G_{i+1}$ is a $p$-group.  Since $G_i = \{1\}$ for sufficiently large $i$, $G_1$ must be the Sylow $p$-subgroup of $I(L/K)$.  (Admittedly Proposition II.10.2 comes shortly after Neukirch asserts that "clearly" $R(L/K) = G_1$, so this argument is not what he has in mind.  But it is an argument, at least.)
For (2): no.  $L/K$ could be unramified, and then we can take $\pi \in K$, so $v(\sigma(\pi)-\pi) = v(0) = \infty \geq s+1$ holds for any $\sigma$, so the latter group is always equal to $G$, while $G_s = \{1\}$ for all $s$ in this case.
Comment: Ah, I worked it out by myself.. This also provides a different proof of (1). The fixed field of $G_0$ is the maximal unramified subextension $T$, so if we choose $\pi$ such that $v(\pi)=1$ we have $\mathcal{O}_L=\mathcal{O}_T[\pi]$ and consequently $G_{s+1}(L|K)=G_{s+1}(L|T)=\{\sigma\in G_0\mid v(\sigma(\pi)-\pi)\ge s+2\}$.
Comment: Thank you, now I understand that (2) is false.
I believed that (1) is true simply because Neukirch states that it is "clear" (sic!). However, I don't understand your counterexample. Isn't $R(L|K)=\{1\}$, as $L|K$ is tamely ramified?
Comment: @carizio: Hmm, I just checked Neukirch, and you're right, that's exactly what it says.  I must be mistaken, so I deleted that part of my answer.  I should think more about this.  All I can see now is that I was actually assuming $x \in \mathcal{O}$ rather than in $K$.
Comment: Thank you again! As my second question comes from the Proposition that you quoted, could you explain me why (for $s\ge 0$) is $G_s\cap\{\sigma\mid v(\sigma(\pi)-\pi)\ge s+2\}=G_{s+1}$? That's exactly what one needs to prove that the homomorphism of the Proposition is injective.
Comment: Nice solution.   But does $\mathcal{O}_L = \mathcal{O}_T[\pi]$ assume that $\lambda|\kappa$ is separable?


apps script how to combine mutiple rows' unqiue value into n-dimensional array based on index column's unique value

Question: I have a google sheet likes this, will have dynamic columns and rows each time when update the sheet

| country| product | type | user|
| -----| ---|--|---|
| JP   | p1 |t1|u1|
| JP   | p1 |t2|u2|
| JP   | p1 |t3|u2|
| JP   | p2 |t2|u3|
| HK   | p3 |t2|u1|
| HK   | p1 |t3|u1|
| KR   | p1 |t2|u1|
I need to put the value into an array , the key should be the unqiue coutry's value, and combine the rest of columns' value (only take unique value), the number of dimensions of  array is based on the number of unique value in "country". in the above example will be 3-dimensional array
I want the outcome array will be like this e.g.
[[JP,p1/p2,t1/t2/t3,u1/u2/u3],[HK,p1/p3,t2/t3,u1],[KR,p1,t2,u1]]
for now i only can get the outcome array like this: i am not able to join values  from same column
[[JP,p1,p2,t1,t2,t3,u1,u2,u3],[HK,p1,p3,t2,t3,u1],[KR,p1,t2,u1]]
this is my code, can anyone help what is the issue?
function testtogetcombine() {
  var spreadsheet =  SpreadsheetApp.getActiveSpreadsheet();
 var sheet1 = spreadsheet.getSheetByName("test");
  var lastRow = sheet1.getLastRow();
  var lastColumn = sheet1.getLastColumn();
  var values = sheet1.getRange(1, 1, lastRow, lastColumn).getValues();

  var newSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('outcome');
  var outLastRow = newSheet.getLastRow();
  var counter=1;

  var orgtitle=["country","product","type","user"]

  var col_geo=[];
  var geo=[];

  for (var c=0; c<=orgtitle.length;c++)  {
    for (var j=0;j<=lastColumn-1;j++) {
      if(values[0][j]==orgtitle[c] ){
              col_geo.push(j)
        }
    }
  }
  for (var i=1;i<lastRow-1;i++) {
         var duplicate = false;
           for (n in geo){
             if(values[i][col_geo[0]]==geo[n]){
                duplicate = true;
             }
            }
              if(!duplicate) {

               geo.push(values[i][col_geo[0]])

              }

  }

  var result=new Array(geo.length);
  for (var j=0;j<result.length;j++){
        result[j]=[];
        result[j].push(geo[j])

  }
var temp=[];
 for (var j=0;j<result.length;j++){

for (var c=0; c<col_geo.length;c++) {
               // temp[c]=[];

        for (var i=0;i<lastRow;i++){

              if (values[i][col_geo[0]] == result[j][0]) {
                  //  temp[c].push(values[i][col_geo[c]]);
                 var duplicate = false;
           for (n in result[j]){
             if(values[i][col_geo[c]]==result[j][n]){
                duplicate = true;
             }
            }
              if(!duplicate) {

              result[j].push(values[i][col_geo[c]]);

              }

              }

          //  if (values[i][col_geo[0]] == "JP"){

          //    var duplicate = false;
          //  for (n in temp){
          //    if(values[i][col_geo[c]]==temp[n]){
          //       duplicate = true;
          //    }
          //   }
          //     if(!duplicate) {

          //      temp.push(values[i][col_geo[c]]);
          //      Logger.log(temp)
          //      temp=[];

          //     }

           }

        }

 }
    Logger.log(result);
    }

Answer: I believe your goal is as follows.

You want to create an array of [[JP,p1/p2,t1/t2/t3,u1/u2/u3],[HK,p1/p3,t2/t3,u1],[KR,p1,t2,u1]] from your showing Spreadsheet.

From your value, I guessed that for example, p1/p2 and t1/t2/t3 and so on are the string values.

In this case, how about the following sample script?
Sample script:
function myFunction() {
  const sheetName = "test"; // Please set your sheet name.

  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const srcSheet = ss.getSheetByName(sheetName);
  const values = srcSheet.getRange("A2:D" + srcSheet.getLastRow()).getValues();
  const obj = values.reduce((m, [a, ...v]) => m.set(a, m.has(a) ? m.get(a).map((e, i) => e.add(v[i])) : v.map(e => new Set([e]))) , new Map());
  const res = [...obj].map(([a, v]) => [a, ...v.map(e => [...e].sort((x, y) => x > y ? 1 : -1).join("/"))]);

  console.log(res); // [["JP","p1/p2","t1/t2/t3","u1/u2/u3"],["HK","p1/p3","t2/t3","u1"],["KR","p1","t2","u1"]]
}

When this script is run res is [["JP","p1/p2","t1/t2/t3","u1/u2/u3"],["HK","p1/p3","t2/t3","u1"],["KR","p1","t2","u1"]].

If you want to retrieve an array like [["JP",["p1","p2"],["t1","t2","t3"],["u1","u2","u3"]],["HK",["p1","p3"],["t2","t3"],["u1"]],["KR",["p1"],["t2"],["u1"]]], please modify as follows.

From
const res = [...obj].map(([a, v]) => [a, ...v.map(e => [...e].sort((x, y) => x > y ? 1 : -1).join("/"))]);

To
const res = [...obj].map(([a, v]) => [a, ...v.map(e => [...e].sort((x, y) => x > y ? 1 : -1))]);

Note:

This sample script can be used for your showing Spreadsheet. If you change the Spreadsheet, this script might not be able to be used. Please be careful about this.

References:

reduce()
Map
Set
Comment: That's what I want!! thanks so much Tanaike, your code much more clear and elegant!!!


How long do you play these notes?

Question:
Here is an image of the notes in question, I've copied the specific part of the sheet music that is confusing me and made it in Illustrator because musicScore and NoteFlight are more headache than they are worth so apologies that it's a bit off.
Anyway...
It's 4/4 and Treble clef
E,D played together as a second. The E is 1/4 note and the D appears to be a whole note. Thats not too diffcult, but what flips the script is that the D is used again in the same bar!?
How does this work? If the first D is played to the count of 4, how can anymore D notes fit in that with out playing 2 seperate D notes? and if that's the case how can I play the first D note for 4 beats?
A similar thing happens in the second bar with the middle C.
So the question is how long do you play the first D in the first bar and the first middle C in the second bar?
The music is To the Stars from DragonHeart.
Comment: Possible duplicate of [Why is there two notes in a row with more beats than the measure?](https://music.stackexchange.com/questions/80472/why-is-there-two-notes-in-a-row-with-more-beats-than-the-measure)
Comment: @DaviebPrime, I strongly agree with you that the first question Carl found is not a duplicate of your Q, and I agree wholeheartedly with Richard about the importance of your Q. I do think it has been asked before on this site. (See the Q I found, above--maybe this is what Richard had in mind.) The challenge is making that prior question easily searchable. If you have thoughts on how to edit the title, body, etc. so the Q is easier to find in a search, they are very welcomed! It's perfectly reasonable for you to disagree with Carl, but personal digs about being paid, etc. aren't constructive.
Comment: I think this is a duplicate, but I wonder if that's the best sample to link to. I'll keep looking on my end.
Comment: @DaviebPrime I agree with you that that question isn't the same as yours, which is why I didn't mark it as a duplicate. Sorry, I didn't mean to belittle your question at all. It's a good one, and important. And perhaps it *isn't* a duplicate, based on my failure to find the question that it's a duplicate of! :-)
Comment: Possible duplicate of [What do multiple notes on top of each other in a staff mean?](https://music.stackexchange.com/questions/30043/what-do-multiple-notes-on-top-of-each-other-in-a-staff-mean)
Comment: @Richard: I've already been given my answer anyway so sure mark it as duplicate. Though I'd advise not doing that and leaving this thread for anyone else who encounters the same issue.
Answer: This has cropped up many times, and is probably answered elsewhere on this site.
There are effectively two voices here. The tails up constitutes the upper (soprano) voice, and the semibreves make up a separate voice (alto).
So the soprano voice has the correct number of beats, making 4, while the lower D and C notes last the whole bar each. Play the D with the E in 1st bar, and C with the E in the next. Hold lower note while the bar lasts - not with the pedal, though.
It's not written well, as without two instruments (or two manuals), it doesn't mak a lot of sense. One can guess that it means you to play the 1st D, then the 2nd, but hold that one through the bar. Same idea for the second bar. Hold the C, then play it again on the semis. They're quick enough not to bother holding that 2nd C. It's probably re-written from a score, where other instruments play the second part, but written by someone who didn't understand the restrictions of playing it on a piano. It would be possible on a guitar, for one player, as the same note can be played on two different strings.
Comment: Should have tried 'rubbish publishing'...
Comment: How does one hold the lower note for the entire bar and play the lower note again in the same bar?
Comment: Must read questions thoroughly before answering! Edited accordingly.
Comment: Ahh, Thank you! so it's not just my own stupidity. It's obviously not very common as, when going through all my sheet music this notation does not occur anywhere else and for the life of me I could not think of a way to word this question on a google search! –
Comment: Maybe it's me, but I see this quite often in guitar sheet music, especially from the baroque area. For the first measure, the whole note D would (probably) be played on the 5th string, 5th position, with the pinky, the other notes on the 4th string. The 2nd bar is pretty much not feasible, without plucking the same C again, but it's quite commonly notated that way. It's just an indication of what the intention is, that bass & melody overlap, and to keep voices consistent on their own. *not* playing the C (because "it's already sounding") is definitely not the way to go. Am I missing something?
Answer: This is a situation that is quite often encountered in part writing for keyboard. One should not forget that in its highest form the piano - for example - is a multi-voiced instrument.
Here the performer 'fakes' it to a certain degree holding the whole note throughout the bar re-sounding the note when the alternate voice demands it. The performer conceptualises two independent voices in mind and 'shapes' the voices accordingly. On the piano the whole note D and C would be played with greater volume than the quarter D to ensure that it carries throughout the bar. Similarly the whole note C would be played more loudly the sixteenth C in bar two. One would aim to play this sixteenth C with much less strength. Any keyboard player with moderate level of skill would be able to do this.
As with much of keyboard playing the overall effect in one of illusion...
Comment: Ah ok ok. So do you play the E with the strengh of the first D or the second?
Comment: Only experimentation and your ear can be your guides. There are a number of variables to consider but the aim is to convey to the listener than there are two independent parts at work

How long do you play these notes?


Efficiently finding $\theta$ such that $\cos\theta = -\frac12$ and $\sin\theta = \frac{\sqrt{3}}{2}$. I know the quadrant, but what are the angles?

Question: I'm having trouble solving trigonometric equations. For example, let's say I'm solving a problem and I arrive at a trigonometric equation that says,
$$\cos\theta = -\frac12 \quad\text{and}\quad \sin\theta = \frac{\sqrt{3}}{2} $$
At this point, I get stuck and I don't have an efficient way to proceed apart from picking up a calculator.
I can figure that the quadrants (from the signs of the ratios) -- but I can't figure out the angles. What is a good way to figure out the angle? Specifically, how do I systematically solve $\sin$, $\cos$, and $\tan$ trigonometric equations? (I can reciprocate the other three into these ratios.)
I don't have trouble figuring out angles between $0^\circ$ to $90^\circ$ (since I have that memorized), but for angles in other quadrants, I get stuck.
Comment: The question ["How to remember a particular class of trig identities."](https://math.stackexchange.com/q/737212/409) may be helpful.
Answer: If you have angle $\theta$ in quadrant $1$, you can find its "corresponding" angle in quadrant $2$ by $(\pi - \theta)$, in quadrant $3$ by $(\pi+\theta)$, and in quadrant $4$ by $(2\pi-\theta)$. For example, $\frac{\pi}{4}$ corresponds to $\frac{3\pi}{4}$, $\frac{5\pi}{4}$, and $\frac{7\pi}{8}$ in quadrants $2$, $3$, and $4$, respectively. (That's how I always think of them at least.)
Also, recall sine functions correspond to the height of the right triangle ($y$-axis), so they are positive in quadrants $1$ and $2$. Cosine functions correspond to base of the right triangle ($x$-axis), so they are positive in quadrants $2$ and $4$. (Tangent functions can be found through sine and cosine functions.)
You can use the following identities (which are derived from the aforementioned facts).

$$\sin\bigg(\frac{\pi}{2}+\theta\bigg) = \cos\theta \quad \sin\bigg(\frac{\pi}{2}-\theta\bigg) = \cos\theta$$
$$\cos\bigg(\frac{\pi}{2}+\theta\bigg) = -\sin\theta \quad \cos\bigg(\frac{\pi}{2}-\theta\bigg) = \sin\theta$$
$$\tan\bigg(\frac{\pi}{2}+\theta\bigg) = -\cot\theta \quad \tan\bigg(\frac{\pi}{2}-\theta\bigg) = \cot\theta$$
$$\sin\bigg(\pi+\theta\bigg) = -\sin\theta \quad \sin\bigg(\pi-\theta\bigg) = \sin\theta$$
$$\cos\bigg(\pi+\theta\bigg) = -\cos\theta \quad \cos\bigg(\pi-\theta\bigg) = -\cos\theta$$
$$\tan\bigg(\pi+\theta\bigg) = \tan\theta \quad \tan\bigg(\pi-\theta\bigg) = -\tan\theta$$
$$\sin\bigg(\frac{3\pi}{2}+\theta\bigg) = -\cos\theta \quad \sin\bigg(\frac{3\pi}{2}-\theta\bigg) = -\cos\theta$$
$$\cos\bigg(\frac{3\pi}{2}+\theta\bigg) = \sin\theta \quad \cos\bigg(\frac{3\pi}{2}-\theta\bigg) = -\sin\theta$$
$$\tan\bigg(\frac{3\pi}{2}+\theta\bigg) = -\cot\theta \quad \tan\bigg(\frac{3\pi}{2}-\theta\bigg) = \cot\theta$$
$$\sin\bigg(2\pi+\theta\bigg) = \sin\theta \quad \sin\bigg(2\pi-\theta\bigg) = -\sin\theta$$
$$\cos\bigg(2\pi+\theta\bigg) = \cos\theta \quad \cos\bigg(2\pi-\theta\bigg) = \cos\theta$$
$$\tan\bigg(2\pi+\theta\bigg) = \tan\theta \quad \tan\bigg(2\pi-\theta\bigg) = -\tan\theta$$

I certainly wouldn't recommend memorizing these though since knowing how the unit circle works basically means you know them already.
For example, in an equation you reach $$\cos \theta = -\frac{\sqrt{3}}{2}$$
You already know that $\cos {\frac{\pi}{6}} = \frac{\sqrt{3}}{2}$ and you also know cosine is negative in quadrants $2$ and $3$, so all you need to do is find the corresponding angle for ${\frac{\pi}{6}}$ in those quadrants.
$$\text{Quadrant II} \implies \theta = \pi-{\frac{\pi}{6}} = \frac{5\pi}{6}$$
$$\text{Quadrant III} \implies \theta = \pi+{\frac{\pi}{6}} = \frac{7\pi}{6}$$
This might take a bit of practice, but once you get this whole "corresponding" angle concept, it all becomes simple. Perhaps you can start by trying to visualize this by solving equations with a unit circle. You'll eventually get the hang of it.
Comment: Oh yes, thanks for pointing out. I'll edit it.
Comment: Thank you, that helped. I think you meant $ \cos ( \frac {3\pi}{2} + \theta) $instead of $ \cos ( \frac{\pi}{2} + \theta) $ in one of the identities you've provided (5th from the last row). I tried editing but it failed because edits need to be of 6 characters minimum.
Comment: To anyone else interested in a good way to remember the identities given in the answer, here's what I use: note that the ratios change into their co-ratios only at 90 and 270 degrees. At 180 and 360, the ratio does not change. To figure out the sign, ask yourself whether the original ratio (before changing in case of 90 and 270 degrees) is positive or negative in the appropriate quadrant. Fore example, consider $ \cos ( \frac{\pi}{2} + \theta ) $. Since we have 90 degrees, cos changes to sin. $ 90 + \theta $ falls in the second quadrant, where cos is negative; so we have $ - \sin \theta $.
Answer: Consider the following equilateral triangle $ABC$, where $D$ is the foot of the altitude $\overline{CD}$

Let $[AB]=a$
Thus $$cos\bigl(\angle DAC \bigr)=cos\Bigl(\frac{\pi}{3}\Bigr)=\frac{AC}{AD}=\frac{1}{2}$$
Consider now the trigonometric identities $$cos\bigl(\pi-\theta\bigr)=-cos\bigl(\theta\bigr)\Rightarrow cos\Bigl(\frac{2\pi}{3}\Bigr)=-\frac{1}{2}$$
$$cos\bigl(\theta+2\pi\bigr)=cos(\theta) \Rightarrow cos\Bigl(\frac{2\pi}{3}+2\pi n\Bigr)=-\frac{1}{2}\; \forall n\in \mathbb{Z}$$
Now back to the equilateral triangle, observe that by the Pythagorean theorem
$$[CD]=\sqrt{{[AC]^2}-{[AD]^2}}=\sqrt{{a^2}-{\Bigl(\frac{a}{2}\Bigr)^2}}=\frac{\sqrt{3}}{2}*a$$ Hence $$sin\bigl(\angle DAC\bigr)=sin\Bigl(\frac{\pi}{3}\Bigr)=\frac{[DC]}{[AC]}=\frac{\sqrt{3}}{2}$$
Since $sin(\theta)=sin(\theta + 2\pi)$
$$sin\Bigl(\frac{\pi}{3}+2n\pi\Bigr)=\frac{\sqrt{3}}{2} \; \forall n\in \mathbb{Z}$$
$\mathbf{PS}$
Keeping in mind the sine- (red) and cosine (green) functions might help with this problems

Answer:
In the above, $\theta$ is measured anticlockwise from the positive horizontal axis and P is the angle with the nearest horizontal axis. P takes values from 0 to $\frac{\pi}{2}$.
Suppose you want to solve $cos(\theta) = -0.5$,

Solve $cos(P) = +0.5$ using inverse cosine on your calculator. $P =\frac{\pi}{3}$  is called the reference angle.
Ask yourself where $cos(\theta)$ is negative. This is in the second and third quadrants. In the second quadrant $\theta = \pi-P = \frac{2\pi}{3}$ and in the third quadrant $\theta = \pi+P = \frac{4\pi}{3}$.
If you want more solutions then solve $\theta = \pi-P+2k\pi$ and $\theta = \pi+P+2k\pi$ instead, where k is any positive or negative integer.

eg2. Solve $\sin(3\theta+1) = 0.5$ for $0\le \theta \le 2\pi$

Solve $\sin(P) = 0.5$ then $P = \frac{\pi}{3}$
Where is $sin$ positive? In quadrant 1 so put $3\theta+1 = P+2k\pi$ and in quadrant 2 so put $3\theta+1 = \pi-P+2k\pi$.

Now solve for $\theta$ and keep any solutions which fall in the range $0\le \theta \le 2\pi$.


How to add a single special character randomly anywhere inside a string? Bash

Question: I have this script that generates a random character between 8-16. I am confused as to how I would add a single random special character from a bank [! @ # $ % ^ & * ( ) _ + ] anywhere randomly inside this string?
if [ $# -eq 0 ] then
    pwdlen=$(((RANDOM % 9 ) +8))
    spclen=$((RANDOM % 1))

    char=(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V X W Y Z)

    chars=(~ ! @ # $ % ^ & * - +)
    #rand2=$random % 11

    max=${#char[*]}
    for i in `seq 1 $pwdlen`
    do
        let "rand=$RANDOM % $max"
        str="${str}${char[$rand]}"
    done
    echo $str
    exit 0
fi

Answer: teststring=foobarspam

specialchars='!@#$%^&*()_+'

randomchar=${specialchars:RANDOM % ${#specialchars}:1}
randompos=$(( RANDOM % ( ${#teststring} + 1 ) ))
newstring=${teststring:0:randompos}${randomchar}${teststring:randompos}

Answer: I am not sure what script language are you using. I wrote a solution for you using PHP. If PHP is not what you are using, you should be able to convert the same logic to other languages and get the same results.
<?php
//This is the original string where you want to add a random character to
$org_string = 'This is My original String';
//calculates the length of the string
$org_length = strlen($org_string);
//find a random position
$pos = rand(0, $org_length-1);

//concatenate the first part of the string, random character, the remaining string
$final = substr($org_string, 0, $pos) . getOne() . substr($org_string, $pos);

//print the final value
echo $final;

//return a random string
function getOne(){
    //the following string is 12 characters in length. it is all available characters that you want to select from
    $str = '!@#$%^&*()_+';
    //return a random character
    return $str[rand(0, 11)];
}

?>

Answer: You can use the following code.
#!/bin/bash

if [ $# -eq 0 ]; then
    pwdlen=$(((RANDOM % 9 ) +8))
    spclen=$((RANDOM % 1))

    char=(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V X W Y Z)

    chars=('~' '!' '@' '#' '$' '%' '^' '&' '*' '-' '+')
    #rand2=$random % 11

    max=${#char[*]}
    for i in `seq 1 $pwdlen`
    do
        let "rand=$RANDOM % $max"
        str="${str}${char[$rand]}"
    done
    A=$(echo $str|wc -c) ## To get the count of
    P=$((RANDOM % $A)) ## To get a random position of where to insert the character.
    I=$((RANDOM % 11)) ## To get a random index number of chars array
    C=${chars[$#]}
    echo $str | sed 's!^\(.\{'$P'\}\).!\1\'"$C"'!'  ## Inserting the special character to string in defined position
    exit 0
fi

Output:
$ for i in `seq 1 10`;do ./test1;done
j^eh8BmD2H
0B01^1AN6EVw
Wu2$LLTILuDN8fSV
e^90gmHjksDo
eB7wa\#fmwf
NVAtJkmfqx~
JaHvD%uyO3rB
ncFrgyyz~UkZ
q0LLRHUNATM8DL
X%ARcXgyC1Do


Generalization of Lagrange's theorem $(1768)$?

Question: Here's the theorem :

Let $p$ a prime number and $u_0,...,u_n$, a list of integers such that $p\not \mid u_n$. Then : $u_nx^n+...+u_1x+u_0 \equiv 0\pmod p$ admits at most $n$ solutions $\pmod p$.
The proof can by done using induction on $n$ and the property of the prime number $p$.

Now, I was wondering how it will work if we consider an integer $k$ instead of $p$. The statement will give :
Let $k$ an integer and $u_0,...,u_n$, a list of integers such that $\gcd(k,u_n)=1$. Then how many solutions $\pmod k$ the equation : $u_nx^n+...+u_1x+u_0 \equiv 0\pmod k$ admits ?
I think we can start with the decomposition theorem $k=p_1^{a_1}...p_l^{a_l}$. Maybe it will give a system in CRT style.
Here's my attempt :
First important fact : if $k\mid u_n\Leftrightarrow p_1^{a_1}...p_l^{a_l}\mid u_n\Rightarrow \exists i\in \{1,...,l\}, \ p_i^{l_i}\mid u_n$.

For a factor $p_i^{a_i}$ we try to find the number of solutions
  $\pmod{p_i^{a_i}}$ of the equation : $u_nx^n+...+u_1x+u_0\equiv 0
 \pmod{p_i^{a_i}}$.
By induction on $n$ I have :
-For $n=0$ : the equation becomes : $u_1x\equiv -u_0 \pmod{p_i^{a_i}}$.
The equation becomes $u_1x\equiv -u_0 \pmod{p_i^{a_i}}$. But we have
  $\gcd(u_1,p_i)=1$ and by property of Bézout we can deduce that
  $\gcd(u_1,p_i^{a_i})=1$. So $u_1$ has an inverse element and we can
  take $x\equiv -u_1^{-1}u_0 \pmod{p_i^{a_i}}$ which represents one
  solution (the only one).
-For $n=n+1$ : the equation becomes $u_{n+1}x^{n+1}+u_nx^n+...+u_1x+u_0\equiv 0 \pmod{p_i^{a_i}}$.If  I
  consider $y$ a solution of the equation with the multiplicity $e=1$
  (for instance) we have the fact that we can factorize the equation by
  $(x-y)^{e}$ .
It gives $(x-y)^{e}P(x)\equiv 0 \pmod{p_i^{a_i}}$ with $P$ a degree
  $n$ polynomial and with highest coefficient $u_{n+1}$ such that
  $\gcd(p_i^{a_i},u_{n+1})=1$. So the equation admits at most $n+1$
  solutions $\pmod{p_i^{a_i}}$.
So there is at most $n$ solutions for $\pmod{p_i^{a_i}}$ and for each
  $i\in \{1,...,l\}$.
If I want to use the CRT it gives a systeme of $l$ lines where each
  polynomials admit at most $n$ solutions. How can I conclude $\pmod k$
  (it's not a field) ?
If we suppose that for each $p_i^{a_i}$ there are at most $n$
  solutions we can factorize the $l$
  lines with $n$ factors.

Unfortunately this fact is false (look at $(x-1)(x-2)(x-4)\equiv 0 \pmod{9}$ which have $4$ solutions instead of $3$).
Here is the main system :
$\left\{\begin{array}{rl}
           u_{n}(x-x_{1_1})(x-x_{1_2})...(x-x_{1_n}) &\equiv 0  \pmod{p_1^{a_1}} \\
              &\vdots \\
           u_{n}(x-x_{i_1})(x-x_{i_2})...(x-x_{i_n}) &\equiv 0  \pmod{p_i^{a_i}} \\
              &\vdots \\
           u_{n}(x-x_{l_1})(x-x_{l_2})...(x-x_{l_n}) &\equiv 0  \pmod{p_l^{a_l}} \\
           \end{array}
            \right.$
And for instance by Euclid's lemma (for the case of $(a_i)_{i\{1,...,l\}}=1$) to count the number of systems :  for $u_{n}(x-x_{1_1})$ we have $(n^{(l-1)})$ systems possible with one solution. It's the same for each $u_{n}(x-x_{i_j})$ with $j\in \{1,...,n\}, \ i=1$ right.If it's the case it will give $n^l$ solutions.
Thanks in advance !
Comment: start with two extremes: first, squarefree numbers $pq,$ then $pqr.$
Comment: @WillJagy later I will post an advancement. But we'll see where the problem is ;)
Answer: By CRT, the number of solutions mod $k$ is the product of the numbers of solutions mod $p_i^{a_i}$.  So we reduce to working mod $p^a$.  But  you want to make your assumption $\gcd(k, a_n) =1$, not $k \not\mid a_n$.
Suppose your polynomial $f(x)$ has degree $n$.  Mod $p$ it may have up to
$n$ linear factors, counted by multiplicity.  Each solution mod $p^{a}$ is also a solution mod $p$.  Hensel's lemma says if  $f(r) \equiv 0 \mod p$ and $f'(r) \not\equiv 0 \mod p$, there is a unique solution of $f(x)=0 \mod p^a$ such that $x \equiv r \mod p$.  But if $f'(r) \equiv 0 \mod p$ (i.e. $r$ is a multiple root mod $p$), there may be more: maybe as many as $p^{a-1}$.  So if $a > 1$ we get
a bound of $p^{a-1} n/2$ solutions mod $p^a$. This is probably not best possible, but it's a start.
Comment: Where does $\frac{n}{2}$ comme from ?
Comment: $f(x)$ has at most $n$ roots mod $p$, counted by multiplicity.  A root  that has multiplicity $m>1$ could correspond to $p^{a-1}$ roots mod $p^a$, while any with multiplicity $1$ just get one root mod $p^a$.  The worst case is that you have $n/2$ distinct roots, each of multiplicity $2$, resulting in $p^{a-1}n/2$ roots mod $p^a$.
Comment: For a root of multiplicity 2, why is p^(a-1) the upper bound (per double root)?  The number of solutions to x^2=0 mod p^a is about p^(a/2).
Comment: It seems that with this answer the maximum case is not reached when each equation $\pmod {p_i^{a_i}}$ has $n$ distinct solutions. I'm confused...
Comment: Maybe it is $p^{a/2}$:  that's $\le p^{a-1}$ if $a \ge 2$, so my bound stands.
Comment: OK.  The words "maybe as many as" $p^{a-1}$ in the answer seemed to say that $p^{a-1}$ was the maximum possible number of liftings of a multiple root mod $p$ to a solution mod $p^a$, which is only true when $n \geq a$. But actually $p^{a-1}$ refers to the number of liftings per element, and the argument is that (number of solutions mod $p^a$) $\leq$ (number of mod $p$ solutions)x($p^{a-1} = $ number of liftings of each solution to an element, not required to be a solution, mod $p^a$).   This could be made clearer in the answer.
Comment: @zyx I noticed that you can have more solutions $\pmod {p^a}$ than for $\pmod p$. Is it due to multiplicity ? That fact contradict my beginning of the proof ?
Comment: @zyx Could you be more precise about the "lifting" argument please ? Moreover notice that for $a<n$ the number of roots $\pmod{p^a}$ is the same as $\pmod p$.
Comment: Whether the number is the same depends on the Newton polygon of f(x).  This may require some correction of my answer, which uses only the multiplicity of the solution mod p.  I think that is correct when f(x) is monic mod p, as was assumed there, but I am not certain at the moment and have deleted the answer until I have time to check it.   @Maman
Comment: As for @RobertIsrael 's lifting argument I think it is as I wrote above: there are $p^{a-1}$ potential solutions mod $p^a$ per solution mod $p$, so the bound is (number of mod $p$ solutions) x ($p^{a-1}$) assuming that all solutions are multiple roots in the extremal cases.  I think the answer would be clearer if edited to say that.
Comment: @zyx maybe $\lfloor \frac{n}{2} \rfloor$ ?


Question about the proof of $e$ irrationality

Question: I found an article with the following elementary proof of $e$ irrationality
https://people.ohio.edu/diao/papers/Irrationality%20of%20e.pdf.
But I am having trouble understanding one step.
It states that, from:
\begin{equation}
 \frac{p_{n+1}}{q_{n+1}} = \frac{n p_{n} - q_{n}}{q_n}
\end{equation}
follows:
\begin{equation}
 q_n \geq q_{n+1}
\end{equation}
I can not understand why this is so. Can anyone explain in more detail?
Comment: Yes, that's a weird step all right. Rearrangements don't seem to help.
Answer: Both fractions$$\frac{p_{n+1}}{q_{n+1}}\quad\text{and}\quad\frac{np_n-q_n}{q_n}$$are equal to the same rational number, but the first one is an irreducible fraction. Therefore, and since both numerators and both denominators are natural numbers, $np_n-q_n\geqslant p_{n+1}$ and $q_n\geqslant q_{n+1}$. Actually, not only we have $q_n\geqslant q_{n+1}$ as, in fact, $q_n=Nq_{n+1}$ for some $N\in\Bbb N$.
Comment: Thank you! "same" and "irreducible" are really a key words for understanding
Comment: Indeed. But it took me several minutes before I was able to see it. Anyway, I'm glad I could help.
Answer: If (as in the paper you cite) you have:
$$
 \frac{p_{n+1}}{q_{n+1}} = \frac{n p_{n} - q_{n}}{q_n}
$$
where $p_{n+1}$ and $q_{n+1}$ are coprime, you must have
$$
q_{n+1} = \frac{q_n}{\gcd(np_n - q_n, q_n)} \le q_n
$$
Answer: The proof states that $p_n$ and $q_n$ are relatively prime.
So, if you rewrite $$\frac{p_{n+1}}{q_{n+1}} = \frac{n p_{n} - q_{n}}{q_n}$$
as $$p_{n+1}q_{n} = (np_{n}-q_{n})q_{n+1}$$ you can see that $p_{n+1}$ has to divide $np_{n}-q_{n}$ in words $np_{n}-q_{n} \ge p_{n+1}$
Now just plug in this estimation to the first equation to the what you need.
By the way, nice proof, thanks for bringing it up.


Sub menu not displaying in Bartik Theme

Question: I am using Drupal 7.9.
I need to display main menu with sub-menu.
print theme('links__system_main_menu', array(
'links' => $main_menu,
'attributes' => array(
'id' => '',
'class' => array('menu'),),
'heading' => array(
'text' => t('Main menu'),
'level' => 'h2',
'class' => array('element-invisible'),
),)
);

That is the code I have used, but it does not show sub-menu items.
Then i have also tried following code :
if ($main_menu){
  $pid = variable_get('menu_main_links_source', 'main-menu');
  $tree = menu_tree($pid);
  $tree = str_replace(' class="menu"', '', $tree);
  $main_menu = drupal_render($tree);
  }
else {
  $main_menu = FALSE;
}
if ($main_menu): print $main_menu;
endif;

Even it does not display sub-menu.
Does anybody know a solution?
Answer: The main menu in Bartik only displays the first level.  Since it's hardcoded in page.tpl.php there's nothing you can do about it.
Here's how to get the menu to work properly:

In your theme settings (admin/appearance/settings/barti) disable "Main menu"
Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it)

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.

Sub menu not displaying in Bartik Theme


Rank of sum of matrix and arbitrarily small matrix

Question: Suppose I have an $n\times n$ matrix $A$ with full rank. Let $B$ be another $n\times n$ matrix and let $c>0$ be a constant. Can we always find a constant $c>0$ sufficiently small such that
$$
A + cB
$$
also has full rank?
Answer: Yes, because the determinant is a continuous function of the matrix entries. If it's not zero then it's not zero for nearby matrices.
Edit in response to comment.
This is true for rectangular matrices too. To prove it, note that Gaussian elimination produces the reduced row echelon form $R$ of $M$ by multiplication on the right by an invertible matrix $A$. Now $M$ is full rank if and only if $R$ has a full rank (identity) matrix in its upper left corner. You can perturb that corner and keep it full rank. Since multiplication by $A$ is a continuous bijection, matrices near $M$ will be full rank.
Comment: Great, thank you for the response. Do you have a similar argument for non square matrices?
Comment: Yes. See my edit.
Comment: Does it hold even if $B$ is not full rank?
Comment: @CloudJR Yes. The rank of $B$ is irrelevant. Read the proof sketch in the answer.
Answer: Another approach, valid over any field with more than $n+1$ elements:
Since $A$ is full rank and square, it has an inverse. Then
$$\det(A+cB)=\det(A(I+cA^{-1}B))=\det(A)\det(I+cA^{-1}B).$$
Since $\det(A)\neq0$, $A+cB$ is full rank iff $\det(I+cA^{-1}B)\neq0$.
Now, if $c\neq0$ then $\det(I+cA^{-1}B)=c^n\det(c^{-1}I+A^{-1}B)$, so $A+cB$ is full rank iff $$\det(c^{-1}I+A^{-1}B)\neq0.$$
This happens iff $-c^{-1}\not\in$Spec$(A^{-1}B)$. So there are at most $n$ values of $c$ which do not give full rank.


Como importar dados (.csv) para o R mantendo o formato original

Question: Estou tentando importar dados do Excel (já em formato .csv) para o R; os valores contidos nos arquivos a serem importados estão nos seguintes formatos, por exemplo, 8509,80...
Para fazer a importação, estou utilizado o comando:
variavel=read.table("dados.csv", header=T, dec=",")

Entretanto, quando da visualização dos dados importados, vejo que o R importou apenas a parte que não é inteira do número (no caso, o R traria para o valor de 8509,80 apenas o 80).
Desta forma, peço a gentileza de me ajudarem a fazer a importação da forma correta, ou seja, o valor de 8509,80 (em padrão inglês seria 8509.80).
Answer: Você precisa definir o separador dos campos. No seu caso, como deve ser o csv europeu/brasileiro, o separador provavelmente é ";".
variavel=read.table("dados.csv", header=T, dec=",", sep=";")

Um atalho para isso é usar a função read.csv2:
variavel=read.csv2("dados.csv", header=T)

Comment: amigo, deu certo, obrigado.
Answer: As funções do base para leitura de tabelas são suficientes para atender a maioria dos casos. No entanto, elas são relativamente lentas, e existem alternativas mais rápidas caso sejam muitos arquivos e/ou eles sejam muito grandes, que também possuem outras pequenas vantagens.
O pacote readr foi criado exatamente com o objetivo de melhorar as funções padrão, nos seguintes pontos:

Os argumentos possuem nomes mais consistentes um com os outros (e.g. col_names e col_types e não header and colClasses).
Sâo aproximadamente 10x mais rápidas.
Mostram uma progress bar caso a leitura demore mais que alguns segundos.
Strings não são transformadas em fatores por padrão.
Os nomes das colunas não são transformados em expressões "válidas" do R, ou seja, as colunas mantém o nome idêntico ao original (mesmo que comecem com número, possuam espaço, etc).

Neste pacote as funções possuem nome similar às do base, substituindo o ponto por um underscore (_). Por exemplo:
#base:
variavel <- read.table("dados.csv", header=T, dec=",", sep=";")
variavel <- read.csv2("dados.csv", header=T)

#readr
library(readr)
variavel <- read_csv2("dados.csv")

De forma análoga, existem as funções read_csv(), read_table(), read_delim(), read_tsv(), read_lines() e read_fwf().
Outra alternativa, também, é a função fread() do pacote data.table. A fread() é ainda mais rápida (cerca de 2x) que as funções do pacote readr, e tenta identificar automaticamente o separador, se há nome de colunas, etc. A função fread() possui argumentos com nomes iguais aos das funções do base, como sep, header e stringsAsFactors. Neste exemplo, ficaria assim:
library(data.table)
variavel <- fread("dados.csv", sep = ";", header = TRUE)

Dependendo do formato dos dados, sep e header podem ser omitidos, mas na dúvida, é mais seguro colocá-los de forma explícita.
Para finalizar, é importante frisar que só faz sentido usar essas funções se a performance da leitura for um problema, ou se o pacote já for carregado de qualquer forma (no caso do data.table). Caso contrário, não há necessidade de carregar um pacote para fazer algo que pode ser feito de forma idêntica no base.
Comment: Muito obrigado pelo esclarecimento.
Comment: +1 só vale a pena colocar a ressalva que o `fread` geralmente dá problema de encoding se os dados tiverem muitos caracteres acentuados etc.


Re-writing Page name

Question: Link#1  "medical.html" we change that page to
Link#2  "medical-transcription.html"
I want the person who clicked Link#1 to go to Link#2, not our home page.  It is transparent to the end user because they find the information they want and it allows us to pass along (and keep) our search engine rankings.
Comment: what web server are you using?
Comment: i am using IIS 7.0 as it have URL redirection is working fine http://outsourcestrategies.com/
Answer: You'll want to setup either a 301 or 302 redirect within IIS, there is a good article on IIS redirection you can refer to.
Comment: Thx for the Reply, but redirection is working fine in .htaccess i am asking is there any possibilities to rename "medical.html" to "medical-transcription.html" people come and clicks on the link medical.html but he see the url is medical-transcription.html. Issue is both are same extinction. if any info pls Help i need urgent :)
Comment: Arun, I must not be understanding what you are asking. If you setup a redirect for http://servername/medical.html to http://servername/medical-transcription.html then it should seamlessly move a user to the 2nd url when they click on the first (and the same for search links, etc.)

Re-writing Page name


R dplyr join by range or virtual column

Question: I want to join two tibbles by a range or a virtual column. but it seems the by - parameter just allow to handle chr oder vector(chr) of existing column names.
In my example I have a tibble d with a column value, and a tibble r with a from and a to column.
d <- tibble(value = seq(1,6, by = 0.2))
r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), class = LETTERS[seq(1,6)])

> d
# A tibble: 26 x 1
   value
   <dbl>
 1   1.0
 2   1.2
 3   1.4
 4   1.6
 5   1.8
 6   2.0
 7   2.2
 8   2.4
 9   2.6
10   2.8
# ... with 16 more rows

> r
# A tibble: 6 x 3
   from    to class
  <int> <dbl> <chr>
1     1     2     A
2     2     3     B
3     3     4     C
4     4     5     D
5     5     6     E
6     6   Inf     F

now I want to join the value column in d within the range of from and to in r:
d %>% inner_join(r, by = "value between from and to")     # >= and <

I can't find a way to do this so decided to join the floor of value in d with the from column in r
d %>% inner_join(r, by = c("floor(value)" = "from"))

of course i can create a second column to solve that:
d %>%
  mutate(join_value = floor(value)) %>%
  inner_join(r, by = c("join_value" = "from")) %>%
  select(value, class)

# A tibble: 26 x 2
   value class
   <dbl> <chr>
 1   1.0     A
 2   1.2     A
 3   1.4     A
 4   1.6     A
 5   1.8     A
 6   2.0     B
 7   2.2     B
 8   2.4     B
 9   2.6     B
10   2.8     B
# ... with 16 more rows

but isn't there a more comfortable way?
Thanks
Comment: Hi. Super interesting thread - just a minor comment -  as far as I can see, no accepted answer yet, although many good answers, incl. your own?
Answer: I don't think inequality joins is implemented in dplyr yet, or it ever will (see this discussion on Join on inequality constraints), but this is a good situation to use an SQL join:
library(tibble)
library(sqldf)

as.tibble(sqldf("select d.value, r.class from d
                join r on d.value >= r.'from' and
                          d.value < r.'to'"))

Alternatively, if you want to integrate the join into your dplyr chain, you can use fuzzyjoin::fuzzy_join:
library(dplyr)
library(fuzzyjoin)

d %>%
  fuzzy_join(r, by = c("value" = "from", "value" = "to"),
             match_fun = list(`>=`, `<`)) %>%
  select(value, class)

Result:
# A tibble: 31 x 2
   value class
   <dbl> <chr>
 1   1.0     A
 2   1.2     A
 3   1.4     A
 4   1.6     A
 5   1.8     A
 6   2.0     A
 7   2.0     B
 8   2.2     B
 9   2.4     B
10   2.6     B
# ... with 21 more rows

Notice I added single quotes around from and to since those are reserved words for the SQL language.
Comment: @JamesCrumpler Yes, functions with non-standard names have to be surrounded by backticks.
Comment: Elegant solution.  I needed to replace the ">=", "<" with single backticks match_fun = list(`>=`, `<`)) in order for the match_fun to work.  Kept getting a logical argument error, in any case, a good solution to categorizing by ranges.
Answer: Ok thanks for advices, this was pretty interesting. I finally wrote a function range_join (inspired by @ycw's code) and compared all described solution in view of runtime.
I like fuzzy_join but with only 50k rows in d it needs more than 40sec. Thats too slow.
Here the result with 5k rows in d
library(dplyr)
library(fuzzyjoin)
library(sqldf)

#join by range by @WiWeber
range_join <- function(x, y, value, left, right){
  x_result <- tibble()
  for (y_ in split(y, 1:nrow(y)))
    x_result <-  x_result %>% bind_rows(x[x[[value]] >= y_[[left]] & x[[value]] < y_[[right]],] %>% cbind(y_))
  return(x_result)
}

#dynamic join by @ycw
dynamic_join <- function(d, r){
  d$type <- NA_character_
  for (r_ in split(r, r$type))
    d <- d %>% mutate(type = ifelse(value >= r_$from & value < r_$to, r_$type, type))
  return(d)
}

d <- tibble(value = seq(1,6, by = 0.001), join = TRUE)
r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), type = LETTERS[seq(1,6)], join = TRUE)

# @useR sqldf - fast and intuitive but extra library with horrible code
start <- Sys.time()
d2 <- tbl_df(sqldf("select d.value, r.type from d
                join r on d.value >= r.'from' and
                d.value < r.'to'"))
Sys.time() - start

# @useR fuzzy_join .... very cool but veeeeeeeeeeeeeeeery slow
start <- Sys.time()
d2 <- d %>%
  fuzzy_join(r, by = c("value" = "from", "value" = "to"), match_fun = list(`>=`, `<`)) %>%
  select(value, type)
Sys.time() - start

# @jonathande4 cut pretty fast
start <- Sys.time()
d2 <- d
d2$type <- cut(d$value, unique(c(r$from, r$to)), r$type, right = FALSE)
Sys.time() - start

# @WiWeber floor
start <- Sys.time()
d2 <- d %>%
  mutate(join_value = floor(value)) %>%
  inner_join(r, by = c("join_value" = "from")) %>%
  select(value, type)
Sys.time() - start

#  @WiWeber cross join - filter
start <- Sys.time()
d2 <- d %>%
  inner_join(r, by = "join") %>%
  filter(value >= from, value < to) %>%
  select(value, type)
Sys.time() - start

# @hardik-gupta sapply
start <- Sys.time()
d2 <- d %>%
  mutate(
    type = unlist(sapply(value, function (x) r[which(x >= r$from & x < r$to), "type"]))
  ) %>%
  select(value, type)
Sys.time() - start

# @ycw re-dynamic join
start <- Sys.time()
d2 <- d %>% dynamic_join(r)
Sys.time() - start

# @WiWeber range_join
start <- Sys.time()
d2 <- d %>%
  range_join(r, "value", "from", "to") %>%
  select(value, type)
Sys.time() - start

Results:
# @useR sqldf - fast and intuitive but extra library with horrible code
Time difference of 0.06221986 secs

# @useR fuzzy_join .... very cool but veeeeeeeeeeeeeeeery slow
Time difference of 4.765595 secs

# @jonathande4 cut pretty fast
Time difference of 0.004637003 secs

# @WiWeber floor
Time difference of 0.02223396 secs

# @WiWeber cross join - filter
Time difference of 0.0201931 secs

# @hardik-gupta sapply
Time difference of 5.166633 secs

# @ycw dynamic join
Time difference of 0.03124094 secs

# @WiWeber range_join
Time difference of 0.02691698 secs

greez WiWeber
Comment: Thanks for sharing your function and comparing the results. I learned a lot! You got my upvote.
Comment: `range_join <- function(x, y, value, left, right){
  x_result <- tibble()
  for (y_ in split(y, 1:nrow(y))){
    d_ <- x[x[[value]] >= y_[[left]] & x[[value]] < y_[[right]],]
    if(nrow(d_) > 0)
      x_result <-  x_result %>% bind_rows(d_ %>% cbind(y_))
  }
  return(x_result)
}`
Comment: range_join gives an error if there are no records that fall between range. I've made an update on separate comment
Answer: You use the cut function to create a "class" in object d and then use a left join.
d <- tibble(value = seq(1,6, by = 0.2))
r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), class = LETTERS[seq(1,6)])

d[["class"]] <- cut(d[["value"]], c(0,2,3,4,5,6,Inf), c('A',"B", "C", "D", "E", "F"), right = FALSE)
d <- left_join(d, r)

To get the right buckets, you just need to work with the cut function to get what you want.
Comment: `d$class <- cut(d$value, unique(c(r$from, r$to)), r$class, right = FALSE)`

I like that, the only disadvantage: its acting like a `left_join`, so I have to remove data from d which are out of range ( less 1)
But thanks that was really helpful.
Answer: We can use mutate and case_when from dplyr.
library(dplyr)

d2 <- d %>%
  mutate(class = case_when(
    value >= 1 & value < 2 ~ "A",
    value >= 2 & value < 3 ~ "B",
    value >= 3 & value < 4 ~ "C",
    value >= 4 & value < 5 ~ "D",
    value >= 5 & value < 6 ~ "E",
    value >= 6             ~ "F"
  ))
d2
# A tibble: 26 x 2
   value class
   <dbl> <chr>
 1   1.0     A
 2   1.2     A
 3   1.4     A
 4   1.6     A
 5   1.8     A
 6   2.0     B
 7   2.2     B
 8   2.4     B
 9   2.6     B
10   2.8     B
# ... with 16 more rows

Update
Here is a workaround by defining a function for this task.
d <- tibble(value = seq(1,6, by = 0.2))
r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), class = LETTERS[seq(1,6)])

library(dplyr)

# Define a function for dynamic join
dynamic_join <- function(d, r){

  if (!("class" %in% colnames(d))){
    d[["class"]] <- NA_character_
  }

  d <- d %>%
    mutate(class = ifelse(value >= r$from & value < r$to, r$class, class))
  return(d)
}

re_dynamic_join <- function(d, r){
  r_list <- split(r, r$class)
  for (i in 1:length(r_list)){
    d <- dynamic_join(d, r_list[[i]])
  }
  return(d)
}

# Apply the function
d2 <- d %>% re_dynamic_join(r)
d2
# A tibble: 26 x 2
   value class
   <dbl> <chr>
 1   1.0     A
 2   1.2     A
 3   1.4     A
 4   1.6     A
 5   1.8     A
 6   2.0     B
 7   2.2     B
 8   2.4     B
 9   2.6     B
10   2.8     B
# ... with 16 more rows

Comment: I agree with @WiWeber, while this works for the specific example, it is not very practical as you will have to change the cases everytime the `r` table is modified, not to mention how tedious it will be to add more cases manually.
Comment: the problem is, the example is pretty simple i need it for dynamic range tibble
Comment: @WiWeber Please see my update. This is a workaround by creating a function `re_dynamic_join`. This will perform the join task and be part of the pipe operation. `dplyr` is the only package needed for this solution.
Comment: @ycw I used your solutions and compared them in a answer above. thanks
Comment: @useR I used your solutions and compared them in a answer above. thanks
Answer: We can use sapply for this
library(tibble)

d <- tibble(value = seq(1,6, by = 0.2))
r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), class = LETTERS[seq(1,6)])
d <- cbind(d, data.frame(class = (unlist(sapply(d$value, function (x) r[which(x >= r$from & x < r$to), "class"]))) ) )

d
   value class
1    1.0     A
2    1.2     A
3    1.4     A
4    1.6     A
5    1.8     A
6    2.0     B
7    2.2     B
8    2.4     B
9    2.6     B
10   2.8     B
11   3.0     C
12   3.2     C
13   3.4     C
14   3.6     C
15   3.8     C
16   4.0     D
17   4.2     D
18   4.4     D
19   4.6     D
20   4.8     D
21   5.0     E
22   5.2     E
23   5.4     E
24   5.6     E
25   5.8     E
26   6.0     F

Answer: I really liked @WiWeber's range_join function, but it gives an error if a record is not within range. Here's a modification
library(dplyr)

d <- tibble(value = c(seq(1,4, by = 0.2),9))
r <- tibble(from = seq(1,5), to = c(seq(2,5),8), class = LETTERS[seq(1,5)])

range_join <- function(x, y, value, left, right){
all_matches <- tibble()
x = as.data.frame(x)
y = as.data.frame(y)
x$index=x[,value]
for (i in 1:nrow(y)){
    matches = x %>% filter(index>=y[i,left] & index<= y[i,right])
    if (nrow(matches)>0){
        all_matches = all_matches %>% bind_rows(matches %>% cbind(y[i,]))
    }
}
all_matches = all_matches %>% select(-index)
return(all_matches)
}

data <- d %>%
range_join(r, "value", "from", "to")

data

R dplyr join by range or virtual column