Orthogonal Subspaces

Question: I am reading orthogonality in subspaces and ran into confusion by reading this part:
Suppose S is a six-dimensional subspace of nine-dimensional space $\mathbb R^9$.
a) What are the possible dimensions of subspace orthogonal to $S$? Answer: Sub spaces orthogonal to S can have dimensions $0,1,2,3.$
b) What are the possible dimensions of the orthogonal complement $S^{\perp}$ of $S$? Answer: Complement $S^{\perp}$ is the largest orthogonal subspace with dim $3$.
Where I am having trouble is understanding how the answers make sense to the question, or how the answers are pretty much the answers. In other words, for a, how is the dimensions $0,1,2,3$? But maybe I am not understanding the question. Any assistance with helping me understand the answer would be appreciated.
Answer: Since the other (very nice) answers here have not satisfied you, let me take a different route. I will illustrate what is going on in a simpler situation, and hopefully it will shed light on your question by analogy. Also, since the algebraic formalism doesn't seem to be to your liking, we'll think very geometrically.
Let's consider a 1-dimensional subspace $S$ of $\mathbf{R}^3$. Such a subspace is simply a line through the origin. In fact, for concreteness, let's take $S$ to be the familiar $x$-axis in $\mathbf{R}^3$.
What are all the possible dimensions of orthogonal subspaces to $S$?
Well, the empty-set is orthogonal to $S$ for trivial reasons, and that provides the unique zero-dimensional example. This is also the case in your problem.
Next, we have one-dimensional subspaces which are orthogonal to $S$. These are lines through the origin spanned by vectors making a "right angle" with the $x$-axis. There are many such lines. The $y$-axis and the $z$-axis provide the most familiar examples. So $1$-dimensional orthogonal subspaces are also possible, there are lots of them, and if you take $S$ together with a one-dimensional orthogonal subspace, there's still plenty of $\mathbf{R}^3$ that remains "untouched".
Now, take any two distinct one-dimensional orthogonal subspaces from the previous example. These lines are spanned by two linearly independent vectors. Thus, taken together they span a $2$-dimensional subspace of $\mathbf{R}^3$, and since both of the basis vectors are orthogonal to $S$, the entire space is orthogonal to $S$. A $2$-dimensional subspace of $\mathbf{R}^3$ is a plane. This plane is going to be the $y-z$-plane, which is probably familiar to you from multivariable calculus. You can probably visualize how the $x-$axis "points out of the $y-z$-plane orthogonally".
But now we're done, because the next dimension to consider would be dimension $3$, but the only $3$-dimensional subspace of $\mathbf{R}^3$ is all of $\mathbf{R}^3$ itself, which would certainly overlap with $S$, and hence not be orthogonal to it.
So the possible dimensions for orthogonal subspaces were 0, 1, and 2. Now, a subspace and its orthogonal complement, taken together, "fill up" the entire ambient vector space. What we noticed in our example was that the $x-$axis and the $y-z$-plane are not only orthogonal, but taken together they fill up $\mathbf{R}^3$. So the orthogonal complement of our one-dimensional subspace of $\mathbf{R}^3$ was two-dimensional.
Now, you can play the same sort of game with the problem in your question...it just won't be so easy to visualize what's going on. If $S$ is six-dimensional in $\mathbf{R}^9$, then you can find orthogonal subspaces of dimensions 0, 1, 2, or 3, and if you take a 3-dimensional orthogonal subspace, then you've filled up all of $\mathbf{R}^9$, so you've found the orthogonal complement.
Comment: Appreciate your nice post very much. The illustration indeed provides additional insight which may not be seen by the formal explanation.
Comment: This was helpful but the explanation following Strang's style is most relevant to me.
Answer: Take all the vectors linearly independent vectors in $S$ and put them in a matrix (as rows). Since $S$ has dim=6, so there are 6 linearly independent vectors in S. Thus the matrix will have size 6x9. Now, rank of this matrix is $6$, and the orthogonal complement to $S$ is the rank of its null space. So, by rank nullity theorem, dimension of orthogonal complement is $3$.
Now, subspaces orthogonal to $S$ consists of vectors that belong to the null space of the above matrix, and are subspaces of the null space of the matrix (any subspace will do). These subspaces can only have dimension $0,1,2$ or $3$.
Hope this helps.
Answer: The orthogonal complement of $S$ is
$$
S^{\perp}=\{v\in\mathbb{R}^9:\langle v, w\rangle=0,\text{ for all }w\in S\}
$$
(where $\langle v,w\rangle$ denotes the inner product). It's immediate that $S^{\perp}$ is a subspace of $\mathbb{R}^9$.
If a vector $u$ belongs to $S\cap S^{\perp}$, then it must be orthogonal to all vectors in $S$, in particular to $u$ itself, so $u=0$. Therefore
$$
S\cap S^{\perp}=\{0\}.
$$
In particular, if $B$ is a basis of $S$ and $C$ is a basis of $S^\perp$, then $B\cup C$ is linearly independent.
Now, another theorem tells us that
$$
S+S^{\perp}=\mathbb{R}^9
$$
which means that $B\cup C$ is a basis of $\mathbb{R}^{9}$. So $C$ must have three elements, $C=\{v_1,v_2,v_3\}$. Hence
$$
\{0\}\subset\operatorname{Span}\{v_1\}
\subset\operatorname{Span}\{v_1,v_2\}
\subset\operatorname{Span}\{v_1,v_2,v_3\}=S^{\perp}
$$
exhibits subspaces of $S^{\perp}$ of dimensions $0$, $1$, $2$, $3$ respectively. They are orthogonal to $S$ because they are included in $S^\perp$.
Finally, since $\dim S^{\perp}=3$, no subspace with dimension greater than $3$ can be included in it. And any subspace orthogonal to $S$ is included in $S^{\perp}$ by definition.
Answer: Suppose $S$ is a six-dimensional subspace of $\mathbb{R}^9$.
a) What are the possible dimensions of subspace orthogonal to S?
Before we get to the answer, let's review the definition of an orthogonal subspace. It is a subspace whose intersection $S$ is exactly the zero vector. Now, how many dimensions could such a subspace have, given that $\dim S = 6$? Certainly the zero vector alone qualifies, which is a subspace of dimension zero. Now, I claim that any such orthogonal subspace could not exceed three dimensions. If it did, it would necessarily contain a nontrivial overlap with $S$.
Let a basis for $S \subset \mathbb{R}^9$ and let $U \subset \mathbb{R}^9$ be a four dimensional subspace. Let $\{b_1, ..., b_9\}$ form a basis for $\mathbb{R}^9$. Then we can pick six of these to form a basis for $S$ and four of these to form a basis for $U$. But this necessarily implies that $U$ and $S$ have a nontrivial intersection! Using this same reasoning, you should be able to understand that the possible dimensions for a subspace orthogonal to $S$ are $0, 1, 2, 3$.

b) What are the possible dimensions of the orthogonal complement $S^{\perp}$ of S?
The orthogonal complement of a set is everything within the stated universe that is not in $S$ itself, plus the zero vector. More formally, it is the set that completes the universal space via direct sum with $S$. Since $S$ is six dimensional, and our universe is $\mathbb{R}^9$, this implies that the orthogonal complement must have three dimensions.
Comment: Is there another way to think about this using the rank of S, which  could be a maximum of 6? Then 9-6, 9-7, 9-8, and 9-9 make up the possible dimensions of subspaces orthogonal to S.
Answer: I use Gilbert Strang's notation in the discussion below. For an $m\times n$ matrix $A$,   $\, C(A^T)$ stands for its row space, and $N(A)$ the nullspace, respectively. In fact, the answer below is mainly borrowed from Strang's "Linear Algebra and Its Applications," 4th Edition.
(a) Subspace $S$'s dimension is 6, and it is a subspace of $\mathbf{R}^9$, thus we can say that there are 6 basis vectors (each vector is $9\times 1$) for $S$. Furthermore, we can construct an $m\times n$ ($m=6$, $n=9$) matrix $A$ with these basis vectors as the rows of matrix $A$. We know the rank $r$ of $A$ is $6$.
Now the original problem can be investigated by using the theorems of the fundamental subspaces of matrix $A$.
From the theorems of four fundamental subspaces in linear algebra, we know the nullspace of $A$ is orthogonal to $S=C(A^T)$, and  $N(A)$ has dimension $3$ ($n-r = 9-6=3$). Note that $3$ is not the only dimension of a subspace which can be orthogonal to $C(A^T)$.  Subspaces of $N(A)$ with dimensions from $0$ up to $3$ are also possible.  Therefore we conclude that the possible dimensions of subspaces orthogonal to $S$ are $0,1, 2, 3$.
(b) Not all subspaces orthogonal to $S$ are its orthogonal complements. The size (dimension) must be right. For example, a 1-D subspace $V$ spanned by $(1,0,0)$ in $\mathbf{R}^3$ can be orthogonal to a 1-D subspace $W$ spanned by a perpendicular vector $(0,1,0)$,  yet $V$ cannot be $W^\perp$ because we can find plenty of lines which are perpendicular to $W$ but lie outside $V$.  (In fact, $W^\perp$ is a 2-D plane, not a line.)
The proper size of $S^\perp$ is readily deduced, again, from the fundamental theorem of linear algebra: row space ($C(A^T)=S$) and nullspace ($N(A)=S^\perp$) of $A$ are orthogonal complements, and their dimensions must satisfy the following equation:
$$\mathrm{dim}\, C(A^T) + \mathrm{dim}\, N(A)
=\mathrm{dim}\, S + \mathrm{dim}\, S^\perp = r + (n-r)= n.$$
Therefore $\mathrm{dim}\, S^\perp = n- \mathrm{dim}\, S=9-6=3$.
(In other words, the orthogonal subspaces of dimensions $0$, $1$ and $2$ are too small to be orthogonal complements to $S$.)
I hope I have adequately addressed your questions.
Comment: In the final computation n - dim S, where does n = 6 come from? Doesn't n = 9?
Comment: @aisync Thank you for pointing out the error in the final computation.    Here is the correction: $\mathrm{dim}\, S^\perp = 9 - \mathrm{dim}\, S=9-6=3$.
Comment: @aisync I have just edited the post to get rid of the error. Thank you again.

