Looking for good, recent examples of Discriminant Analysis (Linear, Quadratic or else) in applied research

Question: We have looked at LDA/QDA several times during my stats masters coursework, but I'm not convinced that it's due to the usefulness of the techniques more than my school being stuck with a 20-year old curriculum.
This answer by Frank Harrell suggests that these techniques aren't very useful nowadays, and even the textbook we're using indicates that LDA/QDA is only expected to perform significantly better than logistic regression when the assumptions are met, which seems fairly disqualifying for most purposes.
To make my title request more specific, I'm looking for at least two different examples (i.e. not the same type of problem, preferably different disciplines) that are

Good: clearly the most optimal tool to solve the problem at hand, not just being used in place of logistic regression because of researcher preference
Recent: published in the last six years
"... or else": need not be textbook LDA/QDA. It's okay if the technique is an extension of the above models, but it should obviously follow the same reasoning i.e. related to a decision rule based on distributional assumptions on predictors conditional to the outcome of interest

Alternatively, it would also be acceptable if someone can provide proof that any formulation of a discriminant-type model can be re-expressed as a regression problem (e.g. linear regression produces results equivalent to LDA).
Comment: For the last part on equivalence check these great answers https://stats.stackexchange.com/questions/31459/what-is-the-relationship-between-regression-and-linear-discriminant-analysis-ld
Answer: I am using LDA for neuroscience research. Traditionally in neuroscience people "analyze one neuron at a time" and use the measures of all the sampled neurons to test statistical significance.
In recent years population-level analysis is gaining its attention. Especially for high level cognition, single neuron usually does not have a one-on-one relation to behavior. By building a classifier on the neuronal population, one can get insight on how information is encoded in the brain.
LDA, albeit simple, has advantages for my and most neuroscience projects. (some are specific to the comparison to LR, some are not)

comparing to logistic regression, most importantly it's easier to classify more than 2 classes with LDA.
usually in neuroscience datasets are high dimensional low sample size. As a linear classifier, LDA fits relatively less parameters. Fancier classifiers may lead to overfitting. LR seems also to perform worse in this case.
LDA is simple to understand and to interpret. In neuroscience, performance is not all that matters. The rationale is to micmic living brain and to understand it. Thus LDA is suitable, textbook LDA is even the best. In multi class situation, classes in LDA are interpreted as the clusters in discriminant space.
Analogy can be drawn between LDA and neurobiology. LDA, assuming identical covariance matrix for each class, use linear combination as discriminant axes, which is feasible biologically and is usually how theoretical neuroscientists assume the neural network to work.
LDA is also a dimensionality reduction algorithm, which is extremely useful to neuroscience, of which the principle is to compress the over-complicated biological data and make understandable visualization...

there is also a good thread here: Logistic regression vs. LDA as two-class classifiers
One recent paper that used LDA for neuroscience.
https://doi.org/10.1038/s41593-017-0003-2
A book chapter on patter classification in neuroscience. It compares a dozen of decoders for the purpose of neuroscience.
http://klab.tch.harvard.edu/publications/PDFs/8404_019.pdf
Comment: +1 I like the way you refer to domain specific examples - cool answer welcome to SE
Comment: Thanks for the answer! Please link to a specific paper or review that shows the technique being applied as you describe and I will accept this.
Comment: 2 links updated. hope it's useful to you.
Comment: +1 Nice detailed answer. Domain-specific examples reveal new insights, always helpful


Organic group membership request

Question: I need help setting up a notification system for when a user requests to join a group.
At the moment, when the user types in their message and click the join button, the administrator receives no email notification of a users join request.
Can anyone help ?
Answer: In OG 7.2 you need to enable Rules module then enable the two rules for "Pending" and "Active" memberships
Answer: If I remember correctly this feature hasn't been implemented. I'm just hiding the field with CSS.

Organic group membership request


Dropping a table in mySQLi db if contains value in name

Question: I'm trying to delete one or multiple tables at once in my mySQLi db if it contains a string variable. So for example lets say I have 5 tables in my db:
Table 1 -
name: db_table1_hello
Table 2 -
name: db_table2_world
Table 3 -
name: db_table3_hello
Table 4 -
name: db_table4_world
Table 5 -
name: db_table5_hello
Now I have a variable called tableString and has the value hello, in theory it would then be used to drop table 1, 3, and 5.
Not really sure on the best way to go about doing this so I thought I'd post it and get an idea from someone with a little more experience then me.
Thanks in advance guys.
EDIT:
$sql = "";

    if(mysqli_query($conn, $sql)){

        header("Location: " . $_SERVER["HTTP_REFERER"]);

    } else {

        echo "Table deletion unsuccessfully
 ";

    }

Comment: You can get table names by `SHOW TABLES [FROM db_name] [LIKE 'pattern']`, and than drop tables that it found.
Answer: Referring to this SO Answer, you can filter tables names from information_schema.tables table like this:
SELECT table_name FROM information_schema.tables WHERE table_name like '%hello%';

So you can create a statement englobing the previous select in this way:
DELIMITER $$
SET @s = SELECT CONCAT('DROP TABLE ',table_name,';')
         FROM   information_schema.tables
         WHERE table_name like '%hello%'$$
DELIMITER ;
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

EDIT:
The question has changed asking for a PHP routine to drop tables.
In PHP you should run the first SQL to get table names, then delete with a loop those tables:
$tableString = "hello";

$sql = "SELECT table_name FROM information_schema.tables WHERE table_name like '%$tableString%'";

$res = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($res)) {
    $tname = $row[0];
    $result = mysqli_query($conn, "DROP TABLE $tname");
    if (!$result) echo "Table $tname deletion unsuccessfully
 ";
}

Comment: Thanks for answering, I've added an edit to my post. How would I implement this into my query `$sql`?


Link To Already Defined Path In Menu Using hook_menu()

Question: I'm sure this is an obvious answer but I seem to be missing something important.
How can I add a link to a menu using hook_menu() to an already defined path?
I'm trying to add a direct link to a node/add page that already exists.
I need to use hook_menu() instead of the control panel.
Answer: You can best use hook_menu_alter(), which should be used when "Additional items may be added, or existing items altered."
In custom_node_add.module :
function custom_node_add_menu_alter(&$items) {
  if (aray_key_exists) { //some sanity checking;
    $items['node/add']['page callback'] = 'custom_node_add_page'
  }
}

function custom_node_add_page() {
  return t("Hello World! This is content on my node/add page");
}

Answer: I really should have spent more time searching.  The following works beautifully in hook_menu();
$items['customeurltocreate/nodetype'] = array(
        'title' => 'Create Node Type',
        'page callback' => '_menu_create_node_type',
        'type' => MENU_NORMAL_ITEM,
    );

function _menu_create_node_type() {
    module_load_include('inc', 'node', 'node.pages');
    return node_add('node_type');
}

Comment: This only works if your module is called after that other module; which is very flakey. You should either force your module to be ran after that other by changing the weight in the system table. Or use [hook_menu_alter](http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu_alter/7)


If $A$ has column $1$ + column $2$ $=$ column $3$, show that $A$ is not invertible:

Question: (a) Find a nonzero solution $x$ to $Ax = 0$. The matrix is $3$ by $3$.
My solution:
$$\begin{bmatrix} { a }_{ 1 } & { b }_{ 1 } & { a }_{ 1 }+{ b }_{ 1 } \\ { a }_{ 2 } & b_{ 2 } & { a }_{ 2 }+{ b }_{ 2 } \\ { a }_{ 3 } & b_{ 3 } & { a }_{ 3 }+{ b }_{ 3 } \end{bmatrix}\cdot \begin{bmatrix} 1 \\ 1 \\ -1 \end{bmatrix}=\begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix}$$
Therefore, the vector $x = \begin{bmatrix} 1 \\ 1 \\ -1 \end{bmatrix}$ solves $Ax =0$
(b) Elimination keeps column $1$ $+$ column $2$ $=$ column $3$. Explain why there is no third pivot.
Now, I have no idea how to approach the second part of this question. I would appreciate a hint that would allow for me to figure it out on my own.
Answer: If there is a third pivot, then elementary row operations can reduce the third row to $(0,0,1)$.
Comment: Ok, I think your hint helped me see the picture better. So, after elimination columns $1$ and $2$ both end in zeros. Then, Column $1$ + Column $2$ $=$ Column $3$ must mean that column $3$ ends in a zero, and thus there is no third pivot. Is that right?
Comment: @Cherry_Developer That's exactly right.


Search using view and facet as block

Question: In my project I need facet search as block view that need to be included in content region. So I created View as block and added facet block in header of the view. Also need infinite scroll, so enabled ajax in view. So issue is that facet search ajax and View ajax causing conflict so that the query parameters are duplicating in URL.
http://localhost.com/sample-page?q=/sample-page?q=/sample-page?filter[0]=category_filter:171&_wrapper_format=drupal_ajax&filter[0]=category_filter:171&filter[1]=category_filter:173&filter[2]=category_filter:174
Is there any workaround to fix this? Any patch is available for this ?
Answer: I applied this patch
https://www.drupal.org/files/issues/2019-07-31/facets-3070461-3-Facet-links-break-in-modal_0.patch and issue resolved. Hope this will be helpful for others.

Search using view and facet as block


Effective way of reading text file in c# for line to line operation

Question: I'm having problem in reading text file for line to line addition  operation. I have used following syntax
StreamReader reader = new StreamReader("input.txt");
    string line;
    while ((line = reader.ReadLine()) != null)
    string[] splitted = line.Split('#');
    string first = splitted[0].Trim();
    string second = splitted[1].Trim();
I have used this syntax to separate the input from text file if file has following values.
12#15
15#7
13#14
23#31
 x= Convert.ToInt32(first);
 y= Convert.ToInt32(second);
 sum = x+y;
 txtBox.text = Convert.ToString(sum);

the problem is it only executes the last line. It only calculate the sum of 23 and 31 and show only but I want to add 12 and 15 first and show it in textbox similarly I want to add others.   please help me in forming appropriate syntax.
Comment: It's unclear what you're asking here.  What code gets executed inside the `while` loop?  What do you mean by "it only executes the last line"?
Comment: look at my example @SangamJung and you will quickly see that you forgot to issue an `Initial Read()` before entering your `while loop`
Comment: I have tried to make my question  little bit clear. And thanx too
Answer: The question is vague one, however, I suggest using Linq:
  var source = File
    .ReadLines("input.txt")           // read line by line
    .Select(line => line.Split('#'))  // split each line
    //.Where(items => items.Length == 2)  // you may want to filter out the lines
    .Select(items => new {            // convert each line into anonymous class
       first = items[0].Trim(),
       second = items[1].Trim()
     });

