Selecionar elementos HTML inserido dinâmicamente com Javascript

Question: Estou desenvolvendo uma espécie de calculadora, onde o cliente coloca algumas informações listadas em elementos "select" e calcula o valor do serviço a ser contratado. Nessa calculadora, há a opção de selecionar o tipo de serviço ao qual o cliente quer calcular os preços, isso é, os parâmetros "name" e "id" mudam de acordo com a seleção do serviço do parte do cliente. Segue abaixo os códigos
HTML

Calcule Preços de Planos

Simule valores para contratar avulso ou planos periódicos.

Calculando para:

                                <input type="radio" id="ph" name="setserv" value="ph" onClick="setCalc()" checked />
                                Diarista Por Hora

                                <input type="radio" id="po" name="setserv" value="po" onClick="setCalc()" />
                                Limpeza Pós Obra

                                            Quero Contratar!

JAVASCRIPT
function setCalcPO() {

    ctd.innerHTML = calcTitDescPO;
    cpa.innerHTML = calcParametrosPO;
    calcPreco.innerHTML = "R$0,00";

}

function setCalcPH() {

    ctd.innerHTML = calcTitDescPH;
    cpa.innerHTML = calcParametrosPH;
    calcPreco.innerHTML = "R$0,00";

}

function setCalc() {

        if (isEasy()) {
            setCalcEasy();
        } else if (isPO()) {
            setCalcPO();
        } else if (isPH()) {
            setCalcPH();
        }

}

$(document).ready(function() {

    setCalc();

});

As funções acima inserem um bloco HTML nas section #calc-tit-desc e #calc-paramentros que são os textos que descrevem o serviço que está sendo calculado e os parâmetros (elementos select) a serem escolhidos pelo cliente. O problema surge do fato de que após a inserção do conteúdo HTML pelo javascript, os valores do select não podem ser acessados, dado que o erro aparece como "não é possível encontrar um valor de um nulo", ou seja, o javascript não consegue encontrar aquele select inserido depois de carregado a página.
Código que é inserido pelo dinâmicamente
var calcTitDescPO = '
Calculando Para Pós Obra
'+
            '
Calcule o valor do serviço de acordo com o tamanho do ambiente e do nível de contaminação por cimento, tinta, argamassa etc.
';

var calcParametrosPO = '
'+
                    '<select name="tamanho-obra" id="tamanho-obra" >'+
                        '<option value="1">- TAMANHO M² -</option>'+
                        '<option value="50">Até 50 m²</option>'+
                        '<option value="100">De 50 à 100 m²</option>'+
                        '<option value="150">De 100 à 150 m²</option>'+
                        '<option value="200">De 150 à 200 m²</option>'+
                        '<option value="maior200">Acima de 200</option>'+
                    '</select>
'+
                '
'+
                '
'+
                    '<select name="contaminacao" id="contaminacao">'+
                        '<option value="1">- CONTAMINAÇÃO -</option>'+
                        '<option value="sem">Sem contaminação</option>'+
                        '<option value="baixo">Baixo</option>'+
                        '<option value="medio">Médio</option>'+
                        '<option value="alto">Alto</option>'+
                        '<option value="critico">Crítico</option>'+
                    '</select>'+
                '
'+
                '
'+
                    '
'+
                        'Calcular'+
                    '
'+
                '
';

Selecionando os valores dos seletores
var obraTamanho = document.getElementById("tamanho-obra");
var contaminacao = document.getElementById("contaminacao");

function calcularObra() {
$(document).ready(function() {

    if(obraTamanho.value !== 0 && contaminacao.value === 0) {
        cpe.innerHTML = "Falta informar o nível de contaminação";
    } else if (obraTamanho.value === 0 && contaminacao.value !== 0) {
        cpe.innerHTML = "Falta informar o tamanho do local";
    }

});

}
E ai usando else if sucessivamente para os dados escolhidos
Alguém sabe como posso contornar isso?
Grato desde já
Comment: Fabio, está faltando código aí não está?
Comment: Só estão faltando as variáveis que guardam o código HTML que é inserido nas section mencionadas. Coloquei-as concatenando linha por linha, vou inserir o código na pergunta, desculpe
Comment: @FábioEspíndola Ainda falta mostrar o código que usa para selecionar os elementos, não?
Comment: Adicionado também
Answer: Acredito que você não postou todo o código, mas eu já passei por um problema parecido, ao criar um botão dinamicamente o evento "click" não funcionava nos botões criados.
Eu tentava pegar o evento da seguinte forma:
$("#idBotao").click(function() {

});

Assim alterei a forma de pegar o evento e funcionou:
$("#idBotao").on( "click", function() {

});


Importing from sibling directories (python 3)

Question: I can't figure out how to import modules from sibling directories in Python 3 using absolute imports.

modify the sys.path.
turn the directory into a pip installable package via __init__.py and setup.py.

For option 1. I figured out how to import modules from sibling directories by modifying the sys.path, but this method seems a little hackey to me. Also, I've read that it is not preferred. Why? Is there something inherently wrong or dangerous about modifying the sys.path?
For option 2. What exactly do I need to do make my package pip installable? I've alreay created my __init__.py file, but it seems that I need to create and configure a setup.py script to prepare my package for distribution? I'm still in the development mode, so is this really the best/pythonic method? If it is, then do I just type python setup.py install into my terminal after creating the setup.py?
Edit: I'm now trying to figure this out using absolute imports as python 3 does support relative imports.
Answer:
From what I've read, Python 3 does not support relative imports

It does.
To import myproject/foo/__init__.py from myproject/bar/baz.py, you can use this:
from .. import foo

Or if you want to import an object/module in foo:
from ..foo import object

This requires myproject to be a package, so myproject/__init__.py has to exist.
Comment: Thanks. I'll try this out when I'm at home. What about absolute imports? Is it possible to import modules across different directories using absolute imports without modifying the sys.path?
Comment: The "relative imports" that are not supported by Python 3 are the implicit ones: https://docs.python.org/2/tutorial/modules.html#intra-package-references


Use of ANCOVA With two group Pre/Post and an Ordinal DV

Question: Say I have a two group pre test / post test design.
The IV is attendance or non attendance at an educational course.
The DV is ordinal from 0 - 5 / Strongly Agree - Strongly Disagree
I have been reading about the benefits of ANCOVA - would it's use be appropriate here and if not, what would be?
Answer: An ANCOVA is simply a multiple regression with no interaction term between the IV and the covariate. You can perform a proportional odds regression given your ordinal outcome.
The ANCOVA is useful if there is balance on the pre-test across both groups and/or you have random assignment to both groups. See Knapp & Schafer (2009) for further discussion of this. Also, Miller and Chapman (2001) provide a very good discussion of ANCOVA.
Knapp, T. R., & Schafer, W. D. (2009). From Gain Score t to ANCOVA F (and vice versa). Practical Assessment, Research & Evaluation, 14(6). Retrieved from pareonline.net/getvn.asp?v=14&n=6
Miller, G. A., & Chapman, J. P. (2001). Misunderstanding analysis of covariance. Journal of Abnormal Psychology, 110(1), 40–48. https://doi.org/10.1037/0021-843X.110.1.40


Give conditions on a,b,c, and d such that A has two, one, and no eigenvalues?

Question: I am given that matrix
$$A=
        \begin{bmatrix}
        a & b \\
        c & d  \\
        \end{bmatrix}
$$
and I need to find conditions on a,b,c, and d such that A has

Two distinct real eigenvalues
One real eigenvalue
No real eigenvalue

I was trying to think this through and all I can figure out is that would it have two distinct eigenvalues if det(A-$\lambda$I)=0?
Comment: **Hint:** For a $2 \times 2$ matrix, $\det(A - \lambda I) = \lambda^2 - (\operatorname{tr}A)\lambda + (\det A)$.  How do you make a quadratic polynomial have two, one, or zero real roots?
Comment: Hint: use the discriminant of the characteristic polynomial.
Comment: Are $a,b,c,d$ real or can they be complex?
Comment: @copper.hat It does not specify
Comment: Compute the polynomial $x \mapsto \det(xI-A)$ and solve for the roots (which are the eigenvalues). Then you have a bit of work to determine conditions so 1-3 above are satisfied.
Comment: I've actually done all that for another problem. So, I have all that. I was suppose to prove the det(a-$\lambda$I)= $\lambda^2$-(tr(a))$\lambda$ + detA and I've solved the quadratic equation for $\lambda$... I sadly still don't know where to go from here
Comment: Well, it is a little cumbersome if $a-d$ are allowed to be complex. You might start with real values, that is fairly straightforward.
Comment: Okay so could I say i have no solutions if 1/2(a+d) = $sqrt{(a-d)^2 - 4bc}$ and 1/2(a+d) = -$sqrt{(a-d)^2 - 4bc}$
Answer: $$det(A-\lambda I)=0$$
$$(a-\lambda)(d-\lambda)-bc=0$$
$$ad-a\lambda-d\lambda +\lambda² -bc=0  $$
$$\lambda² -(a+d)\lambda+(ad-bc)=0  $$
Making analysis under discriminant and you will see...
$(a+d)²-4(ad-bc)>0$ it is $\Delta >0 <=>$ $2$ real eigenvalues
$(a+d)²-4(ad-bc)=0$ it is $\Delta =0 <=>$ $1$ real eigenvalues
$(a+d)²-4(ad-bc)<0$ it is $\Delta <0 <=>$ $0$ real eigenvalues
Well, all this is because $R$ is incomplete field, in case you have Complex matrices you lost the characteristic of order set, but you have that all polynomials have that same number of roots that their's  degree, then you have one(multiplicity 2) or two eigenvalues.
Comment: Yeah but you do not prove the converse (<=). But you can change your => to <=>! BTW, `\Longrightarrow` yields $\Longrightarrow$ and `\Longleftrightarrow` yields $\Longleftrightarrow$.
Answer: So it seems you did compute the characteristic polynomial $X^2-(a+d)X+ad-bc$ and its discriminant, though it seems you used an incorrect formula for the latter. The correctly computed discriminant is $(a+d)^2-4(ad-bc)=a^2+d^2-2ad+bc$ which is also $(a-d)^2+4bc$. Supposing the entries $a,b,c,d$ are themselves real, you will be in cases 1, 2, 3 according as this discriminant is positive, zero, or negative. (In case of complex entries $a,b,c,d$, it is unlikely there are any real eigenvalues at all, but the precise conditions become rather complicated to state; notably "one real eigenvalue" could either be a double root, or be paired with another non-real complex root.)


MariaDB trigger with IF-statement doesn't work and returns no errors

Question: I wrote a rather simple trigger in MariaBD 10.11.2, but it doesn't produce any output, not even an error.
CREATE TRIGGER Automatic_Employee
BEFORE INSERT
ON Test_Results
FOR EACH ROW
BEGIN
  IF (CURRENT_USER() = 'FOO') THEN
    SET NEW.Employee_ID = 0;
  END IF;
END