Orthogonal Subspaces


Como usar funções que estão em um arquivo diferente? - Python

Question: Estou com um problema para usar funções que estão em um arquivo diferente do local onde estou chamando estas funções. Basicamente meu projeto está organizado da seguinte maneira:
Lista_I (Pacote Contendo os Arquivos)
    __init__.py
    funcoes_uteis.py
    PDI.py

No arquivo PDI.py tenho o seguinte código:
import numpy

def aplicar_mascara_media_aritmetica(imagem):

    filtro = numpy.zeros((3, 3))

    for i in range(1, len(imagem) - 1):
        for j in range(1, len(imagem[0]) - 1):
            filtro[0][0] = imagem[i - 1][j - 1]
            filtro[0][1] = imagem[i - 1][j]
            filtro[0][2] = imagem[i - 1][j + 1]
            filtro[1][0] = imagem[i][j - 1]
            filtro[1][1] = imagem[i][j]
            filtro[1][2] = imagem[i][j + 1]
            filtro[2][0] = imagem[i + 1][j - 1]
            filtro[2][1] = imagem[i + 1][j]
            filtro[2][2] = imagem[i + 1][j + 1]

            imagem[i][j] = calcular_media(filtro) #não funciona

    return imagem

E no arquivo funcoes_uteis.py eu tenho a função calcular_media(filtro) que está sendo chamada no arquivo PDI.py. Já tentei fazer import funcoes_uteis mas não está funcionando. Não sei se isto tem a ver com a versão do python que estou usando, mas por via das dúvidas, estou utilizando a versão 3.6 do python.
Alguém pode me ajudar com este problema? Agradeço desde já!
Answer: No PDI.py adicione:
import funcoes_uteis

E chame:
imagem[i][j] = funcoes_uteis.calcular_media(filtro)

Ou se não quiser usa como funcoes_uteis.calcular_media chame assim:
from funcoes_uteis import calcular_media

E chame:
imagem[i][j] = calcular_media(filtro)

Criei dois scripts de teste bem simples
PDI.py
import funcoes_uteis

def aplicar_mascara_media_aritmetica():
    return funcoes_uteis.calcular_media(2)

print(aplicar_mascara_media_aritmetica())

funcoes_uteis.py
def calcular_media(imagem):
    return imagem

E então executei no cmd:
Comment: desinstalei tudo sobre python que tinha na minha máquina e reinstalei. Agora ta funcionando normal do jeito que você ensinou, obrigado por responder e pela paciência!
Comment: Tentei fazer das duas formas, mas nenhuma delas funcionou
Comment: @CloudAC não funcionou é muito ambíguo e não me diz nada a respeito para que eu entenda aonde foi a falha, que erro que deu na tela?
Comment: "No module named funcoes_uteis". É como se ele não tivesse enxergando o arquivo.
Comment: @CloudAC editei a resposta, veja a parte do exemplo e o teste que fiz em meu computador, você provavelmente se confundiu em algo.
Comment: @CloudAC Quem executa o teu script python? É o Django/Flask ou está usando com wsgi e Apache?
Comment: então, eu instalei o python a partir do Anaconda 4.4.0 e estava executando os scripts com a IDE PyCharm. Mas tentei agora executar o script direto pelo cmd do windows e obtive o mesmo problema
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/65677/discussion-between-guilherme-nascimento-and-cloudac).


What proportion of the positive integers satisfy this number-theoretic inequality?

Question: Let $\sigma(x)$ be the sum of the divisors of the positive integer $x$, and let the abundancy index of $x$ be defined as
$$I(x) = \frac{\sigma(x)}{x}.$$
My question is this:  What proportion of the positive integers satisfy
$$\frac{\zeta(3)}{\zeta(2)}\cdot\frac{2n}{n + 1} < I(n) < \frac{2n}{n + 1}?$$
Note that we have the rational approximation $\zeta(3)/\zeta(2) \approx 0.7307629694$.
Comment: Helpful: http://www.ams.org/journals/mcom/1972-26-119/S0025-5718-1972-0327700-7/S0025-5718-1972-0327700-7.pdf
Comment: Mits Kobayashi is the expert on such inequalities; I believe one of his recent papers has an algorithm for calculating the proportion you're interested in.
Answer: I'll copy part of my
(not really mine,
but I found it)
answer from here:
Does this inequality hold true, in general?
I did a Google search for
"density of euler phi function".
The second link is
http://www.ams.org/journals/proc/2007-135-09/S0002-9939-07-08771-0/S0002-9939-07-08771-0.pdf.
This paper,
by ANDREAS WEINGARTNER,
is titled
"THE DISTRIBUTION FUNCTIONS OF σ(n)/n AND n/ϕ(n)".
Here is its abstract:
"Let σ(n) be the sum of the positive divisors of n. We show that
the natural density of the set of integers n satisfying σ(n)/n ≥ t is given
by
$\exp\big(−e^{t e^{−γ}(1 + O(t^{−2}))}\big)$
, where γ denotes Euler's constant. The same
result holds when σ(n)/n is replaced by n/ϕ(n), where ϕ is Euler's totient
function."
This paper has clearly done
the heavy lifting.
If we put $t = 2$,
and use $\gamma \approx 0.5772156649$
(I show each stage in the computation for checkability),
$te^{-\gamma} = 1.1229189671$,
$e^{te^{-\gamma}}=3.0738134815$,
$\exp(-e^{te^{-\gamma}})
=0.0462444658
$.
This is the density of $n$ for which
$\dfrac{n}{\phi(n)}
> 2
$.
The density for which
$\dfrac{n}{\phi(n)}
< 2
$
is one minus this
or $0.9537555342$.
Do this for your bounds.
Comment: The problem with this answer is that it ignores the error term $O(t^{-2})$, which is $O(1)$ when $t=2$. The quoted result is only non-trivial when $t\to \infty$.
Comment: It would certainly be nice if a better result could be found. Alternatively, numerical experimentation could give an empirical answer.


I'm totally new to classical guitar, I see people playing barre chords

Question: How are these barre chords notated on sheet music? Do you just do a barre chord if you want?
I just want to make sure sure, if it's a minor chord/major chord, do you play a major/minor chord?
Answer: Composing music is always a balance between including the information needed for the performer to realize your ideas, and leaving enough up to the performer to not stifle the music1 or insult their intelligence.  For guitar, this is especially tricky because there are (for most of its range) multiple ways to play any given note, and a variety of techniques to achieve certain things.  So you'll see a variety of levels of detail in the notation.
Classical guitar music tends to leave off as much as possible, I think to respect the player's intelligence. If the composer wants a specific voicing, this is usually done by giving the position number--the fret at which your first (index) finger resides--given in roman numerals.  At this point, there will only be one way to do things.  A number by itself means to just camp your hand there, and a number preceded by a "B" means to barre.  A number with a "C" means to place the capo at that fret, and then after that you can move the hand freely or even barre further up the neck, so there might be multiple symbols in play at once.

1My biggest complaint about modern avant garde music is how composers, I suppose in an effort to do completely original things, will sometimes write absurdly specific things into the sheet music.  Things I've actually seen include:

Note durations given in time elapsed, with absurd levels of precision (as opposed to the normal relative note durations plus a tempo indication)
An indication for a violinist to bow at a very specific measured distance from the bridge (as opposed to just sul tasto or sul ponticello and letting the player find what they think sounds best)
Instruction for wind players to use the wrong fingers.  Not to play with an alternate fingering (which is more reasonable, but still pretty dubious in most situations), but to hold the instrument wrong.  I still have no idea what the point of this was.

The end result is that the poor performers are thinking so hard about the stupid things they're being asked to do that they can't focus on actually playing music, and the result is just dead, awkward sound.
Comment: I've actually seen a C mean to barre as well, supposedly from the spanish "cejilla".
Comment: Yuck, well that's annoying.  So you'll have to go by context then.
Comment: According the Spanish Wiki article for "cejilla' it can refer both to the barre (as technique) and capo (as device, 'capodastro').
Comment: I'm still new to classical guitar playing, but I haven't come across any scores where `CV` would mean 'put a capo at V'.  Capo, the device, is  not used that much in classical guitar playing (but I could search delCamp to be sure). and certainly isn't moved in the middle of playing.  Capo if used would be specified at the start, just as any alternative tunings would be.
Answer: It will have the notes of let's say a b minor chord and the position will be indicated with Roman Numerals.