You can add as many Select (line to line opetations) as you want. Then you can proceed the items in a foreach loop:
  foreach (var item in source) {
    ...
    // Let's read some fields from the anonymous object
    var first = item.first;
    var second = item.second;
    ...
  }

Edit: according to the edited question you want just to sum up which can be done via Linq as well:
  var result = File
    .ReadLines("input.txt")
    .Select(line => line.Split('#'))
    //.Where(items => items.Length == 2)  // you may want to filter out the lines
    .Sum(items => int.Parse(items[0]) + int.Parse(items[1]));

  txtBox.text = result.ToString();

Comment: what will be syntax for using values stored in first and second inside foreach loop
Comment: @Sangam Jung: just `item.first;` or/and `item.second;`
Comment: I have tried to make my question  little bit clear. And thanx too
Comment: @Sangam Jung: well, ut seems that you want to *sum up* the `first` and `last` which can be done with a help of *Linq* as well (see my edit).
Answer: It doesn't only read the last line, you just never do anything with the other iterations. Currently you just keep reassigning line with the value of the latest line that has been read, I presume you hope to save these to a list or similar
StreamReader reader = new StreamReader("input.txt");
string line;
List<string> allLines = new List<string>();
while ((line = reader.ReadLine()) != null)
     allLines.Add(line);

Comment: Note: There are more concise ways to write this code, this answer just fixes the issue you mention in your question.
Comment: I have tried to make my question  little bit clear. And thanx too
Answer: here you can test your File and Load The data into a DataTable this should be pretty straight forward.
DataTable dtTextFileData = new DataTable();
dtTextFileData.Columns.AddRange(new []
{
    new DataColumn("First", typeof(string)),
    new DataColumn("Second", typeof(string))
});

StreamReader file = new StreamReader(@"c:\YourFilePath\input.txt");
string line = file.ReadLine();
while (line != null)
{
    string[] fields = line.Split('#');
    DataRow dr = dtTextFileData.NewRow();
    dr["First"]  = fields[0].ToString();
    dr["Second"] = fields[1].ToString();
    dtTextFileData.Rows.Add(dr);
    line = file.ReadLine();
}

Comment: I have tried to make my question  little bit clear. And thanx too


Service WAS was not found on computer '.'

Question: I am using Windows 7 Professional. When I am trying to start DefaultAppPool in IIS 7.0, I am getting error -

Service WAS was not found on computer '.'.

Is there any changes in setting need to be done?
Answer: Well, start off by checking if it is installed.

Control Panel > Programs > Programs and Features > Windows Process Activation Service
Comment: and then run **iisreset /restart** to make sure both services will run
Comment: In case it helps anyone else, I already had these enabled but was still getting the error.  I just disabled IIS features, restarted my pc, enabled them again, then restarted again and it solved my issue.
Answer: Control Panel > Programs > Turn Windows features on or off > Windows Process Activation Service > SELECT ALL > Click OK
Comment: This was the missing part for me. Thanks @Bopanna!


Solve the equation $z^{4} + (1-i)z^{2} - i = 0$ for $z\in\mathbb{C}$

Question: The proposed equation is given by:
$$z^{4} + (1-i)z^{2} - i = 0$$
MY ATTEMPT
I tried to start solving it like this:
\begin{align*}
(a+bi)^4 + (i - 1)(a + bi)^2 -i = 0 & \Longleftrightarrow a^4 + 4a^3bi - 6a^2b^2 - 4ab^3i + b^4 = 0\\\\
& \Longleftrightarrow a^4 + b^4 = 2ab(3ab + 2b^2i - 2a^2i)
\end{align*}
But I couldn't do it further.
Comment: Set $Z=z^2$, then you'll have a second order equation...
Comment: This quartic is actually a quadratic in $z^2$ which you can solve immediately by formula. After that, the trick is to simplify, take the square roots to find $z$ and simplify some more. There's no need to write $z = a+bi$ right at the beginning.
Answer: HINT
Here it is an alternative way to solve it for the sake of curiosity.
\begin{align*}
z^{4} + (1-i)z^{2} - i = 0 & \Longleftrightarrow (z^{4} + z^{2}) - i(z^{2} + 1) = 0\\\\
& \Longleftrightarrow z^{2}(z^{2} + 1) - i(z^{2} + 1) = 0\\\\
& \Longleftrightarrow (z^{2} - i)(z^{2} + 1) = 0
\end{align*}
Can you take it from here?
Comment: as I undesrtood, roots of (z^2 + 1) = 0 are ±1. But I'm not sure about (z^2 - i) = 0, are the roots ±√i?
Comment: The roots of $z^{2} + 1 = 0$ are $\pm i$. To obtain the roots of $z^{2} - i = 0$, you can express $i = \cos(\pi/2) + i\sin(\pi/2)$ and apply the DeMoivre's formula. Can you take it from here?


menu callback path construction

Question: It seems there is hardly any documentation on page call backs using URLS
This being the case I have 2 questions:
What is a legal callback path?
and what becomes the URL to access that path?
Here is the code on my custom module:
<code>  $menu['tipFeed/arguments/%'] = array(
'page callback' => 'tipfeed_create',
'page arguments' => array(2),
'access arguments' => array('access arguments page'),
'type' => MENU_CALLBACK,
);
</code>
Here is the function it refers to:
<code>function tipfeed_create($first){
     return 'cool';
}
</code>
My module is called tipFeed.
why is the URL http://www.example.com/tipFeed/arguments/1 saying page not found?
Any help would be great, thank you
Comment: I've made a couple mistakes when doing hook_menu entries.
Make sure your hook_menu callback is returning $menu. Also as @zhilevan said, clear the cache after any hook_menu change. For this callback, % is a wildcard. tipFeed/arguments will be an invalid path, but tipFeed/arguments/anythinghere would be a valid path.
Answer: everything is ok, just try to clear cache and don't forget never, after any change in hook_menu clear cache

menu callback path construction


How do I convert gauge32 to integer?

Question: Can anyone help me in this? I am trying to monitor the humidity for my network device and I did the snmpwalk which is:
snmpget -v2c -cpublic -mALL 172.x.x.x .184.108.40.206.4.1.13742.4.2.x.x.x.x
and it stated:
SNMPv2-SMI::enterprises.137220.127.116.11.1.x.x = Gauge32: 2147483647
So what does the gauge32 means? And is there any way I can convert it to integer?
Comment: Gauge32 is an unsigned 32 bit integer internally. What is the problem you are facing? The conversion to integer is almost automatic.
Comment: Thank you for your response Sir. I edited my question
Comment: Possible duplicate of [Definition of SNMP Gauge32 vs Counter32](http://stackoverflow.com/questions/2718283/definition-of-snmp-gauge32-vs-counter32)
Answer: The MIB object that you are trying to poll is defined in PDU-MIB from raritan [1]
<code>RelativeHumidity   ::= TEXTUAL-CONVENTION
           DISPLAY-HINT "d"
                   STATUS      current
                   DESCRIPTION
                       "Data type for reporting sensor readings and thresholds
                       associated with humidity sensors. Relative humidity is
                       expressed as percentage and is defined as the ratio of the
                       partial pressure of water vapor in a gaseous mixture of
                       air and water vapor to the saturated vapor pressure of water
                       at a given temperature."
                   SYNTAX Unsigned32 (0..100)

humidity                OBJECT-TYPE
                        SYNTAX        RelativeHumidity
                        MAX-ACCESS    read-only
                        STATUS        current
                        DESCRIPTION
                            "The value of the external humidity sensor reported
                            as relative humidity (a percentage)."
                        ::= { humiditySensorEntry 3 }
</code>
So your relative humidity should be in range [0..100]. There could be two problems:

The NET-SNMP fails to display the value properly for some reason
The SNMP Agent does not implement this object or humidity sensor is not installed or disabled on device

How do I convert gauge32 to integer?


Using jQuery UI datepicker in Lotus Domino - prev/next disappeared

Question: I'm developing a Lotus Domino app that uses jQuery's datepicker. When I reference the jQuery code from code.jquery.com, I can see the prev and next arrows at the top of the calendar, but when I download this code from the site, put it in my NSF file, and reference it from there, the arrow graphics disappear.  The calendar still works, and when I hover where prev and next should appear, I can see the title text.  Just no graphics.  Ideas?
Heading code:

<link rel="stylesheet" media="all" type="text/css" href="svr/file.nsf/css/jquery-ui.css"; />
;
;

Body code:

[HCTDate] <---- Notes field defined as Text, Editable

$('#HCTDate').datepicker({ });

Comment: better add the code to question than in comments
Comment: your HTML and script will help to answer you... just reading your post... and guessing.. what you might have done wrong... is not a way to ask questions....
Comment: Heading code:
Comment: Body code:

[HCTDate]   <---- Notes field defined as Text, Editable

        $('#HCTDate').datepicker({
        });
Answer: Be sure that you also added the image files to your .NSF and that the paths are correct.
Answer: download the jquery-ui zip file for the theme and extract it to the domino/html folder.
put your link as
"<link rel=\"stylesheet\" href=\"/jquery-ui/css/ui-lightness/jquery-ui-1.10.3.custom.css\"/>"


Align some descendants to bottom, and some to top

Question: As a root view of my app, I have a ZStack, and I would like to add two floating bars, one to the bottom, and one to the top of the viewport.
With a single bar it's easy (ZStack(alignment: .top)), but is there a way to add multiple descendants, and have one aligned to the top, and a second one to the bottom?
I tried removing alignment from ZStack, and adding .frame(alignment: .top) / .frame(alignment: .bottom) to the children, but this didn't do anything.
Yes, it could be hacked around by wrapping a top-aligned ZStack with another, bottom-aligned one, but it seems rather inelegant.
Answer: Here is possible approach
ZStack {

 // content here

}
.overlay(YourTopView(), alignment: .top)
.overlay(YourBottomView(), alignment: .bottom)

Other possible variant is to use one .overlay with VStack having two views and Spacer in between.
Answer: Here's another approach that allows overlap of the top and bottom-aligned views.
ZStack() {
    VStack() {
        topView()
        Spacer()
    }
    VStack() {
        Spacer()
        bottomView()
    }
}

Answer: You can just add a VStack inside your ZStack like this
ZStack {
    VStack {
        YourTopView()
        Spacer()
        YourBottomView()
    }
}

Comment: Thank you, this also works - I originally expected the spacer to block clicks into underlying content, but it apparently doesn't.


Apagar valor do file com a informação que vem do banco de dados

Question: Tenho um formulário de cadastro onde entre os campos tem um campo file. Ele cadastra normalmente.

  Foto do(a) Vereador(a):
    <input type="file" name="Foto" class="form-control" id="fileUpload" placeholder="Foto do Vereador(a)">

    Excluir

JQuery
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $("#imagem").attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#fileUpload").change(function(){
    readURL(this);
    $("#imagem").css("display","block");
    $("#excluir").css("display","block");
});