This is the code in question. I have similar triggers for this table, where part of the results is entered automatically. I am logged in as FOO and the field remains [NULL] instead of 0 after I enter my input. Everything else works.
Any ideas why? Thanks in advance.
Answer: Your code should give you an error about unknown Employee_ID.
To set the value for a column in inserted rows, you use notation new.column.
Your code should look like this:
CREATE TRIGGER Automatic_Employee
BEFORE INSERT
ON Test_Results
FOR EACH ROW
BEGIN
  IF (USER() = 'FOO@localhost') THEN
    SET new.Employee_ID = 0;
  END IF;
END

The CURRENT_USER() function returns the CREATOR in stored routines and in triggers. The USER() function returns the username and the host name for the user running the query.
Comment: I had a look at it again, and you were completely right. Thank you, Sir! =)


Parse error: syntax error, unexpected '$pasta' (T_VARIABLE) in

Question: Pessoal eu estou tendo esse erro, li que essa mensagem aparece quando ocorre um erro em uma linha anterior do código, o que e estranho pra  mim é que está acontecendo na primeira linha do arquivo.
Parse error: syntax error, unexpected '$pasta' (T_VARIABLE) in
<?php
 $pasta = $_SERVER["DOCUMENT_ROOT"]."/arquivos/";

 if(is_dir($pasta))
 {
  $diretorio = dir($pasta);

  while($arquivo = $diretorio->read())
  {
   if(($arquivo != '.') && ($arquivo != '..'))
   {
    unlink($pasta.$arquivo);
    echo 'Arquivo '.$arquivo.' foi apagado com sucesso.
';
   }
  }

  $diretorio->close();
 }
 else
 {
  echo 'A pasta não existe.';
 }
?>

Comment: Como você executou este arquivo?
Comment: Rapaz, copiei seu codigo daqui e apresentou o mesmo erro, porém quando reescrevi, exatamente igual, funcionou
Comment: pois é, é exatamente o que o outro companheiro falou.
Answer: Os seus espaços não são espaços e nem tabs, o que esta dentro disto a seguir (do quadro cinza abaixo):

Veja:

O valor ASCII de espaço (" ") é 32
O valor ASCII de tab ("\t") é 9
Já o valor ASCII desse caractere que você usou como espaço é 8195

Ou seja, apesar de parecer espaço ele não é.
É outro caractere, mas não é nem espaço e nem tabulação, com certeza você esta usando um editor de texto que não serve para escrever códigos, provavelmente esta usando Microsoft Word ou WordPad ou o TextEdit do Mac OSX em modo "documento avançado"
Assim o PHP não vai funcionar e nenhum outro tipo script provavelmente, então recomendo que reescreva manualmente o seu código usando um editor de texto apropriado, como um destes:

SublimeText: https://www.sublimetext.com
Notepad++: https://notepad-plus-plus.org
https://code.visualstudio.com
Comment: não sabia que isso ocorria usando editores não específico para códigos, já me deparei com problemas assim em que o código, após reescrito em um editor, funcionava, obrigado pela informação.
Comment: @WeesSmith editores chamados richtext usam esquemas proprios, tipo MSWord, Wordpad, etc. Isso porque eles não são só texto, são codificações proprias
Comment: Entendi, aqui mesmo no Stack já vi problemas similares ao dele, agr sei um motivo possivel.
Comment: cara eu vou reescrever, faz sentido o que falou mas o estranho é que eu ele esta no sublime eu não sei porque de ter acontecido mas vou reescrever manualmente
Comment: Muito obrigado pela resposta.
Comment: por nada caro @MarcosGoulartdeOliveira essa sua duvida é muito interessante para a comunidade, fazia tempo que queria falar deste tipo de problema. Assim que reescrever com um dos programas que citei por favor comenta aqui se funcionou, eu ficaria muito grato com o seu feedback ;)
Comment: Opa, desculpa a demora pra responder sou novo programando e como usuário no stack, antes eu só entrava pra ver respostas nunca tinha respondido ou perguntado antes. Mas funcionou sim. Mas não foi exatamente como tu falou eu estava usando o sublime mas eu copiei grande parte do código de um site quando eu reescrevi ele funcionou mas desde o começo estava no sublime,
Comment: @MarcosGoulartdeOliveira provavelmente o autor do tal site formatou a postagem pelo word ou outro programa assim e na hora de copiar pro site dele ficou com este aparentes espaços, ai por isto você acabou pagando o preço hehehe, então a documentação do https://php.net tem muitos exemplos prontos, convém copiar de lá, exemplo: http://php.net/manual/pt_BR/function.dir.php e modificar a sua necessidade :)
Answer: Simplesmente reescrevi o código e funcionou:
if(is_dir($pasta)){
    $diretorio = dir($pasta);
    while($arquivo=$diretorio->read()){
        if(($arquivo!='.')&&($arquivo!='..')){
            unlink($pasta.$arquivo);
            echo "Arquivo $arquivo foi apagado com sucesso.
";
        }
    }
    $diretorio->close();
}else{
    echo "A pasta não existe";
}

Acredito que seja exatamente o que o @GuilhermeNascimento disse agora na resposta dele.


Do all periodic sound waves have harmonics?

Question: I 've read that all periodic sound waves have a fundamental frequency and I was wondering if all periodic sound waves also have harmonics (integer multiples of a fundamental frequency). If that question rings true then how come its like that and how can I apply this information in composing a song?
I am aware that a simple sine wave doesn't have harmonics but I was thinking more in the "real world" not computer simulations.
Comment: Note that all periodic ocean waves, light waves, and all periodic waves in general also have fundamental frequencies. It's not just sound waves. I can't think of a way to use this information in composing, and none of the answers so far address that, probably for the same reason. Understanding acoustics can help in orchestration and arrangements of ensembles, so that's sort of related.
Answer:
I 've read that all periodic sound waves have a fundamental frequency

That's true - if a wave is periodic, it has a fundamental frequency.
(Oddly, just because a wave has a fundamental frequency, it doesn't necessarily mean that there's any energy at that frequency though - it may be that all the energy is in the harmonics!)

I was wondering if all periodic sound waves also have harmonics. (I am aware that a simple sine wave doesn't have harmonics but I was thinking more in the "real world", not computer simulations.)

Yes, all periodic waves except (as you say) sinusoidal waves have harmonics. This is a result of the Fourier theorem, which states that any PERIODIC function f(x) may be expressed as the sum of a series of sinusoidal functions (possibly with different amplitudes and phase offsets).
While that might sound a bit abstract, it's an excellent way to analyse sound, as it's exactly what our ear does - pick out energy at different frequencies.
If you're interested in "real-world" rather than computer-generated scenarios, it's worth noting that few sounds - certainly no acoustic instrument sounds - are exactly periodic - they change over time. Having said that, even when a sound is only roughly periodic, It's still a valid idea to think of it as consisting of a set of harmonics that themselves change in amplitude (and even frequency) over time.
There may also be other partials in a sound that aren't close to being integer multiples of the fundamental - these are often called 'inharmonic partials'.
Some energy in a sound often isn't easily modelled as a 'partial' of a steady frequency at all - this energy is often just called 'noise'.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/75319/discussion-on-answer-by-topo-morto-do-all-periodic-sound-waves-have-harmonics).
Answer: Talking about periodic signals does not require any knowledge of sines / Fourier analysis, nor reference to any physical systems. The no-nonense definition is just this:

A periodic signal with period  is a function  : ℝ → ℝ such that  : ℝ+ is the unique smallest positive number for which
                 ( + ) = ()    ∀ ∈ℝ (there is no  <  that would also always give ( + ) = ()).

(We need the restriction forbidding  <  because else any signal with period  would also qualify as periodic with period 2· or 3· and so on.)
That readily allows us to also define the fundamental frequency as simply the reciprocal: f = 1⁄.
As I promised, this does not yet make any reference whatsoever to sinusoidal components – in fact, it also applies to functions that cannot be represented by a Fourier series, such as
       ⎧ 0                  if  is integral
() := ⎨
       ⎩ sin (1⁄1−cos(2·π·))   else

In this signal, you have in essence locally (close to 0, 1, 2 etc.) the ripple-frequency go up arbitrarily high, without decreasing its amplitude). This can't be constructed as just a superposition of constant-frequency sine parts. Thus it's also not really possible to talk of harmonics.
Now, such a "signal" fortunately can never actually turn up in the physical world – you'd basically have an ultraviolet catastrophe at each of the points where the frequency goes infinite. Actual physical signals, if they are periodic, can be decomposed into a superposition of sinusoidals, with the slowest-oscillating sharing the fundamental frequency of the signal. (That includes, of course, the audio example above, which is effectively bandlimited through Nyquist-sampling. Mind, this is for this signal not possible without hefty aliasing artifacts.)
And then, the answer to your question is yes, as topo morto explained: if a signal has no harmonics, then by definition of "harmonic", the signal is actually just a single sinusoidal.
Comment: @Dave: Such a series would (almost everywhere) fail to converge -- even at points where the original function looks (and is!) nice and smooth.
Comment: Maybe I'm mathematically naive, but what is the problem with a Fourier series where a_n goest to infty for large n?
Answer: According to http://hyperphysics.phy-astr.gsu.edu/hbase/Waves/funhar.html:

The lowest resonant frequency of a vibrating object is called its fundamental frequency. [Emphasis added.]

And according to http://hep.physics.indiana.edu/~rickv/Standing_Waves_on_String.html:

The lowest standing wave frequency is called the fundamental or first harmonic.