You would see a whole slew of notes that fit the B minor chord and you would see an indication of position seven and know it is the minor barre on fret seven.
Comment: I use lower case letters for minor chords for a reason. There is a tradition in western music to notate the words minor and the letter name of a minor  scale in lower case letters.
Answer: A barre is usually notated above the staff with the letter C (for capotasto) or B (for barre) with the fret number in roman numerals.
Answer: Scores vary as to how much fingering information they contain.  There may be none, in which case the player uses his own judgment and experience.  That applies especially to scores that aren't specifically arranged for guitar.
Notation like CII or BIV is commonly used to mark points where a barre is needed (or suggested) to play that combination of notes.  A horizontal line might be added to mark the length of such fingering.
Other notations may be used as well, such as numbers in circles to suggest a string.  Numbers without circles indicate left hand finger use.  Roman numeral without C or B usually means 'position' rather than barre.  Books normally have a preface explaining the notation.
A barre is also indicated if you are told to use fingers 1 2 3 1 1 for a particular chord or arpeggio.
There certainly is an element of 'if you want'. Barre notation is part of the fingering help aimed at the student.  Advanced players may be prefer to start with an unmarked score that they can annotate with their own preferences.
Answer:
I just want to make sure sure, if it's a minor chord/major chord, do you >play a major/minor chord?

This question is different from the barre question, which has been well answered above. So it's worth noting that barre notation has nothing to do with what notes/chords you play. It only has to do with where and how on the guitar you play them. If the chord is a minor chord, CV is simply suggesting you play that chord as a barre chord in 5th position (perhaps because you need to go there to play a high first string note, or because it makes an easier transition to or from other notes).
Answer: The barre is usually shown by a Roman numeral above the bar/s. There really is no need for C or B as well, because the RN means nothing else. Never seen lower case, because the barre sign only means 'play from this fret'.
There is, however, a half- or part-barre sign, which means, as suggested, only barre some strings. It is C with a vertical line through it, like a cut-time sign.
There is nothing telling whether the chord is major or minor, except the dots themselves, which are self-explanatory, and the direction the piece is moving, sonically. Usually a good clue in itself.


How do I do a 'required if other field = x' using the entity validation api?

Question: I have a field in a content entity that is required if another field in it is checked, otherwise it can be blank.
My guess is that I'd need to make some kind of Validation Constraint Plugin for this - is there an easier way to do this, or a module where something like this already exists?
Answer: That sounds like a job for Drupal's Form API states.
Just add a hook_form_alter similar to this, in a custom module:
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID_TO_ALTER') {
    $form['OPTIONALLY_REQUIRED_FIELD']['#states'] = array(
      'visible' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
      'required' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
    );
  }
}

Comment: The answer is irrelevant, as the author asked about Entity Validation API. Better read this https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint
Comment: Hmm.  The OP marked this as correct.  This is a 2yo question, so I think it can stand.
Comment: The `required` state does currently not work in D8 core, see [bug report on d.o](https://www.drupal.org/project/drupal/issues/2855139).
Answer: The form_alter() solution will only work when you're using a form to save the entity, so I believe that the answer is not the correct one. Here's how you do it with Drupal's Entity Validation API:
Create a constraint and add it to the entity type instead of adding it to a field. Ex:
## See hook_entity_type_alter().
function custom_validation_entity_type_alter(array &$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('ConstraintName');
  }
}