$("#excluir").click(function(){
    $("#fileUpload").val("");
    $("#imagem").css("display","none");
    $("#excluir").css("display","none");
});

Tudo bem, tudo certo! O único problema é quando tento trazer esse campo na edição do usuário. Na hora de trazer os resultados do banco de dados para a edição estou fazendo dessa forma:

  Foto do(a) Vereador(a):
    <input type="file" name="Foto" class="form-control" id="fileUpload" value="<?php echo $visualizar->FotoUsuario; ?>">
    <img id="imagem" src="<?php echo "../../fotos/".$visualizar->FotoUsuario; ?>" alt="Preview da sua imagem" style="width: 130px; margin-top: 10px;" class="img-thumbnail" />

    Excluir

O problema está quando clico no link Excluir:

Ele não está apagando o value do campo file. O Jquery é o mesmo que passei mais acima.
Answer: Tente fazer com attr:
$("#excluir").click(function(){
    $("#fileUpload").removeAttr("value");
    $("#imagem, #excluir").css("display","none");
});

Comment: Olá Lucas. Não funcionou. O nome da imagem continua no value do campo file.
Comment: Usa o removeAttr, tente agora
Comment: Obrigado Lucas.


Justfication of the summability of $XY$ where $X$ and $Y$ are summable independent random variables.

Question:
Suppose $\Omega$ is a countable sample space, $P$ a probability measure on $\Omega$, and $X$ and $Y$ are independent random variables on $\Omega$ with $E(|X|)<\infty$, $E(|Y|)<\infty$. Show that $E(|XY|)<\infty$.

By definition,
$$E(X)=\sum_{\omega\in\Omega}X(\omega)P(\omega)\text{.}$$
It is well-known that if a series converges absolutely then every rearrangement of it converges to the same limit, and that a sequence diverges to $\infty$ if and only if every subsequence of it diverges to $\infty$. Hence it suffices to show that there exists arrangement of $\Omega=\{\omega_1,\omega_2,\omega_3,\dots\}$ and a grouping of the terms such that
$$[XY(\omega_1)P(\omega_1)+\cdots+XY(\omega_{N_1})P(\omega_{N_1})]+[XY(\omega_{N_1+1})P(\omega_{N_1}+1)+\cdots XY(\omega_{N_2})P(\omega_{N_2})]+\cdots<\infty\text{.}$$
Let $\{x_n\}$ and $\{y_n\}$ be the sequence of values taken by $X$ and $Y$, respectively.  Arrange $\Omega$ in a sequence $\{\omega_n\}$ so that ...
This is what I tried. I don't know how to proceed any further. For example how to arrange the points so that $\sum_n X(\omega_n)Y(\omega_n)P(\omega_n)=\sum_j\sum_k x_jy_k P(X=x_j,Y=y_k)$?
Comment: In the discrete case you can say $|X| \in \{x_1, x_2, x_3, ...\}$ and $|Y| \in \{y_1, y_2, y_3, ...\}$ and then write your sums only over the first $n$ terms, take $n\rightarrow\infty$.  $$\sum_{i=1}^n\sum_{j=1}^n x_iy_jP[|X|=x_i, |Y|=y_j] = ...$$
Answer: As $X$ and $Y$ are independent, the joint distribution satisfies
$$
F_{X,Y}(x,y) = F_X(x)F_Y(y),\ x,y\in\mathbb R.
$$
It follows that $$\mathsf P_{X,Y} = \mathsf P_X\times \mathsf P_Y,$$ and as the product of $\sigma$-finite measures is again a $\sigma$-finite measure, from Tonelli's theorem it follows that (as $(x,y)\mapsto |xy|$ is a non-negative measurable map)
\begin{align}
\mathbb E[|XY|] &= \int_{\Omega^2} |X(\omega)Y(\omega)|\ \mathsf d\mathbb P(\omega)\\
&= \int_{\mathbb R^2} |xy|\ \mathsf dF_{X,Y}(x,y)\\
&= \int_{\mathbb R}{\int_\mathbb R}|xy|\ \mathsf d F_X(x)\ \mathsf d F_Y(y)\\
&= \int_{\mathbb R}|x|\mathsf dF_X(x) \int_{\mathbb R}|y|\ \mathsf dF_Y(y)\\
&= \mathbb E[|X|]\mathbb E[|Y|]\\
& < \infty.
\end{align}
Answer: Since $X$ and $Y$ are independent, we get that $|X|$ and $|Y|$ are independent (used in the middle step) therefore
\begin{align*}
\mathbb E[|XY|]&=\mathbb E[|X| \cdot|Y|]\\
&=\mathbb E[|X|]\cdot\mathbb E[|Y|]\\
&<\infty
\end{align*}