So to your question, "[Do] all periodic sound waves also have harmonics (integer multiples of a fundamental frequency)" the answer is no. These two citations show that, in physics, harmonics refer somewhat narrowly to natural/resonant modes of vibration. But many sounds we hear are not the result of resonance--they are instead generated through forced vibration, which is a different category from natural/resonant vibration.
The passage below (about bees' wingbeat frequency) does a good job of illustrating the difference. It's comparing the fundamental frequency of a bee's wings with the actual frequency at which bees vibrate their wings:

In support of the stiff element hypothesis, the first fundamental frequency (602±145 Hz) was substantially higher than the wingbeat frequency of our individual bees (234±13.9 Hz; paired t-test, P=9.2×10−8, n=6; Fig. 3).

http://jeb.biologists.org/content/220/15/2697
Just because bees can beat their wings at a periodic frequency (which produces a sound that we hear) does not mean that the wingbeat frequency automatically qualifies as a fundamental frequency or as a harmonic. Only those special resonant modes qualify as harmonics.

I've read that all periodic sound waves have a fundamental frequency

As you'll appreciate now, this is also false. There's an important difference between forced vibration/oscillation and natural vibration/oscillation. According to the definitions above, the fundamental frequency only refers to the lowest resonant vibrational mode.
Note about Terminology
The term "harmonic" can describe:
 - component frequencies of a complex waveform (detached from any physical origin), and
 - vibrational modes of an oscillating physical system (which is the source of sound waves)
If we were to see a wave oscillating like this picture shows and asked "what are we hearing?" I would reply "the third harmonic frequency [of the string's vibration]." I agree that, if we let the string vibrate this way, then the waveform of the resulting sound wouldn't have a third harmonic. But despite this, I still think we should say that we are hearing the third harmonic frequency [of the oscillating system]. If we are attaching the sound wave itself to its physical origins--the real-world oscillating system--and ignoring computer-generated noises (and this is what I see the OP asking), then we should speak in terms of the oscillatory frequencies that produce the sounds. For these oscillatory frequencies, the term harmonic refers more narrowly to resonant frequencies.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/75320/discussion-on-answer-by-jdjazz-do-all-periodic-sound-waves-have-harmonics).
Answer: The more mathematical way to state it is: if a signal is periodic with period 'T' then it's power spectrum can have non-zero values only at frequencies of '1/T, 2/T, 3/T...'.   that is, integer multiples of the fundamental frequency 'f0=1/T'.


Plain Unstrucutred HTML Content Types, How to Pull image from them in Views

Question: This is a plain unstructured node with no CCK structure or anything like that (the site includes thousands of posts so it is impossible to retroactively go back and re-insert the images in using CCK).
How can I pull the first image in the node out and use that image within a view as a thumbnail image? (It's a related posts view)
I'm not 100% sure how to create a view theme, the drupal documentation on it is really confusing and I can't find a good tutorial on how to create a custom view theme either.  So since I think that is the best solution if you know how to do that, could you point me to a tutorial or something that actually teaches you how to create your own themed view (one that makes sense).
Thanks for any tips or advice.
Answer: you will need to only create one view theme. That will be a theme for the BODY field of your node. It's actually super simple.

create a PHP file in your theme folder called views-view-field--YOURVIEWNAME--body.tpl.php
your file has one variable you need to worry about, $output and that's the HTML. Write your PHP code to isolate the very first image tag and then this site has a nice example of how to do that

I think the code in this file would end up looking like this
<code>  $first_img = '';
  $numMatches = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $output, $matches);
  if($numMatches){
    $first_img = $matches [1] [0];
  }else{ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  echo '<img src="' . $first_img . '" alt="thumbnail" class="thumb"/>';
</code>

add some CSS to make the thumbnail, or alternatively you can use theme with imagecache I think.
refresh your template cache

You're done!


Why doesn't re.sub work in this python2 case?

Question: import re
text = "PO 00000  Frm 00001  Fmt 0624  Sfmt 0634  E:\CR\FM\A07JN6.000  S07JNPT1"
text = re.sub(text, " ", text)

print(text)

I'm on Python 2.7.15. The output is PO 00000  Frm 00001  Fmt 0624  Sfmt 0634  E:\CR\FM\A07JN6.000  S07JNPT1. Why doesn't the output become " "?
Comment: Because the string is not a valid pattern for itself. Why are you using regex for this?
Comment: I get the same result if I seek a partial version of the string. `text = re.sub(text[0:65], " ", text)`. It is part of a larger function that requires regex.
Comment: You can escape them using re.escape ... to look for eactly that _text_
Comment: The first 65 characters also includes the bad escapes. Try using `re.escape`. Note this would be an error in more recent versions of Python.
Answer: Looks like you need re.escape
Ex:
import re
text = "PO 00000  Frm 00001  Fmt 0624  Sfmt 0634  E:\CR\FM\A07JN6.000  S07JNPT1"
text = re.sub(re.escape(text), " ", text)

print(text)

Note: You can also use str.replace for this case.


Stepwise model selection by AIC

Question: I am learning about performing stepwise model selection by AIC and having some questions:

What is the regularization parameter for step-AIC?
In what way is forward step-AIC an evolution of univariate screening?
What is the potential problem regarding the computational burden?
Answer: Preamble: Avoid doing stepwise model selection via AIC if there are plan to use the model for anything else other than prediction. Please see this thread for more details: Algorithms for automatic model selection. To your side questions:

The "regularisation parameter" is number of parameters in the model.
It really isn't an evolution; more like a slightly more principled version of it. It is a bit unclear what you mean by "computational burden" but realistically, the actual computational burden is not huge, especially within the context of GLMs where we can warm-start our IRWLS.

Again, avoid using stepwise regression unless there is an extremely good reason (e.g. expensive to collect new data for multiple variables, very constrained memory spaces, etc.) and there are not intention to interpret the model causality/statistically/whatever. CV.SE has some excellent threads on the matter, see for starters: A more definitive discussion of variable selection, Choosing variables to include in a multiple linear regression model and Stepwise AIC - Does there exist controversy surrounding this topic?.

Stepwise model selection by AIC


Programmatically disable content translation options in content edit form

Question: I want to programmatically disable the content translation options located at the bottom of the content edit form (see yellow area in screenshot):

I know that i can disable the revision information options with the following code in a form_alter hook:
$form['revision_information']['#access'] = false; // <--- works

But that doesn't work with the translation options, at least with what I tried:
$form['content_translation']['#access'] = false; // <--- doesn't work

So ideally, how can i disable the whole yellow area?
Answer: You can not access to content_translation property in the hook_form_alter but you can do it in after_build callback.

after_build: runs after the form or element is built for display.

Try with the following:

Add #after_build to the form:

/**
 *Implements hook_form_alter().
 */
function myModule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_YouContentType_edit_form') {
    $form['#after_build'][] = 'myModule_after_build';
  }
}

Implement your after_build function

    function myModule_after_build($form, &$form_state){
      $form['content_translation']['#access'] = FALSE;
      return $form;
    }

Comment: i'm glad that help! :)


reload page on right click, but no context menu

Question: There is a webapp where I want to reload the page on right click and along with that behavior I don't want the context menu to be showed.
Answer: You are looking for something like this:
 function click(e) {
  if (navigator.appName == 'Netscape' && e.which == 3) {
   window.location.reload();
   return false;
  } else {
   if (navigator.appName == 'Microsoft Internet Explorer' && event.button==2)
    window.location.reload();
    return false;
   }
   return true;
  }
 document.onmousedown=click;
 document.oncontextmenu=new Function("window.location.reload();return false;"); // line added

Besides reload you may use:
 history.go(0);
 window.location.href=window.location.href;

Comment: The page is reloading but what about the context menu? I don't want that. One more thing, I have a textarea field on the page and I'm not allowed to write something (but I can do in IE).
Comment: This traps the context menu prior to launching and reloads the page. as far as the textarea. I could not tell you without seeing code or a test page.
Comment: See http://synaptik.co.cc/james I am using Google Chrome and the context menu is still there.
Comment: The following line needs to be added to the bottom of the script. It will also disable the right click in the text area as well. document.oncontextmenu=new Function("window.location.reload();return false;");
Answer: The shortest way would probably be to intercept the right-click event in the body tag, like so:

        Testing 1 2 3 ...

"return false" prevents the default contextmenu from popping up.
Writing your own event handler function will give you more control, though.
Answer:
No context.

window.onload = function(){
    document.getElementById('nocontext').oncontextmenu = function(){
        history.go(0);
        return false;
    }
}

Note: I copied what Jared Farrish posted on his jsfiddle and what James mentioned about using history.go(0); I tested above script in Explorer 9, Firefox and Safari.


Need to transfer all charts from Excel in PPT

Question: I have a script which transfer all my charts to PPT perfectly but the issue is all chart paste in different slides. I have small charts that mean in a single slide can be store 4 charts. Is there any kind of script which arrange the charts as well in PPT slide and paste at least 4 charts in single slide of PPT.
Currently I'm using the below code
Sub Chart_TRF()
Dim PApp As PowerPoint.Application
Dim PPres As PowerPoint.Presentation
Dim PSlide As PowerPoint.Slide
Dim slide_index As Integer

Dim Chrt As ChartObject

Set PApp = New PowerPoint.Application

PApp.Visible = True

Set PPres = PApp.Presentations.Add
slide_index = 1
For Each Chrt In ActiveSheet.ChartObjects
Chrt.Copy
Set PSlide = PPres.Slides.Add(slide_index, ppLayoutBlank)
PSlide.Shapes.Paste
slide_index = slide_index + 1
Next Chrt

MsgBox ("PPT is created for all Charts")

End Sub

Please let me know if you have any query on this.
Thanks
Answer: I have amended your code so that each slide will contain 4 charts.  You can change the starting left and top positions, along with the gap between charts, as desired.
Sub Chart_TRF()

    Const START_LEFT_POS As Long = 20 'change the starting left position as desired
    Const START_TOP_POS As Long = 20 'change the starting top position as desired
    Const GAP As Long = 30 'change the gap between charts as desired

    Dim PApp As PowerPoint.Application
    Dim PPres As PowerPoint.Presentation
    Dim PSlide As PowerPoint.Slide
    Dim PShape As PowerPoint.Shape
    Dim slide_index As Integer
    Dim chart_index As Integer
    Dim left_pos As Integer
    Dim top_pos As Integer

    Dim Chrt As ChartObject

    Set PApp = New PowerPoint.Application

    PApp.Visible = True

    Set PPres = PApp.Presentations.Add

    slide_index = 0
    chart_index = 0
    left_pos = START_LEFT_POS
    top_pos = START_TOP_POS
    For Each Chrt In ActiveSheet.ChartObjects
        chart_index = chart_index + 1
        If chart_index Mod 4 = 1 Then
            slide_index = slide_index + 1
            Set PSlide = PPres.Slides.Add(slide_index, ppLayoutBlank)
            top_pos = START_TOP_POS
        End If
        Chrt.Copy
        Set PShape = PSlide.Shapes.Paste(1)
        If chart_index Mod 2 = 1 Then
            With PShape
                .Left = left_pos
                .Top = top_pos
                left_pos = left_pos + .Width + GAP
            End With
        Else
            With PShape
                .Left = left_pos
                .Top = top_pos
                left_pos = START_LEFT_POS
                top_pos = top_pos + .Height + GAP
            End With
        End If
    Next Chrt

    MsgBox ("PPT is created for all Charts")

End Sub

EDIT
Here's the code that will copy the charts from all worksheets in the active workbook.
Sub Chart_TRF()

    Const START_LEFT_POS As Long = 20 'change the starting left position as desired
    Const START_TOP_POS As Long = 20 'change the starting top position as desired
    Const GAP As Long = 30 'change the gap between charts as desired

    Dim PApp As PowerPoint.Application
    Dim PPres As PowerPoint.Presentation
    Dim PSlide As PowerPoint.Slide
    Dim PShape As PowerPoint.Shape
    Dim slide_index As Integer
    Dim chart_index As Integer
    Dim left_pos As Integer
    Dim top_pos As Integer

    Dim Chrt As ChartObject
    Dim ws As Worksheet

    Set PApp = New PowerPoint.Application

    PApp.Visible = True

    Set PPres = PApp.Presentations.Add

    slide_index = 0
    chart_index = 0
    left_pos = START_LEFT_POS
    top_pos = START_TOP_POS
    For Each ws In ActiveWorkbook.Worksheets
        For Each Chrt In ws.ChartObjects
            chart_index = chart_index + 1
            If chart_index Mod 4 = 1 Then
                slide_index = slide_index + 1
                Set PSlide = PPres.Slides.Add(slide_index, ppLayoutBlank)
                top_pos = START_TOP_POS
            End If
            Chrt.Copy
            Set PShape = PSlide.Shapes.Paste(1)
            If chart_index Mod 2 = 1 Then
                With PShape
                    .Left = left_pos
                    .Top = top_pos
                    left_pos = left_pos + .Width + GAP
                End With
            Else
                With PShape
                    .Left = left_pos
                    .Top = top_pos
                    left_pos = START_LEFT_POS
                    top_pos = top_pos + .Height + GAP
                End With
            End If
        Next Chrt
    Next ws

    MsgBox ("PPT is created for all Charts")