Next, in your ConstraintValidator::validate() method, you will get receive the entity as the first argument and you can perform the validation. Here's a code sample from the same article.
Answer: Managed to get this working a different way, though Change G's way looks a lot simpler. If you want to go pure entity this way worked for me.
I created an entity validation plugin, based on this blog article (https://www.drupalwatchdog.com/volume-5/issue-2/introducing-drupal-8s-entity-validation-api). The comment module in core modules has a working example of this.
One issue I ran into is that the comment CommentNameContraintValidator class declares a $context class property; I can't figure out how this works for that class, but when creating my own it overrode the $context class property in the ConstraintValidator abstract class you need to extend from. When I removed the $context class property, it correctly used the parent $context class property and worked.
My guess is that it has to do with the ContainerInjectionInterface, which the CommentNameConstraintValidator implements and I didn't. I've stopped digging for now though.


6/8 at 60 BPM - not sure where the metronome fits in

Question: I'm learning a piece of music on the guitar which is in 6/8, it says 57BPM - but for this question lets say 60bpm
On YouTube I found a metronome click for 60 BPM in 6/8 time.
I'm slightly confused as to where the 60bpm fits in, in 6/8 time.  If I tap on beats 1 and 2 - I'm sure this is slower than 60bpm and when I tap every note of the within the bar - I'm finding is way faster than 60bpm?
On my own metronome I'm not sure what to set it, obviously if this was 1/4 note in 4/4 it would be fine - but with 6/8 I'm not sure at all.
Answer: You need to understand the strong and weak beats in a bar of 6/8. You would have:

ONE two three four five six

Which means you have the strong beat on one and then on four. So I suggest setting your metronome so that every tap of the metronome is on one then on four then on one of the second bar then on the four etc.. You'd say that a dotted quarter is at 60bpm. You would see this at the beginning of the score as such:

There are numerous free online metronomes, no need to search for a video on youtube, where you can do all kinds of things. Like you can have 6 beats, where the first and fourth ones are accented.
For some reason though, the video you provided has every single beat on the metronome (that is 6 per bar) and it has accented two of them. This is a good thing for a beginner
Comment: That video is indeed accenting 1 and 4, but at the wrong tempo. Why do people do this sort of thing? Ignorance is not bliss!
Comment: The video in question, however, has 40 dotted quarter notes per minute, not 60.  It's simply incorrect.
Comment: @Tim I suspect that it's because it's easier for digital metronome programmers to avoid the complication of having to consider the time signature when translating from "bpm" to the amount of time separating beats. Of course, it's particularly complicated because the unit of time given in the metronome marking isn't always the nominal "beat" of the time signature (6/8 is probably the most prominent example of that, but others are common).
Comment: @Tim - My answer tries to explain why people do this sort of thing - some music notation software will in fact tell you that you are at 60 bpm with the tempo in the video.
Answer: The video you found is incorrect.
A metronome marking equates a number of beats per minute with a note value.  The note value is normally a dotted quarter note, as in the other answer, but it could also be the eighth note.  It will never be the quarter note.  But the video you've found, which purports to be at 60 beats per minute, has 60 quarter notes per minute.
This is of course equivalent to 120 eighth notes per minute or 40 dotted quarter notes per minute.  Neither of these is 60 beats per minute in 6/8 time.

If I tap on beats 1 and 2 - I'm sure this is slower than 60bpm

You're right.  It's 40 bpm.

and when I tap every note of the within the bar - I'm finding is way faster than 60bpm

It is.  It's 120 bpm.
Answer: At least one music notation software, Musescore, actually treats the quarter note to have the definitive pulse, so assuming phoog's answer is correct and the video is at quarter note = 60 BPM or dotted quarter = 40 BPM, Musescore will in fact treat this as correct. This is at its most obvious in Musescore's Play Panel, which displays what Musescore treats as the BPM regardless of the actual meter or notated tempo of your piece at this point.
Comment: The existence of software that uses "bpm" incorrectly does not change the fact that the video is incorrect.  "Beat" does not universally mean "quarter note."  Also, you do not have to assume that my answer is correct; you can measure it.  I timed ten measures of that metronome track with a stopwatch, and it came out at exactly 30 seconds (0.5 minutes).  Ten measures of 6/8 is of course 60 eighth notes or 20 dotted quarters.  Dividing 60 eighths by 0.5 minutes yields 120 eighths per minute; 20 dotted quarters divided by 0.5 minutes is of course 40 dotted quarters per minute.


Rewrite the equation of line $l$ in Cartesian form

Question: The question asks to rewrite the following vector equation of line $l$ in Cartesian form $$l: \vec{r}= (4\vec{i}+0\vec{j}+2\vec{k}) + \lambda(3\vec{i}+\vec{j}+0\vec{k})$$
When I try to do it I result in the following Cartesian equation $$\frac{x-4}{3}=y=\frac{z-2}{0}$$
Is this correct?
Comment: Division by zero is not defined. So, you can write the equation as $$\frac{x-4}{3}=y,\quad z=2$$
Comment: This makes sense, thanks
Comment: Feel free to submit this as an answer.
Answer: Notice that division by zero is not defined. So, you can write
$$\frac{x-4}3=y,\quad z=2.$$


Linear Algebra - linear functionals

Question: Let $S$ be a set of vectors in $V$. Define $S^0$ to be the set of linear functional that vanishes on $S$.
Show that $$S^0  = \langle S\rangle^0$$
I am really confused what is meant by $S^0$
Comment: $S^0$ is defined to be the set of linear functionals that vanish on $S$.
Comment: aka the annihilator
Comment: Using mathematical notation, perhaps?
Answer: A linear functional on $V$ is a linear map
$$
f\colon V\to K
$$
where $K$ is the base field (in your case it may be the reals or the complex numbers, please add details), where $K$ is considered as a vector space.
The set of linear functionals on $V$ is usually denoted by $V^*$; so
$$
S^0=\{f\in V^* : f(x)=0,\text{ for all }x\in S\}
$$
Now, set $T=\langle S\rangle$, the subspace spanned by $S$. It is rather easy showing that
$$
T^0\subseteq S^0
$$
because $S\subseteq T$. For the converse inclusion, take $f\in S^0$ and try showing that, for all $x\in T$, it must be $f(x)=0$ (that is, $f\in T^0$).
Answer: By definition
$$f\in S^0\iff\;\forall\,s\in S\;,\;\;f(s)=0$$
What you have to prove is that a linear functional (i.e., an element of $\;V^*$) vanishes on a set $\;S\;$ iff it vanishes on the vector subspace that set generates, for example
$$f(s)=0\;\;\forall\,s\in S\implies \;\forall\;\text{linear combination}\;\sum_{i=1}^m a_
is_i\;,\;\;a_i\in\Bbb F\;,\;$$
$$s_i\in S\;,\;\;f\left(\sum_{i=1}^m a_is_i\right)=\sum_{i=1}^ma_if(s_i)=0 \;(\text{fill in details})$$
Answer: $S^0=\{f:V\to\Bbb R \mid \forall s\in S: f(s)=0\}$.
Show that, if $f\in S^0$ then $f\in \langle S\rangle^0$ and the other way around, if
$g\in \langle S\rangle^0$ then $g\in S^0$. (One of these is trivial, the other follows by linearity.)

Linear Algebra - linear functionals


Theming a node edit Form - Move Author Information to another positon

Question: I am theming the DRUPAL 7 NODE EDIT FORM following the instructions in the post.
Everything is working fine.
However, I want to move the "Authoring Information" from the bottom of the page to another position on my node. How do I do that?
I thought I would be able to use this:
<?php print drupal_render($form['author']); ?>

But it does not seem to work.
Comment: Make sure you clear the cache, if you modify your templates. It should work.
Answer: You can use the Display Suite module.

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (Drupal 7 only) is available for even more drag and drop fun!
Answer: The only solution I found to this was to use a View.

In Views under relationship, select Content: Author The in fields,
add an author field.
Then in under Contextual Filters select Content
NID
Use the following settings for Content NID: WHEN THE FILTER VALUE
IS NOT AVAILABLE: Provide Default Value / NODE ID from URL

Then simply create a block and display it on the node page.
Answer: Try the following:
<?php print drupal_render($form['author']['name']); ?>
<?php print drupal_render($form['author']['date']); ?>

The author fieldset is part of the additional_settings group.  To render the author field you have to call it directly.
Display Suite is great, but it won't let you access the author field directly.


Bounds for a parameter-dependent quadratic form

Question: Let $A\in\mathbb{R}^{n\times n}$ be a symmetric matrix, $x(t)\in\mathbb{R}^n$, and $t\in\mathbb{R}^+$. I'm interested in finding upper and lower bounds for the following quadratic form
$$ f(x(t)) = x(t)^{\intercal}A x(t)$$
assuming that $\Vert x(t) \Vert \leq \beta$, $\beta\in\mathbb{R}^+$. Any help will be appreciated!
Comment: The lower and upper bound are the same as for $x^TAx$ where $\|x\|\le \beta$ i.e. $\lambda_\min(A) \,\beta$ and $\lambda_\max (A)\,\beta$
Comment: @RyszardSzwarc can you please elaborate a bit more? This result is actually useful. Many thanks.
Comment: Sorry, the upper bound is$\lambda_{\max(A)}\beta^2.$ The lower bound is $\lambda_{\min(A)}\inf_t\|x(t)\|^2.$ I will post the answer shortly.
Answer: For any symmetric matrix $A$ there holds $$\lambda_{\max(A)}= \max\{x^TAx\,: \,\|x\|\le 1\}, \quad \lambda_{\min(A)}= \min\{x^TAx\,: \,\|x\|\le 1\}$$
(see part hessian)
Therefore by homogeneity $$ \lambda_{\min(A)}\|x\|^2\le x^TAx\le \lambda_{\max(A)}\|x\|^2$$ i.e.
$$ \lambda_{\min(A)}\|x(t)\|^2\le x(t)^TAx(t)\le \lambda_{\max(A)}\|x(t)\|^2\qquad (*)$$
Thus $$\sup \{x(t)^TAx(t)\,:\,\|x(t)\|\le \beta\}\le \lambda_{\max(A)}\sup_t\|x(t)\|^2\le \lambda_{\max(A)}\beta^2$$ Moreover the equality occurs when $x(t)\equiv \beta\, v_{\max(A)}$, where $v_{\max(A)}$ is the unit eigenvector corresponding to the eigenvalue $\lambda_{\max(A)}.$
By $(*)$ we get
$$\inf_t x(t)^TAx(t)\ge \lambda_{\min(A)}\inf_t\|x(t)\|^2$$
The equality occurs when $x(t)=\|x(t)\|\,v_{\min},$ where $v_{\min}$ denotes the unit eigenvector corresponding to $\lambda_{\min(A)}$. The bound is equal $0$ if $\|x(t)\|$ is not bounded away from $0.$
Comment: This is very clear. Many thanks!


MS Access vba query where

Question: Simple Question.
For example, i have a Customer that have 10 Orders and each order include 6-10 Items.
i want to create a vba query that will desplay all the items of a specific customer.
My query is:
x = CustomerNum
Query = "Select OrderNum from CustomerOrderT Where CustomerNum = " & x
Set result = CurrentDb.OpenRecordset(Query)

y = result!OrderNum
'(there is a lot of orders on y)

Query = "Select Product From OrderProducts Where OrderNum = " & y
Set result = CurrentDb.OpenRecordset(Query)

The problem is that i only see the Products of the first order and i cannot see the products of all the orders that i select on the first query.
Need some help to handke this situation.
Thank you very much.
Comment: that is because you only get the first order, you need to loop through the returned record set and get each order number.
Answer: You can just execute a single query for all orders:
x = CustomerNum
Query = "  SELECT CustomerOrderT.CustomerNum, " & _
                  CustomerOrderT.OrderNum, " & _
        "         OrderProducts.Product " & _
        "    FROM CustomerOrderT INNER JOIN OrderProducts " & _
               ON CustomerOrderT.OrderNum = OrderProducts.OrderNum " & _
        "   WHERE (((CustomerOrderT.CustomerNum)=" & x & ")) " & _
        "ORDER BY CustomerOrderT.OrderNum, " & _
        "         OrderProducts.Product;"

And then loop over all the records, noting each change in OrderNum
But beware of building SQL like this if you don't control how variable CustomerNum is assigned, as you open yourself to SQL injection attacks.
Comment: On the contrary, it doesn't matter whether the code is VBA or whether the VBA project is locked, if you're executing custom-built SQL against a database, but you allow a user to enter a malicious SQL-snippet in a cell or InputBox, and that snippet ends up being inserted into a SQL string, then you have major issues.
Comment: @caiohamamura in Excel VBA you would be using the ADODB API/library, which completely supports parameterized queries, as does DAO which Access uses. Also with Windows Authentication to the database server there's no need to store credentials anywhere, be it in code or in some connection file. Bad code is on the programmer, not the language.
Comment: That's my point. The problem of SQL injection is for user to input something like `1 GO DROP TABLE AnyTable GO`. If you trust the users which will have access to the workbook you probably should not care about them inserting such things in the filter cell or input box.
Comment: Excel VBA code has almost no security at all so SQL injection attacks can't be avoided, VBA even password protected can be easily accessed/hacked. So one shouldn't use it if there are concerns about security.
Comment: I know, but in excel VBA it is almost impossible to avoid a malicious user to hack SQL string as (s)he can easily modify the code. The only solution to that is to login into database with limited permissions. Then you don't need to care about SQL injection either, because injecting will just return an error.
Comment: Or force client-access to use Stored Procedures
Comment: That said if you're worried about users (...colleagues??) modifying the code to malicious intent, you have worse problems than SQL injection.

MS Access vba query where


How to go instruction by instruction shown by disassembler in a core in gdb

Question: I am trying to analyze a core dump. There is very little stack frame on the core, so I am using disassembler. Now the disassembler gave a list of instruction in assembly. Now I want to check what is the value of a particular register . As the same register is used multiple number of times I think the value I am trying to access is the last present value. So, is there a way that I can go to particular instruction and then check the register value?
Example:
gdb binary core
disas /s fucntion_name
   0x00007fbb3cc51a9c <+0>:     push   %rbp
   0x00007fbb3cc51a9d <+1>:     mov    %rsp,%rbp
   0x00007fbb3cc51aa0:  sub    $0x10,%rsp
   0x00007fbb3cc51aa4:  mov    %rdi,-0x8(%rbp)
   0x00007fbb3cc51aa8:  cmpq   $0x0,-0x8(%rbp)
   0x00007fbb3cc51aad:  je     0x7fbb3cc51b0b
   0x00007fbb3cc51aaf:  mov    0x2030c3(%rip),%eax
   0x00007fbb3cc51ab5:  test   %eax,%eax
   0x00007fbb3cc51ab7:  je     0x7fbb3cc51b0b
   0x00007fbb3cc51ab9:  mov    -0x8(%rbp),%rdi
   0x00007fbb3cc51abd:  callq  0x7fbb3caf8df0
   0x00007fbb3cc51ac2:  mov    -0x8(%rbp),%rax
   0x00007fbb3cc51ac6:  mov    0x28(%rax),%eax
   0x00007fbb3cc51ac9:  lea    -0x1(%rax),%edx
   0x00007fbb3cc51acc:  mov    -0x8(%rbp),%rax
   0x00007fbb3cc51ad0:  mov    %edx,0x28(%rax)
   0x00007fbb3cc51ad3:  mov    -0x8(%rbp),%rax
   0x00007fbb3cc51ad7:  mov    0x28(%rax),%eax
   0x00007fbb3cc51ada:  test   %eax,%eax
   0x00007fbb3cc51adc:  jne    0x7fbb3cc51b02
   0x00007fbb3cc51ade:  mov    -0x8(%rbp),%rax
   0x00007fbb3cc51ae2:  mov    0x2c(%rax),%eax

Now, suppose I want to check the value of register "rbp" at instruction whose address is 0x00007fbb3cc51ac2; how can I check?  I can't run the program, as it is just a core file from the customer.
Comment: You can't see previous register value in same frame (at least in core dump), but with my rudimentary knowledge of x86-64 assembly I can't see any instruction that changes rbp after beginning of the function. You can see value of rbp in previous frame by doing "up" and examining value there.
Answer:
As the same register is used multiple number of times I think the value I am trying to access is the last present value.

Using the register doesn't alter its value, only writing to it does.
If the register is written to multiple times, then yes: you will see in the core dump the last value written to it.

So, is there a way that I can go to particular instruction and then check the register value?

What you are asking for is effectively reverse debugging. While it can be done, it carries a very significant overhead (in both memory and execution speed). A "normal" core dump certainly doesn't have the info to perform reverse debugging.

I want to check the value of register "rbp" at instruction whose address is 0x00007fbb3cc51ac2; how can I check?

That's relatively easy: since %rbp is only stored to once (instruction at 0x7fbb3cc51a9d) the value should be the same as it is at any other location in the function.
Note: this assumes that every function you called saved and restored the value of %rbp (which is required by the ABI). It is possible that one of the routines is buggy and didn't correctly restore the value, in which case you are mostly screwed. However, you should also be able to restore the value of %rbp from %rsp: they were equal after 0x7fbb3cc51a9d, and then %rsp was decremented by 0x10 at 0x7fbb3cc51aa0. So it must be that %rbp == %rsp + 0x10.


Delete UITableVIewCell from another view controller file in Xcode

Question: I have an array "numbers" which I call in my table view file to make the table view cells. When one is clicked it goes to a view controller which shows details about that cell, and in within that view controller is a delete button. How would I delete the item from the array, and reload the data in the table view controller?
So I set it up that when the delete button is clicked it runs an exit code, and deletes the item from the array, and reloads the data. I tried testing it but it never seems to execute.
This is in the detailViewController where it runs the exit function and runs the protocol to delete the item from the array
func deleteNumber() {
    self.delegate?.unwind()
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // Change `2.0` to the desired number of seconds.
        self.performSegue(withIdentifier: "unwindToNumbersList2WithSender", sender: self)
    }
}