If $U$ and $V$ are independent discrete random variable, then $\mathbb E[UV]=\mathbb E[U]\cdot\mathbb E[V]$, indeed
\begin{align*}
\mathbb E[UV] &= \sum_{u,v} u v p_{U,V}(u,v)\\
&=\sum_{u,v} uv p_U(u) p_V(v)\\
&=\sum_u up_U(u) \sum_v vp_V(v)\\
&=\mathbb E[U]\cdot\mathbb E[V]
\end{align*}
This is true also when $U$ and $V$ are not discrete (see @Math1000 's answer).
Comment: How do you prove the second inequality? Please use the definition in the first display of my post.
Comment: I see only one inequality, do you mean equality ? Also if you did put a downvote on my answer do you think you can explain what is bad about it ?
Comment: I did not downvote but your last sentence is weird, why do you claim this is true if $U$ and $V$ are not independent?
Comment: Well it is indeed weird and alos wrong, I meant when they are not dicrete of course. Never theless I would say that @Math1000 's answer is much better but the conceptual step really is that $E(XY)=E(X)E(Y)$ when $X$ and $Y$ are independent.
Comment: Please explain why $E[U]=\sum_u up_U(u)$. The definition is $E[U]=\sum U(\omega)P(\omega)$ where the sum is taken over all sample points $\omega$.
Comment: There may be infinitely many sample points at which $U$ takes the same value. How can you group them together?
Comment: Define $p_U(u)=\sum_\omega 1(U(\omega)=u) P(\omega)$, similarly for $p_V$.


Magnitude of a multivariate normal distribution

Question: Let's say $X \sim \mathcal{N(0,\Sigma)}$ where $\Sigma \in \mathbb{R}^{n \times n}$. Is there anything we can say about
$$\mathbb{E}_{x\sim X}\left[\sqrt{\sum_i^n x_i^2}\right]$$
Comment: Related: https://math.stackexchange.com/questions/827826/average-norm-of-a-n-dimensional-vector-given-by-a-normal-distribution.
Comment: @StubbornAtom Problem is they use a diagonal covariance matrix. I was hoping to have a more general solution.
Comment: Google something along the lines of 'expected norm of gaussian vector'.
Comment: See, https://mathoverflow.net/questions/155829/euclidian-norm-of-gaussian-vectors
Answer: The question is vague. A crude upper bound can be obtained with Jensen's inequality:
$$E(\|X\|_2)\leq \sqrt{E(\|X\|_2^2)}=\sqrt{\sum_{i=1}^n \Sigma_{ii}} = \sqrt{\operatorname{trace}(\Sigma)}$$


Casting UIViewcontroller, ends up as

Question: I have a custom class that inherits from UIViewController and when I want to navigate I am casting a seque to this class like this
MyCustomViewController *vc =  ((MyCustomViewController *)segue.destinationViewController);

And that works but if I look in Xcode the vc variable is really a UINavigationController (which I think is my root problem).
And then I next try to set some variables on that view and get an exception

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[UINavigationController
  setMyVarID:]: unrecognized selector sent to instance 0xbe59ec0'

This is all storyboard ios views which I have not dealt with at all before but am trying to chase down a bug in code that is already done.
Any ideas on how to get that cast working correctly or what else I could be doing wrong?
Answer: If you could provide a screen shot of your StoryBoard setup that would be helpful in determining what the exact questions is.
Consider this setup:
VC1 -> Modal Segue -> NAV1 -> Root View Relationship -> VC2
If the Navigation Controller (NAV1) has a Root View relationship to a View Controller (VC2) and you have a segue form VC1 to NAV1, then in the prepareForSegue: method, your destination view controller isn't the NAV1 but instead is the Root View (VC2).
So you need to assign the class to the VC2 (UserWishListRoomsViewController) instead of the NAV1 (it should be a generic UINavigationController) and then the code should work.
Answer: Objective C will let you cast an id to anything.  You need to cast it to UINavigationController and probably get the topViewController for it.

Casting UIViewcontroller, ends up as


Implementing preprocess function for custom template

Question: In Drupal 7, I'm creating thank you page for a custom form and have following in my mymodule.module:
function mymodule_menu() {
  $items = array();

  $items['mymodule/thank_you/%'] = array(
    'title' => 'My Module Thank You Page',
    'description' => 'my module thank you page',
    'page callback' => 'mymodule_thank_you_page',
    'access arguments' => array( 'access mymodule thank you page' ),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_theme() {
  return array(
    'mymodule_thank_you' => array(
      'variables' => array(
          'form_id' => NULL,
          'content' => NULL,
          'title' => NULL,
      ),
      'template' => 'thank-you',
      'file' => 'mymodule.theme.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),
  );
}

function mymodule_thank_you_page() {
  drupal_set_title( t( 'Thank You.' ) );

  $variables = array();

  return theme( 'mymodule_thank_you', $variables );
}

In mymodule.theme.inc, I have:
function template_preprocess_mymodule_thank_you( &$variables ) {
  $variables['title'] = 'test';
}

The problem I'm facing is that while I can access the thank-you template correctly, it doesn't read any of the variables I define in the preprocess function in the theme.inc file. Can anyone advice what I'm doing wrong for this?
Answer: I tried your thing on my local server. And its working fine. Just try in your template:
<?php
  // Print your defined variable here like this.
  print $title;
?>

Comment: Wierd. For me, it doesn't work as it tries to look for mymodule.theme.inc file in the templates folder instead of looking for it in main folder. For now, I've added the mymodule.theme.inc functions in mymodule.module and it seems to be working but there must be a cleaner solution to put everything in theme.inc file and still keep it in module's root folder instead of putting it in templates folder.


Convergence or divergence of $\sum_{n=1}^\infty (-1)^{n+1}(2+(-1)^n)/n$?

Question: Is $$\sum_{n=1}^\infty (-1)^{n+1}{(2+(-1)^n)\over n}$$ convergent or divergent?
Comment: Hint: break it up into two series. One is easily shown to be convergent while the other is easily shown to be divergent.
Comment: @MhenniBenghorbal no, it diverges.
Comment: @LeGrandDODOM: You are right!  I was checking that!
Answer: Here I provide an answer using basic convergence tests as well as one without such tests
$$\sum_{n=1}^\infty (-1)^{n+1}{(2+(-1)^n)\over n}$$
$$=\sum_{n=1}^\infty (-1)^{n+1}\frac{2}{n} + \sum_{n=1}^\infty (-1)^{n+1}\frac{(-1)^n}{n}$$
$$=\sum_{n=1}^\infty (-1)^{n+1}\frac{2}{n} - \sum_{n=1}^\infty \frac{1}{n}$$
The first series is clearly convergent by the alternating series test, though the latter is the harmonic series, which is divergent. As a result, the original sum must diverge.
As an addendum, the first sum can be shown to be $\log(4)$ using Taylor Series, which is clearly convergent. Let's do so.
We know that the definition of the Taylor Series centered at $x=a$ is $\sum_{k=0}^{\infty} \frac{f^{(n)}(a)(x-a)^n}{n!}$. Let's use the fairly well known fact that
$$\frac{1}{1-x} = 1+x+x^2+x^3\cdots$$
We then know that
$$-\log(1-x) = \int_0^x \frac{1}{1-t}$$
And we combine these facts (assuming a lot of little things in the process) yielding
$$-\log(1-x) = -\int_0^x \frac{1}{1-t} dt = \int_0^x \left(1+t+t^2+t^3\cdots\right) dt = x + \frac{x^2}{2} + \frac{x^3}{3} + \cdots = \sum_{x=1}^{\infty} \frac{x^k}{k}$$
When we evaluate this series at $x=-1$ we get
$$-\log(2) = \sum_{x=1}^{\infty} \frac{(-1)^k}{k}$$
Multiplying by $-2$ we get that
$$2\log(2) = -2\sum_{x=1}^{\infty} \frac{(-1)^k}{k} = \sum_{x=1}^{\infty} (-1)^{k+1}\frac{2}{k}$$
Thus we have the series we desired.
If you want to show that the latter sum diverges without using tests then observe that the harmonic series is the following:
$$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \frac{1}{5} + \frac{1}{6} + \frac{1}{7} + \frac{1}{8} + \frac{1}{9} + \frac{1}{10} + \frac{1}{11} + \frac{1}{12} + \cdots$$
The harmonic series will thus be greater than the following series at any finite point, as each term is larger
$$\frac{1}{2}+\frac{1}{4}+\frac{1}{4}+\frac{1}{8}+\frac{1}{8}+\frac{1}{8}+\frac{1}{8}+\frac{1}{16}+\frac{1}{16}+\frac{1}{16}+\frac{1}{16}+\frac{1}{16}+\cdots$$
Notice, however, that the fractions form blocks, namely
$$\frac{1}{2}(1)+\frac{1}{4}(2)+\frac{1}{8}(4) + \frac{1}{16}(8) +\cdots$$
We can rewrite this as
$$\frac{1}{2}+\frac{1}{2}+\frac{1}{2} + \frac{1}{2} +\cdots$$
And the above series clearly diverges. Since the harmonic series is greater at each finite point, the harmonic series must likewise diverge.
Comment: Some caution is needed before you write $\sum_{n=1}^\infty (-1)^{n+1}{(2+(-1)^n)\over n}=\sum_{n=1}^\infty (-1)^{n+1}\frac{2}{n} + \sum_{n=1}^\infty (-1)^{n+1}\frac{(-1)^n}{n}$. It would be notationally more correct to work with partial sums at that point.
Comment: @LeGrandDODOM This is true, however I felt that the answer would be less intuitive and thus harder to understand... ForgotALot posted an answer using that logic, so I figured that would suffice should the OP take that route. There is definitely still room for improvement, so feel free to post a more carefully crafted answer!
Answer: Hint:  the sum of an even $n=2k$ term and the following term is $$-{3\over n}+{1\over n+1}=-{2n+3\over n(n+1)}=-{4k+3\over 2k(2k+1)}.$$
That looks divergent to me based on $\sum 1/k$ diverging.


What is the first scale one should learn on guitar

Question: The title really sums it all up but I'll try expand it slightly. Lets say I'm learning guitar and would like to improve my guitar work. Which of the scales should I learn first and why?
Comment: Identifying the "first" scale you should learn is irrelevant. You should learn ALL of them. It doesn't take much time at all.
Comment: This is a tough one. 'Silver Light', 'DRL', and 'yossarian' all have great answers. Major for theory vs Pentatonic for quick jamming. Both great starting points. I think DRL had lots of great information but some drifted into modes etc. That weren't all that focussed on the actual question of a persons first scale (but it was a great answer). Overall I think yossarian touched nicely on which you would choose depending on what you wanted to achieve (or the angle you wanted to approach) in improving your skill on guitar (guitar work). Which is why I'm giving him the correct answer.
Answer: It really depends what type of music you want to do; and how deeply you want to understand the mechanics of music itself.
If you just want to get straight into jamming a tune; learn the pentatonic scale, its about the easiest scale to learn and very versatile; something like 70% of the licks in all popular since the mid 60's is pentatonic based, and even before that most blues was pentatonic based (with an added note between the third and the forth intervals)
Here is Pentatonic scale in A
<code>$6.5  $6.8  $5.5  $5.7  $4.5  $4.7  $3.5  $3.7  $2.5  $2.8  $1.5  $1.8
</code>
Its a good idea to learn this up and down; learn it well slowly before you start to speed up.  A wise man once told me that if you never practice to play things slowly first you never learn how to play slowly.   Practice it in different keys; its a good idea to find backing tracks to jam over, be musical.
Here is Blues scale in A (with the added note)
<code>$6.5  $6.8  $5.5  $5.6  $5.7  $4.5  $4.7  $3.5  $3.7  $3.8  $2.5  $2.8  $1.5  $1.8
</code>
Note the added chromatic interval this where that classic blues sound comes from; its a good idea to try sliding into this note, or bending into it rather than playing it straight all the time; be expressive with it its the blues.
If you want to take this further you could bleed over into the natural minor as the mood takes you, since it differs from the pentatonic by only two notes.
A Minor scale
<code>$6.5  $6.7  $6.8  $5.5  $5.7  $5.8  $4.5  $4.7  $3.4  $3.5  $3.7  $2.5  $2.6  $2.8  $1.5
</code>
These scales are all pretty interchangeable in the key of A minor; however learning the minor scale particularly give you a whole new range of options.
A minor contains all of the notes of the Key of C Major, and so is rooted in C major, starting from its 6 interval (Aeolian Mode).  This being the case, if you play A minor from its 3rd interval you are playing C Major.   Because of this you have access to all of the other modes of the C Major Scale.
B Locrian - C Ionian(Major) - D Dorian - E Phrygian - F Lydian and  G Mixolydian
If you start the A minor scale from each of the notes above, and carry on through an octave, you are playing the corresponding mode above.   Each of these modes sounds good at certain times (over certain chords (their own)); each mode contains 'deviant'(from the major scale) intervals, which when embellished over the right chords really bring out the sound of the mode.
So technically by 'really' leaning A minor you have learned a whole branch of music theory, actually using this stuff really opens up your playing.
The stuff that I have just mentioned is the essential 'in the box' stuff.  Things can get a lot more interesting if you start swapping modes in and out of your root key, from A minor to A Dorian for instance.   A Dorian is rooted in G Major/E Minor, so you have the whole set of modes again from a different key signature, but you can remain rooted in the key of A.
Im not going any further since i'm already Waaay past the scope of the answer, so in summary:
Pentatonic/blues is a good first scale to learn if you just want to get playing.
Then if you want to take your knowledge further, the minor scale is only two extra notes, and it gives you access to all of the above and a whole world more.
Comment: Your first scale is a minor pentatonic. Although it is often referred to as just pentatonic, the third is flat so it's minor. The major pentatonic is not used as much, but sounds quite different (Stir It Up for instance).
Comment: The major pentatonic is simply a different position of the same same scale.
Comment: I'm not sure what that means. The two scales have different notes in them. That makes them not the same. Do you meant that C minor and A maj pentatonic have the same notes? That is certainly true, but they're not the same scale when you put them in the same key.
Comment: What I mean is the major Pentatonic shape can be found in one of the 5 positions(similar to modes) of the Pentatonic scale on the neck, it is used very often, as a mode of the Minor pentatonic, in rock/popular music.
Comment: Right, I gotcha. I think it would be clearer if you said A Minor Pentatonic, since you do call it out as the key of A. If you had said it was the C Pentatonic, I'd have suggested you call it the C Major Pentatonic, since that is a more complete description of the scale. When teaching someone A minor, you might tell them that it's the same notes as C major, but you wouldn't tell them it's also a major scale and leave it ambiguous as to whether the key was A or not. But it's not a huge deal as the minor pentatonic scale is often referred to as just pentatonic.
Comment: Pentatonic merely means 'five noted'. This can't point to major or minor specifically.If anything, the Am / Cmaj. pent. will be called C pentatonic, as all music is referenced to the major scale notes : e.g. "the minor scale has a flat third. " Never heard "the major scale has a sharpened third " !!! So, maj. and min. pents DO have the same notes,BUT the key centre / home notes are different.                                                   The pent. scales are easiest to learn on guitar and provide mostly 'good' notes to solo with, giving either a country(maj.)or blues(min.)feel to your solo
Answer: I would suggest a major scale. Although, pentanotic and blues scales are easier, because they have less notes and easier shapes, the major scale will give you a great starting point, because all other scales are, in one way or another, modifications of a major scale.
Here's the formula:
<code>root note + 1 tone + 1 tone + 1/2 tones + 1 tone + 1 tone + 1 tone + 1/2 tones
</code>
Here is C major scale on 5th string:
<code>$5 3 5 7 8 10 12 14 15
</code>
And the same scale in one position:
<code>$5 3 5 $4 2 3 5 $3 2 4 5
</code>
Good luck in your playing!
Comment: Major scale is not a good scale to learn if you want to get jamming straight away; minor scale is much better for that and easier shapes are a matter of opinion, try playing the pentatonic in all five positions for instance.
Comment: @DRL quite possible, I'm just judging from my own experience. It was the first scale I've learned, and it helped me very much, when I learned the next ones, including pentatonic.
Comment: @DRL, Major scale is better to learn if you're interested in theory. Minor pentatonic if you just want to get playing.
Comment: Well you right in that the major scale is the root of all music; but there are many ways to approach the learning of it, since its all linked.   Going in via the minor scale teaches, everything that the major scale teaches you, your just going about it from a minor perspective.
Comment: There are a couple of mistakes in your first tab.  The 6th fret on the A string is an Eb, which is not in the C-Major scale.  Instead it should be the 7th fret, which is an E-natural.  Also, the 13th fret on the A-string is Bb, which also isn't in the C-Major scale; this should be the 14th fret, which is B-natural.  Finally, you should include the final C, located at the 15th fret.
Comment: @Yossarian, you clearly haven't read/understood my answer correctly; there is more than one way of approaching theory learning.
Comment: @DRL, I did understand your answer. You have a rather convoluted way of getting to the major scale. Any music theory course is based entirely off the major scale. Minor is referred to as relative to a major scale or having a flat 3rd and 7th that's the 3rd or 7th from a major scale. The same way that chords are refered to as having notes flat or sharp compared to the major scale. Everything starts with the major scale, not the relative minor. I know that all these things are highly interconnected, and you can make the leap from minor to major, but for theory major makes the most sense to start
Comment: It depends what want to learn; my way of getting to major scale is no more or less convoluted than learning the major scale itself; 'any music course is based entirely of the major scale' is a very black and white statement, i'm sure you have attended all of these courses.  Of course learning the major scale is the most important aspect of music, and yes im very aware of the relationship between music and the major scale whether you **must** use the major scale as the **only** angle to learn music theory is a different story altogether, and totally a matter of opinion/preference.
Comment: @Yossarian And again you have missed my point; this as you can see, my answer offers a natural progression from pentatonic/blues in to modal playing and theory.  Could you approach from major? yes, do you need to be able to approach from minor? yes.  Can minor teach you anything about major? yes.
Comment: @DRL, All I said was that if you wanted to start from a jamming sense, then do what DRL said. If you want to start with music theory, do what Silver Light said. I learned how to play the way that you explained it. That's cool. It's how I teach people to play too. But, if someone came to me and said, "I want to learn Jazz and music theory", I'd start with the major scale. That's all I'm saying and why I added my own answer.
Comment: "major scale is the root of all music". Pentatonic-scale based music has existed a lot longer and has been found in primitive tribes and ancient Chinese and Japanese music. The major scale was an outgrowth of Gregorian chant from Europe and its strength in theory is because western music is based on it. I think it's safer to say that pentatonic is more of a root.
Comment: @Tin Man; I meant from the perspective of the mechanics of western music; not historically; music as a language has existed in various forms since the dawn of man; and in that time it has been developed and advanced, what we have currently is the result of that process, pentatonic is certainly part of that and it may have been early on the timeline; but its not the root... mechanically.
Comment: Major is the best general answer to a general question. If he asked about a specific task or style, equivocating might be practical. But he didn't. Major scale. 7 out of 8 music teachers agree with me.
Answer: Silver Light and DRL both give excellent answers outlining scales to start out with, but I think they've missed the important aspect to choosing between the two, what type of music do you play, how do you learn, what do you want to learn?
If you a rock / blues player that wants to get jamming with some friends as quickly as possible, then start with your minor pentatonic scale (often referred to as just pentatonic). It's very accessible and is used by a lot of the guitar greats of the 60s-70s. You can play it over an awful lot of music.
If you are a jazz player, start with your major scale. It's as useful for jazz as the pentatonic is for blues. And more importantly leads us to my last point:
If you want to learn music theory, start with your major scale. All music theory is based off your major scale. Absolutely all of it. If that's what you're interested in, learn it as soon as possible. Certain types of playing will absolutely need this knowledge (see Jazz and to a lesser extent Classical).
Here is your C Major Scale
<code>$6 8 10 $5 7 8 10 $4 7 9 10 $3 7 9 10 $2 8 10 $1 7 8 10
</code>
Here is your C Minor Pentatonic Scale
<code>$6 8 11 $5 8 10 $4 8 10 $3 8 10 $2 8 11 $1 8 11
</code>
Note that your first note in each scale is the root note of the scale. Low E, 8th fret is a C, so the scale is a C scale. If you were to move everything down one fret, then you would have a B scale. One more fret, and it's Bb / A#, etc. This is one of the big advantages of learning scales and chords on the guitar, once you know one, you know them all.
Comment: ", but I think they've missed the important aspect to choosing between the two,"  - Again did you actually read my answer?
Comment: @DRL, see my answer above. I disagree with you approach for learning theory. While you can certainly learn theory after the fact from knowing your minor scales, I don't think it's the best way to approach it if you want to start with theory. The major scale makes way more sense for that approach.
Comment: "After the fact"?  I have explained in clearly how they are related and how by learning minor, you can learn all the modes of the major scale; i _left out_ a lot related to minor scale theory which can only really be learned via the minor scale.
Comment: In addition; you have stated above "what type of music do you play, how do you learn, what do you want to learn"; and offered an either/or answer; if you properly _read_ my answer you will see it makes the clear link between jamming with the pentatonic scale and theory, progressing through into the minor scale which is not very different and so is a _natural_ progresssion.
Comment: @DRL, I presented an either or because the question asked what to learn first. You can't learn two different things first. As I've said, I don't have anything against your approach, and it was the one that I learned and what I usually teach. But I think that it's not perfect for everyone. I'm not sure why you are getting so worked up about me having a different answer than you.
Comment: Im not getting worked up, and your answer is valid, i'm just stating that either method is not necessarily better or worse that the other, and that you can learn just as much about theory going in via the minor scale as you can via any other method.
Comment: Haha. Ok. You can certainly end up in the same place either way. But if you have clear goals in mind, then there's a better place to start. If someone said, "I wanna jam with a blues band" then the major scale wouldn't be the best starting point. If they want to learn how to do chord composition and voicings, then the pentatonic scale won't give the basis they need. Of course, if they want to become a well rounded player, they need to know it all eventually.
Answer: If you want to rock right now, then the E minor pentatonic is a great place to start.  It's really easy to play, sounds awesome and it's used in a bunch of tunes like Rumble, Shakin' All Over, Back in Black and many, many more.  Here's the pattern:

That being said, it's not a great place to start if you want to understand what you are doing.  Although it won't hurt to learn it first either.
To really understand how music in the Western world works, you should start with the Major scale because it's the starting point for music theory. It's the starting point for music theory because of the strong tension and resolution of the tritone in the V chord that is derived from the Major scale, but that's a topic for another time.
It's also important to remember that you're not only learning patterns, but what these different scales sound like.  Learning to recognize these sounds is arguably as important if not more important than learning patterns.  Remember, you make music with your ears, not with your eyes.
A one octave C Major scale in open position is pretty easy to play and to understand.
If you're familiar with reading scale diagrams already, you can start by playing it and listening carefully to it's sound.  It sounds pretty light and happy.

If you want to understand what's going on with Major scales, it's actually quite simple.
First, the musical alphabet.  A B C D E F G
The notes in a C Major scale are C D E F G A B C.  There are no sharps or flats.  The notes that are not sharp or flat are called natural notes.  The natural notes are all the white keys on a piano.
You see how the C Major scale Starts on C (hence the name C Major) and ends on a C?  This is pretty important and why it's called C.
So the next question that needs to be answered is why is the scale type "Major" and not something else.  Because of the spacing between the notes.
There are two distances you need to be aware of on the guitar fretboard, tone and semitone.  A tone (T) is the distance of two frets and a semitone (S) is the distance of one (the adjacent fret).
The distances between the notes in a C Major scale are T T S T T T S.  So, the distances between the notes are what give the scale it's sound, not the notes.
Try starting on a C note anywhere on any string, then on that same string moving up toward the body, play T T S T T T S.  You will get a Major scale.  It's obviously a bit awkward to play all on one string, but it will help you understand what is happening.
A lot of people will ask why any of this matters.  It depends how far you want proceed with your development as a musician and how serious you are.  If you just want to strum a few chords, it's probably not important.  If you want be a good Jazz player, you'll need to learn this stuff.  And why not?  It's not that hard!
Answer: The seventh mode of melodic minor.  Also there are plenty of symmetric scales out there, meaning the number of modes (starting points) doesn't necessarily go up to seven.
Comment: Please justify this ! The 7th mode of melodic minor could start on 2 different notes ! Take Amin. ascending the 7th note is G#; descending, it's G natural.How confusing is that for a beginner ? What's a symmetric scale ?
Answer: The C major scale in the first position would be an easy scale to learn first.
I remember when I was 10 or 11 and I'd already learned to play all the first position chords. Then "La Bamba" came out (redone by Los Lobos) and of course I had to figure out that solo... which is the C Major scale played all in the first position.
The good thing about figuring this out is that the scale already has a context - C/F/G, and it has a melody you can hum/sing and a distinct rhythm!  Perfect for a beginner!
Don't worry about knowing the scale and the notes - go by the sound of the notes and being able to play with the record/cd/mp3.   Use the open strings!  Once you can manoeuvre your fingers around the open position - you can then begin to study what you've just learned ;-)
Comment: Are you advocating learning the C Major scale first?  Your answer is a little rambly and unclear.
Comment: Matthew, you're right - I wrote this in a hurry.  But yes, the C major scale in the first position would be an easy scale to learn first.  Learning it in context of a song also makes it easier for beginners to digest.


Flex: getting scroll bars on the controls I want and only in viewable area

Question:
Flex scroll bars are giving me a really hard time. I want to control exactly which boxes they appear for but after hours of trying random things, my best solution (see below) seems a bit kludgy and unreliable. If I force a scroll bar to appear, (*ScrollPolicy="on") the scroll bar appears disabled, because it spans the entire size of the box, even though that is out of bounds of the viewable area.
I have this one box at the top of the page that runs off the side of that screen, and that's fine--let it run off the side and don't give it a scroll bar. But I have this other box which runs off the side, which is also acceptable, but I want scroll bars to serve that region and only that region and I want those scroll bars to appear in the viewable area. That is, I don't want to have to move the horizontal scroll bar so that it will allow me to see the vertical scroll bar.

Now the best I could do is as follows: I found the parent of the main box you see in my diagram (which is actually the great-great-grandparent) that never gets bigger than the viewable area, which is an mx:Canvas. Then I force the size of the parent of the box containing my stuff down to the size of the parent mx:Canvas, which then causes the scroll bars to appear where I want. So, it's something like:
<mx:Canvas id="main_canvas" width="100%" height="100%">

a lot of other tags that are parents
  <mx:Box width="100%" height="100%" maxHeight="{main_canvas.height}" maxWidth="{main_canvas.width}">
    <mx:Box width="100%" height="100%">

the rest of the tags
The above tags are an abstraction, btw. Due to the enormous number of experiments I've conducted trying to get the scroll bars where I want them, there's a very tall hierarchy of mx:*Boxes, mx:Canvases and even an mx:VDividedBox.
It seems to work, but it's probably needlessly complicated, and I have a feeling that customers will find a way to make it fail.
I'm using the 3.5 SDK.
Comment: Thanks, guys, but I already gotta Tumbleweed badge :)
But if there's someone wrong w/my question, I'm open to suggestions. I wouldn't even necessarily veto edits.
Answer: In the end, the best I could do was wrap whatever I wanted to have scrollbars in an mx:Canvas and then set its maxWidth to a parent component's width that is limited to the width I want, and finally put an mx:Box inside the mx:Canvas. At least, that seemed to work in most cases when controls are vertically stacked and I want a horizontal scrollbar to span the whole width of that mx:Canvas. Usually this was enough and somehow the vertical scrollbar issue sorted itself out, but on a couple of occassions, I had to resort to Flex: getting the height of a collection of controls to calculate the maxHeight of some of the child aggregate controls, which I find a bit kludgy.


Is there a visual code editor feature that can list current page's functions/methods?

Question: Tried Command-P for a function name on the current TypeScript file, but it did not find the function which, I know, exists on the page.
Went thru docs and but this is a specific need.
Does anyone figure if such a thing exists whereby you just do a keyword combo and get a list of the current page's function names listed? or Alternatively, have the ability to search for that function name ( to go to its declaration) ? Maybe Command-P, can be extended to include currrent page's functions/methods? That would be awesome..
Comment: What do you mean when you say page? A source file that's in focus?
Comment: Left panel, Outline
Answer: You're most likely looking for 'Go to Symbol' feature.

You can navigate symbols inside a file with ⇧⌘O (Windows, Linux Ctrl+Shift+O).
– source
Comment: In built-ins, unfortunately not. I opted in for `vim` emulation with [this](https://marketplace.visualstudio.com/items?itemName=vscodevim.vim) 'Keymap Extension'. Now, I'm able to navigate back in cursor last "stops" using Ctrl+O, which BTW works across files too.
Comment: It's not `most likely`. It's `exactly`. :)
Comment: Felicio, do you also happen to know how to go back to the last cursor location with a keyobard combo (and keep going back as long as you do that combo) in Visual Code Editor? The Visual Basic 6 ( of the good old days ) had this feature and I oved it.  I'd like to map that feauture if exists to a keyboard combo that I like. So far what I do "undo" and "redo" to see where I was but this is not only stupid but also limited to the last cursor position only.
Comment: Felicio Fanntastico.


Explain to a layman how to choose between path analysis or multiple regression with one dependent variable

Question: Path analysis and hierarchical multiple regression are the two most common analytic methods used to examine a theoretical model. There is one dependent variable. No one has explained why they choose one method other the other.  In laymen's language please lay out the pros and cons!
Comment: Can you clarify what you mean by "hierarchical multiple regression"? It might also help if you can provide some context (eg, your field); it is not my impression that path analysis is 1 of the "most common analytic methods".
Answer: A multiple regression model is a special case of a path model.  There are many analyses that can be conducted via path models.  Only some of those can be fit with multiple regression models.  If a multiple regression model is a viable option, either could be used.  In that case I (and I suspect most data analysts), would use a standard multiple regression instead of a path analysis, because it would be more familiar to a wider audience.
Comment: The question seemed to be about hierarchical regression specifically and not just single-level regression, no?
Comment: Well, never mind. The title and the text don't match. Also, I could see the OP saying that multiple regression is one of the two most common analyses, but I couldn't see it for multilevel modeling.
Comment: Hmmm... those are good points, @PatrickCoulombe. We could seek to clarify the question. In particular, "hierarchical multiple regression" could mean any of several things.


How can i restrict the values of a variable?

Question: Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
while(true) {
    String comando = sc.next().toUpperCase();

    if (comando.contentEquals("RP")) {
        String categoriaPro = sc.next();
        if(!categoriaPro.equals("Medicina")) {
            System.out.println("Categoria inexistente");
        }else if(!categoriaPro.equals("Enfermagem")) {
            System.out.println("Categoria inexistente");
        }else if(!categoriaPro.equals("Auxiliar")) {
            System.out.println("Categoria inexistente");
        }
        String nomePro = sc.next();
        prof.NomeVerificacao(profissional , nomePro, categoriaPro);
    }

    if(comando.contentEquals("SAIR")) {
        break;
    }
}

for(Profissional pro : profissional) {
    System.out.println(pro);
}

This is my main.
public class Profissional {
    private String nome;
    private String categoria;

    public Profissional(String nome, String categoria) {
        this.nome = nome;
        this.categoria = categoria;
    }
     // getters and setter

    public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
        if (profissional.isEmpty() == true) {
            profissional.add(new Profissional(nome, categoria));
        } else {
            int i = 0;
            for (; i < profissional.size(); i++) {
                if (profissional.get(i).nome.equals(nome)) {
                    System.out.println("Profissional existente.");
                    break;
                }
            }
            if (i == profissional.size()) {
                profissional.add(new Profissional(nome, categoria));
            }
        }
    }
}

i'm trying to create Object, in this case is a professional of an hospital.
What is done is that can't have more that one professional with the same name, but what i can't figure it out is how to restrict the value of "categoriaPro" to "Medicina", "Enfermagem" and "Auxiliar".
And if it isn't one of them i print the messagem "Categoria inexistente".
but it isn't working.
can any body help??
Comment: You should follow the Java Naming Conventions: method names should be written in camelCase, i.e. `NomeVerificacao` should be `nomeVerificacao`.
Answer: To restrict the variable to certain values checkout this.
Also you need to have an AND statement after the conditions and only if they all fail print "Categoria inexistente"
if(!categoriaPro.equals("Medicina") && !categoriaPro.equals("Enfermagem") && !categoriaPro.equals("Auxiliar")) {
    System.out.println("Categoria inexistente");
}

The above checks if it is not any of them.
Comment: That's true, but it will add to the list anyway!
Comment: how do i reset the main without running the list.add()?


The configuration space of directed great circles on the sphere

Question: I am reading a proof of Pu's inequality in Katz' book "Systolic geometry and topology". In section 6.4, he describes a fibration $q : SO(3) \to S^2$ which I can't quite figure out.
First, he thinks of $SO(3)$ as the unit tangent bundle of $S^2$ (the round $S^2$ in $\mathbb{R}^3$) by identifying $g \in SO(3)$ with $dg(v) \in TS^2$ for some fixed $v \in TS^2$ of unit length. He then says that a fiber of $q$ corresponds to an orbit of the geodesic flow on $SO(3)$. So a fiber of $q$ over a point is the collection of unit tangent vectors over some (directed) great circle in $S^2$.
He says that for this fibration, we should think of the base space as the configuration space of all directed great circles in $S^2$. So I guess that if we could see $S^2$ as that configuration space, we could just send $g \in SO(3)$ (viewed as a unit tangent vector) to the directed great circle to which it is pointing. However, I don't see how to identify $S^2$ with its directed great circles, anyone has an idea?
Answer: A great circle is the same data as two antipodal points, namely the two points furthest away from the circle. That is, the space of great circles is the space of two antipodal points on $S^2$, which is $\mathbb{RP}^2$. The direction picks one of these points (say, the point that appears on the left as you follow the direction around the circle), which corresponds to the double cover $S^2 \to \mathbb{RP}^2$.
Answer: If you have a directed circle, use the right-hand rule that would position your thumb in the appropriate direction. That direction will give the right point on the sphere.


How do I declare two or more data types on the same line??(New to programming)

Question: I am having difficulty combining two data types on the same line for simplicity purposes... Here is my current code:
public class countryPopulations{

    static String zero = "Canada ";
    static String one = "USA ";
    static String two = "China ";

    static double Canada = 35.16;
    static double US = 316.1;
    static double China = 1.357;

    static String million = " million";
    static String billion = " billion";

    public static void main(String[] args){

        System.out.println(zero +Canada + million);
        System.out.println(one +US + million);
        System.out.println(two +China + billion);

    }

}

As you can see this is a lot of work just to print "Canada 35.16 million" on one line, or "US 316.1 million". I hope I have included enough information and if anyone could help that would be great! Also if you have any additional information that you could share or tips about the code I have just presented (as I am clearly a beginner at programming) that would be awesome.. Thanks again!
Comment: Unless you are going to perform math operations on those doubles, then you could simply do `static String canada = "Canada 35.16 million"` etc for US and China
Comment: Look t the format method on String - which is probably in the tutorial you are using
Comment: http://stackoverflow.com/questions/20117500/java-one-line-variable-declaration and http://stackoverflow.com/questions/100633/why-do-you-not-declare-several-variables-of-the-same-type-on-the-same-line
Answer: One possible option is to use array(s), and something like
String[] countries = { "Canada", "USA", "China" };
double[] population = { 35.16, 316.1, 1.357 };
String[] suffix = { "million", "billion" };
for (int i = 0; i < countries.length; i++) {
    System.out.printf("%s %.3f %s%n", countries[i], population[i],
            (i == 2) ? suffix[1] : suffix[0]);
}

Or, you could use a Country POJO like
static class Country {
    String name;
    double population;
    boolean billion = false;

    public Country(String name, double population, boolean billion) {
        this.name = name;
        this.population = population;
        this.billion = billion;
    }
    public String toString() {
        return String.format("%s %.3f %s", name, population,
                (billion) ? "billion" : "million");
    }
}

public static void main(String[] args) {
    Country [] countries = new Country[] {
            new Country("Canada",35.16,false),
            new Country("USA",316.1,false),
            new Country("China",1.357, true)
    };
    for (Country c : countries) {
        System.out.println(c);
    }
}

Comment: Thanks @Elliott Frisch, what is a POJO?
Answer: What you are doing is not combining two data types.
As in this case
System.out.println(zero +Canada + million);
Since your first argument to System.out.println is zero  which is string.
What java will do is to convert following arguments to string or
if they are objects it will call toString method in the Object class.


During the draft, why are draft rights traded and not draft picks?

Question: If I remember correctly, during the NBA draft and maybe even the NFL draft, if teams trade picks, they can't announce the trade until both teams have drafted their respective players.  Only then can they announce the trade.
I read somewhere that before the draft, they can trade picks and announce on the news.  During the draft, they can only trade draft rights and not draft picks.  Why do these league do this?  What is the reasoning for this?
Comment: I'm not sure about the [tag:nfl] here - I don't believe this applies to the NFL, I only hear of "draft rights" being traded in the NBA.
Answer: One reason why draft rights are traded in the NBA are because you're not allowed to trade consecutive first round picks.  I.e., if you trade your only 2020 first round pick, you must make a 2021 first round pick - you can't trade it.  However, you can make the pick then trade the player's rights.
Second, on draft day, picks can only be traded until 2:00 PM Eastern Time; after that, they must trade draft rights.


Is it a good idea to use virtualization for apache/php and Mysql servers?

Question: we (our company) provide SAAS (software as a service) applications, and we think about virtualization to host our apache/php servers, and our mysql master/slave servers.
Is it a good idea?
Mysql servers need fast I/O and memory, and both need high network bandwith.
How to make the right choice?
Thanks
Best regards
Cédric
Comment: It depends on what the underlying infrastructure is.  Are your machines using local storage or are you backing everything with a fiber channel connected SAN?  What kind of load will the mysql servers get?  What virtualization solution are you using?

You shouldn't really have any issue virtualizing the apache/php machines.
Comment: Local storage for sure, as we have confidentiality issues and we cannot buy or rent a filer.
Answer: It depends on your virtualisation solution and setup. If done correctly, it will have little difference compared to a physical machine. If done incorrectly, it will result in slow-downs. There are just too many possibilities.
If your storage-pool uses images residing on top of an existing file-system, it will be less efficient as compared to a raw partition or even fiber-channel storage. If your VM defaults to a 10Mbps NIC, it may slow things down. If you use OS-level virtualisation, it can help reduce memory requirements because the kernel and libraries can be shared across VMs.
You need to understand your requirements and study the different virtualisation platforms available and architecture best-practices used.
Answer: I'll defer to the experts here but in the meantime, I thought I'd ask some questions that might help to formulate a more specific answer:

What type of virtualization infrastructure do you have?  Are we talking about a single VM server? Multiple VM servers? Storage via fiber-connected SANs? Storage via local disks? How scalable is it to respond to additional resource needs? How many other VMs would be running on the same host?
How quickly do you anticipate load on mysql growing? What type of SQL transactions will be initiated by users and how often?

My limited experience with VMs have led me to believe that disk IO is where a significant bottleneck is.  For that reason, I'd be more concerned about mysql than apache/php or network bandwidth.
Just my 0.02.
-M


Mockito - Spring Mvc Service test (Null pointer)

Question: I'm new to Testing side.I'm using Spring Mvc in my application. I followed some tutorials to write for controller and service Test Case. I'm facing error in service test. Please help !
Service :
<code>@Autowired
private PatientDao patientDao;

@Autowired
private PrefixDao prefixDao;

public Patient createPatient(Patient patient) throws Exception {
    patient.setAgeorDob();
    return createPatientInSync(patient);
}

private synchronized Patient createPatientInSync(Patient patient)
            throws Exception {
        try {
            Prefix prefix = prefixDao.getPrefixForType(PrefixType.PATIENT);
            patient.setPatientNo(prefix.getPrefixedNumber());
            patientDao.createPatient(patient); //SAVE PATIENT
            prefixDao.incrementPrefix(prefix);
        } catch (ConstraintViolationException ex) {
            throw new InternalErrorException("Please enter valid data", ex);
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new InternalErrorException(
                    "Please create Prefix for Patient", e);
        }
        return patient;
    }
</code>
Service Test case:
<code>@ContextConfiguration(locations = {
        "classpath:/applicationContext-resources.xml",
        "classpath:/applicationContext-service.xml",
        "classpath:/applicationContext-dao.xml",
        "classpath:/applicationContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class PatientServiceTest {

    @Autowired
    @Mock
    private PatientDao patientDao;

    @InjectMocks
    private PatientServiceImpl patientService = new PatientServiceImpl();

    private PrefixDao prefixDao;

    @Before
    public void doSetup() {
        patientDao = mock(PatientDao.class);
        prefixDao = mock(PrefixDao.class);
        // Mockito.mock(PatientDao.class);
    }

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSaveUser() throws Exception {

        Patient mockPatient = new Patient();
        mockPatient.setFirstName("Aravinth");
        mockPatient.setSex(Gender.Male);
        mockPatient.setAgeOrDob("24");

        Prefix prefix = new Prefix();
        prefix.setPrefixType(PrefixType.PATIENT);
        prefix.setPrefix("Pat-");
        prefix.setSequenceNo(23);

        when(prefixDao.getPrefixForType(PrefixType.PATIENT)).thenReturn(prefix);
        System.out.println(prefix.getSequenceNo());

        mockPatient = patientService.createPatient(mockPatient);

        assertEquals("Aravinth", mockPatient.getFirstName());

        verify(patientDao, times(1)).createPatient(mockPatient);
    }
}
</code>
Verify times works fine.I got Nullpointer in assertEquals.
Comment: Check in your patientDao instance, when createPatient called, it return null.
Comment: For getting familar with Mockito take a look at [this tutorial](http://www.vogella.com/tutorials/Mockito/article.html). From taking a closer look at you test code I notice two things: 1. you are not calling the `PatientSeriveImpl` you probably wanted to test in the first place and 2. verifying the number of calls to `createPatient` here is useless, as the only call is from your code.
Comment: updated my dao code.. @PupCode
Comment: you're not right, your dao is a Mock Object, so it don't run your actually code ... and i see in the doc this instruction to put in before annotation :
    ´MockitoAnnotations.initMocks(this);´
Comment: Hi pup. same error :-(  share any example link
Comment: to you service : http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Mock.html
Comment: You are mixing things up: By supplying a context configuration and running the test with the Spring runner, you basically indicate the test is an integration test, where you want to test all the different objects involved in a certain method call. On the Other hand you have the annotation @Mock on your DAO which suggests, you want all method calls of the DAO to be mocked. So what exactly are you trying to test here?
Comment: @hotzst I tried to write Integration test. my test includes for Both Prefix and Patient.I'm new to testing. suggest some examples,it would help me.
Comment: Tnx !! yeah! you are correct .. see my updated code, it works
Answer: Need to @Mock PrefixDao first.
If you are using Junit 5, no need to run initMocks(this). Otherwise you need this: MockitoAnnotations.initMocks(this);
With that, the mockito will wire two mock Dao objects to your service.
Also I don't see you mock action for patientDao.
When(patientDao.create()).thenReturn(...);


$\sqrt{I}=R \iff I=R$

Question: Let $R$ be a commutative ring with identity and $I$ and ideal. I have a proof that $\sqrt{I}=R \iff I=R$ and I am wondering if its correct:
"$\Leftarrow$":Obvious, since $I\subset \sqrt{I}$
"$\Rightarrow$":We know that $\sqrt{I}=\bigcap{p_i}$ where $p_i$ is prime and $p_i\supset I$ for all $i$. Because $\bigcap{p_i}=R$ we get that there isn't any proper prime ideal containing $I$ and because each proper ideal is contained in a (proper) maximal ideal we get that $I$ is maximal.
Let $x \in R\setminus I$. Then by maximality of $I$ we have $xI=R$. But this means that $x$ is invertible and therefore also $x^n$. Since $x \in \sqrt{I}\Rightarrow x^n \in I$  we have that $I=R$ since it contains an invertible ellement.
Thanks in advance !
Comment: How about just "$1^n\in I$ for some $n$" for $\implies$?
Comment: @Math_QED This set contains all the elements $x$ where $x^n \in R$ for some $n$.
Comment: I'm a beginner in ring theory so I was wondering, what does $\sqrt{I}$ mean?
Comment: @Arthur .Aaah it is so obvious. Of course. Thanks :) !
Comment: Okay thanks. Good to know!
Answer: It's much simpler to use the definition: if $\sqrt{I}=R$, then $1\in\sqrt{I}$, so $1^n\in I$, for some $n$.
Your proof is incorrect. From $\bigcap_i p_i=R$ you argue that $I$ is maximal, which is wrong. You should instead argue that there is no prime ideal containing $I$. Therefore $I$ is not a proper ideal.
Comment: What I had in mind is that since $I$ is not contained in any prime ideal (therefore in any maximal ideal) the is it itself maximal or the whole $R$.Anyway thanks for the answer !
Comment: @NickA. If $I$ is not contained in any maximal ideal, it cannot be maximal because it is contained in itself.

$\sqrt{I}=R \iff I=R$


How to deal with varying accuracy after every run of algorithm

Question: I am not talking about how to get the same result every time which can happen by setting the random state parameter to a number.
I am referring to the fact that since with one run I get 99.2 with the next 89.3, then the other 93.5. If it has so much variation on every random cross validation how can you rely on that?
Example:
from sklearn import datasets
iris = datasets.load_iris()
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
 columns= iris['feature_names'] + ['target'])

X = data1[['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']]
y = data1[['target']]
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.20)
model = LogisticRegression()
model.fit(X_train, y_train)
prediction = model.predict(X_test)
print('Accuracy:',accuracy_score(prediction,y_test))
print(classification_report(y_test,y_pred))

I you run this you will get tremendously different result any time.
Comment: I'm not quite clear what is your question here, exactly.
Comment: if you run it, one time you will receive 99% accuracy which sounds great but if you run it again you will receive 85%.Therefore how can you tell if this model is good if it gives so many different results?
Answer: Cross validation, as you have seen, involves randomization. Therefore, any result derived from it will have some randomness. It is always good practice to repeat cross validation a couple of times (e.g., using different RNG seeds) to see how strong this randomness is.
If you have a small dataset, or a large model, your randomness will be larger than with a large dataset or a small model. And yes, if the randomness is high, then the "best" model derived from CV is a bit dubious.
One way of dealing with this is the so-called "one standard error rule", which attempts to balance this noise against the complexity of the models under consideration.
If you want more stability, consider rerunning the CV multiple times and averaging the results. Nothing keeps you from using each observation multiple times in different holdouts. (Of course, this only makes sense if the rest of the holdout sample differs each time, but the randomization should ensure this.)
Don't overdo it, though. Taken to extremes, this can lead to overfitting to your CV sample.
Incidentally, accuracy is not a good error measure.
Comment: "Acceptable" will depend on what you will use your model for, there is no general "maximal acceptable variation in quality".
Comment: it would be best for each try to not differ much from the previous ones correct? How much is acceptable though?5% is ok?


How to redirect URL with language prefix to the same URL with no prefix (default language)

Question: I have installed i18n module so two languages Japanese and English are available. I have set Japanese to the default language and also "language Language negotiation" to "path prefix only". So all the URL without language prefix show the Japanese pages and English pages with the prefix of "en".
What I want to do is to redirect some of URL with prefix to the same URL without prefix as I need to make some of the pages available only in Japanese. For example, when a user is trying to view my-site.com/en/cart the user is automatically redirected to my-site.com/cart as I want to make the my-site.com/en/cart unavailable.
I have tried path redirect  but the redirect doesn't work though I set two cases as below

"Language" to "All languages " ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".
"Language" to "English" ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".
Answer: The below answer requires that at least part of your website is using Page Manager + Panels. In my opinion, they should anyway, but others will disagree.
Both of these modules are tools, as opposed to solutions, so this answer will require that you research and understand these two modules. Link to excellent video tutorial. At the time of writing, this requires the -dev version of Ctools.
At the time of writing, this Ctools patch must be applied for the following instructions to work.

Ensure that the page you want to redirect from, is managed by Page Manager. This page will have 2 variants.
Add a "HTTP response" variant, with a 301 response to cart. More details on this step in another question. It's important that this variant is the topmost one. You can reorder them afterwards, if need be.
On the HTTP variant, go to the "Context" tab on the left side, add a "Language" context, selecting "Current language".
Go to the "Selection rule", and add a "User:Language" == "English".
Add a second variant, this time a Panels variant.
In the second variant, add all the content that you wish to be part of the Japanse page.
Comment: Thanks for your response. It looks a bit complicated but I think it's a good opportunity to learn Page manager module as it seems to be very powerful. OK now I set up a variant "HTTP response" but don't find where to configure "Language == English" in the list of "Selection rule" I can see "User:language" but not the langue currently viewed with the prefix. Would you please specify me a bit more?
Comment: I made a mistake. The language handling is not complete, and a patch is necessary for my instructions to make sense. Sorry about that. Added link to the answer. Also expanded the step by step instructions, hopefully they are a bit easier to follow now. :)
Comment: Thanks I see. I just realized that the patch is for D7 but I'm on D6.  It seems that I even probably can redirect some users with only specific roles to another language using this function. I was thinking there is no way to achieve that.  I really hope this will be back ported to D6. Or I wish I could do that if I was a coder :)
Comment: The patch actually applies cleanly against Ctools-6 aswell. I would give it a try. :)
Comment: I also just tried to apply the patch to D6 making three plugin files and allocating them in respective directories. Then I fellowed your instruction until 3. When I add context "Language" two text forms appears, one for "Identifier" and the other one for "Keyword" but nothing mentioning "Current language"...
Answer: In .htaccess, add directive
RewriteRule ^en/(.*)$ http://my-site.com/$1 [L,R=301]
RewriteRule ^cn$ http://my-site.com [L,R=301]