End Sub

Comment: Thanks a lot @Domenic. This code is working absolutely fine.
Comment: That's great, thanks for the feedback, cheers!
Comment: Hi Domenic,

Using this code i can extact PPT from the active sheet is there any option which extract all the ppt from all sheets in workbooks.
Comment: I have edited my post and added the code to copy charts from all worksheets in the active workbook.


Let $f \in Map(\mathbb{Z})$ be given by $f(n) = n+1$ for every $n \in \mathbb{Z}$. Find all elements in $Map(\mathbb{Z})$ that commute with $f$.

Question: Let $f \in Map(\mathbb{Z})$ be given by $f(n) = n+1$ for every $n \in \mathbb{Z}$. Find all elements in $Map(\mathbb{Z})$ that commute with $f$.
I understood that I need to show $f^m$ $\forall m \in \mathbb{Z}$ commute with $f$. For the positive integer $m$ it is easy but what can I do for negative integers? It would mean to find the inverse I guess. Also how do I show that any other element of $Map(\mathbb{Z})$ doesn't commute with $f$?
Please some help..!!
Edit : I think for the negative index $m \in \mathbb{Z}$, $f^{-m}(n) = n -m$, it can also be shown easily that for all integer $m$, $f$ commutes with $f^m$.
Comment: Well, say $g$ commutes with $f$.  Deduce that $g(n+1)=g(n)+1$ for all $n$.  Now let $g(0)=m$.  Show, inductively, that $g(n)=n+m$ for all $n$
Comment: What is Map$(\mathbb Z)$?
Comment: Yes.  My method, if you can push it through, will show that "$g$ commutes with $f$ if and only if $g(n)=n+g(0)$ for all $n$".  Note, for instance, that $g(n+1)=g(n)+1\implies g(1)=g(0)+1$. Now show that $g(2)=g(0)+2$.  Now use induction to show that $g(n)=n+g(0)$ for natural numbers $n$.  Now do the same for the negative integers.
Comment: It's not also mentioned clearly but I think it means the collection of all functions on $\mathbb{Z}$.
Comment: Pick $g \colon \mathbb{Z}\to \mathbb{Z}$ and suppose that $g\circ f = f \circ g$. Then for $n$ integer, we have $g \circ f^n =f^n \circ g$. Evaluate this last functional equality at $0$ . Edit: I'm late, this is exactly what @lulu is suggesting.
Comment: @lulu I understand
Answer: Let $g$ commute with $f$, then $g(f(n))=f(g(n))$, which implies $g(n+1)=g(n)+1$, so we only need to know one value of $g$ to determine the function. If $g(0)=m$ then $g(n)=m+n$ and so the set of functions commuting with $f$ is:
$$\lbrace g\in Map(\mathbb{Z})\mid g(n)=n+m \forall n\in\mathbb{Z} \text{ for some } m\in\mathbb{Z}\rbrace$$
Comment: So $g=f^m$?....


Is this proof correct? (chernoff bound)

Question: In Stanford cs 265 lecture5.
Following is the proof of the first statement of corollary6.

Where $X=X_1+\dots+X_n$, $X_i$ are independent 0/1 random variables.

Theorem 2

We can see that the proof apply theorem 2 to $Z$.
My question:
I think $Z$ is not the sum of $0/1$ random variables So we can't apply Theorem2 to $Z$,  because $Z$ can be $2n$. So is this proof wrong?
Comment: The corollary is false in general since it would suggest that all random variables $X$ with a finite mean have $P[X>t]$ that decays exponentially with $t$. There must be some additional (hidden) assumptions on $X$ that would give meaning to this corollary.
Comment: @Michael X is the sum of independent 0/1 variables. Thanks for your remind, I have edited my question
Answer: Oh, after dicussing with my classmate, I found that $Z$ equals the sum of $2n$ 0/1 random variables, so we can apply theorem2 to $Z$.

Is this proof correct? (chernoff bound)


Characterization for invariant subspace

Question: I have the following problem consisting of 3 parts of which I'm not being able to figure out the last.
Notation: $T^*$ is the adjoint operator of $T$. $Im(T) = \{T(v) : v \in V\}$. $Ker(T) = \{v \in V : T(v) = \vec{0} \}$
Let $V$ be a finite vector space with inner product over $\mathbb{R}$, let $S$ be a subspace of $V$ and $T: V \to V$ a linear operator.

Prove that $S$ is $T-invariant \iff S^{\bot}$ is $T^*-invariant$.

Suppose $dim(S) = 1$. Prove that $S$ is $T-invariant \iff \exists \lambda_0$ eigenvalue of $T$ such that $S \subset Ker(T - \lambda_0 I)$.

Now suppose that $dim(S) = 2$ and $dim(V) = 3$. Prove that $S$ is $T-invariant \iff \exists \lambda_0$ eigenvalue of T such that $Im(T - \lambda_0 I) \subset S$.

I thought about using the fact that $Im(T)\ \bot\ Ker(T^*)$ and part 2 but I haven't been able to make it work right.
Comment: the cursive can be done using ```\textit{}``` or ```\emph{}``` in any online LaTeX editor. Making them inside ```$  $``` doesn't seem right and in MSE, we use MathJax. You can make the cursive using ```_   _``` the bold one can be made using ```**    **```. In any LaTeX editor, the bold can be done using ```\textbf{}```. You can visit TeX SE for more info. I hope it'll help :)
Comment: I don't get why you call those corrections "LaTeX errors". In my course's notes it's all in the way I did it in the first place.
Comment: The so-called '$\text{LaTeX}$ errors ' are called errors(My apologies) cause I just fixed ```dim``` to ```\dim``` and ```Ker``` to ```\ker``` and ```Im``` to ```\text{im}```. The cause was, these are the standard LaTeX codes for the symbols. Again, I'm sorry if it hurt you. -Regards, Ralph
Comment: No hurt feelings. My question was basically if these were actually standards. Again, my textbook writes it exactly the way I did, so I naturally assumed this was a correct way of doing it. Furthermore, I'm very used to reading things like $T-invariant$ in cursive instead of plain text as to emphasize that it's a specific defined term.
Answer: You already have a lot of the crucial ideas laid out! The relation between part 3 and part 2 is seems to be that you are exchanging everything with a dual-ish concept, so to speak: we're looking at images instead kernels, and rather than $S$ being one-dimensional, the orthogonal complement $S^\bot$ is one-dimensional. So, somehow once we know part 2, part 3 should not be too far away.
So, assume the conditions of part 3 and that $S$ is $T$-invariant. By part 1, this means $S^\bot$ is $T^*$-invariant. But since $\dim(S^\bot) = \dim V - \dim S = 1$, we can apply part 2 to $T^*$ and $S^\bot$, and we find that this is equivalent to there being an eigenvalue $\lambda$ of $T^*$ so that $S^\bot \subset \ker (T^* - \lambda I)$. But if you know the relation
$$ W \subset U \implies U^\bot \subset W^\bot,$$
then we can deduce $\ker(T^* - \lambda I)^\bot \subset (S^\bot)^\bot = S.$ And you've already indicated that you know that $\text{im}(T - \lambda I) \bot \ker((T - \lambda I)^*)$. Hence
$$ \text{im}(T - \lambda I) \subset \ker((T - \lambda I)^*)
= \ker(T^* - \lambda I) \subset S.$$
This proves the one direction, and the other direction goes similarly by working backwards if you know that $\ker(T)$ and $\text{im}(T^*)$ are not only orthogonal, but that they are indeed even orthogonal complements of one another, i.e. applying $\bot$ to one gives you the other.
All of these relations I am using are fairly elementary properties of orthogonal complements in finite dimensions, so I'm kinda hoping you already know about them, but if that's not the case, it might be a good exercise to try and prove them yourself! Hope that helps, let me know if something is still unclear!
EDIT: I indeed left out an argument why, in the above, $\lambda$ is an eigenvalue of $T$, we only know it is an eigenvalue of $T^*$. This part can be tricky if you approach it from the wrong angle; an eigenvector of $T^*$ will in general not be an eigenvector of $T$, so there is no way to directly compare things. However, there is still hope for an elementary proof.
We know that $\text{im}(T - \lambda I) \subset S$. But that means $T - \lambda I$ can be understood as a map from the 3-dimensional space $V$ into the 2-dimensional space $S$. Hence, simply by the rank-nullity theorem, it must have a nontrivial kernel, so there is a $v \in V$ with $Tv  - \lambda v = 0$. But that must be exactly your eigenvector!
Comment: I did get all of this on my own, and tried to put it in a comment but it was too big. The problem is that you only showed that there exists an eigenvalue of $T^*$ that satisfies that, and the problem asks for an eigenvalue of $T$. I haven't been able to prove that this is also an eigenvalue of $T$, and until you do that this solution is wrong.
Comment: Ah, it may have been worthwhile to mention that this was the part you're struggling with. Even if you can't put it in a comment, it might have been good to edit your original post. That way I wouldn't have spent so much time on proving something you already know :) But okay, I added an elementary proof for why $\lambda$ is an eigenvalue of $T$, and from the right angle, it's not all that bad.
Comment: Definitely should've edited my original post. I didn't think of that, I'm still new here. Thanks!
Answer: Given that I had already done what Lukas wrote, but a little clearer in my opinion, I'm going to lay it out. Still, this is not a valid proof because it lacks one last step which I will explain further below.
First, let's find a more useful way of writing the right-hand side of the equivalence:
$$Im(T - \lambda_0 I) = Ker((T - \lambda_0 I)^*)^{\bot} = Ker(T^* - \lambda_0 I)^{\bot}$$
Also,
$$Ker(T^* - \lambda_0 I)^{\bot} \subset S \iff S^{\bot} \subset Ker(T^* - \lambda_0 I)$$
By part 1. we have that
$$S \text{ is } T-invariant \iff S^{\bot} \text{ is } T^* - invariant$$
$$\text{Since } dim(V) = 3 \text{ and } dim(S) = 2 \implies dim(S^{\bot}) = 1$$
so by part 2. we have
$$S^{\bot} \text{ is } T^* - invariant \iff \exists \lambda_0 \text{ eigenvalue of } T^* \text{ such that } S^{\bot} \subset Ker(T^* - \lambda_0 I)$$
The problem with this as I said in a comment above is that here $\lambda_0$ is a value of $T^*$, and I need to prove that there exists an eigenvalue of $T$ that satisfies the property.
I can't use that the eigenvalues of $T$ are the conjugates of the eigenvalues of $T^*$ without giving a proof of it because such theorem is not in the course's notes where this problem came from. I did see some proofs of it (e.g. Do T and T* have the same eigenvalues with the same algebraic multiplicity?) but both proofs use theorems that are not in the book either (i.e. Schur decomposition and $\overline{det(A)} = det(A^*)$) so I can't imagine that they would expect you to prove either of these for a problem that should come almost inmediately from the previous parts.
In conclusion, I'm looking for a different way to prove that this $\lambda_0$ that appears at the end of the proof is also an eigenvalue of $T$.