Then in the table view controller it runs this:
func unwind() {
        numbers.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        saveNumbers()
}

I also tried using:
func unwind() {
        numbers.remove(at: indexPath.row)
        tableView.reloadData()
        saveNumbers()
}

So I wanted it to run an either delete the row or delete the item from the array, and reload the data, but neither of those ran. Is there a way I can delete it from the detail view controlle?
Comment: Use notification center
Comment: @SPatel what do you mean by that?
Comment: Your code looks fine to me. Are you sure `indexPath.row` has the right value? Are you sure `saveNumbers` does not restore the datasource?
Comment: @VinodVishwanath let me check that. I'm thinking I may have a problem with the protocol cause I don't think that's running either
Answer: You can use NotificationCenter for doing this,
First you need to add notification in UIViewController like this
let DELETE_DATA = "DELETE_DATA".notificationName()

NotificationCenter.default.addObserver(self, selector: #selector(self.delete_data), name: DELETE_DATA, object: nil)

Make a function named delete_data
 @objc func delete_data(_ notification : NSNotification){
    let userData = notification.userInfo as? [String:Any] ?? [String:Any]()

    // here you can get your wanted index to be deleted.
}

From details view controller you need to POST this notification with index you want to delete
let obj = ["index":`your index to be deleted`]

NotificationCenter.default.post(name: DELETE_DATA, object: nil, userInfo: obj)

Comment: For the first part should I declare that in viewDidLoad() of the detail view controller then add the function in the table view controller
Comment: You need to do addObserver at place where you need to delete item from array in viewDidLoad() and let DELETE_DATA = "DELETE_DATA".notificationName() this you can define global so you can use it in another controller when you post notification
Comment: This is a bad answer. The notification center is just one of many ways to broadcast messages for the detail-view-controller to communicate with its delegate. The OP has already established a perfectly reasonable way for this communication and using the NotificationCenter is an unnecessary tangent.
Comment: Well, I still tried it but I kept getting the error Extra argument 'object' in call. What does that mean?


MySQL - Split two columns into two different rows

Question: I don't have any idea to create this sorry if it is a silly question.
I have a table two teams and total watch and I will use this information later a different place so my idea concat this two column in one column but two different rows:
HomeTeam      AwayTeam     Totalwatch
A              B              100
A              C               90
C              A               80
D              B               70
C              E               50

Can I this
Teams          TotalWatch
A                100
B                100
A                 90
C                 90
C                 80
A                 80
D                 70
B                 70
C                 50
E                 50

I have a few columns so they will repeat as well.
Just a note I know how can concat in one-row use with concat function I do not know how can I make with two rows
Answer: You can use UNION ALL and an ORDER BY Totalwatch DESC to get the results ordered according to Totalwatch.
SELECT HomeTeam AS Teams, Totalwatch  FROM YourTable
UNION ALL
SELECT AwayTeam, Totalwatch FROM YourTable
ORDER BY Totalwatch DESC;

Answer: Simply use UNION ALL:
SELECT *
FROM(
    SELECT HomeTeam Teams,TotalWatch FROM Your_Table
    UNION ALL
    SELECT AwayTeam,TotalWatch FROM Your_Table
    )D
ORDER BY TotalWatch DESC

Answer: Try this bro.. :)
SELECT HomeTeam,Totalwatch
FROM   YourTable

UNION ALL

SELECT AwayTeam,Totalwatch
FROM   YourTable


Get the status of IE popupwidow created from a c# application

Question: I have created an internet explorer toolbar using C#. On clicking on that toolbar button , I want to open internet explorer popup window. I have used web browser control with in the form and its invoke script method. With in the java script I have  used window.open method to open the new window popup. I need to identify whether the popup is closed or not with in the form?.
Answer: Since this is from within a Windows application, you might find it easier to create a separate form with its own (visible) WebBrowser control, with its Url property set to whatever address you were using in the javascript window.open method.
Here is a simple example of how to do this from a button's click event:
private void button1_Click(object sender, EventArgs e)
{
    Form f = new Form();
    WebBrowser wb = new WebBrowser();
    wb.Url = new Uri(@"http://www.stackoverflow.com");
    wb.Dock = DockStyle.Fill;
    f.Controls.Add(wb);
    f.FormClosed += f_FormClosed;
    f.Show();
}

void f_FormClosed(object sender, FormClosedEventArgs e)
{
    MessageBox.Show("popup has closed");
}

Comment: Thank you MusiGenesis, but i need to open a popoup of internet explore, not in webBrowser. what i have done is i, just added sone html nd js code to the webBrower document text nd opened the popup of ie, bt wt my problem is i cant access the status of this popup created in my application


Sudden loss of connectivity in our SBS 2011 domain network

Question: In our company we are having one windows sbs 2011 domain controller and around 50 pcs with Windows XP professional sp3 and some laptops with Windows 7 professional SP2; Antivirus is Symantec Endpoint Protection loaded in separate pc made server and all are configured; working perfectly until today afternoon.
All of a sudden lot of calls started coming to IT ROOM complaining about the lost of connection between dc and the clients. We checked the pc's in our IT ROOM for myself and colleague starting to troubleshoot from our pc's since we also lost the connectivity.

ping not working from any pc to DC
ping not working with default gateway from the pc's lost connection
layer 2 connectivity is ensured OK by connecting my pc through live bootcd and ping works with dc, gateway; I opted for live boot cd since I rebooted my pc and the dc couple of times; no effect
default gateway which is our ADSL ROUTER LAN IP is pinging from the DC and internet is working
DC's antivirus, Symantec Endpoint Protection, is stand alone not in sync with the Symantec server. Also a client pc which is loaded with kaspersky antivirus also having the same problem. So the Symantec Endpoint Protection server possibility can be isolated.
Restarted the DC and chose last known good configuration; same symptom
found one windows server 2003 loaded as a member server in the domain still working; pinging with the DC; able to access the folders in DC ; afraid to restart and check since on a Windows XP machine lost connectivity after restarting