How fast is the BPM should you start to use double bass pedal?

Question: First I am quite new to drums, like playing frequently for about a year.
But I am quite depressed with my own progress and I have many questions in my head, here's one of them:
I never learnt / tried to use double bass pedal, so I almost always want to push my limit (speed, stability, etc.) on my right foot on base drum.
But now when I play some songs with 160-180BPM, with some 16th notes on bass drum, my foot cannot keep it up. It is not even a continuous non-stop 16th bass drum groove, it's just some random two consecutive 16th notes which I supposed should be played using sliding / heel-toe technique.
However even with these technique, I still cannot play it stably under 160-180bpm, so I wonder: Is it normal, or is it just me lacking enough practice?
So I would like to know, is there a common upper bound speed (in BPM) for single foot on bass drum playing 16th note? Like, if beyond this bound, double-bass pedal must be used while when within this bound, you can reach it with enough practice?
Comment: I would give yourself around five years to get to a point where you feel like you're *really* playing the drums with enough skill to gig. Some get there faster, some take longer, and all of us know what it's like to feel like you've put in so much time and not gotten anywhere. If you can be more patient, and practice at least a little every day, you **will** reach a point where you can easily tell that you've learned a lot of drumming. At the same time, if you're like me, you'll never be fully satisfied and always learning, but there comes a point where it is more of a joy than a chore.
Answer: Working on single kick drum technique is akin to practicing your single strokes with one hand or a wind player practicing their single tonguing. At some point it's easier to bounce or double-tongue. The threshold you're asking about is actually the threshold you yourself described: 160-180bpm. This varies according to the individual but it is also a pretty reliable range for understanding how / when to transition between techniques.
Excellent drummers work on this transition so that it is so smooth, you cannot tell the difference between their single strokes / bounces; wind players do the same thing. When it comes to your kick drum, you must also do the same thing.
What to do:

Get a metronome
Start at 60 bpm (or as low as you need to, say, 40bpm) with quarters, then 8ths, then triplets, then 16ths, then triplets, then 8ths, then quarters, 1 measure each
Do this 4x
Now click up to 66
Repeat 4x
Now click down to 63
Repeat 4x
Now click up to 69
Repeat 4x
Now click down to 66
Repeat this process until you max out your personal speed
Now do this every day forever until you literally melt everyone's faces with your blast beats and impossibly intricate pedal work
Then start from the beginning and do it all over again
Comment: Is this in relation to a single pedalled or double pedalled bass drum?
Comment: @Tim Both - you can only master coordination at fast tempi by mastering coordination at slow tempi. Each foot individually; both feet together.
Answer: A few comments from someone who has been playing about five years but can't play 16ths on the kick at that speed...

Double bass is a whole realm of technique on its own. Just as
getting single stroke rolls with sticks to sound great at speed
takes work, so too does double bass. Double bass practice does help
footwork in general of course, but I'd view it more as an expansion
of possibilities of the sound than simply as a way to play the kick
faster. It is likely in the same realm of effort to learn as
developing a fast double stroke with one foot.
Syncopated kick exercises at slower speeds will likely also help
develop speed. At least in as much as the issue is in thinking in
terms of doubles, not just the mechanical technique. Kick heavy 16th
note funk can sound great at much slower tempo and is wonderful foot
practice. Patterns for sticks (e.g. Stick Control) can be done with
the feet as drills. If you are getting frustrated playing fast,
dropping down in tempo and playing something different or with more
notes might be a way to get there.
You are absolutely right to focus on playing tight while trying
to get faster. Playing half the notes and sounding great is a better
bet than sloppy and fast.
It takes a long time. Probably a lot longer for some of us than
others. I find looking back on my own progress is the best way to
get perspective. One thing I like about drums is there are both
quantitative measures like "I can play this at 140 now and six
months ago it fell apart at 110" and very subjective ones like "I
remember how stressed I was even beginning to play this a couple
months back and now it grooves."
Kind of a minor point and probably not much help, but I find the
kick drum to be a bit more finicky than other drums in terms of
good tuning helping me to play it well. Both due to the dynamics of
the beater on the head and because the extreme bass notes are
already a bit harder to place in time and if the drum sounds muddy,
it is even harder. If the batter head is loose at all, try tightening
it up.
Answer: I used to do 16th notes pretty consistently on single right foot at about 100 bpm when after about 5 years of playing. On double peddle my left foot lagged and could only do consistent 80 bpm but I could snap a higher speed like 140 bpm with that laggy foot, just not consistent because a lot of music doesn't require that. I didn't do a lot to purposefully work up my speed. There are techniques that help you pull it off and I didn't know any then.
If you are playing extremely fast blast beats, consistent 120 bpm per foot on a double peddle is pretty fast, you could hit about 240 bpm, and if your hands can keep up to that, you are gold.
BTW I just started playing again after 15 years, and have degenerative neurological disorder. Can only do consistently for 2 min 16ths on single bass at 50 bpm. How is that for frustrating? I forgot how good drumming makes me feel. Even if I am terrible it hits the spot. Remember to have fun.