Characterization for invariant subspace


concerning irregular tuplets

Question: An n-tuplet is a division of a given pulse in n even parts; hence, a quintuplet is playing 5 notes in the space of one, usually a quarter note, as a 13-tuplet is dividing a note in 13 even parts.
What I don't get, is that I have seen some tuplets put as 2/5 or 3/5 (often when dealing with polyrythms) — that is, playing tuplets of a certain number of figures, rather than unit divisions.
Could someone explain to me this, and how to feel and play them?
Comment: After answering your question, I wonder if I misunderstood. Do you mean "3:2", meaning "play 3 in the time of 2", or do you mean "2/5" (which I haven't encountered; please include an example if possible), which presumably means "divide into five units, but only play two of them." (Or neither, in which case, please clarify the question.)
Comment: i will do, when i am at home, i saw it on a guitar book
Answer: Tuplets notated as X:Y mean
Play these X notes in the time normally allotted to Y of the same type of note.
Thus 2:5 written over an eighth-note tuplet in 4/4 time would mean "play these two eighth notes over 2.5 beats."
Similary, 3:5 written over a eighth-note tuplet in 6/8 time would mean "play these two eighth notes over 12/3 beats (or 5 beats, depending how one is counting).

concerning irregular tuplets


C# Dynamic DataGridViewCell Click Event

Question: I have one DGV to be clicked and another ones to be created in accordance with this click type and to be displayed in screen for a special job purpose. During creation process of other DGV's some cells (some row-column logic) will be clicked automaticaly with program code. Code below performs AUTO CLICK code part of this action. But I believe there must be a another method (as in Button PerformClick Event Fire) to achive this click action:
            DataGridViewCell dc;
            dc = MyDataGridView[0, 0];
            Rectangle rect = this.MyDataGridView.GetCellDisplayRectangle(0, 0, true);
            MouseButtons b = new MouseButtons();
            MouseEventArgs mev = new MouseEventArgs(b, 1, rect.X, rect.Y, 1);
            DataGridViewCellMouseEventArgs e = new DataGridViewCellMouseEventArgs(0, 0, rect.X + 2, rect.Y + 2, mev);
            MyDataGridView_CellMouseClick(dgvEntegCompany, e);

Comment: What is your question? A `DataGridView` already has a `CellMouseClick` event.
Comment: Why you want to explicitly execute the event handler ?
Comment: please think of "Button PerformClick" event when you need it dynamically, this time I need to click any required cell (col, row) of DataGridView. Code above solves my problem although  but I think there must be a SendMessage script for this...
Comment: It is unclear what you mean by… _"please think of "Button PerformClick" event when you need it dynamically,"_  ?… In addition, your comment… _"Code above solves my problem although but I think there must be a SendMessage script for this"_  ?… What "problem" does the code solve? The posted code looks unnecessary. Again what "problem" are you having and "how" is the posted code solving this problem or not solving it. I have already asked… what is your question.
Comment: thanks, I have an edit...
Comment: I mean no disrespect, however, are you intentionally dancing around a question. With each edit, we get a little more info about "what" you want to do, but still the problem is unknown and no question is asked. Please edit your statement to include a problem statement and what you have tried to solve the problem. I will refrain from any more fruitless back and forth and assume I am missing something. Good Luck.
Comment: **What I need is**: Fire Event Code for _DataGridView Cell Click At Any Column - Row_. Hope this is clear...
Comment: @biryaz Your edit is even more confusing. The answer to "Fire Event Code for DataGridView Cell Click At Any Column - Row" is a `CellClick` event, like you can see in my answer. I agree the code you provided is very confusing. At least you should comment every line to explain what are you trying to achieve. Perhaps we're missing something.
Answer: The question is not very clear. Are you just looking for a CellClick event?
EDIT: So do you need to execute the content of your CellClick? CellClick is an event, so it's triggered at the occurence of cell-click event. It can contain a call to a method, that you can also call independently, "dynamically", if you will.
    // CellClick event
    private void dgItems_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        MyMessage(e.RowIndex, e.ColumnIndex);
    }

    // A user method
    private void MyMessage(Int32 irow, Int32 icol)
    {
        System.Windows.Forms.MessageBox.Show("A cell [" + irow  + ", " + icol  + "] was clicked!");
    }

    // invoking from a button
    private void button1_Click(object sender, EventArgs e)
    {
        MyMessage(this.dgItems.SelectedCells[0].RowIndex, this.dgItems.SelectedCells[0].ColumnIndex );
    }

EDIT 2:
There's no such thing as AUTOCLICK.

If you want to execute a code inside the would-be-event, see code above
If you want to perform visual changes, such as select a cell, just do it. Note, that this action is dependant on the setting of SelectionMode, it behaves way different for Cell and FullRowSelect, for instance. It's gonna be something like this:

    this.DataGridView1.ClearSelection();
    this.DataGridView1.Rows[0].Cells[3].Selected = True;

If you're looking for a way to invoke an action (aka computer AI player), you're most likely have to study multi-threading, i.e. BackgroundWorker and create a separate thread for controlling a game/simulation/etc. Then the question would be still light-years off

Remark: You have to do much better job expressing your questions, meaning putting much more effort into composing it. You're just wasting community time this way.
Comment: I'm still not sure if I understand you correctly, but if you mean to run the same method from a `CellClick` event and a `Button`, see a simple way in my edit. Otherwise please explain more clearly, what you're trying to achieve.
Answer: I will assume that is what you mean by…

"Fire Event Code for DataGridView Cell Click At Any Column – Row"

… Is that you want to subscribe to the grids event that will fire when any cell in the grid is "clicked" on by the user.
If this is the case… then, subscribe to the grids CellClick or CellMouseClick events.
If you want to subscribe to the grids CellMouseClick event, then the code for that can be done in the designer or you can add the code in the forms constructor after the InitializeComponent(); method is called and it will look something like…
dataGridView1.CellMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_CellMouseClick);

Then you need to create the event handler method… dataGridView1_CellMouseClick. In this event you can check the DataGridViewCellMouseEventArgs object to see which cell was clicked. The object has a property for the row index and column index of the clicked-on cell. Below is an example.
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
  // This event will fire whenever a user clicks on a cell
  // we can get the row and column index of the "clicked" cell
  MessageBox.Show("Cell at Row: " + e.RowIndex + " Col: " + e.ColumnIndex + "  was clicked");
}

This event will fire each time the user clicks on a cell in the grid.
It is unclear what exactly you are trying to accomplish with the current code.
Comment: Good point, I didn't realise the OP might not know how to subscribe to an event.
Comment: @Oak_3260548 ... I am still not sure if this is what the OP is asking. Like you commented, your answer is also correct.
Comment: I am very embarressed :), Forget **the grid is "clicked" on by the user.** , instead of user, code itself will create a grid and click a cell (detected by program code). As if you play chess against computer after your move machine will decide which figure will be moved and where to be moved...
Comment: I do not know what to say about your last comment that is not counterproductive. Your comment makes it sound like the computer has a mind of its own… _"As if you play chess against computer after your move machine will decide which figure will be moved and where to be moved."_ …?  Machines are dumb and do NOT … _"decide which figure will be moved and where to be moved"_ … your code decides this.
Comment: I am sorry but I am done with this back and forth commenting that is getting absolutely nowhere. Maybe, edit your question with your last comment so others may be able to help. I am obviously out of ideas in relation to your whimsical question. Good Luck.
Comment: all the best @JohnG, thanks for so much efforts of yours...
Answer: even these two lines of code would perform the required action:
DataGridViewCellEventArgs e = new DataGridViewCellEventArgs(ColIdx, RowIdx);
MyDataGridvView_CellClick(myDGV, e);

C# Dynamic DataGridViewCell Click Event


How can I change the "connect to team server as" user in TFS 2013 server?

Question: In Team Foundation Server 2013 I cannot seem to change "connect to team server as" user.
TFS server is pointing to our Visual Studio Online https://ourtfs.visualstudio.com/defaultcollection and the the account that the TFS server is using to checkout code is also "Account Service (ourtfs)" even though there is no such account on our network!
(The current user seems to be one made up when the VSO was setup!)
How can I change it to checkout our code using a network account?
See the "Connect to Team Foundation Server as:" in the dialog below, in our case the account is "Account Service (ourtfs)".
Answer: If you are configuring a local build controller or agent to talk to VSO then this is the correct account.
Every VSO account has a "service account" that can be used for unattended access. When you connect the build service it uses your MSA/AAD credentials to retrieve this account and password from VSO and configured the build service to use it.
That's the only way it works as an MSA/AAD token only lasts for 48 hours and you don't want to be relogging in every 2 days.
http://nakedalm.com/tools/vso-service-credential-viewer/
I have an app that can retrieve the credentials if you need to use them outside of the build service.
Comment: MrHinsh has found the solution for me, thanks for your time. The issue with checking out files with the Service Account was that I was still using tf.exe from VS 2010 instead of VS2013, I've fixed up my scripts and now the checkout is working.
Comment: That explains the account but I dont see how it may fix my issue. How can I checkout items through my build if its using this "service account"?
Comment: I also see that the app requires "Team Explorer 2015" which I dont have.
Comment: Team explorer is free and available as part of Visual Studio 2015 on http://visual studio.com
Comment: Well that would be great. I got TFS Workspace errors when a checkout was attempted. I've since deleted the log file. I'll recreate it.
Comment: We're just moving to 2013 so 2015 is not an option right now.
Comment: If you email me the log I can take a look
Comment: Thanks Ive just emailed you.
Comment: Just to clarify, Ensure your scripts are using tf.exe from VS2013 and not VS2010 i.e. "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\tf.exe"


How to Import column from xlsx > Create Json Array > Update SQLite DB

Question: I need help converting the xlsx or a csv file into something that looks like the example below so that I could import it into SQLite.
Stocks_Update = [
    {'stock_ticker' : 'TSLA'},
    {'stock_ticker' : 'MSFT'},
    {'stock_ticker' : 'AAPL'},
    {'stock_ticker' : 'GOOG'},
    {'stock_ticker' : 'FB'},
    {'stock_ticker' : 'SQ'},

]

The columns looks like this in excel

I have found a way to import it using
import pandas as pd
from pandas import ExcelWriter
from tkinter import Tk
from tkinter.filedialog import askopenfilename

root = Tk()
ftypes = [(".xlsm","*.xlsx",".xls")]
ttl  = "Title"
dir1 = 'C:\\'
filePath=r"C:\Users\home\Desktop\code_projects\FIRE_Dashboard\stock_ticker.xlsx"
#filePath = askopenfilename(filetypes = ftypes, initialdir = dir1, title = ttl)

The tutorial where I found this makes the imported file into a pandas dataframe. But I need to make that array instead.
stocklist = pd.read_excel(filePath)
stocklist=stocklist.head()