N.B: all the clients are getting IP from dhcp in DC
When pinging request timed out is the result and the gpresult of the client pc's give generic failure
The current problem is temporarily solved !!!
I need a permanent solution.
The full details are at http://social.technet.microsoft.com/For ... e3d9354ac5 where I posted this issue first
Comment: Disagreeing with Susan Bradley about how SBS server works is a lot like disagreeing with Shakespeare about what the author of "*Romeo and Juliet*" was thinking when he wrote the balcony scene, by the way.
Comment: There's a running troubleshoot at the link, but really the issue should have been summarized with your discovery of a workaround here, not a pointer to the offsite link (or the link as a reference, not the canonical detail of the issue)
Comment: Your link is broken. I'm not sure what exactly you're saying the cause/temporary fix was?
Comment: Now I edited my link Please have a look!
Answer: I scanned through that really long troubleshooting session, and it looks like the problem was the antivirus on the server playing with firewall settings?
If that's the case, your permanent solution was alluded to in your troubleshooting session. Don't install that Symantec AV on the server, or at least don't use anything that inserts a third-party firewall. Use the built-in firewall that is managed by Windows and group policy.
Comment: Hi Bart Silverstrim I agree with you and I also suspect something has caused from symantec antivirus only   Now my question is that symantec antivirus was working without any problems in that server for the past 5 1/2 months ; how all of a sudden it would have caused this issue?\
Comment: Hi As the issue is temporarily solved by disabling some policies in SBS 2011, I need to know the facts on the effect of this policies on this network issue I suspect something from firewall component of Symantec Endpoint protection has changed the settings in the firewall of SBS 2011 Please help me to get the facts and solve the issue permanently   And another question is two 2003 servers were not affected by this issue but all the windows xp, vista & windows 7 clients all got affected
Comment: Could a component have been updated or auto-updated? Check your version numbers. It's pretty obvious that something in that AV is causing the problem; is it worth your time to continue tracking the component, or just scrapping that AV and using another solution on the servers?
Answer: It's either a problem with your Antivirus software (seems most likely) or someone changed the Policies you disabled to make the network work again (possibly firewall settings, IPSec, authentication, etc).
Comment: Hi Chris Then how was the same symantec endpoint protection was working without any problems for the past 5 1/2 months ? Myself only handling the server; no policies or settings changed in the server
Comment: Symantec and McAfee have had some pretty impressive bloopers pushed out as updates in the past. I wouldn't discount that for a moment, this could be another. I don't deal with Symantec anymore.
Comment: Hi As the current network is brought to normal after the resetting of IP & WINSOCK , is it safe to re-enable the disabled policies? Thanks
Comment: I still don't know what is actually wrong, and it sounds like you don't either... So I don't know if it's safe to reenable the policies or not, we don't know what they broke in the first place.
Comment: Actually I have elaborated my issue in the link at http://social.technet.microsoft.com/Forums/en-US/smallbusinessserver/thread/c2f80047-cc73-43ae-9b4d-a7e3d9354ac5 And my question is what do the disabled policies have effect on the client ? After doing the reset of ip & winsock in client and having the mentioned policies enabled in the dc , the problem was not solved.Only the combination of resetting IP & WINSOCK with mentioned policies disabled, only then the network connectivity established .....Any ideas?
Comment: Yep, read all that, still don't know what the problem is. Have you looked at the RSOP for the Policies?
Comment: When I faced that problem, I ran gpresult in the affected client pc ; I got the result of some texts noting about the applied policies, in the end of the text I got something " general failure" .I am waiting for re-enabling the disabled policies and test during the off production hours and will update all


admin approval required for specific roles registered using profile2_regpath

Question: I am using profile2_regpath for registrations .
I have 3 roles. Students, Centers and Organisations. Is it possible to activate the users which are registered for Student role without admin approval ?
The users who registered for centers or organizations role must need admin approval.
Default "Account settings" in Drupal have the option to activate users without admin approval but I can not specify the roles there.
Any clue? or any other module which I should be using instead profile2_regpath
Answer: You may be able to use Rules to accomplish this. Create a new Rule that is triggered when a user account is created. Then add a condition that checks what the role of the user is. And finally, an action that activates the user account. I think that would work - although I'm not sure if those triggers/conditions/actions exist. They probably do. :-)


Log4j multiple log files using rootLogger

Question: I want to store all log details of my entire application in two different files.
For eg: one file will contain all DEBUG information and the other will contain only ERROR
my current log4j.properties file looks like this
log4j.rootLogger=DEBUG, file1
#Log Message in debug.log file
log4j.appender.file1=org.apache.log4j.FileAppender
log4j.appender.file1.File=log/debug.log
log4j.appender.file1.layout=org.apache.log4j.PatternLayout
log4j.appender.file1.layout.ConversionPattern=%-4r %d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n

log4j.rootLogger=ERROR, file2
#Log Message in error.log file
log4j.appender.file2=org.apache.log4j.FileAppender
log4j.appender.file2.File=log/error.log
log4j.appender.file2.layout=org.apache.log4j.PatternLayout
log4j.appender.file2.layout.ConversionPattern=%-4r %d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n

but this only updates the error.log file(any file mentioned last)
The best solution that i have come across till now is using
log4j.logger.OTHER_LOGGER=DEBUG, file2
log4j.additivity.OTHER_LOGGER = false
#File Appender
log4j.appender.file2=org.apache.log4j.FileAppender
log4j.appender.file2.File=log/admin.log
log4j.appender.file2.layout=org.apache.log4j.PatternLayout
log4j.appender.file2.append=false
log4j.appender.file2.layout.ConversionPattern=%-4r %d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n

and using
private static final Logger logger = LoggerFactory.getLogger("OTHER_LOGGER");

but the problem in using this is when the log is updated is shows like
0    22 Oct 2012 20:38:50 [main] INFO  OTHER_LOGGER  - testclass

Now here instead of the mentioning the class from where the log is reported, it says OTHER_LOGGER
Thus the best way to go about it would be using two rootLooger's but somehow it does not allow it
Could anyone please help me out?
Answer: Again, it's the good job for LevelMatchFilter. Just use LevelMatchFilter with property LevelToMatch = ERROR for the appender "file2".
You should use XML configuration because filters are unsupported by properties configuration. Here I tried to write XML configuration that you need:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="file1" class="org.apache.log4j.FileAppender">
            <param name="File" value="log/debug.log"/>
            <layout class="org.apache.log4j.PatternLayout">
                    <param name="ConversionPattern" value="%-4r %d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n"/>
            </layout>
    </appender>

    <appender name="file2" class="org.apache.log4j.FileAppender">
            <param name="File" value="log/error.log"/>
            <layout class="org.apache.log4j.PatternLayout">
                    <param name="ConversionPattern" value="%-4r %d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n"/>
            </layout>

            <filter class="org.apache.log4j.varia.LevelMatchFilter">
                    <param name="LevelToMatch" value="error" />
                    <param name="AcceptOnMatch" value="true"/>
            </filter>
            <filter class="org.apache.log4j.varia.DenyAllFilter" />
    </appender>

    <root>
            <level value="debug"/>
            <appender-ref ref="file1" />
            <appender-ref ref="file2" />
    </root>
</log4j:configuration>

Comment: thnks. Although I have to use XML, I think this should do the trick.
Could you please covert the above properties file into XML, I am not very familiar with it
Thanks again
Comment: Do you want to write all or only messages with level DEBUG to log/debug.log?


Term for 'key change' when going for the chorus

Question: There are songs that change key midway. The most common one I've heard is they change the key when going for the chorus. After that, when the song goes back to the verse, they change the key back.
Some people might say that it's modulation, but I don't think it is, it's different from modulation. I'm sorry I'm not an expert in music so I can't explain it well.
Here is an example:

The key change happens around 1:11. To my understanding that's not modulation.
Does someone know that is it called? Besides key change, of course.
(if it's actually called modulation, then mod can just delete this question)
Comment: It's actually called modulation, which is another word for key change.
Comment: A lot of songs actually go to IV at the start of a chorus, which is not a key change, and not really a modulation. The key sig. stays the same, and at the end of the chorus, there's often a V chord to come back to the verse, in the original key, which is where the song was anyway.
Answer: If a different pitch from the original becomes the new tonal center for a length of time, you have modulated keys (changed key). In the case of the video you've shared, the tonal center moves from E (in the verses) to F# (in the choruses).
However, there are many instances-both in "classical" (art) music and pop music-where a different pitch becomes the new tonal center for only one beat/count or one bar/measure; in these instances, it is not considered a full modulation, but rather a tonicization. The reason for this term "tonicization" is the new tonic (also called home note, "do", tonal center, 1, etc.) that is represented.
Because each entire verse centers around E, and each entire chorus centers around F#, I would personally say that this particular song modulates multiple times, rather than saying F# is temporarily tonicized. The tonicization of F# occurs for many measures, too many to not be considered a complete modulation.
In summation, moving to a different tonal center briefly is tonicization; changing the tonal center/key for a longer length of time is a modulation.
Comment: I need your view on another answer below
Answer: I would call this key exchange and not a modulation (based on Czech book "Základy harmonizace" (The basic of harmonization)).
The modulation uses pivot chords to change tonal centre, whereas key exchange does not. It changes the tonal centre directly, without any warning. There is jump from E to F#, but no preparation using pivot chords. It jumps directly from one key to another.
Comment: Modulations don't have to use pivot chords, and an abrupt change to a new key is often called a _direct modulation_, though this would seem to imply that the key will return home eventually.
Comment: @DavidBowling So we've got different views of modulation here. I still can't find an answer that satisfies me
Comment: @Albert -- it isn't just my view of modulation. [See the Wikipedia page on modulation](https://en.wikipedia.org/wiki/Modulation_(music)), which lists no less than eight different types of modulations. Modulation by pivot chord (which they call _common-chord modulation_) is only one; direct modulation (which they also call phrase, abrupt, or static modulation) is another.


X-Forward-Proto custom header

Question: I am leveraging AWS ALB & My setup is as follows :
ALB]--HTTPS--[NGINX]--HTTP--[ALB]--HTTP--[APP/NGINX]
the problem is I am using NGINX to forward X-Forwarded-Proto=https to the application through the ALB , but the ALB is stripping it down, the application needs X-Forwarded-Proto=https so that it can issue secure cookies and set STS header. We have tried setting this header in NGINX, but looks like APP ALB strips it down. and per AWS support this is by design.
there is a workaround to use a custom header to save the X-Forwarded-Proto value from the first ALB and send it along to the second ALB and that won't get strip down when it reaches the APP, can anyone advise on how to implement this on NGINX or suggest a different workaround to this problem
Answer: From this forum link, they said that Application Load Balancer will pass the X-Forwarded-For/Proto/Port https://forums.aws.amazon.com/thread.jspa?messageID=738145.
If in your case the X-Forwarded-Proto header always getting value HTTP. Then, that's mean AWS ALB is not stripping the X-Forwarded-Proto header, instead, they will replace it. If its true that AWS ALB replace X-Forwarded-Proto, you can use custom HTTP header to pass the header in first nginx instance. Like this one
<code>Location /{
    proxy_pass http://upstream;
    proxy_set_header X-Custom-Forwarded-Proto $http_x_forwarded_proto;
}
</code>
Hope this will help. Thanks