Implementing Turn-based web game using MVC/Javascript

Question: I am implementing browser turn-based game, using javascript and asp.net MVC, probably going to use html5 at the future.
I have some issues regarding it, since I am pretty new to asp.net MVC and javascript:

I don't know how can I interact between javascript and MVC,
which means how can I make a GUI that doesn't reload the page but send the information given to a function/action at the server that uses it and update the GUI accordingly.
for example: clicking on a button will call a server-side function that will update some fields at the website without reloading the page.
naturally, I want to make the javascript responsible for the GUI only,
and all the calculations will be on the server side, and it seems that:

Click on something
Send information to sever-side function
Calculate and update GUI

I have lot of data need to be saved for each player during the fight
and I wonder whats the best place to save this data.
I will probably have a Battle object containing the data, that will both access the database and update the gui using javascript.
Since its a turned-base game, I will have to implement a system that will sync between the players. The best way i think to do that is to create a timer on each client,
that every 2 seconds will take information from the database and update the GUI accordingly if something has changed (for example, the other player done his move with X type of move dealt X damage). Do you have a better solution for this?

Thanks.
Comment: For your synchronization of the clients I would recommend SignalR - https://github.com/SignalR/SignalR
Comment: Sounds like you need to look up AJAX.
Comment: SignalR could be awesomely applied here!
Answer: Yes, you need Ajax and possibly some JavaScript libraries to assist in your single page app. You might start your prototyping by using jQuery to get used to the Ajax approach:

And your MVC application on the back-end would need an action in a controller to support the /Battle/Hit URL
public class BattleController : Controller
{
    [HttpPost]
    public ActionResult Hit(BattleModel model)
    {
        string whoToHit = model.opponent;
        int bonusDamage = model.bonus;
        // do battle, persist to database, etc
    }
}

This is, by no means, a complete solution. However, it should get you started thinking in terms of MVC and JavaScript/jQuery. Once you get the hang of it, I'd highly recommend exploring some alternates to jQuery if your application gets more complex. jQuery.ajax can quickly turn into spaghetti code!
Answer: I would look into javascript long polling and server side asynchronous handling - so that client is updated right away something happens server side. Example in java: http://www.playframework.org/documentation/1.2/asynchronous
For creating the model client side you can take a look at backbone.js
Btw, googling for asp.net ajax chat application may give you some good starting points in client communication


Separating the Worker and Manager Nodes - How to replication the Manager Configuration in the work nodes

Question: I am to configure the APIM Gateway with the Pattern Worker and Manager.
My doubt is how to replication the configuration maked in Manager to workers node.
Is possible to make only configuration in axis2.xml in worker and the others  configurations how(jms,thrift,enviroment) to replicate when the worker node start?
Thanks a lot.
Comment: Your question is not clear. Please explain further.
Comment: For example: I have the configurarion in the Gateway Manager but I will to start two nodes worker. I Have that to configure something at worker node further carbon.xml and axis.xml? I hope that configuration how api-manager.xml, jndi.properties etc, related about the Gateway isn´t necessary because already was configure in Manager.
Comment: In the Gateway Worker Node I hope that not necessary to configure anything because Worker will start with configuation maked in the Manager. This is correct? Thanks a lot.
Answer: The manager does not share configurations with worker nodes. Worker-manager pattern is used to share deployable artifacts from manager to workers. So you have to do configurations in all nodes.
But you can automate this process using a tool like puppet.
Comment: Thanks a lot for the response.