exportList= pd.DataFrame(columns=['Stock', "RS_Rating", "50 Day MA", "150 Day Ma", "200 Day MA", "52 Week Low", "52 week High"])

So that I could import it into SQLite using
def update_Stocks():
    for data_point in Stocks_Update:

        try:
            Stocks.create(stock_ticker=data_point['stock_ticker'])
        except IntegrityError:
            update_record = Stocks.get(stock_ticker=data_point['stock_ticker'])
            update_record.stock_ticker = data_point['stock_ticker']
            update_record.save()

I am completely lost on where to even get started, as I am not even sure if the thing I need as a final result is a json array or not but it looks similar. Any help on how to do this is much appreciated along with helping a noobie with the correct terminology. Maybe if I knew what it was called I would be able to find a guide for it online.
Anyway thanks again :)
Comment: If you have a CSV file with your data, no need to resort to python to import it into a sqlite database. Just use the sqlite3 command line program: https://sqlite.org/cli.html#csv_import
Comment: Thank you for that link, I will check it out right now :)
Comment: Thanks again, was able to figure out how to import CSV using that and another documentation i found :)
Answer: Wasn't able to find a way on how to do it with python code but found a workaround with
https://www.sqlitetutorial.net/sqlite-import-csv/


Solution for a system of linear ODEs?

Question: Given a system of linear ODEs by
$$\mathbf{y}'(t)=\mathbf{A}\cdot\mathbf{y}(t)$$
where $\mathbf{y}(t)$ is a vector of $n$ equations and $\mathbf{A}\in\mathbb{R}^{n\times n}$
What is the relationship of the solution of a transformed system
$\mathbf{g}'(t)=\kappa\mathbf{A}\cdot\mathbf{g}(t)$
to the solutions of the original, i.e. how to go from a solution of the transformed to the original.
My initial guess is $\mathbf{y}(t)=\mathbf{g}(t/\kappa)$.
Answer: Since the system equations are globally Lipschitz, the solutions are unique (from the same starting point), so if we let
$z(t) = g({t \over \kappa})$, we see that
$z'(t) = {1 \over \kappa} g'({t \over \kappa}) = A g(t) = A z(t)$.
Assuming that $y(0) = g(0)$, we see that $y,z$ satisfy the same differential equation and have the same initial condition, hence $z=y$.
Comment: I believe I have a typo. that I will fix when I hlget to my laptop.

Solution for a system of linear ODEs?


System.Drawing.Font to reflect CSS Font

Question: I'm creating some images of text in code that need to reflect a CSS Font as closely as possible.  The CSS class looks like this:
.font
{
      letter-spacing: -0.7px;
      font-family: segoe wp,segoe ui,verdana,arial,helvetica,sans-serif;
      font-size: 1.15em;
      padding: 10px;
}

My image code looks like this:
using (var helper = new Bitmap(1, 1))
using (var gHelper = Graphics.FromImage(helper))
using (var font = new Font("Segoe WP", 1.15f, GraphicsUnit.Point))
using (var brush = new SolidBrush(Color.White))
{
    var size = gHelper.MeasureString(concept, font);

    using (var image = new Bitmap((int)size.Width + _padding, (int)size.Height + _padding))
    {
        using (var g = Graphics.FromImage(image))
        {
            g.Clear(Color.Black);
            g.DrawString(concept, font, brush, (float)_padding / 2, (float)_padding / 2);
        }

        var converter = new ImageConverter();
        var b = (byte[])converter.ConvertTo(image, typeof(byte[]));

        return File(b, _contentType);
    }
}