X-Forward-Proto custom header


Can't bind a custom view

Question: I'm using a custom view, com.deadballapp.deadball.ui.pitch.PitchLiveView, but my binding class is unable to access this view. The binding class is able to access cl_pitch_live
PitchLiveView isn't inflated, it's a class that extends View which I'm using to draw to the Canvas so any solution to binding to a custom view I've seen here, here and here don't seem to apply
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cl_pitch_live"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/pitch_green">

        <view
            android:id="@+id/view_pitch_live"
            class="com.deadballapp.deadball.ui.pitch.PitchLiveView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/nav_header_vertical_spacing"
            android:layout_marginBottom="@dimen/btm_sheet_peek_height" />

        <include layout="@layout/bottom_sheet_pitch_live"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

Any ideas?
Comment: first thing `view` should be `View`.
Comment: Using `View` then that would refer to the `View` base class? They're referring to a custom class, like they do here https://developer.android.com/guide/topics/ui/custom-components#modifying.
Comment: Can you edit your question with what actually happens when you attempt this? Compile time error, runtime errors? I have tested this and it works fine for me.
Answer: This is the alternate method to define custom view in layout xml.
 <com.deadballapp.deadball.ui.pitch.PitchLiveView
     android:id="@+id/view_pitch_live"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginTop="@dimen/nav_header_vertical_spacing"
     android:layout_marginBottom="@dimen/btm_sheet_peek_height" />