The images that are being produced by this code are VERY small.
The letter spacing I'm guessing will require that I make a loop and draw each letter individually, but how do I work with EMs inside of C#?
Answer: In my opinion you can't work with EMs, because they're not fixed.
Read this part (extracted from http://webdesign.about.com/od/typemeasurements/qt/how-big-is-an-em.htm):

But How Big is an Em?
  According to the W3C an em:   "is equal to the
  computed value of the 'font-size' property of the element on which it
  is used. The exception is when 'em' occurs in the value of the
  'font-size' property itself, in which case it refers to the font size
  of the parent element." In other words, ems don't have an absolute
  size. They take on their size values based on where they are. For most
  Web designers, this means that they are in a Web browser, so a font
  that is 1em tall is exactly the same size as the default font size for
  that browser.
But how tall is the default size?
  There is no way to be 100% certain,
  as customers can change their default font size in their browsers, but
  since most people don't you can assume that most browsers have a
  default font size of 16px. So most of the time 1em = 16px.

So you can try:
using (var font = new Font("Segoe WP", 16 * 1.15f, GraphicsUnit.Point))

knowing from the very beginning that this is only an approximation!!
Answer: using (var font = new Font("Segoe WP", 1.15f, GraphicsUnit.Point))
Point != Em.
IIRC, em is just a ratio from the default font.
Answer: Your graphics object assumes that you are drawing to the screen with a low resolution. Create a new graphics object and define a more appropriate resolution
Bitmap bmp = new Bitmap(2000, 500);
bmp.SetResolution(300, 300);
Graphics g = Graphics.FromImage(bmp);
// render your text.

You could also use System.Drawing.TextRenderer, which gives good results.

System.Drawing.Font to reflect CSS Font


What is the relationship between hyperbolic geometry and Einstein's special relativity?

Question: I am a third year math student writing a term paper on hyperbolic geometry and I would like to understand its relationship with special relativity. I have read that the hyperboloid model of hyperbolic geometry, also known as the Minkowski model, takes place in Minkowski space (which I don't understand well) which is also the most convenient setting to formulate Einstein's theory of special relativity. Can someone clarify this for me? It has been pointed out to me that velocity in special relativity is a point in hyperbolic space, so I would like to use techniques and formulas in hyperbolic geometry to discuss things in special relativity.
Comment: There are entire books (or at least entire book chapters) about "the relationship of hyperbolic geometry ot special relativity," so it would be really nice if you could narrow this down. Can you pick a particular task or concept that you want to understand first?
Comment: It's possible that this would be better suited on the physics SE site.
Comment: I'd like to understand this relationship well, too :) Someone said that *velocity* is a point in hyperbolic space? I know the geometry of Minkowski 4-space is hyperbolic, but I never thought of its points as velocities, I thought of them as *events*. Maybe there are actually two models floating around here.
Comment: I had the same feeling Daniel Rust expressed. Still, this does straddle mathematics and physics pretty equally. If you express interest in moving it to the physics site we can definitely start the migration process.
Comment: @rschwieb I did not know this was so well documented. If you know of some text that explains this, please tell me.
Comment: Also, as for moving my question to the physics site, I am not sure since I am more interested in the mathematical side of this, but please do so if you think that people are more knowledegable about this there.
Comment: @Sid Yeah, for example chapter 2 of [Road to Reality](http://www.amazon.com/The-Road-Reality-Complete-Universe/dp/0679776311/ref=sr_1_1?ie=UTF8&qid=1379511981&sr=8-1&keywords=road+to+reality#_) is a simple example. I'm pretty sure the connection has been well-documented for about 100 years or so, although those working on it might not have had as good of a picture as we do now.
Comment: @rschwieb Thanks I will check this out.
Comment: @Sid [This google search](https://www.google.com/search?q=hyperbolic+geometry+spacetime&btnG=Search+Books&tbm=bks&tbo=1) and [this search in googlebooks](https://www.google.com/search?q=hyperbolic+geometry+spacetime&btnG=Search+Books&tbm=bks&tbo=1) returned an awful lot of candidates.
Comment: @Sid I have to eat my words about the second comment I made :) The first source I cited even talks about points of Minkowski space as velocities. I guess I didn't absorb it very well the first time through. Good luck!
Comment: @rschwieb Thank you. I am writing a term paper about hyperbolic geometry, my plan is to include a brief discussion about the Minkowski model and special relativity in the end. I've been reading that book you suggested, it's very nice and simple. I can't really cite books like that though but there's quite a few papers out there that discuss this material. I appreciate how you have helped me.
Comment: @Sid I think that particular Penrose book is just fine to cite anywhere, even a term paper. He is a reputable author with peer reviewed publications after all :) But I guess if you are playing it really safe, you can just fall back on the "academic" references he gives, sure. Good luck in your writing!
Comment: Hyperbolic geometry is to Minkowski space as spherical geometry is to Euclidean space.
Answer: The connection here is the Minkowski space, which can be used to describe both.
Hyperbolic geometry
For example, take hyperbolic 2-space in the hyperboloid model. You'd represent hyperbolic points as points on the hyperboloid, namely as
$$\left\{(x_1,x_2,x_3)^T\;\middle|\;x_1^2-x_2^2-x_3^2=1\right\}$$
This expression $x_1^2-x_2^2-x_3^2$ is the quadratic form which lies at the foundation of the Minkowski space $\mathbb R^{1,2}$. The corresponding bilinear form can be used to compute distances, as
$$d(x,y)=\operatorname{arcosh}\left(x_1y_1-x_2y_2-x_3y_3\right)$$
You can even think about this projectively: you may use a vector which does not lie on the hyperboloid, then use that vector to define a line which will intersect the hyperboloid in a given point, which is the point it specifies. This will work for every vector whose quadratic form is positive.
This idea is also very useful to define lines. A hyperbolic line (i.e. a geodesic) connecting two hyperbolic points is modeled by the intersection between the hyperboloid and a plane spanned by these two points and the origin. You can describe this plane by its normal vector, and you can compute that normal vector as the cross product of two vectors representing the two points. Conversely, you can obtain the intersection between two geodesics by computing the cross product between two normal vectors of such planes, although the quadratic form for that point likely won't be $1$ yet, but any other positive value instead. Therefore, this normal vector of the plane is a reasonable (and homogenous) representation of the line. Its quadratic form will be negative.
Common vocabulary
Now change the vocabulary to use terms which are common for Minkowski spaces. A vector whose quadratic form is positive is said to be time-like. So points of the hyperbolic plane correspond to time-like vectors, with scalar multiples of a vector representing the same point. Likewise a vector whose quadratic form is negative is called space-like. So a line in hyperbolic geometry corresponds to a space-like vector, and all its multiples. In between these two, there are those vectors for which the quadratic form is zero. These correspond to ideal points of your geometry. in a certain sense, an ideal point is as much a line as it is a point.
The set of hyperbolic isometries are those linear transformations of your vector space which preserve the set of ideal points, i.e. which preserve the light cone. These correspond roughly to Lorentz transformations in relativistic vocabulary (with some care because here we identify scalar multiples but there we don't, but the central idea of preserving the light cone remains).
Relativistic geometry
So where do these physically sounding terms come from? Imagining the whole vector space as some kind of space-time-diagram should be fairly simple. The first dimension (with the positive sign) would be time, the other two would be space. A vector would denote an event in this diagram. An event where all spatial coordinates are zero would happen at the same place as the origin, but at some different time. An event with zero time coordinate would happen at the same time but at some other place. The light cone would correspond to a cone of slope $1$, which is the speed of light in our coordinate system. Light travels from the origin along the light cone.
But time and space are relative, so the above choice of coordinate system is only valid for a given inertial system. To convert between inertial systems which meet at the origin, you'd again use a Lorentz transformation, i.e. a transformation which preserves the light cone. Using such a transformation, any event which is a time-like distance away from the origin can be made to happen at the same place but in the past or the future. You'd use an inertial system which travels to that event or came from it. Likewise, any event which is a space-like distance away can be made to happen at the same time, using the right movement to compensate.
Conclusion
So conversions between inertial systems correspond to isometric transformations of the hyperbolic space. And objects in hyperbolic space correspond to (equivalence classes of) events in space-time diagrams.
The above would generalize for higher dimensions, but the part about two points spanning a line would be more complicated to read, since you'd more likely talk about three points spanning a plane. $ $ $ $
Comment: I had this on my favorite list for quite some time now, never finding the time to write an answer, and always hoping someone of those who wrote comments naming suitable literature would provide one. Noone did, and I didn't find time to read any of this either, so here is my very own formulation of this relationship. Feel free to edit or provide a better one.
Comment: Great to see an answer after all this time, this is very useful.


Basic Algebra: square numbers

Question: I am new to calculus. Can you help me with this?
$a+\sqrt{a}=4$
$5a+a\sqrt{a}=? $
Answer: $$a+\sqrt{a}=4\iff \sqrt a=4-a\underbrace{\implies}_{\mathrm{squaring}} a=a^2-8a+16.$$
$$a+\sqrt{a}\implies a=4-\sqrt a\underbrace{\implies}_{\times a}  \color{red}{ a^2=4a-a\sqrt a}.$$ Substitute $a^2$ in the first equality and get
$$a=a^2-8a+16=\color{red}{4a-a\sqrt{a}}-8a+16.$$ This is equivalent to say $$5a+a\sqrt{a}=16$$ and you are done.
Answer: Set $a=x^2$, $x=\sqrt a$ to obtain basic quadratic equations.

Basic Algebra: square numbers


Should barré chords have an acute accent on the E?

Question: I was always taught that it should, but the Wikipedia article doesn't use the accent at all. I'm British — is it an American thing to ignore the accent?  I am preparing some content for an American music site and I'd like to be accurate for as much of the world as possible.
Comment: This is more of a linguistic than a musical question... IMHO if a word _has_ an accent then you should write it
Comment: If you're using a Mac, it's Alt+E, then the e again. Alt+130 on the numpad for PC.
Comment: Well it obviously comes from the French so either, the é is to be kept as in "cliché" or maybe the word evolved differently in your countries, which happens all the time. Either way, I'm French so I guess I'm not on the most suited to answer this question.
Comment: There is an acute accent over the e, which eludes me on my keyboard ! But, I don't think it would be used if written 'barred'. I'm off to find an AZERTY board, like the French use.
Comment: @lukech sunovabic! I've been using octal this whole time without knowing it! The way I've always typed this on a PC is Alt+0233. é. 130 is way shorter.
Answer: The New Oxford American Dictionary says:
bar•ré |bäˈrā|
noun Music
a method of playing a chord on the guitar or similar instrument with a finger laid across the strings at a particular fret, raising their pitch.
ORIGIN late 19th cent.: French, literally 'barred,' past participle of barrer.

I never realized that the "é" is supposed to have an accent and is supposed to be stressed. I've always pronounced it like the English "bar", which I now realize was not the original pronunciation.


How to set SMART goals for a sports performance skill that is hard to measure

Question: I have been reading 'Building a Tennis Champion' and they talk about setting SMART goals.  For the specific part they use an example of measuring first serve percentage.  That is obviously something that is relatively easy to measure and so I can create a SMART goal listed as: "Improve first serve percentage by 10% from 40% to 50% in 6 months.
But I also want to work on some biomechanical items.  For example, in tennis I overuse my arm and want to  change my technique so that I am using my legs and hips more to hit the ball.  This is not so easy to measure?  How can I make a SMART goal for this goal?  Or do I just have to observe my body and measure how I think I am hitting?
Comment: This appears to be a combination of personal planning and fitness development skills question, than about a specific competitive sport. For the latter it would be better on Physical Fitness SE, but the former has no directly relevant site to my knowledge. In any case, is this a question that would only be about tennis, or is tennis merely a placeholder sport?
Comment: How did you determine that you overuse your arm?
Comment: @PhilipKendall If you don't use your body, and overuse just the arm, reliability of shot suffers.  I found this via video.  Are you suggesting video and check that way?
Comment: That would seem to be one way, yes. The real point is that you had some way of determining _THING_ in the first place, whatever _THING_ may be, so you can use the same method again to determine if _THING_ has improved. "Measurable" doesn't have to be "quantitative".
Answer: The goal doesn't have to be in competitive play, it can also be a goal in practice/training.  Using the provided example:

Spend 30 minutes per day for 4 weeks doing simple hits from a ball machine where I focus on leg/hip motion driving the power to the hit.

Specific, Measurable, Time-bound, at least.


Induction range - should the arbitrary integer include the base case?

Question: Let's say I have a claim, $P(n)$, that I want to show true for all $n \in \mathbb{N^+}$.
I would start by showing $P(1)$ holds. Then for the inductive step, I would take an arbitrary integer $m > 1$, and assume $\forall i \in \mathbb{N^+}\: i < m$, $P(i)$ holds.
My question is the subtle difference betwen letting $m \geq 1$ or $m > 1$. If it were $m \geq 1$, then it would be redundant if you examined $m=1$, as you would have a vacuous statement so you're proving $P(1)$ unconditionally, but that's exactly what we did in the base case!
So I would think $m > 1$ would be better style, but I'm not sure what's more commonly accepted in the mathematics community. I've seen it written both ways, but using the non-strict inequality seems iffy to me.
Answer: In fact, you need to make sure that the arbitrary case includes the base case, otherwise you can't make the inductive step. You could have the case where $P(1)$ is true, but $P(1)$ does not imply $P(2)$ for some reason.
For example, there's a false proof that "all horses in a group are the same horse" that goes something like this:

In a group of 1 horse, all horses are the same horse.
If, in a group of $n$ horses, they're all the same horse, then in a group of $n+1$ horses, they're all the same horse.
PROOF: Take the group of $n+1$ horses and remove one horse. You now have a group of $n$ horses, which by assumption are the same horse. Replace the horse you removed and remove a different one, all $n$ horses are again the same horse. Therefore all the horses in the group are the same horse, so the statement is true for $n+1$.
Therefore, all horses in any group are the same horse.

The failure is specifically because when you have a group of 2 horses you can't remove 1 horse, then replace it and remove another, and use that to compare the horses in the group, because you've never had any other horses to compare against.
Comment: Thank you. I'm wondering if you could clarify why you can't make the inductive step if the arbitrary case doesn't include the base case, as here it seems like you would need two base cases, one for $n=1$ and one for $n=2$. But in my scenario, I don't exactly see why taking $m>1$ would invalidate the proof if you're just proving $P(m)$.
Answer: In the context you describe, you are correct that $m>1$ is what you need. Indeed if you used $m\geq1$ then for $m=1$ the set of inductive assumptions would be empty and the induction argument you make using them for $m=1$ might be false. That is why mathematical induction uses two steps.
If the context were slightly different, where the inductive step was stated as: assume $P(m)$ holds to prove $P(m+1)$ holds, then you would use "for $m\geq1$." That may be the kind of situation in which you saw it used.


Strange behavior while dividing i w tagach windows phone

Question: When I run the following code, it doesn't work (it's not dividing), but return 0 Math.Pow() works.
{
    suma = 1;

    foreach (var liczba in Lista_liczb)
    {
        suma = suma*liczba;
        ilosc++;
    }

    var potega = 1/3; //Math.Pow(ilosc,-1);
    double wynik = Math.Pow(suma,potega);
    textBlock2.Text = Convert.ToString(wynik);
}

Comment: The problem is that this line doesn't work:
var potega = 1/3; //Math.Pow(ilosc,-1);
and I have no idea, what could be the reason
It's just not dividing...
Answer: Your potega variable is an Int32 (assuming you're using Visual Studio, hover over var to check the type), which truncates the result of 1/3, or 0.3333, to 0.
Either make potega a double:
double potega = 1 / 3;

Or cast one of the numbers to a double first:
var potega = 1d / 3;


Number of basis representations of Boolean vectors

Question: Suppose I have a basis $v_1, ..., v_n$ of boolean vectors and a boolean vector $v$ that was constructed by iterated $v = v_i$ $OR$ $v_j$ statements. I want a way to figure our how many unique combinations $v_I$, $I = \alpha_1,...,\alpha_k$, $\alpha_i \neq \alpha_j \forall i \neq j$ there are that, when union/or'd, yield $v$. The only thing I know about the basis vectors is that each basis vector has an entry that is true only for that basis vector, and false for all other basis vectors (note then that the vector $(TRUE,...,TRUE)$ has exactly one representation). The order of the basis vectors does not matter - I treat $v_i$ $OR...OR$ $v_j$ and $v_j$ $OR...OR$ $v_i$ equally. An analytic method is preferred but a polynomial-time algorithm would be great too. A polynomial-time algorithm for an upper bound for the number of basis representations (over the whole space) would be incredible, but if someone answered the main question I could probably do that on my own or with an optimization suite.
Answer: For each i, let S(i) be the index of the bit that is set only in the
i'th basis vector v_i
If V is the result of orring together some subset T of basis vectors,
then for each i, the S(i)'th bit is set in V iff v_i is in T.
So for any vector V there is at most one such representation.
Comment: Thanks. Do you have an answer for when the basis does not have that property?
Comment: My guess is that the answer will depend on the precise meaning of "basis"
Comment: What do you mean?
Comment: Do you know anything about the v_i or are they an arbitrary collection of vectors?
Comment: Essentially arbitrary. The vectors represent all the edge cuts of a graph, which in turn are formed through the disjoint union of basis  vectors (the fundamental cuts) with the property I originally described.


Is the Poisson distribution the only one where the mean and variance of the variate are equal?

Question: Or is this possible in another probability distribution?
Comment: Given any random variable $X$ with finite variance,  $Y=X+{\rm Var}(X)-{\rm E}X$ satisfies your requirement.
Comment: @Landscape Thanks, great answer.
Comment: You are welcome.
Comment: Another _named_ discrete example is the Flory distribution with pmf: $$f(x) = \frac{x-1}{2^x}$$  with domain of support $X = 2, 3, 4, ...$ . The mean and variance is 4.
Answer: No. Take a standard normal distribution $\mathcal{N}(0,1)$ and shift its mean by 1: $\mathcal{N}(1,1)$. This has a mean and variance of 1.
You can do this with any mean-square convergent distribution.
However, you might be asking because for the Poisson distribution, this is always true, regardless of its parameterization. In this case, I believe it is the only discrete distribution for which this property holds. To have such a property, you must have a one-parameter distribution, and there are only a handful such named distributions.
(Edit: As Robert Israel points out in the comments, it is certainly possible to construct such a distribution).
Plenty of other distributions have this property at certain values of their parameterizations (e.g. geometric distribution with $p=0.5$).
Comment: Only a handful?  Oh, you're talking about **named** distributions.
Comment: A nice family of discrete distributions with the property, supported on $\{0,1,2\}$, is $p_0 = 1 - t + t^2/2$, $p_1 = t - t^2$, $p_2 = t^2/2$, for $0 \le t \le 1$.
Comment: @RobertIsrael Yes, sorry I didn't make that clear!


Why replace Pearson's correlation with DCC GARCH? (non-technical)

Question: How you would try convincing a non-technical audience that applying DCC GARCH for correlation estimation is better than Pearson's correlation?
The task becomes even more challenging since, as seen in the below image, the GARCH-based correlation follows quite closely the Pearson's correlation calculated with a rolling window.

I am considering the following:

In the above graph, in the beginning of 2016 the 'GARCH' correlation spikes under zero while the Pearson's rolling window doesn't react equally. It's true that there was a huge diversion between the two timeseries at this point so I could argue that, in this example, the 'GARCH' one is much faster to react.
The 'GARCH' model includes the necessary mathematical framework to react to extreme conditions (the implementation I am using assumes a t-distribution for the posterior probabilities)
Pearson's correlation was established around 1900 while Engle's paper regarding DCC-GARCH was published around 100 years later. There has been significant research activity in the meantime so the underlying maths are bound to be more advanced.
Comment: I'll just summarise by saying that the answer depends on the question -- and the audience. I might easily prefer correlation as easier to explain to a "non-technical" audience (not defined here: I'm reminded of a view once held at the _New York Times_ that scatter plots were too difficult for the readership).
Comment: I count as non-technical in this area: I have never used GARCH. What I see is that the methods both show low correlations and broadly agree. Perhaps in your field the correlations seem interesting. In some areas a correlation around 0.1 is a discovery; in others a correlation below 0.9 signals a failure. I would want to know how much data each was based on, why the differences are as credible as the similarities and why you want to tell me that one method is better. #3 is bogus as a criterion: why not argue that a method that's been around for a century has proved its durability?
Comment: @NickCox , thanks for your comment. Regarding your questions: 1. monthly observations so around 60 points 2. Because I think that anything more 'mathematical' will be better than just applying a rolling window - EmptyHead's answer below gives an explanation based on the weighting 3. In general, isn't it the case that some methodologies are widely used given their simplicity? For example, correlation can be calculated by any user in excel or any other 'slightly statistical' software and the formula is being taught at highschools
Comment: #1 What's the window? #2 Really, anything is better? #3 Agreed, but I am not sure where that takes your argument.
Comment: @NickCox #1. 24 obs #2. That's heading towards a philosophical discussion #3. OK let's take as a example quantum mechanics. They are complicated, not taught in high schools but I think that they can provide a 'better' approach in a few problems compared to 'more mainstream' theories?
Comment: Okay, how about this rationale: recruiting for a job. Recruiter has only two strategies on selecting applicants: a) only based at the most recent performance, and b) with a clear focus to the most recent performance, some less focus to all your previous performance in the past on average, the least focus to your early career experience. Which recruitment strategy is better in your view? To me option b) is obviously better. Why? It has a comprehensive view on the candidate ... if good the most recent performance is due to luck strategy a) may lead to the consequences of hiring a wrong person.
Comment: I guess it is clear that recruting strategy a) is analogous to the rolling window correlation and strategy b) to "DCC GARCH".
Comment: @NickCox I agree, it all boils down to the audience finally
Answer: Well, abusing a lot of technical details, DCC GARCH is a "weighted correlation" in some sense ... while your rolling window correlation is also a "weighted correlation" where weights follow a specific pattern ... then significantly simplifying the  only difference is in the weighting scheme for modelling association=correlation ...
Obviously DCC GARCH employs far more complicated weighting scheme than a simple rolling window (e.g. all observations in DCC are taken into consideration and etc.), so the question is, do you really needs this extra complexity? If you pursue "diagnostics" of association between variables goals then probably rolling window correlation is sufficient ... if refer to the fundamental summary work (at least in the context of volatility modelling)

Andersen, T. G., Bollerslev, T., Christoffersen, P. F., & Diebold, F. X. (2006). Volatility and correlation forecasting. Handbook of economic forecasting, 1, 777-878.

it all starts with a rolling window weighting scheme and gets more complicated as we move further on. Well, again to non technical audience the difference is how you assign weights to measure your dependence, rolling window is a very rough weighting scheme, only certain period equally weighted observations are taken into consideration. For example (the most simplified one I guess), observations that happened long before have no impact on your association measure while in DCC GARCH they are taken into account, though receive less attention=less weight (maybe even significantly less weight) but still influence your final association estimate. Hope it helps.
Comment: thanks, I was actually thinking to use the 'inclusion of all observations' and argument but I had forgotten to list it - thanks for reminding and providing extra points.
Answer: I assume that first you want to find out which of the two methods is better and only then try convincing the audience. Otherwise you might (inadvertently) be trying to deceive the audience.
So how do you find out which of the two methods is better? You need a performance criterion. You may be interested in how well a method fits the data in sample and/or how accurately it forecasts out of sample. Once you choose the performance criterion, you would measure the performance of the two methods and see which one is better according to the chosen criterion.
In-sample fit: For example, you may know the true conditional correlations, e.g. if you have simulated the data. Then you can measure the goodness of fit (e.g. $R^2$) of the fitted correlations due to rolling-windows and DCC. Whichever yields a better fit (a higher $R^2$) is better. Then it should be easy to convince the audience by showing the fitted vs. true and the errors. Better fit and smaller errors should be a convincing argument that one method works better than another.
Out-of-sample forecasting: Another example is when you do not know the true conditional correlations. Then you can compare the forecasting performance of the two methods. You would compare the forecast errors of the rolling-window and the DCC forecasts and see which ones are smaller. Again, it should be easy to convince the audience that a method that forecasts better is a better method for forecasting.
How do your three points fit into this framework?

It's true that there was a huge diversion between the two timeseries at this point so I could argue that, in this example, the 'GARCH' one is much faster to react.

This aligns well with my propositions. If you know what the true correlation was, you can measure the goodness of fit of the competing methods and argue for the one that has the better fit.
If you can demonstrate that

The 'GARCH' model includes the necessary mathematical framework to react to extreme conditions (the implementation I am using assumes a t-distribution for the posterior probabilities)

analytically or by simulations and, morever, show that the rolling-window method does not have these benefits, then this is in line with my propositions. If not, it might not be very convincing.
I find this more of an emotional rather than a rational argument. I suppose you could construct examples where one method beats another and vice versa, i.e. DCC is not always and everywhere superior to the rolling-window method. The interesting question is, which one tends to do better in practice. A more convincing argument could be to collect sufficiently many real-world out-of-sample forecasting examples that favour DCC over the rolling-window method.


Expose Fileserver (SMB) over WEB / HTTP(S) Interface

Question: I have a Windows Fileserver (SMB), for internal storage. I'm looking for a way to add a Web-interface to expose the fileserver over HTTPS.
The requirements are:

Accessible over HTTPS in a standard browser as a Web application.
The Web application shall be able to display and modify the content of a SMB-share.
Media playback (video and audio) would be great. But download and relying on the browser are ok.
Linux or Windows.
Open Source

If it is a bad idea to have this setup, please let me know. I can be okay with moving from the Windows file-server SMB platform to another Linux platform.
Comment: IIS?...........
Comment: I updated the post. IIS may be a good read-only choice.
Comment: WebDAV?.........
Comment: IIS for R/O access is an overkill and resource hog, but it gets the job done!
Comment: It would be amazing to finally have a solution for this problem that includes LDAP support and actually sets the file permissions based on that. Nextcloud etc. only work when the files are owned by www-data.
Comment: User management can be different from the users on the file-server. I can go with web-ui uses one user-identity on file-server. It's for home-purpose currently.
Comment: Web-based HTML5 player for video would also be a good feature.
Answer: NextCloud has WebDAV functionality / integration and can replicate data between off-site <-> on-premises in the way you want. This is no open source / free software, but you might want to give it a try.
https://nextcloud.com/files/
P.S. I have nothing to do with this company, just in case :)
Comment: Maybe not my choice. Thanks anyway!
Answer: Pydio has Web UX for CIFS/SMB shares:
https://pydio.com
Comment: I have seen Pydio specification, but I have not give it a try. Is it worth a try? Are you using it?
Comment: I am personally not - we use Syncplicity for content sharing, but our company evaluated Pydio for some customers
Answer: I guess OwnCloud might be a bit overkill for your needs, but still going to mention it. :)
Comment: I have been looking in this direction also. Currently I use Seafile as a sync-server, but its currently not connected to the file-server-files.
Answer: SMB with encryption directly over the WAN or Internet. Mount the shares with native OS tools.
Microsoft considers Internet transport acceptable for modern SMB.
Comment: SMB is chatty though, and the round-trip latency really kills performance.


Evento ao fechar aba/navegador

Question: Bom galera blz, queria saber como faço para chamar um evento quando fecho aba ou navegador e quando fechar queria que fizesse um update no mysql ex: logado=1, ai quando fecha faz update para logado=0
Comment: Por que não usar o `SESSION` do PHP?
Comment: Como faria para quando fechar a aba ou navegador destruir a session ?
Comment: Pode usar [`beforeunload`](https://developer.mozilla.org/pt-BR/docs/Web/Events/beforeunload) com javascipt, embora não funcione em 100% das situações.
Answer: Você poderia usar um beforeunload para chamar teu evento antes que a janela feche, apesar de não ser compatível com alguns navegadores.
$(window).on('beforeunload',function(){
    //meu evento
});

Uma solução alternativa, seria enviar em periodos de tempo constantes um POST avisando ao server que o user ainda está online, como por exemplo:
var online = setInterval(function (){
    //fazer teu post aqui
}, 60000);

Assim a cada 60 segundos o usuário será atualizado com o horário atual, depois para verificar se ele está online ou não basta verificar se a última vez em que foi visto já tem mais de 60 segundos.
Comment: Obrigado amigo me ajudou bastante.

Evento ao fechar aba/navegador


onto Linear mapping

Question: Let $D$ be a square with vertices
$(0, 0), (1, 1), (2, 0), (1, −1)$ and $D^*$ be a parallelogram
with vertices $(0, 0), (1, 2), (2, 1), (1, −1)$. Find a linear
map T taking $D^*$ onto $D$.
The answer is $$T(x,y) = (x, (-x/3)+(2x/3)),$$ but I'm not sure how to get that?
Answer: Hint: Based on what they tell us, it suffices to take a $T$ satisfying $T(1,1)=(1,2)$ and $T(1,-1)=(1,-1)$. This is enough for us to deduce what $T$ is.
Comment: @user3427042 If there is such a linear map at all, the fourth point is redundant: $(1,-1)=(2,0)-(1,1)$, so it provides no additional information. You should check, however, that T(1,-1)=T(2,0)-T(1,1)=(1,-1)
Comment: why is that enough, and not all 4?

onto Linear mapping