You can bind this as other views, either by using View Binding or findViewById
Comment: Do you have a source for why the `view` tag isn't supported with data binding?
Comment: I had thought this way using `view` tag works with custom view defined as inner class as in the Notepad example. Updated the answer. Just for [reference](https://developer.android.com/codelabs/advanced-andoid-kotlin-training-custom-views#0)
Comment: When I tried referencing it in my example, it did show `unresolved reference` error with data binding/ view binding.

Can't bind a custom view


PHP tables causing issues

Question: ive been finishing a school project which needs to get a response from a server so ive written some php code. Ive got everything to align up with tables but when I implement it, I get a Giant gap in code. Has anyone seen this before, I know its the  tabs causing this but idk why they keep messing it up, ive tried to move them, but everything in them and more with no luck. below is the outcome of this code,
thank you for your help. Code's outcome
<?php

  // create short variable names
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$outdate = $_POST['outdate'];
$indate = $_POST['indate'];
$numberofpeople = $_POST['numberofpeople'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$cardtype = $_POST['cardtype'];
$cardnum = $_POST['cardnum'];
$specialrequests = $_POST['specialrequests'];

  $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>

<?php
//displays what the user put in the form by using the vairables
 echo "
";
 echo '
Thank you '.$fname.' '.$lname.' for your Reservation

';
echo 'The following is the infomation you entered:

';
echo "
Number & Street	$address	<br/
";
echo "
City	$city

";
echo "
ZipCode	$zip

";
echo "
State	$state

";
echo "
Check-In Date	$indate

";
echo "
Check-out Date	$outdate

";
echo "
Number of People	$numberofpeople

";
echo "
Phone	$phone

";
echo "
Email	$Email

";
echo "
Card-Type	$cardtype

";
echo "
Card-Number	$cardnum

";
echo "
Special Requests	$specialrequests

";
echo  "
";
?>

Comment: code has some mistakes. That's why you got an incorrect output. do you need a verbal answer or the correct code as an answer
Comment: If you could point me in the right direction that would be much appreciated
Comment: hope this answer will help you that
Comment: You need to match your opening and closing tags for starters. The line with `h1` doesn't have an opening `` but has a closing ``. Then, you have `` line breaks between `td` and `tr` for an unknown reason, with possibly unpredictable results. Try fixing those for starters.
Answer: <?php

// create short variable names
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$outdate = $_POST['outdate'];
$indate = $_POST['indate'];
$numberofpeople = $_POST['numberofpeople'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$cardtype = $_POST['cardtype'];
$cardnum = $_POST['cardnum'];
$specialrequests = $_POST['specialrequests'];

$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>

Thank you <?php echo $fname." "; ?><?php echo $lname; ?> for your Reservation

The following is the infomation you entered:

    Number & Street
    <?php echo $address; ?>

... complete other in this fashion

Inside the table, you put a h1 tag
some tags were not hadn't an enclosing tag at some lines.
Make sure that your code has lots of vulnerabilities. please learn some good programming techniques to implement your code

Complete the other tables rows.
Comment: Sahan, this didn't fix the gap in-between the "The following is the infomation you entered:" and the "address" sections. if its ok with you could i get a bit more assistance on it
Comment: I update it. extract this and complete table rows for others
Comment: *"Make sure that your code has lots of vulnerabilities"* that. Are there any examples of input filtering or other checks in your code?

PHP tables causing issues


How fast does Drupal send email?

Question: My SMTP server has sending limit up to 5 messages per second. On Drupal 6 site I have up to 500 users in organic groups to whom I would like to send newsletter.
What sending limit should I set for successful broadcast? Does Drupal send messages momentarily or during longer period?
UPDATE
I use Messages & Notifications modules which allow me to limit

number of messages
sending time in seconds
sending time in % of cron time

The only way to solve my problem I've found up to now is limiting the number of messages to 5 and setting cron to run every 15 minutes. But it is very sad to wait whole day to send about 500 messages.
Answer: If you start tracing from drupal_mail(), you will end up in the MailSystem.  The DefaultMailSystem::mail() method sends out mail, unless another module has done otherwise.  This hands off the email to the PHP mail() function, which does something system dependent.
As far as I been able to tell when I have debugged email problems, Drupal doesn't do any throttling.  Typically, PHP doesn't throttle either.  After that, it really varies and totally depends on the php.ini settings and other server setup.
Comment: Thanks for the hint! But there is a way to limit sending mail - I use Messages & Notifications (updated question).
Answer: I've had problems with mails not reaching a custom Google apps email address from the default mail function. Therefor I use SMTP module to handle my emails. It connects to every mail account(supports SMTP), and uses that to send a mail.
It works with Google Apps, and mail is sent instantly.
Comment: I also use SMTP module, otherwise I wouldn't be able to send emails via SMTP. And I also used free Google Apps account, but it allows sending up to 500 messages per day. Recentrly I've subscribed to AWS SES account, but it has limitation of 5 emails/second.

How fast does Drupal send email?


Diameter of set in metric space

Question: I do agree with the statement that
$$d(A) = \sup{\{d(x, y):x, y \in A\}}$$
But why can't we use maximum because according to me its max will also give diameter.
I know it should not be correct, so please give me the correct explanation with example where the $\max$ formulation will be wrong.
Comment: The max doesn't always exist.
Comment: This site prefers that you use $\LaTeX$. I edited your post to show you how. You can hover your mouse over it and right-click and see the markup. At least that works on Mac, I don't know about other OS's. Or you can see the markup by editing your post. As Zachary notes, the max doesn't always exist. Can you think of an example?
Answer: It is possible for the supremum of a set to be a value that is not in the set, and as a result the set has no maximum value (since the maximum of a set is always taken to be the largest element in the set).
For a simple example, consider the open interval $A = (0, 1) = \{x \in \mathbb{R}: 0 < x < 1\}$. What's the largest distance two elements of $A$ can be? It's not 1, because there are no elements in $A$ that are 1 apart (since 0 and 1 aren't elements of $A$). However, for any distance less than 1, you can find two elements of $A$ that are further apart than that. In fact, the set of distances is equal to $[0, 1) = \{x \in \mathbb{R}: 0 \le x < 1\}$.
Since 1 is not an element of that set, the maximum of the set cannot be 1. However, it also cannot be any number less than 1, since there is always a larger number than it in the set. Hence, the set has no maximum value. However, the set does have a supremum, and the value of that supremum is 1.
Comment: Thnx for answer
Comment: If you think this answer is satisfactory, you should hit the accept button.

Diameter of set in metric space


How can I only show the exact lines from a file with a keyword?

Question: I am looking for a way to only show certain strings with the help of a keyword from a file. So for example if someone inputs a certain playername in a textfield only the commands done by that player will be shown from the logfile.
Logfile
Command: .gm fly on [Player: PlayerOne (Guid: 135) (Account: 256) X: 16222.640625 Y: 16253.207031 Z: 12.735716 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]
Command: .gm on [Player: PlayerTwo (Guid: 136) (Account: 257) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]
Command: .mod sp 5 [Player: PlayerThree (Guid: 137) (Account: 258) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]

PHP Script I have so far
It only dumps the whole GM.log file for now.
$logfile = "/logs/GM.log"; // Directory where the GM.log is stored.

$file = fopen($logfile, "r") or die("Unable to open file!");

$read = fread($file,filesize($logfile));

    echo nl2br($read); //Dump the whole file for now.

fclose($file);

I am not asking for someone to code the exact code for me, I'm rather asking for hints on how I would do it the best way.
Comment: You can make a condition on every line and see if it contains your keyword, you can use this: `if (strpos($ine,'player1') !== false) {
    echo $line;
}`
Comment: FYI: You can take a tour here: http://stackoverflow.com/tour and see how this site works and where everything is
Answer: Something like this should work for you:
Just get your file into an array via file(). Then use simply preg_grep() to identify the lines you want.
<?php

    $lines = file("logs.txt");
    $lines = preg_grep("/Player: PlayerTwo/", $lines);
    print_r($lines);

?>

output:
Array ( [1] => Command: .gm on [Player: PlayerTwo (Guid: 136) (Account: 257) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)] )


Inserções no mongo como fazer?

Question: Estou fazendo um programa que irá realizar inúmeras inserções no mongo(cerca de 500.000).
Porém percebi fazendo alguns testes, que quanto mais entradas no mongo eu tenho, mais demorado é a inserção.
Meu código:
def savePostRecommendation(uid, recs, db):
    temp = db.posts.find_one({'uid':uid})
    if(temp is None):
        db.posts.insert({'uid':uid,'recs':recs})
    else:
        db.posts.update({'uid':uid},{'uid':uid,'recs':recs})

Minha teoria:
Estou fazendo uma consulta para verificar se existe a entrada temp = db.posts.find_one({'uid':uid}), pois se a função fosse apenas db.posts.insert({'uid':uid,'recs':recs}), se o código fosse executado novamente haveria duas entradas no mongo com o mesmos valores. Então acho que quando mais entradas no mongo eu possuo essa busca que faço demora cada vez mais.
A minha pergunta é: Como faço para inserir no mongo um valor definindo meu atributo uid como uma chave primária como SQL faz. Para assim então eu inserir a entrada sem verificar se existe e que não haja uids duplicados?
Answer: MongoDB não tem um tipo de auto-incremento como nos bancos de dados SQL, porém _id é algo muito especial para ele. O que você pode fazer é indicar qual é o _id manualmente:
db.posts.save({'_id':uid,'recs':recs});

Importante se atentar que esse valor seja sempre único (se ele for omitido, mongoDB irá criar o hash padrão). Voce pode economizar if else usando a expressao save que irá criar um novo ou atualizar se identificador já existir.

Inserções no mongo como fazer?


How server response can satisfy dataSource.transport.create?

Question: I'm using kendoGrid and my remote data is from php.
this is an example of the grid:
$('#grid').kendoGrid({
    columns: [
        {field: 'Agent_Code', title: 'Agent code'},
        {field: 'Agent_Name', title: 'Agent name'},
        {field: 'Short_Name', title: 'Short name'},
        {field: 'More_Info',  title: 'More info'},
        {command: {name: 'edit'}}
    ],
    toolbar: [
        {name: 'create'}
    ],
    dataSource: {
        transport: {
            create: {
                url: 'ajax/create.php',
                type: 'POST',
                dataType: 'json'
            },
            read: {
                url: 'ajax/read.php',
                type: 'POST',
                dataType: 'json'
            },
            update: {
                url: 'ajax/update.php',
                type: 'POST',
                dataType: 'json'
            },
            destroy: {
            },
        },
        schema: {
            type: 'json',
            data: 'data.results',
            model: {
                id: 'Agent_Code',
                fields: {
                    Agent_Code: {editable: true, nullable: false, type: 'string'},
                    Agent_Name: {editable: true, nullable: false, type: 'string'},
                    Short_Name: {editable: true, nullable: false, type: 'string'},
                    More_Info:  {editable: true, nullable: false, type: 'string'}
                }
            }
        }
    }
});

The grid populates correctly because I set "dataSource.schema.data" to "data.results" so the grid know how to locate the data at the server response.
server 'json' response structure for "transport.read" is:
{
    code: 'ok',
    data: {
        id: [' ', ' '],
        results: [
            {Agent_Code: ' ', Agent_Name: ' ', Short_Name: ' ', More_Info: ' '},
            {Agent_Code: ' ', Agent_Name: ' ', Short_Name: ' ', More_Info: ' '}
        ]
    }
}

My problem is that I don't understand how to do that for "dataSource.transport.create" and "dataSource.transport.update" the server receive the data correctly, store it to DB and response with:
{
    code: 'ok',
    text: 'operation succeeded'
}

but the grid don't understand that everything is OK and update the grid.
What is missing here?
Regards
Answer: You need to modify your schema definition adding errors to it.
schema   : {
    type : 'json',
    data : 'data.results',
    model: {
        id    : 'Agent_Code',
        fields: {
            Agent_Code: {editable: true, nullable: false, type: 'string'},
            Agent_Name: {editable: true, nullable: false, type: 'string'},
            Short_Name: {editable: true, nullable: false, type: 'string'},
            More_Info : {editable: true, nullable: false, type: 'string'}
        }
    },
    errors : function(a) {
        return a.code !== "ok";
    }
}

This errors function returns true or false depending on code.
In addition and since you seems to do not return the record when it is updated or inserted, you should modify data to do not try to find it when update or create but find it when read.
You might define it as:
data : function (a) {
    if (a.data && a.data.results){
        return a.data.results;
    } else {
        return null;
    }
},

Now, the schema definition would be:
schema   : {
    type : 'json',
    data : function (a) {
        if (a.data && a.data.results){
            return a.data.results;
        } else {
            return null;
        }
    },
    model: {
        id    : 'Agent_Code',
        fields: {
            Agent_Code: {editable: true, nullable: false, type: 'string'},
            Agent_Name: {editable: true, nullable: false, type: 'string'},
            Short_Name: {editable: true, nullable: false, type: 'string'},
            More_Info : {editable: true, nullable: false, type: 'string'}
        }
    },
    errors : function(a) {
        return a.code !== "ok";
    }
}

NOTE: If you always return ok then you might avoid defining errors, the only important part is redefining data.
EDIT: You can read more in KendoUI site:

About using it here and specifically on using errors and error here.
You can also check DataSource.schema.errors documentation and DataSource.error](http://docs.kendoui.com/api/framework/datasource#events-error) event handler documentation.
Comment: I didn't understand why the if statement contains **a.data &&**. Additionaly, can you point me to documentation regarding this issue I didn't found any at kendoui website
Comment: I check for `a.data` because when the server send the result to the `update` the JSON does not include it but this is executed anyway so it prevents from crashing. Then I check for `a.data.results` because here is where the information is actually coming. Yes, I might have checked only for the first condition hoping that the message is well formed but I did prefer to do this since it is more secure. I will update my answer for including references to Kendo UI documentation.


Como dar um "refresh" após de fazer update do novo vídeo?

Question: Na minha visão, eu tenho um vídeo antigo, quando eu faço "upload" de vídeo novo,
quero automaticamente recarregar um novo vídeo após de "upload".
Segue o código View:

    <video class="embed-responsive-item" controls>
        <source src="/Files/GetVideo?id=2" type="video/mp4">
        Seu navegador não suporta vídeo em HTML5.
    </video>

Segue código Javascript:
 $('#embed_video video').get(0).load();

Código do javascript só funciona na primeira vez, na segunda vez o vídeo não atualiza, fica como antigo.
Segue código Controller:
public ActionResult GetVideo(int id)
{
    using (var ctx = new Entities())
    {
        var result = ctx
            .Video
            .FirstOrDefault();
        byte[] video_byte = result.Video;
        return new RangeFileContentResult(video_byte, "video/mp4", "NomeDoArquivo.mp4", date);
    }
}

Alguma solução ?
Desde já agredeço.
Comment: Caro Matheus, tinha variaveis erradas no script, adicionei também mais uma checagem, agora creio que o código esteja 100%, se puder atualizar para o nome é melhor.
Comment: @GuilhermeNascimento Sim essa eu vi, não avisei para você.
Answer: Isto ocorre porque esta em cache, pois provavelmente o nome é o mesmo, uma maneira de resolver é usar uma querystring randômica (o que não se repete, como algo baseado em timestamp).
No entanto primeiro é necessário pegar o currentSrc (https://html.spec.whatwg.org/multipage/media.html#dom-media-currentsrc), algo como:
var videourl = $('#embed_video video').prop("currentSrc");

Então limpar a querystring:
videourl = videourl.replace(/\?(.*?&)?_=\d+$/, "?$1");

E aplicar a nova:
videurl = videorl + "_=" + Date.now();

Pode fazer uma função assim:
function updateVideo(query, play) {
    var el = $(query).get(0); //usei o .get para ficar mais "limpo" o código, mas o resultado é indiferente no final

    if (!el) alert('Não encontrado'); return;

    var videourl = el.currentSrc;

    videourl = videourl.replace(/\?(.*?&)?_=\d+$/, "?$1");
    videourl = videourl + (videourl.indexOf("?") !== - 1 ? "&" : "?");
    videourl = videourl + "_=" + Date.now();

    el.pause();
    el.src = videourl;

    if (play) el.play(); //o play já executa o load
}

O uso seria algo como:
updateVideo('#embed_video video', true);

Ou sem autoplay:
updateVideo('#embed_video video', false);

Answer: Acho que eu respondi essa mesma pergunta ou uma muito semelhante ontem mesmo...
mas segue abaixo:
document.getElementById("VideoReload").load();

Comment: Já tentei e nada acontece, ele permanece o vídeo antigo.
Comment: Mas se você consultar diretamente a sua action, ela retorna o conteúdo correto?
Comment: Ele funciona só na primeira vez ao chamar `action`, na segunda, terceira etc... nunca chama ação.