Não consigo colocar o .value no codigo JavaScript fica dando erro

Question:

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS</title>

    <form class="form" action="" method="get">

Name:<input type="text" class="name">

Sobrenome:<input type="text" class="sobrenome">

Peso:<input type="text" class="peso">

Altura:<input type="text" class="altura">

        <button>Enviar</button>

    </form>

```

function meuEscopo(){
const form = document.querySelector(".form");
const resultado = document.querySelector(".resultado");
const pessoas = [];

function recebeEventoForm(evento){
    evento.preventDefault();
    const nome = form.querySelector(".nome");
    const sobrenome = form.querySelector(".sobrenome");
    const peso = form.querySelector(".peso");
    const altura = form.querySelector(".altura");

    pessoas.push({
        nome: nome.value,
        sobrenome: sobrenome.value,
        peso: peso.value,
        altura: altura.value
    });
    console.log(pessoas);

    resultado.innethtml += `<p>${nome.value} ${sobrenome.value} ${peso.value} ${altura.value}</p>`
 };

 form.addEventListener("submit", recebeEventoForm);

}
meuEscopo();

quero que salve no document a cada vez que escrever os dados e clicar no botao de enviar, porém da erro no value.

Comment: Para prosseguir dentro do objetivo do site é importante [edit] sua postagem removendo o código atual e em vez dele postar um [mcve] do problema e, se possível, uma descrição melhor da dificuldade em resolver. Para entender que tipo de pergunta serve para o site vale a pena ler [O que é o Stack Overflow](https://pt.meta.stackoverflow.com/q/7256/70) e o [Guia de sobrevivência (resumido) do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8089/70).
Answer:
const nome = form.querySelector(".nome");
Name:

Classe HTML contem o "name", e você usou o "nome" no javascript.
Mudança seria->
const pessoas = [];

function recebeEventoForm(evento){
    evento.preventDefault();
    const nome = form.querySelector(".name");
    const sobrenome = form.querySelector(".sobrenome");
    const peso = form.querySelector(".peso");
    const altura = form.querySelector(".altura");

    pessoas.push({
        nome: nome.value,
        sobrenome: sobrenome.value,
        peso: peso.value,
        altura: altura.value
    });
    console.log(pessoas);

    resultado.innethtml += `<p>${nome.value} ${sobrenome.value} ${peso.value} ${altura.value}</p>`
 };

 form.addEventListener("submit", recebeEventoForm);


Spring Integration "onSuccessExpression" syntax in the advice bean

Question: I have a configuration class for the Spring Integration flow that has a file output channel adapter at the end of the flow. I am using ConsumerEndpointSpec.advice() to send out a notification once the file is copied. Here is my Advice bean:
@Bean
public Advice outboundFileCopyAdvice()
{
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setOnSuccessExpression("??");
    advice.setFailureChannel(fileCopySuccessChannel);
    advice.setOnFailureExpression("??");
    advice.setFailureChannel(fileCopyFailureChannel);

    return advice;
}

I'd like to ask what expression I should put instead of "??" to get a reference to the Message<File> object. I found out that I can use expressions like "payload.toString()" or "headers['someKey']", but I was not able to come up with an expression that provides a reference to the whole message object.
Thank you.
Answer: The variable #root refers to the message object (the root object for the expression evaluation).
payload.foo and headers['bar'] are shortcuts for #root.payload.foo (java: message.getPayload().getFoo()) and #root.headers['bar'] (java: message.getHeaders().get("bar")).
SpEL Documentation here.
Comment: Thanks a lot, Gary!


change python list format using numpy

Question: The list that I am getting is in the following format:
arr = ['43f4cc160,2021-06-17,Dan Abramov', ' 1 file changed, 10 insertions(+), 19 deletions(-)', '', 'a0d2d1e1e,2021-06-16,Dan Abramov', ' 1 file changed, 4831 insertions(+), 6450 deletions(-)']

and I want to have following format
expected_array = ['43f4cc160; 2021-06-17; Dan Ab; 1 file changed, 10 insertions(+), 19 deletions(-)', 'a0d2d1e1e; 2021-06-16; Dan Ab; 2 file changed, 150 insertions(+), 19 deletions(-)'
]

I converted python list to numpy array using np_array = np.array(arr) but I could not merge two string to make it one like '43f4cc160,2021-06-17,Dan Abramov', ' 1 file changed, 10 insertions(+), 19 deletions(-)', '', to '43f4cc160; 2021-06-17; Dan Ab; 1 file changed, 10 insertions(+), 19 deletions(-)' so I can split in such way:
np.char.split(expected_array, ',')
This way I can have commit_hash, date, name, file_log.
Comment: string manipulations are easier in lists than arrays.
Comment: @hpaulj Can you give me a hint on how you will approach when using string manipulation?
Answer: Try
[i+j for i,j in zip(arr[::2],  arr[1::2])]

The idea is to step through the list in pairs, and string concatenate them.
(I haven't tested this.)
Comment: This is what it gave `['43f4cc160 2021-06-17 Dan Ab 1 file changed, 10 insertions(+), 19 deletions(-)', 'a0d2d1e1e 2021-06-16 Dan Ab', ' 1 file changed, 4831 insertions(+), 6450 deletions(-)', '6cbf2a8b3 2021-06-15 Dan Ab 1 file changed, 14303 insertions(+)', 'c0a77029c 2021-06-15 Dan Ab', ' 1 file changed, 1 insertion(+), 1 deletion(-)', 'f283d7524 2021-06-15 Dan Ab 1 file changed, 5260 deletions(-)', '03c5314b4 2021-06-15 Dan Ab'
`. There is some string which does not has `.. changed .. insertion(+)`. It's may be there was not such adjacent string. I will dig into it. Thank you.
Comment: It seems like some were not merged.
Answer: Multiple strings can be joined together using the "join" method:
expected_array = ["".join(arr)]

Edit:
I misread the question, maybe this works:
[arr[i].split(',') + [arr[i+1],] for i in range(0,len(arr),3)]

Comment: My bad, I didn't read the question fully. Answer edited.

change python list format using numpy


Unable to get javascript to make first letter of every word LARGER on my site to load properly

Question: I'm trying to use javascript to make the first letter of every word LARGER in titles with the class 'field-name-title' (so basically all nodes).
I found a couple of Javascript-based solutions online, notably here and here. But whenever I try and implement them nothing happens (by which I mean the titles that are supposed to be changed are NOT).
What's I've tried:
1) I replaced the boilerplate class name in the javascript linked to above with my class name (ir. replaced 'title-case' in the one with 'field-name-title', etc.).
2) I've ensured I have a first-letter class in my stylesheet with the following property:
.first-letter {
  font-size: 1.4em; // I also tried % such as 115%
}

3) I put my javascript file in js/first-letter.js. I referenced it in my .info file as 'scripts[] = js/first-letter.js.
4) I've flushed caches repeatedly (and besides aggregation is turned off).
What am I missing?
Answer: If Alireza's answer doesn't work, try this one.
js/first-letter.js
(function ($) {
 $( document ).ready(function() {
  $('.field-name-title').html(function(i,el) {
    return el.replace(/\b([A-Z])/g, "$1");
     });
  });
}(jQuery));

Comment: thanks yet again. that worked perfectly. I can't tell you how much I appreciate all your help.
Answer: If you have used the first reference , then change script to this :
(function ($) {
  $( document ).ready(function() {
    $('.field-name-title').html(function(i,el) {
      return el.replace(/\b([A-Z])/g, "$1");
    });
  });
}(jQuery));

for more info check Working with JavaScript and jQuery


Aplicar máscara ao digitar no campo input, ao digitar um numero mostrar asterisco invez de números ou letras

Question: como faço para aplicar máscara no campo input, quando o usuário for digitar ao invés de aparecer os números/letras eu quero que apareça nesse campo input o caracteres especiais (*). Exemplo: 999******99.
Comment: O `input type password` não resolveria seu caso ?
Comment: Não porque quando o usuário for digitar ele irá completar com asterisco, eu preciso que quando ele digitar irá aparecer número + asterisco + número.
Answer: Achei essa resposta no SOEN (https://stackoverflow.com/questions/45113132/partial-password-masking-on-input-field). Podes adaptar a sua realidade, ela faz praticamente o que você quer.

 var ssn = document.getElementById('ssn');
    ssn.addEventListener('input', ssnMask, false);
    var ssnFirstFive = "";
    var secondHalf = "";
    var fullSSN = "";

    function ssnMask(){
        if (ssn.value.length <= 5){
            ssn.type = 'password';
        }
        else{
            detectChanges();
            secondHalf = ssn.value.substring(5);
            ssn.type = 'text';
            ssn.value = "•••••";
            ssn.value += secondHalf;
            fullSSN = ssnFirstFive + secondHalf;
        }
    }

    function detectChanges() {
        for (var i = 0; i < 5; i++){
            if (ssn.value[i] != "•"){
                ssnFirstFive = ssnFirstFive.substring(0, i) + ssn.value[i] + ssnFirstFive.substring(i+1);
            }
        }
    }
<input type="password" id="ssn" maxlength=9 />
Comment: Obrigado, vou implementar essa solução no meu formulário, era isso mesmo que estava precisando. vlwwww
Comment: Aceite a resposta então como resolvida. :)


How do I create a Rust macro to define a String variable with the value of its own identifier?

Question: I want to write a macro to define something like below:
let FOO: String = "FOO".to_string();

It is possible for me to have a macro:
macro_rules! my_macro {
    ($name: ident, $val: expr) => {
        let $name: String = $val.to_string();
    }
}

and use it as my_macro!(FOO, "FOO");
However, this is a bit redundant. I expect to have something like my_macro!(FOO), and it can expand and use the $name as identifier, but also in the string value.
Answer: You want stringify!:
macro_rules! str_var {
    ($name:ident) => {
        let $name = String::from(stringify!($name));
    };
}

fn main() {
    str_var!(foo);
    println!("foo: {:?}", foo);
}

Comment: It's just too bad you can't seem to use `stringify` in attributes.


SASM program parameters to debugger

Question: I have installed a SASM on linux, I want to input parameters to starting program and observe registers behavior, but I don't now how input this paramteres to SASM debugger or something..
Answer: When you start debug program, in "GDB Command" on the bottom just type "run arg1 arg2 arg3..."
Answer: another way is to put the command line arguments in the input box
and use char zz[100] ;
then :
get(zz) will read all args (except arg[0]  ) into zz and you will haave to
parse the string yourself
Comment: That's another way to get input, but it would be from stdin not command line.
Comment: To be fair, the question just asks for "parameters" or "input", so this answer could work if it didn't call them "args", especially "command line arguments".

SASM program parameters to debugger


Why is covariate balance fundamental for causal inference in observational data but unnecessary in experimental data?

Question: The observational case
For observational data, Hernán & Robins (2023, p. 49) state:

In the absence of marginal randomization, [computing the average causal effect in the entire population] requires adjustment for the variables $L$ that ensure conditional exchangeability of the treated and untreated

Adjustment can then be achieved via regression adjustment in an outcome model, standardization, stratification/restriction, matching or IP weighting. When using matching or weighting, for example, packages offer a multitude of methods and diagnostics to evaluate the degree of balance achieved.
If our generated pseudo-population is greatly imbalanced, we will consider our estimate most surely biased and, thus, invalid.
The experimental case
In the context of randomized clinical trials, Senn states explicitly in myth number 2 of the article "Seven myths of randomisation in clinical trials" (p. 1441):

There is no requirement for baseline balance for valid inference.

Likewise, in his guest blog post "Randomisation is not about balance, nor about homogeneity but about randomness", he unambiguously states:

Randomisation does not produce balance
This does not affect the validity of the analysis

, as well as,

Balance is a matter of precision not validity

The question
How does the process by which data is created alters the role of balance, from one of ensuring validity into one of ensuring precision?
Answer: In short
Balance is necessary but not sufficient for observational data, as most of the "work" is done by the causal assumptions. Whereas in experimental studies, balance is not as irrelevant as suggested by the quotes from Senn, as observed covariates have to be taken into account even if there's randomization.

The confusion in the question usually has the implicit erroneous reasoning that in observational data:

Identification of the causal effect requires adjusting for some variables

Adjustment on $L$ will usually involve some balancing of units across levels of $L$

Thus, the balancing itself is identifying the causal effect by inducing conditional
exchangeability

Balancing is a statistical property, and it cannot on its own identify a causal effect. We will always need to appeal to causal assumptions.
The issue, as common to most attempts of drawing causal inferences, is unobserved confounding.
The observational case
Note that the observational case assumes already that $L$ ensures conditional exchangeability, i.e. that $L$ is a sufficient adjustment set (and thus, that there is no unmeasured confounding after adjusting for $L$). The very same property of "sufficiency" is what we are assuming. Without this causal assumption, balance does not achieve valid inferences of a causal effect. Balancing is then just a way to assess how well we are adjusting for $L$.
We introduced exchangeability as an assumption.
The experimental case
Here, the design introduced exchangeability into our data.
Remember that exchangeability is a property of the distribution of (potential) outcomes—not the covariates. Thus, as Senn states in the comments in the blog post:

RCTs are good at dealing with confounding, not because confounders are eliminated but because their joint effect can be estimated.

Thus, when randomizing, we do not care about adjusting for confounders for validity, nor we worry about unobserved confounders—there cannot be confounders (as in "common causes of exposure and outcome") since randomization is not caused by any covariate by definition!
We can still have prognostic factors, i.e. causes of the outcome, that can be unbalanced across treatment arms. And note that myth 6 of the article clearly states that one must not ignore them just because we randomized (p. 1446):

In fact, it is not logical to ignore prognostic covariates even if they are perfectly balanced once they have been observed. Valid inference depends on conditioning on what is known. It is only when the actual distribution of covariates has not been observed that it is acceptable to substitute their distribution in probability. [...] Obviously, what has not been measured cannot be put in the model, and it is here that randomisation proves valuable. However, if it was chosen to measure something because it was prognostic, then it is not reasonable to behave as if one had not seen it.

We would thus include them in the model or perform post-stratification, so balance is not irrelevant in the experimental case.

However
Consider the critic that Greenland, Robins & Pearl (1999, p. 35, bolding mine) raise regarding randomization:

Neither restriction nor matching prevents (although they may diminish) imbalances on unrestricted, unmatched or unmeasured covariates. In contrast, randomized treatment allocation (randomization) offers a means of dealing with confounding by covariates not explicitly accounted for by the design. It must be emphasized, however, that this solution is only probabilistic and subject to severe practical constraints. [...] Thus, even in a perfectly executed randomized trial, the no-confounding condition $\mu_{A0} = \mu_{B0}$ is not a realistic assumption for inferences about causal effects. Succesful randomization simply insures (sic) that the difference $\mu_{A0} - \mu_{B0}$ and hence the degree of confounding, has expectation zero and converges to zero under the randomization distribution; it also provides a permutation distribution for causal inferences (Fisher, 1935; Cox, 1958, Chapter 5).

To which Senn would likely reply (p. 1442, bolding mine):

In fact, the probability calculation applied to a clinical trial automatically makes an allowance for the fact that groups will almost certainly be unbalanced, and if one knew that they were balanced, then the calculation that is usually performed would not be correct. Every statistician knows that you should not analyse a matched pairs design as if it were a completely randomised design. In the former, there is deliberate balancing by the device of matching; in the latter, there is not. In other words, not only despite but also because we know that in practice many hidden confounders will be unbalanced, the conventional analysis of randomised trials is valid. If we knew these factors to be balanced, then the conventional analysis would be invalid.

The defense of Senn seems relatively weak, and in the rest of the section in the paper he seems to imply that given that there is no better alternative, we should be content with taking shelter in the randomization distribution. Personally, I feel this is not entirely honest or transparent to the interpretation that readers will give to the results of an RCT, but maybe that is the subject for another question altogether...
Comment: It might help to put a bold summary at the top. My first read of this made me think you dispute the claim, yet now I am not sure.
Comment: Hope it is more clear now!
Comment: very helpful research. I'm confused what's the difference between 「observed covariates have to be taken into account 」vs 「Senn myth 3: Observed covariates can be ignored」?
Comment: @wei Thanks! The fact that observed covariates [known to be prognostic factors] have to be taken into account in the model is the conclusion of why "Observed covariates may be ignored because one has randomised" is a myth (the sixth and not the third one).


URL for Created Services View?

Question: Apologies for the newb question, but: Is there a way to see the entire URL of a Services View I've created? I know it lets me name the path, however when I navigate to the URL, I get "View not found" (though the Views preview shows perfectly). I keep thinking maybe I'm just typing it in wrong? Right now, I'm navigating to:
http://domainnamehere.com/endpointname/views/viewname
Thanks all.
Answer: the right url will like domain/endpoint/services_url If you need to get any view the url will be like
domain/endpoint/viewname?display_id=block_id
More details found here

URL for Created Services View?


My NetBeans installation fails to run my simple application

Question: I have a problem with Netbeans. It does not run my code, and I am sure my code is correct.  Here is what NetBeans looks like when I try to run:
enter image description here
Answer: first, check your JDK version. Maybe it not compatible with your NetBeans version.
if are you installed the correct version, configure JDK in your system.
control panel -> system -> advanced system setting ->environmental variable(in Advanced tab) ->Now you can see the list of paths. So click on the new button and copy the path of JDK where you installed JDK. By default, it will be such as "C:\Program Files\Java\jdk1.8.0_221\bin". Then paste the path and click OK -> Now under the user variables section, Click on New button. new user variable window will open. In variable name, type JAVA_HOME into it and variable value, give the path "C:\Program Files\Java\jdk1.8.0_221" and click on OK. Then again click on OK.


An alternative definition of the limit of a function

Question: In a course on real analysis one usually comes across the definition of the limit of a function:
Given a function $f:A\to \mathbb{R}$ where $A\subseteq\mathbb{R}$, then if $c\in A$ is an limit point of $A$, we say that
\begin{align}
\lim_{x\to c}f(x) = L
\end{align}
If
\begin{align}
\forall_{\varepsilon>0}\exists_{\delta>0}
0<|x-c|<\delta \implies |f(x)-L|<\varepsilon
\end{align}
When one uses this definition of a limit in a proof, it tends to get a bit messy, sometimes you have to do this "trick" where you restrict $\delta$ to always be less than a certain constant, to get some constant lower bounds in either of the inequalities. It also happens frequently that one starts with a $\delta$ and investigates what happens to $|f(x)-L|$, and then from that guess what a suitable relationship between $\varepsilon$ and $\delta$ should be. This approach seems to be a bit convoluted at times, so I propose an alternative definition which I believe is more rational
Given $f:A\to\mathbb{R}$ with $c\in A$ as before, then if there is a surjective function
\begin{align}
g:(0,a)\to(0,b)
\end{align}
That satisfies
\begin{align}
0<|x-c|<\delta \implies |f(x)-L|<g(\delta)
\end{align}
Then
\begin{align}
\lim_{x\to c}=L
\end{align}
This seems superficially more complicated, because now suddenly we have to check the surjectivity of a function, but what is interesting is that both quantifiers and a whole variable ($\varepsilon$) is now imbedded into a single statement about a function. The motivation behind the definition is that if one can find such a $g$, then given any $\varepsilon>0$, one can find $0<\varepsilon'<\varepsilon$ where $\varepsilon'\in(0,b)$, and since it is in the image of $g$ there is some $\delta$ such that $g(\delta)=\varepsilon'$ and from there you can prove that the limit holds in the traditional sense. Note that one can also prove surjectivity by proving that a function is bijective, and you can prove the latter by constructing the inverse, thereby entirely avoiding the use of quantifiers.
My questions then are:
Does this alternative definition seem correct, and useful?
Is there something analogous to this that is already used?
Comment: @Carlyle The point is that you need to *prevent* $x=a$: if $f(x)=0$ everywhere except for $f(0)=1$, we still have $\lim_{x\rightarrow 0}f(x)=0$. Incidentally, your proposed definition (once fixed) is basically an instance of the logical technique of [Skolemization](https://en.wikipedia.org/wiki/Skolem_normal_form), whose role is exactly to replace complicated-quantifier expressions with an $\exists_{functions}\forall_{elements}$-expression.
Comment: The proposition in your second displayed formula should have $0<|x-a|<\delta$, not $|x-a|<\delta$, otherwise you are defining continuity.
Comment: @NoahSchweber I appreciate the comment. I am still not quite sure what the problem is, are you saying that when I add the quantifier over $x$, the problem is fixed, or still not?
Comment: @Carlyle I was talking about the first and yes, both are wrong. The statements with $|x-a|<\delta$ define what everyone else calls "$f$ is continuous at $x=a$ (with $f(a)=L$)"
Comment: @Carlyle Adding the requirement $x\not=c$ would do the job, as would adding "$0<$" appropriately. But what's written right now is not quite correct.
Comment: Your proposition replaces $\forall \varepsilon, \exists \delta$ by $\exists a, \exists b, \exists g, \forall \delta$. On first impression, this does not look like an improvement.
Comment: @NoahSchweber but does adding a quantifier over $x$ not ensure that the condition "gets checked" for all those $x\neq c$ as well?
Comment: @Jean-ArmandMoroni, generally complexity is better understood with the amount of switches between quantifiers, a string like $\exists_a\exists_b\exists_c\exists_d\exists_f$ is a lot simpler than $\forall_a\exists_b\forall_c\exists_d$. Even though the latter has less quantifiers, so I don't think this is that big of a concern, especially considering one usually thinks of the domain and co-domain as being information about the function, and you could naturally place the condition on $a$ and $b$ together with the condition that $g$ is surjective
Comment: @Carlyle Agreed. Still, there are more variables in your definition, so a principle such as Ockham razor would prefer the usual definition. And I fail seeing a case where the new definition would be useful.
Comment: @Jean-ArmandMoroni, $a$ and $b$ are technically variables, but they are still in some non-formal way "less variable" than $\epsilon$ and $\delta$ in the normal definition, in the sense that they are only a variable until you decide upon some fixed numerical value for them, so I still don't think that this alone is enough to disregard the definition, but usefulness might well be, for that, I know of at least one limit which is at most the same difficulty to prove using this definition, which is the limit of $\frac{1}{x}$ as $x\to a\neq 0$. But it remains to be seen if there are more examples
Answer: You asked: "Is there something analogous to this that is already used?"
There is indeed a way of defining limits with fewer quantifier alternations, as you suggested.  This way can be viewed as a formalisation of the approach with functions that you sketched.  Namely, one has $\lim_{x\to c} f(x) =L$ if and only if for all $x$ infinitely close to $c$ but different from $c$, one has $f(x)\approx L$ where $\approx$ is the relation of infinite proximity.  Here $a\approx b$ iff $a-b$ is infinitesimal, and a number is infinitesimal if it is smaller in absolute value than every positive standard real number.  A recent breakthrough showed that such a framework can be achieved conservatively over ZF (without the axiom of choice and without ultrafilters).  See here for further details.
Comment: Thank you for the answer, I'm sorry that someone downvoted your it, it seems perfectly fine to me
Comment: @Carlyle, perhaps they feel that the real numbers could not *possibly* contain infinitesimals.  Why, Cantor already said so.


Data from @Input different in function than in template

Question: I have a container that passes an Observable called positions$ to a component, which ultimately returns an array of objects. When I bind that array to the template, it displays the data as I would expect, but if I try to access that same data in one of my functions within that same component, it comes back with following:

That is logged to the console long after the expected data has displayed in the template, so I know I'm not clicking the button too quickly. Why aren't I getting the same data in both places? Here is my relevant code:
container typescript:
positions$: Observable<Position[]>;
...
this.positions$ = this.store.pipe(select(fromStore.getAllPositions));
this.store.pipe(select(fromStore.getPositionsLoaded)).subscribe(loaded => {
  if (!loaded) {
    this.store.dispatch(new fromStore.LoadPositions());
  }
});

container html:
<app-position-form
  [loading]="loading"
  [positions]="positions$"
  [positionsLoading]="positionsLoading$"
  (add)="addPosition($event)">
</app-position-form>

component typescript:
@Input() positions: Position[];
...
addPosition() {
    // Does NOT work as expected
    console.log('existing positions', this.positions);
}

component html:

    {{position.position}}

Answer: Your template that is working is using an async pipe to display the "postions", so "positions" appears to be an Observable.
In the component that gets the @Input, you have the input typed as a Position[], but I'd bet that what you're actually getting at runtime is an Observable
If so, the component will have to subscribe to the Observable to get the data.


Closed form for recurrence relation

Question: Is there a closed-form solution to the following recurrence:
$$T(n) = T(n-1) + T(n-3)$$
If yes, what is it and how can it be proven/derived?
If not, then why because a somewhat similar recurrence like fibonacci has closed-form solution.
Comment: There is a closed form solution. The roots of the characteristic equation are given by the Cardano formula, Unattractive but explicit.
Comment: Fibonacci is solved by looking for solutions of the form $T_n=t^n$. Do the same here. If you find several solutions, any linear combination is also a solution.
Comment: Possible duplicate of http://math.stackexchange.com/questions/889311/general-formula-of-fibonacci-look-alike-series.
Answer: The explicit formula looks like this:
$$T(n) = a_1 x_1^n+a_2 x_2^n+a_3x_3^n,$$
where $x_{1,2,3}$ are the three roots of $x^3-x-1=0$ and $a_{1,2,3}$ are determined by the initial conditions.
But through my magic crystal ball I see that you do not really want an explicit formula, rather you need a method to calculte $T(n)$ in short time for inputs up to $n\approx 2^{64}$. The following method takes only $O(\ln n)$ time:
The map $(T(n), T(n+1), T(n+2))^t\mapsto (T(n+1), T(n+2), T(n+3))^t$ is linear, i.e. given by some $3\times 3$ matrix $A$. Then we have $$(T(n), T(n+1), T(n+2))^t = A^n\cdot(T(0), T(1), T(2))^t$$
and we can find $A^n$ by repeated squaring in $O(\ln n)$ operations.
Comment: The characteristic roots are (according to maple)
\begin{align*}
  x_1 &= \frac{\bigl(108 + 12\sqrt{69}\bigr)^{2/3} + 12}{6\cdot \bigl(108 + 12\sqrt{69}\bigr)^{1/3}} \\
  x_2 &= \frac{\bigl(108 + 12\sqrt{69}\bigr)^{2/3}(-1 + \sqrt{3}i) - 12(1 + \sqrt3 i)}{12 \cdot \bigl(108 + 12\sqrt{69}\bigr)^{1/3} }\\
  x_3 = \overline{x_2} &= \frac{\bigl(108 + 12\sqrt{69}\bigr)^{2/3}(-1 - \sqrt{3}i) - 12(1 - \sqrt3 i)}{12 \cdot \bigl(108 + 12\sqrt{69}\bigr)^{1/3} }
\end{align*}
Comment: @Hagen I liked that crystal ball comment. This was helpful. Thanks.
Answer: The characteristic equation $z^3=z^2+1$ has a real root, let $t$, and a pair of complex conjugate roots $p\pm iq$, or $re^{\pm i\theta}$ in polar form.
The general solution is
$$T_n=At^n+B(re^{i\theta})^n+C(re^{-i\theta})^n.$$
Assuming that the initial values are real, so is the general solution, and by conjugation
$$At^n+B(re^{i\theta})^n+C(re^{-i\theta})^n=A^*t^n+B^*(re^{-i\theta})^n+C^*(re^{i\theta})^n.$$
This shows that $A$ is real, and $B, C$ are complex conjugates.
The general solution can be rewritten as
$$T_n=at^n+(b-ic)(re^{i\theta})^n+(b+ic)(re^{-i\theta})^n=at^n+2r^n(b\cos(n\theta)+c\sin(n\theta)).$$
It has a pure exponential term and an oscillating exponential term.

Closed form for recurrence relation


How to set page variable from custom module

Question: In Drupal 8:
I have custom module code that declares its own theme can twig template.  How do I make module variables available to my Drupal theme's page.html.twig?
I have tried various preprocess_page* functions; however, those functions don't see the variables the module is passing to it's own themed twig templates.
Can the module's controller inject something into the page variables?
Can a Drupal theme's preprocess functions access some variables flowing from a custom module to the module's twig templates?
The controller file:
class PromtController extends ControllerBase
{
    public function program($id)
    {
        $program = PromtService::program((int)$id);

        return [
            '#theme'   => 'promt_program',
            '#program' => $program,
            '#title'   => $program['title']
        ];
    }
}

The module code:
function promt_theme()
{
    return [
        'promt_program' => [
            'template' => 'promt_program',
            'variables' => [
                'program' => null
            ]
        ]
    ];
}

Comment: Normally, the hook_preprocess_page() implementation would appear in your .module file, the same file where you implemented hook_theme().
Comment: The hook_preprocess_page() function; however, does not seem to have access to the programs variable being passed from the controller to the theme.

I need to inspect the programs variable I'm passing in, in order to pull out phone numbers, etc to add as contact information in page.html.twig.  Either hook_preprocess_page() needs to be able to find that variable some where in &$vars[] or the controller needs to pass it in, in a special way, such that it becomes part of the page array.
Answer: As far as I can tell, this should be handled in the custom theme, not in the custom module.  This is because the module really has no idea how a custom theme wants to render stuff.
In any case, in the custom theme, the only way I can figure out how to make the data available is to register a hook_preprocess() function in the theme, check the hook that's called, and declare a static variable that sticks around until it can be injected later on.
The custom module's "promt_program" hook will be called earlier than the theme's "page" hook. I'm pretty sure that will always be true.  So, we grab the location_id and then inject it later on.
This preprocess function will get called many, many times, so it seems important to make it thin.
function cob_preprocess(&$vars, $hook)
{
    static $location_id = null;

    switch ($hook) {
        case 'promt_program':
            if (!empty($vars['program']['location_id'])) { $location_id = $vars['program']['location_id']; }
        break;

        case 'page':
            if ($location_id) {
                $query = \Drupal::entityQuery('node')
                    ->condition('status', 1)
                    ->condition('type', 'location')
                    ->condition('field_promt_id', $location_id);
                $nids  = $query->execute();
                if ($nids) {
                    $vars['node'] = \Drupal::entityTypeManager()->getStorage('node')->load(current($nids));
                }
            }
        break;
    }
}


Phrase words matches anywhere in the multi fields and stemming also reduce the boosting on keyword stuffing

Question: Data Types

Title: string
Keywords: string
Description: string

Search Requirements:

ALL search terms MUST be found somewhere in the title or keywords or description

Don't search the whole DOCUMENT for terms… but search SEVERAL FIELDS to find a match for the terms.

All the fields don't need to contain all the search terms, but all the search terms must be found
EG: searching for "bake cake" should match:

title contains "cake" and description contains "bake" so that BOTH terms are found

Because atlas search grammar did not allow us to do that, we created a concat field: title + keywords into a NEW field
The biggest problem we have seems to follow from the fact that we cannot get a good AND clause on our search terms

"bake cake" should match "bake" AND "cake", instead, using Atlas search without our hacks we will get
"cake cake cake cake" and that ranks higher than "cake bake"!

Field boosting is important

Matching in the "title" should rank higher than matching in the "description"

Word order matters

"bake cake" should boost results where "bake" precedes "cake"
A perfect match is preferred

Keyword stuffing should be penalised.

After computing a score, the score should be un-boosted based on frequency of matching the search terms
"bake cake" should rank "bake a cake" HIGHER than "bake a cake bake a cake cake cake cake"

Shorter data should rank higher

"cake" as a search term should rank

"cake fun" higher than
"cake and fun and baking and frosting"
Because all else equal, the first string is SHORTER than the second string

Stemming matters (plurals in particular)

this currently does NOT work in our current implementation b/c we had to hack around Atlas to get proper AND matching for search terms

I have tried to achieve the above by using MongoDB Atlas, but have not been successfull. Hence I am  looking at alternatives such as ElasticSearch, Solr etc for the same. I am also open to evaluating any other similar platform as well.
Answer: Recommendations about a specific technology isn't well-suited for Stack Overflow, since they're usually limited to your specific use case. However, all you're asking for can be solved in Elasticsearch and Solr. I'll try to point you in the correct direction for each of your wishes in Solr.

You can do this by either using edismax with qf set to the fields you want to search (and you can then score hits in each field differently by using the field1^10 field2 syntax). You can also implement it by copying all the content from the fields you're interested in into a common field (usually named _text_ by default). This won't allow you to dynamically weigh hits from each of the fields differently.

Implemented through the weights given for qf.

Implemented by using pf/pf2/pf3 and ps/ps2/ps3 parameters, or by generating shingles when indexing as a spearate field and then using 1. or 2. to score that field differently.

You say penalized, but your description seems to indicate that you just shouldn't consider the number of terms. Be aware that this will reduce effectiveness of scoring larger texts, where a single mention of a term will be the same as someone mentioning the term in multiple paragraphs. Solr won't let you disable only termfreq when considering scoring, and since you want positions to be relevant you can't use the omitTermFreqAndPositions setting for a field. You can apply a negative boost (which usually is just a larger boost to those document that doesn't match) anything which have the query terms in quick succession after each other, but this will require manually tuning your queries and weights to get the results you're looking for. There is no automagic solution for this that is "smart".

Scoring will considers the length of the content in the field, and shorter content will be scored higher by default.

Stemming is configured on a per field basis, and you can use this to stem one field and not another, then index the same content into both fields (using a copy field instruction), and use 1/2 to apply different weights to the different fields.
Comment: Thanks for the response. You have shared some really helpful information regarding solr.
Answer: Ok, I came here because Meteor was tagged but I see this doesn't seem to be Meteor related. Anyway, I am not sure you mentioned the type of search you are trying to do.
This is about the type of searches: https://www.youtube.com/watch?v=-sRcpGpd-0s
I think you need search indexes (as opposed to DB indexes) and the Atlas search function. This might be what you are using, I am not sure from your post. Some good details are here: https://www.youtube.com/watch?v=-sRcpGpd-0s and there is also a more recent video which I can't find right now (Karen is the host of it). In this newer video released a month ago or so, Karen introduces this website which might help you in tuning your search indexes properly https://www.atlassearchsoccer.com/
Comment: ok, sorry to give you only links but the answer to this is pretty complex not really a yes / no or short opinion. This will help you to build your indexes for a correct matching of what/how you want to search for things. You have a search analyzer tool there that you will most probably need to use for building your indexes. https://www.mongodb.com/developer/products/atlas/analyzing-analyzers-build-search-index-app/  Ok, and I just found the video with Karen I was referring to above: https://www.youtube.com/watch?v=2oJuXx6mceE
Comment: Thanks for response and valuable links.


Is this cello distorted?

Question: So I've been listening to 2CELLOS and their cover of AC/DCs 'Thunderstruck'. Several times during the song they play with an unusual timbre. Bringing out some of the high frequencies and mechanical sounds you wouldn't usually hear from the cello in recorded music.
Here's an example, the melodic lines from this point:

I can't work out if this is an electronic distortion effect, a recording trick, or whether a cello could make this same kind of sound acoustically.
Are we hearing a (fairly subtle) distortion effect here? Or is this sound being produced another way?
Comment: Your link does not work.  Is the recording in question done when they're using acoustic or electric cellos?
Comment: Link is fine for me... & yeah, does sound like they've got a bit of amp-sim going on with it; but I couldn't say more for certain
Comment: @CarlWitthoft They are seen playing acoustic cellos, but they definitely have to for aesthetic purposes (it's music video set in, probably, the renaissance age). We might be hearing electric cellos, or the effect could have been applied to audio from an acoustic instrument.
Answer: To answer the question directly, yes: I do think there is some form of distortion used. My guess would be that they recorded the cellos with contact pickups as well as microphones, and the final mix is a blend of the more naturally acoustic mic'd tone and the rawer contact pickup tone. The contact pickup will pick up a lot more stray knocks, taps and upper harmonic content.
For the section that OP highlights in the video, it sounds like there is a sub-octave mixed in to the lead line (copying the original vocal line). In some sections it sounds like overt distortion, with a corresponding bass reduction, whereas in other sections it sounds more like heavy compression or limiting verging on 'brickwalling', with clipping in the signal. My guess is that a lot of production techniques went into producing this track!
As an aside I wince slightly seeing the state of those cello bows by the end of the video.
Comment: The frayed bows are something of a trademark for them. By the end of a live show they've destroyed several bows on stage.
Comment: Well, we bowmakers have to make a living, too.
Comment: All very true, but think of the horses!
Comment: You should see Charlie Daniels'  bow!
Comment: @ABragg You do know the horses can live quite comfortably without their tail hair, right? and that one tail can produce many bowstrings?
Answer: While it's not a standard distortion, there is definitely an effect there in the recording process.
Comment: Cellos played this way will sound grungy on their own, but I agree: it's been enhanced with reverb and probably how it's miked.

Is this cello distorted?


Expectation inequality

Question: Let $X, Y$ be random variables with $0 \leq X \leq Y$ and $\mathbb E[Y]=1$. Let $t>0$. Does the inequality
$$
\mathbb E[e^{tX}] \leq x\, \mathbb E[e^{tY}]+1-x
$$
where $x=\mathbb E[X]$ hold?
Comment: I think its true but I'm not sure where to start
Comment: well, it's true for sufficiently small $t$ since we can just make it small enough for the LHS to be less than 1-x. It is also true for large enough $t$ since then the difference between $Y$ and $X$ means the exponential in $Y$ dominates. The question is if it holds for all positive values of $t$.
Comment: I don't think it's for small t. If the moment-generating function exists, it should be continuous in t. Bringing all terms on one side and looking at RHS - LHS a continuous function of t, it is negative at $t=0$ for $X \neq Y$; hence, negative for small t. I'm so rusty I was lacking the confidence to post this as a counter; but I think it's not true.
Comment: That was @iMath...
Answer: This inequality does not hold in general. For example, take $X$ and $Y$ such that:

with probability $\frac{2}{3}$, $X = 0$ and $Y = \dfrac{1}{2}$,
with probability $\frac{1}{3}$, $X = 2$ and $Y = 2$.

In this case, the inequality would write:
$$
\frac{2}{3}+\frac{e^{2t}}{3} \leq \frac{2}{3}\left(\frac{2e^{t/2}}{3} + \frac{e^{2t}}{3}\right) + 1 - \frac{2}{3}
$$
As $t$ tend to $+\infty$, this would lead to $1 \leq \frac{2}{3}$, wich is of course absurd.

However, it can be made true under certain hypotheses: namely, if we assume that $X = ZY$ (hence $0 \leq Z \leq 1$) where $Z$ is independent of $Y$.
The convexity of the function $\exp$ then gives:
$$
e^{tX} = e^{t(Z\times Y + (1-Z)\times 0)} \leq Z e^{tY} + (1-Z)e^0
$$
for every $t > 0$. Taking the expectations, the independence gives
$$
E(e^{tX}) \leq x E(e^{tY}) + 1 - x
$$
since $x = E(YZ)=E(Z)\times 1$.
Comment: Brilliant, thanks.
Answer: By series expansion $e^{tX} = 1 + tX + \frac{t^2X^2}{2!} + \frac{t^3X^3}{3!} + \cdots +\frac{t^nX^n}{n!} + \cdots.$
$M_X(t) = E(e^{tX}) = 1 + tm_1 + \frac{t^2m_2}{2!} + \frac{t^3m_3}{3!}+\cdots + \frac{t^nm_n}{n!}+\cdots$
Thus, $E(e^{tX}) > 1+tE[X]$ and hence $E(e^{tX})>1+tx$ since $E[X]=x$.
Similarly, $E(e^{tY})>1+t$
Now,
\begin{eqnarray}
 xE(e^{tY})+1-x &>& x(1+t)+1-x      \nonumber \\
   &>& x+tx+1-x \nonumber \\
   &>&1+tx \nonumber \\
   &>& E(e^{tX})
\end{eqnarray}
Since $X\leq Y$, thus, $E(e^{tX})\leq E(e^{tY})$ and hence the inequality follows.
Comment: There seems to be a mistake in the last inequality: you know that $E(e^{tX}) \geq 1 + tx$ but you use the reversed inequality.

Expectation inequality


What constitues algebraic competency?

Question: A bit of background to my question: last year I signed up for a refresher course in Maths at a university, because I seem to have forgotten most of what I learned in school about Maths but feel interest and need to get better at Maths though.
I take a course grouped into various segments. At the end of that (probably) multi-year journey stands the option to continue the course and study Maths at university level (to go for an associates degree or bachelor.)
In higher courses we will learn Calculus (which I never learned in school) and of course other advanced subjects. I read feedback from other students that being "algebraic competent" is very important to grok the more advanced topics, I also read on this website for example that "algebraic competency" is very important for Calculus and the lack thereof is often cause for struggling later on.
So, what would that "algebraic competency" be? Being able to manipulate even complex equations with ease? Or … something else? And how can I learn it?
Since this is my second try at the subject of Maths, and I also have more resources available to me than when I was young, I now have the option to already learn more about subjects that I can see will give me trouble later on.
Comment: The best people to ask are the math faculty at the university you are dealing with.
Answer: From my experience, Calculus teachers will expect you to know how to do some "basic algebra". They might give you a quick refresher at the start of the first semester but if at that point things are still fuzzy, you will feel that the course is heavy and hard to follow. So for example, being able to:

Isolate a variable ($2x+1=3x\Rightarrow x=1$)
Know your exponent and log laws
Know basic math symbols and notation such as $\mathbb{R}$, $\Rightarrow$, $\infty$, etc.
Knowing what a function is and their properties
Know your basic functions, their domains, ranges and graphs (not quite algebra but still useful)
Knowing vocabulary such as "constant", "variable", "factor", "polynomial", "degree", "term", etc.
Being able to use factorisation (of polynomials)

will all come in handy. You don't have to know everything from the start, but the more proficient you will be with this, the more smoothly Calculus will go.
Let me give you an example. In the first Calculus course, you will have to calculate limits like one:
\begin{equation}
\lim_{x\rightarrow\infty}\dfrac{x^2-x}{x-1}
\end{equation}
In order to do this, you have to see that $x^2-x=x(x-1)$ which will allow you to cancel out the $x-1$ on the numerator and denominator and get to the final answer (which is $\infty$). But if you are not used to do factorization, your eye might not see it and you might get stuck on the problem longer than normal (as in someone who is "algebraically competent").
The list I gave you already covers a lot but probably isn't complete. It's a good place to start.
Comment: would you say multivariable calculus is part of algebraic competency?

What constitues algebraic competency?


What is a babel preset? What does stage mean?

Question: What is a babel preset and why do I need it?
There are several questions about specific babel presets but none explain the need for it (e.g. what's the difference between babel-preset-stage-0, babel-preset-stage-1 etc)
Also the babel docs do not explain the necessity: https://babeljs.io/docs/plugins/preset-latest/
Answer: Babel Presets:

Technically presets are collections of plugins (as Quentin says)
The usecase is the support of particular language features.

Read this excellent post: https://www.fullstackreact.com/articles/what-are-babel-plugins-and-presets

A preset is a set of plugins used to support particular language features.
The two presets Babel uses by default:

es2015: Adds support for ES2015 (or ES6) JavaScript
react: Adds support for JSX

... ES2015 is just another name used for ES6 ... [1]

Preset stages:
Stages represent the status of experimental features. Pre stage-3 should be used with caution.

... Beyond ES7, proposed JavaScript features can exist in various stages: [1]
stage-0 - Strawman: just an idea, possible Babel plugin.
stage-1 - Proposal: this is worth working on.
stage-2 - Draft: initial spec.
stage-3 - Candidate: complete spec and initial browser implementations.
stage-4 - Finished: will be added to the next yearly release. [2]

[1] https://www.fullstackreact.com/articles/what-are-babel-plugins-and-presets
[2] https://babeljs.io/docs/plugins/
Answer: From the docs:

Presets are sharable .babelrc configs or simply an array of babel plugins.

Babel is a tool for transforming JS.
A plugin a some code for performing a particular transformation.
You have to specify which plugins you want to use with a config.
A preset is just a prewritten config you can use to get common sets of transforms.


Find a generating function for unlabeled graphs

Question: Let's take a graph(undirected) of $m$ edges and $3$ vertices. Now I want to derive a polynomial for which the coefficient of $x^m$ denotes the number of unlabeled graphs of $m$ edges.
How to derive the polynomial in this case? Also is deriving a polynomial means deriving a generating sequence?
Answer: Here we require the cycle index of the action on the edges of the
symmetric group  $S_3$ on the vertices. We find:

 The identity: $a_1^3.$
 Three reflections: $3 a_1 a_2.$
 Two rotations: $2 a_3.$

We get for the cycle index
$$Z(G_3) = \frac{1}{6} ( a_1^3 + 3 a_1 a_2 + 2 a_3 ).$$
Evaluate at $1+z$ for the generating function:
$$Z(G_3; 1+z) = \frac{1}{6}
((1+z)^3 + 3 (1+z) (1+z^2) + 2 (1+ z^3))
\\ = \frac{1}{6}
(1+3z+3z^2+z^3 + 3+3z^2+ 3z + 3z^3 + 2+2z^3)
=  1 + z + z^2 + z^3.$$
This means there is one graph on three vertices taking into account
ismorphisms having  zero, one, two and three edges.

The general case is described and implemented at the following MSE
link.


Can't get any Javascript file working properly in blazor

Question: relatively new to blazor..
I have been using MVC, and webforms but made a dive into blazor and .net core...
What a pain it has been so far from start to finish... Anyway my issue...
I am trying to follow this codepen, typewriter text `https://codepen.io/hckkiu/pen/KKzgEMr`

Very easy to implement anywhere but blazor... So i have my CSS and javascript file loading correctly but the output is never there..

Can anyone tell me why its not loading / blazor / c#
The javascript is blinking but no text continuation.

            I'm a

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

    typing(0, $('.typewriter-text').data('text'));

    function typing(index, text) {

        var textIndex = 1;

        var tmp = setInterval(function () {
            if (textIndex < text[index].length + 1) {
                $('.typewriter-text').text(text[index].substr(0, textIndex));
                textIndex++;
            } else {
                setTimeout(function () { deleting(index, text) }, 2000);
                clearInterval(tmp);
            }

        }, 150);

    }

    function deleting(index, text) {

        var textIndex = text[index].length;

        var tmp = setInterval(function () {

            if (textIndex + 1 > 0) {
                $('.typewriter-text').text(text[index].substr(0, textIndex));
                textIndex--;
            } else {
                index++;
                if (index == text.length) { index = 0; }
                typing(index, text);
                clearInterval(tmp);
            }

        }, 150)

    }

});

CSS
bodys {
    width: 100%;
    height: 100%;
    background-color: #3a3a3a;
}

.containers {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;
}

.typewriter {
    font-family: sans-serif;
    color: black;
    padding-left: 30px;
    display: block;
}

.typewriter-text {
    padding-right: 10px;
    color: red;
    border-right: solid #ffe509 7px;
    text-transform: uppercase;
    animation: cursor 1s ease-in-out infinite;
    font-weight: bold;
}

@keyframes cursor {
    from {
        border-color: #ffe509;
    }

    to {
        border-color: transparent;
    }
}

@media (max-width: 767.98px) {
    .typewriter {
        font-size: 35px;
    }
}

@media (min-width: 768px) {
    .typewriter {
        font-size: 60px;
    }
}

Answer: glad to see you are trying out Blazor!
The first lesson should be - Don't try to do everything in JavaScript. Take what you want to do and translate it to Blazor. Using JS libraries and components is an advanced topic - start with plain C# Blazor - Blazor University is a good resource.
Here is a working repl : https://blazorrepl.com/repl/GOvEwjOY58lmz0ao15
and the code for that - there is no JavaScript required for this in Blazor.
Note: in the real world you would make this implement IDisposable and use a cancellation token to cancel the long running Task

I'm a
      @typewriterText

    @code {
        string[] jobs = { "photographer. ", "designer. ", "developer. " };
        string typewriterText;
        Task worker;
        protected override void OnInitialized()
        {
            worker = Typewriter();
        }
        async Task Typewriter()
        {
            var index = 0;
            while(true)
            {
                var textIndex = 1;

                while( textIndex < jobs[ index ].Length + 1 )
                {
                  typewriterText = jobs[ index ].Substring( 0, textIndex );
                  textIndex++;
                  StateHasChanged();
                  await Task.Delay(150);
                };

                StateHasChanged();
                await Task.Delay(2000);

                textIndex = jobs[ index ].Length;

                while ( textIndex + 1 > 0 )
                {
                    typewriterText = jobs[ index ].Substring( 0, textIndex );
                    textIndex--;
                    StateHasChanged();
                    await Task.Delay(150);
                };

                index++;
                if ( index == jobs.Length )
                {
                    index = 0;
                }
            }
        }
    }

Comment: Thank you so much Mister Magoo. I never thought about doing it in code... Appreciate your help!!
Answer: You will have to call the javascript after your component/page is rendered, $(document).ready will not help in this case as the component might be rendered after the page load.
See below example to call the javascript that will then do the functionality that you want:
In your component:
@inject IJSRuntime JSRuntime;

// or

[Inject] protected IJSRuntime JSRuntime { get; set; }

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("startTyping");
    }
}

Javascript file:
window.startTyping = () => {
    typing(0, $('.typewriter-text').data('text'));
    // other js code here
}

See here for reference: https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
Comment: Thanks for your comment @Umair i tried your version but i get errors in my javascript. Could you post how my javascript file should look. Maybe i have done this wrong after imputting the window.startTyping ... I also got interop error saying window is not defined


close_fds=(name == 'posix')

Question: I was reading through some code on subprocesses and came accross this line
proc = Popen(
            cmd.split(), stderr=stderr, stdout=stdout,
            close_fds=(name == 'posix'), cwd=self.path, **kwargs)

the first few args are pretty self explanatory but I couldn't understand what the
close_fds=(name == 'posix')

part does. Could someone explain how close_fds works and what the ( name == 'posix') returns?
Also name isnt declared anywhere in the scope.
Thanks.
Answer: name == 'posix' evaluates to either True or False depending on whether name is 'posix'. Then this True or False becomes the value of the close_fds parameter to Popen. Basically, it's a way of providing a bit of platform-specific customization: on Windows the file descriptors won't be closed before the command is executed, while on UNIX-like OSs (including Mac OS X and Linux) they will be. This is due to the difference in behavior of this option on the two platforms. See the subprocess.Popen docs for more on this argument.
name is defined somewhere or you'd get a NameError. It might be a global, potentially imported from another module using a wildcard import (from xxxx import *).
Comment: +1  Indeed, it is [`os.name`](https://github.com/klen/dealer/blob/fefb10b889fcf109eee3d9841924f516141f3a36/dealer/git.py).
Comment: upon further examination @pilcrow is right. `os.name` has been imported.

close_fds=(name == 'posix')


Setting up a small DHCP server for small network on windows server 2003

Question: I am trying to set up a DHCP server on a Windows 2003 machine for a small network. I have used this guide[http://www.windowsnetworking.com/articles_tutorials/dhcp_server_windows_2003.html] to setup the DHCP server, windows is now showing me that this is now a configured role.
My question is there anything I need to do after the steps mentioned in guide. I have connected the server machine and the 3 machine i want to make a network with to a linksys router, all connetions are working but none of my machines are getting assigned an IP, I am also unable to ping the server machine.
Comment: Why deploy a new Server 2003 box this late in its lifecycle?  If at all possible, you shouldn't be using anything older than Server 2008 R2.
Answer:
You may need to authorize the DHCP server if you haven't already
If there's a DHCP server on the LinkSys router, you'll need to turn it off
Make sure your server has a static IP address
Ensure that you've bound your DHCP server to the correct NIC
Make sure your server's firewall is not set to block DHCP requests
Issue an ipconfig /renew on one of your clients to force it to try and pick up an address from DHCP.


Is it ok to release a demo EP with average quality on Spotify?

Question: My rock band was recording a Demo EP with a friend of a member of the band. This friend lost his job and house and left the country before he had a chance to mix and master the tracks. And he didn't give us a copy of the individual tracks to master. So we're pretty much stuck with OK recordings. They're not terrible, but they're not fantastic either.
We've invested a lot of time on this, and I'd like to release it onto Spotify, iTunes, etc... We're just starting to try to get our name out there, and I believe that having SOMEthing (even if it isn't amazing.) to show people is better than nothing. Some people in the band believe that it is better to have an amazing album to wow people. Because if peoples' first impression of us is that we suck, then we wouldn't be able to win those people as fans. I think the recordings are good enough to distribute.
Is it considered good industry practice to only release and distribute "polished music"? Or is it ok for an artist to release and distribute an average quality album?
Its easier to listen to music, rather than talk about it. Here's a couple of tracks off this EP that I want to release:
www.eighthDaySlc.com
Thank you!
Comment: Well, mastering is a process you do on the mixed down stereo tracks. So that's something you still can do in order to improve the sound. If you're happy with your performance and the sound isn't horrible, put it out there. Try to get some honest opinions from your friends before if you're not sure.
Comment: Is the album of the quality of "Whats the Point?" or "Breaking Free"?
Comment: Yes it is @Eichhörnchen.
Comment: Yes? Uh... The tracks sound very different, which does it sound more like? haha
Comment: And you're right @Meaningful Username. We can master ourselves. Thank you for your comment.
Comment: @Eichhörnchen, sorry! I didn't see your `or`. It would sound more like **Whats the Point**. Although **Breaking Free** is supposed to be part of the same release. It might sound different because we did the vocals ourselves on **Breaking Free**
Answer: Think about what you want with your band. Are you looking to go and tour the world? Are you looking to play local clubs while you're all working? Something in between?
Next, consider how important this album is to your goal. If this is just a demo, it's probably alright to release, and if you're constantly writing and will have something new next year that will show development as a band, then your album is also probably ok for now.
I live in LA and I play in a few bands. The hardest thing for us is that there is an incredible amount of competition everywhere. We may be good, but there are so many more groups out there who can shred twice as hard as us. Additionally, as far as live music goes, people can go and see their favorite bands everywhere at any time: why would they bother going out to see my band? Therefore, a great sounding album and a noticeable social media presence is the best (and I would maybe even say only) way to gain interest in your music because, quite frankly, people besides your friends and family will be too lazy to go and see you play at a bar even if your album sounds professional and up-to-par with "industry standards".
So, here's a couple of things I noticed. The song What's the Point sounds decent. I would say it's totally releasable, but there are a few weird moments with the drums that you may want to fix. If people hear a boo-boo in the drums on the album, how might that effect their perception of you? how might they think it sounds when you play live? The song was a little empty too, I might on the recording do some guitar doubling and maybe increase the bass frequency range. I might also suggest a greater dynamic range in guitar tone. In the solo it sounds good, but in some of the other parts, it could be a little less distorted. The song Breaking Free sounds a little more demo-y than the first as well. You should be able to ask your friend for the stems to your production if you want to keep working on them. He can send them from anywhere in the world he has wifi.
So these were just some thoughts, just think about how nowadays your music is kind of like a marketing tool to encourage people to come to your live show. Think about all the bands in the world you are up against right now, and work towards the best product you can possibly produce. Good Luck!
Answer: Once your music hits the public domain, it no longer belongs to you It belongs to your fans. Even if you do label it as a DEMO and release a good studio version later, some fans will prefer the DEMO.
If your putting something in the public domain for all to see, its needs to be completed to a quality you all satisfied with as a band. If you release something half baked you will always be making excuses about how good it "could be" instead of just doing it.


Finding euler cycle

Question: I have an application which creates graph with an Euler cycle. My second application is for finding Euler cycle.
Creating Euler cycle:

Create a cycle e.g. 3->6->5->2->0->1->4->3 because Euler cycle should be connected graph
Then creating random edges.
Saving graph to file.

Finding Euler cycle is based od DFS.
Finding Euler cycle works for 100,200,300 nodes. When it's e.g. 500, application don't show Euler cycle. If you have any suggestions, what should I change in code, post it.
Here is a code for creating graph with Euler cycle:
#include<iostream>
#include<vector>
#include<algorithm>
#include<vector>
#include<ctime>
#include<cstdlib>
#include<list>
#include<stack>
#include<ctime>
#include<fstream>
using namespace std;

    bool matrix[1500][1500];
int main()
{
    srand(time(0));
    ofstream zapis;
    zapis.open("graph cycle euler.txt");

vector<int> cycle;
    //bool macierz[500][500];
    int N, density;
cout<<"N and density: "<<endl;
cin>>N>>density;

    for (int i = 0; i<1500; i++)
    {
        for (int j=0; j<1500; j++)
        {
            matrix[i][j]=0;
        }
    }

for (int i = 0; i<N; i++)
{
    cycle.push_back(i);
}

random_shuffle (cycle.begin(), cycle.end());

matrix[cycle[0]][cycle[cycle.size()-1]]=1;
matrix[cycle[cycle.size()-1]][cycle[0]]=1;

for (int i=0; i<cycle.size()-1; i++)
{
    matrix[cycle[i]][cycle[i+1]]=1;
    matrix[cycle[i+1]][cycle[i]]=1;
//    cout<<cycle[i]<<" "<<cycle[i+1]<<endl;
}

int randnumber, randnumeber2,randnumber3;

//ile=ile-2*N;
int howMany=0;
for (int i=0; i<N; i++)
{
    howMany=howMany+i;
}
howMany=howMany*60/100-N;

while(howMany>=0)
{

    randnumber=rand()%N;
    randnumeber2=rand()%N;
    randnumber3=rand()%N;

    if((matrix[randnumber][randnumeber2]==0) && (matrix[randnumeber2][randnumber3]==0) && (matrix[randnumber][randnumber3]==0) && (randnumber!=randnumeber2) && (randnumber!=randnumber3) && (randnumeber2!=randnumber3))
    {
        matrix[randnumber][randnumeber2]=1;
        matrix[randnumeber2][randnumber]=1;
        matrix[randnumeber2][randnumber3]=1;
        matrix[randnumber3][randnumeber2]=1;
        matrix[randnumber][randnumber3]=1;
        matrix[randnumber3][randnumber]=1;

        howMany=howMany-3;
    }
}

int M=0;
for (int i=0; i<N; i++)
{
    for (int j=0; j<N; j++)
    {
        if(matrix[i][j]==1)
        M++;
    }
}

zapis<<N<<endl<<density<<endl<<M<<endl;

for (int i=0; i<N; i++)
{
    for (int j=0; j<N; j++)
    {
        if(matrix[i][j]==1)
        zapis<< i <<" "<< j<<endl;
    }
}

}

End here is my code for finding Euler cycle.
#include<iostream>
#include<vector>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include<list>
#include <stack>
#include<fstream>
using namespace std;

int s;
list<int> L[3000];
stack<int> stos;
void dfs (int v)
{

while (!L[v].empty())
    {

        int x=L[v].front();
        L[v].pop_front();
        for (list<int>::iterator y=L[x].begin(); y != L[x].end(); y++)
            if (v==(*y))
            {
                L[x].erase(y); break;
            }
    dfs(x);
    }
stos.push(v);
}

int main()
{
    ifstream odczyt;
    odczyt.open("graph cycle euler.txt");
int N, gestosc, m;
odczyt>>N>>gestosc>>m;

int w1,w2;
for (int i=0; i<m; i++)
{
    odczyt>>w1>>w2;
    L[w1].push_back(w2);
    //L[w2].push_back(w1);
}

int start=0;

dfs(start);

    while(!stos.empty())
    {
        cout<<stos.top()<<" ";
        stos.pop();
    }
}

Comment: Euler cycle visits all edges. Are you confusing it with the Hamiltonian cycle?
Answer: The application does not show or keeps computing? I am guessing your program with 500 is running forever due to if((matrix[randnumber][randnumeber2]==0) && (matrix[randnumeber2][randnumber3]==0) ... this condition is not true for the random numbers generated and thus howMany is not decremented, and the loop continues for a long time.
I am not sure what logic you are using for creating the graph. If the degree of all vertices is even, euler cycle will always exist in the graph. You have lot of random in your code, which may take a while.
You really do not need to do all the DFS and other things you have done to find euler cycle. Here is a simple logic:
-- Check to make sure degree of all vertices is even. If not, Euler cycle does not exist. The proof is pretty straightforward and left as an exercise :)
"As a generalization of the Königsberg bridge problem, Euler showed (without proof) that a connected graph has an Eulerian cycle iff it has no graph vertices of odd degree." --- http://mathworld.wolfram.com/EulerianCycle.html
-- Pick any vertex and keep traversing any edge incident on the vertex, which has not been traversed earlier. Keep traversing.....Eventually you will end up with the euler cycle, when all your edges have been traversed.
Please note that this is not same as hamiltonian cycle problem which is NP-C. Finding Euler cycle is polynomial, O(E), since you will be traversing every edge just once.
Comment: program creating my graph is working. Program finding Euler cycle doesn't work. I showed these program because it can help to advice.
Comment: you really dnt need to do `dfs`. just keep randomly walking the graph and you will be fine. it will be much easier to code also. I am guessing when you have 500 nodes, your code is taking too long to compute, since it works for smaller inputs.

Finding euler cycle


Another OPTIMIZING macro vba code for excel 2007. the code is a sort of transposer for my data

Question: Hello this code was not done by me originally and there are some thigns here i dont quite understand i have altered it a bit from my coworkers code to suit my data and it works. but too slow.  and when i have 4000+kb excel files it might freeze altogether. ( I have checked tho that when and after this transposer runs it will still be within the excel row limit, i had done calculations before and made a macro to automatically split excel files based on number of columns and rows to make sure this is so ). This code seems to start out fast then goes slower the longer it runs. at least this is what it seems liek to me.
Feel free to suggest any ways to make this code faster/better! Thank you for your time.
Sorry that I dont understand this code super well.
i have turned off screen updating, automatic calculation, etc etc.
Dim InitRange As Range
Dim Counter As Range
Dim paracount As Long
Dim Filler As Range
Dim ParaSelect As Range
Dim Paraloc As Range
Dim Paravalloc As Range
Dim Unitloc As Range
Dim methodloc As Range
Dim CurNum As Long
Dim MaxNum As Long
Dim eCell As Range
Dim checkRow As Long
Dim InsertRow As Long
Dim x As Long
Dim y As Long
Dim vRow As Long

CurNum = 0
MaxNum = 0

x = 1

Range("K1").End(xlToRight).Offset(0, 0).Select

Set ParaSelect = Range("K1", ActiveCell)
InsertRow = ParaSelect.Count - 1

Set InitRange = Range("A4", "F4")
Set Counter = InitRange

Do
MaxNum = MaxNum + 1
InitRange.Offset(MaxNum, 0).Activate
Loop Until ActiveCell = ""

Set eCell = InitRange.Offset(0, 0)

Do
eCell.Offset(x, 0).Activate
Rows(eCell.Offset(x, 0).row & ":" & eCell.Offset(x, 0).row + InsertRow - 1).Insert
x = x + InsertRow + 1
If x > MaxNum * (InsertRow + 1) Then Exit Do
Loop

Range("A1").Activate

Set Filler = InitRange

Set Paraloc = Range("G4")
Set Paravalloc = Range("H4")
Set Unitloc = Range("I4")
Set methodloc = Range("J4")

vRow = 0
y = 0
Do

ParaSelect.Copy
Paraloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

ParaSelect.Offset(1, 0).Copy
methodloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

ParaSelect.Offset(2, 0).Copy
Unitloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

ParaSelect.Offset(CurNum * (InsertRow + 1) + 3, 0).Copy
Paravalloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

Filler.Offset(y, 0).Copy
CurNum = CurNum + 1
y = y + 1
checkRow = 1
Do
Filler.Offset(y, 0).PasteSpecial xlPasteValues
y = y + 1
Filler.Offset(y, 0).Activate
checkRow = checkRow + 1

Loop Until checkRow > InsertRow
Loop Until CurNum >= MaxNum

Jon made a good suggestiong >.> i should defiantely provide something to show you guys what this code is about.  Picture 1 is what the file looks like before it is transposed

Picture 2 is what the files looks like after it is transposed. No worries column k and after will be deleted.
NOTE:  The files may have any number of columns and rows
Comment: So your just taking the data from column k and over and putting them into rows for the each object ID? Looks fairly simple. I'll throw something together real quick for you. Hopefully you're learning something from my code writing.
Comment: For sure i am learning lots. I at least have an idea how to utilize arrays now and how they work! =)
Answer: The primary reason this code is slow is all the cell references in the loops. It would run much faster if you copied the data to a variant array and work on that.
Steps you should follow:

Work out the source data range, and set a Range variable to that
Dim rngData as Range
Set rngData = Your Source Range

Copy the data
Dim varSource as Variant
varSource = rngData

Calculate the size of the destination data and Dim a variant array to that size
Dim varDestn() as variant
Redim varDestn(1 to NumberOfRows, 1 to NumberOfColumns)

Calculate the new data.  Copy values from varSource(row,col) to varDestn(row,col)

Delete the original data (if required)

Put the new data on the sheet
Set rngData = Cells(1,1) _
.Resize(UBound(varDestn,1), UBound(varDestn,2)) _
.Offset(TopLeftCellRow, TopLeftCellCol)
rngData = varDestn

In general keep the number of references to the worksheet to a minimum, especially in loops
Comment: What is advanced to one person can be bread and butter to another.  There are many answers here on SO that address use of this method google will produce many more.  If you get stuck trying to use this method, post another question
Comment: Chaostryder, this is basically what I did in the code I just added. For people that program a lot in VBA I would think it would be pretty normal to use arrays, but for beginners it is something you normally stumble onto on the net since Excel doesn't produce this type of code when you record a macro.
Comment: Thanks Chris. Just a question: is this considered mroe advanced coding?  I've been doing some excel coding for about a month now or so and I've never touched arrays etc yet. i will be sure to google this up tho. sounds very promising. May i ask you if i run into problems?
Answer: It's hard for me to figure out exactly what you are trying to do here without the actual workbook. So I did my best, hopefully there are no errors. If I had the actual workbook or an example I could probably get you a really nice optimized code. Here's my first pass:
    Dim InitRange As Range, Counter As Range, Filler As Range, ParaSelect As Range, Paraloc As Range
    Dim Paravalloc As Range, Unitloc As Range, methodloc As Range, eCell As Range
    Dim paracount As Long, CurNum As Long, MaxNum As Long, checkRow As Long, InsertRow As Long
    Dim x As Long, y As Long, vRow As Long

    CurNum = 0

    x = 1

    Set ParaSelect = Range("K1", Range("K1").End(xlToRight))
    InsertRow = ParaSelect.Count - 1

    Set InitRange = Range("A4", "F4")
    Set Counter = InitRange

    MaxNum = InitRange.Resize(1, 1).End(xlDown).row - 4

    Set eCell = InitRange

    'Not sure what you are trying to accomplish here so I'll the original code (except for non essential code.
    Do
        Rows(eCell.Offset(x, 0).row & ":" & eCell.Offset(x, 0).row + InsertRow - 1).Insert
        x = x + InsertRow + 1
        If x > MaxNum * (InsertRow + 1) Then Exit Do
    Loop

    Set Filler = InitRange

    Set Paraloc = Range("G4")
    Set Paravalloc = Range("H4")
    Set Unitloc = Range("I4")
    Set methodloc = Range("J4")

    vRow = 0
    y = 0

    Do

        ParaSelect.Copy
        Paraloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

        ParaSelect.Offset(1, 0).Copy
        methodloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

        ParaSelect.Offset(2, 0).Copy
        Unitloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

        ParaSelect.Offset(CurNum * (InsertRow + 1) + 3, 0).Copy
        Paravalloc.Offset(y, 0).PasteSpecial xlPasteValues, Transpose:=True

        Filler.Offset(y, 0).Copy
        CurNum = CurNum + 1
        y = y + 1
        checkRow = 1
        Do
            Filler.Offset(y, 0).PasteSpecial xlPasteValues
            y = y + 1
            checkRow = checkRow + 1
        Loop Until checkRow > InsertRow
    Loop Until CurNum >= MaxNum

OK, this should be pretty efficient. Make sure you test it first, don't know if I got any of my offsets off at all.
Sub TransposeIt()

    Dim i As Long, j As Long, k As Long
    Dim rData As Range
    Dim sData() As String, sName As String
    Dim wks As Worksheet
    Dim vData As Variant

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    'Initialize worksheets
    Set wks = ActiveSheet

    'Get data
    Set rData = wks.UsedRange
    vData = rData
    ReDim sData(1 To 10, 1 To rData.Columns.Count - 10)
    rData.Offset(1).Clear
    rData.Offset(10).Resize(1).Clear

    For i = 1 To UBound(vData)
        For j = 1 To UBound(sData)
            For k = 1 To 6
                sData(j, k) = vData(i, k)
            Next k
            sData(j, 7) = vData(1, j + 10)
            sData(j, 8) = vData(i, j + 10)
            sData(j, 9) = vData(3, j + 10)
            sData(j, 10) = vData(2, j + 10)
        Next j
        'Print transposed data
        wks.Range("A" & Application.Rows.Count).End(xlUp) _
           .Offset(1).Resize(UBound(sData), UBound(sData, 2)) = sData
    Next i

    Application.ScreenUpdating = True
    Application.EnableEvents = True

End Sub

Comment: Let me know if you liked the new one I added. It should go lightning fast compared to what you were doing before. Granted I might have made a few mistakes so you might have to step through to get all the numbers right.
Comment: Sorry, didn't see this 'til this morning. Posters on stackoverflow are super fast, I have a hard time keeping up with them. But it looks like they took care of you well. Let me know if you have any other questions about what the code does or any errors, don't know if I'll respond fast enough but people seem to know how to do it well.
Comment: Hey jon i have added two pictures to decribe sorta what the code does see if they help! . im currently trying ur code on some of the alrger files to see if it works. but i think its still takign quite a while.  Is there any more efficient way to work with this code?
Comment: I'll take a look. It was pretty difficult to do without seeing what was actually going on.
Comment: Please ntoe taht the files may have any number of columns and rows.   thanks jon ur a true sport. and i think this question might be a more difficult/take time because no one else has attempted it yet
Comment: Hey Jon it works! for the most part and super fast thanks! jsut need to step thru and yes, change a number or two
Comment: Good to hear. I probably should have copied the data down and got it work myself, but you'll be able to figure that out. Good luck with your future projects!
Comment: hey Jon,  would u mind taking a look at this post http://stackoverflow.com/questions/7420510/excel-2007-vba-macro-error-9-subscript-out-of-range
Comment: ya no problem thank you jon. and it works great and shouldnt have problems frm here on because i already used it to process my data and handed that in lol


How to control start and stop video streaming from ESP32-CAM?

Question: I'm using ther ESP32-Cam and have started to play around with the ESP32-CAM Example 2 : Live Video Streaming Server application which works great.
I'm interested in starting and stopping the stream not by command from the client (via Start Stream/Stop Stream button in browser) but I want to control the Start/Stop option from the ESP32 directly.
I could just call WiFi.disconnect(false, false); to stop the stream but it's not great (if there was other data transmission going on as well) and a call to WiFi.reconnect(); won't automatically resume the stream either. How can this be done?
Answer: Append the following code to the end of app_httpd.cpp:
void stopCameraServer(){
  if (camera_httpd != NULL) {
    httpd_stop(camera_httpd);
  }

  if (stream_httpd != NULL) {
    httpd_stop(stream_httpd);
  }
}

And add this at the top of CameraWebServer.ino:
void stopCameraServer();

Then you could stop the HTTP server by calling stopCameraServer()


How to derive this frequency response?

Question: Given this difference equation $y(k)$ ...
$$y(k) = \frac{1}{K^2} \sum_{m = k-K+1}^k \; \sum_{n = m-K+1}^m x(n) - \frac{1}{L^2} \sum_{m = k-L+1}^k \; \sum_{n = m-L+1}^m x(n)$$
... how does one derive this frequency response $H(f)$?
$$H(f) = \frac{1}{K^2} \left( \frac{\sin{\pi f K}}{\sin{\pi f}} \right)^2 e^{-2j\pi f(K-1)}  -  \frac{1}{L^2} \left( \frac{\sin{\pi f L}}{\sin{\pi f}} \right)^2 e^{-2j\pi f(L-1)}$$

My (attempt at) derivation, using only the first lowpass filter of $y(k)$:
$$\sum_{m = k-K+1}^k \; \sum_{n = m-K+1}^m x(n) = \\
\left[x(k-2K+2) + x(k-2K+3) + \dots + x(k-K+1) \right] +\\
\left[x(k-2K+3) + x(k-2K+4) + \dots + x(k-K+2) \right] +\\
\cdots +\\
\left[x(k-K+1) + x(k-K+2) + \dots + x(k) \right] =\\
\left[ x(k-2K+2) + 2x(k-2K+3) + \cdots + (K-1)x(k-K+1) + \cdots + 2x(k-1) + x(k) \right]$$
Applying $Z$-transform, we get
$$X(z) \left[ z^{-2K+2} + 2z^{-2K+3} + \cdots + (K-1)z^{-K+1} + \cdots + 2z^{-1} + 1 \right]$$

Now, if the above is correct, then the question boils down to how can this
$$\left[ z^{-2K+2} + 2z^{-2K+3} + \cdots + (K-1)z^{-K+1} + \cdots + 1 \right]$$
when evaluated on the unit circle $z=e^{j2\pi f}$, be equal to this?
$$\left( \frac{\sin{\pi f K}}{\sin{\pi f}} \right)^2 e^{-2j\pi f(K-1)}$$
Answer: Note that $$\left[ z^{-2K+2} + 2z^{-2K+3} + \cdots + (K-1)z^{-K+1} + \cdots + 1 \right]$$ is
$$\left[ z^{-K+1} + z^{-K+2} + \cdots + z^{-1} + 1 \right]^2$$
which is
$$\left[ \frac{(z^{-K}-1)}{(z^{-1}-1)}\right]^2$$
$$=\left[ \frac{(z^{-K/2}-z^{K/2})/z^{K/2}}{(z^{-1/2}-z^{1/2})/z^{1/2}}\right]^2$$
$$=\left[ \frac{(z^{-K/2}-z^{K/2})}{(z^{-1/2}-z^{1/2})}\right]^2 z^{-(K-1)}$$
which for $z=e^{j2\pi f}$ is
$$\left( \frac{\sin{\pi f K}}{\sin{\pi f}} \right)^2 e^{-2j\pi f(K-1)}$$
Comment: So "obvious" in hindsight. One slight correction: the $z^{-(K-1)/2}$ outside angle brackets should really be just $z^{-(K-1)}$.
Comment: Not obvious at all! I actually didn't know how to square a large multinomial like that; I had to play with it for a while. I don't know why they never teach these things... I fixed the mistake. Thanks for catching it!

How to derive this frequency response?


Why doesn't Flink dashboard show the number of records received from the source or written to a sink?

Question: The Flink dashboard is great and shows a lot of details for jobs that are running. One thing I have noticed, however, is that the source and sinks of a job will show the records received and records sent as 0 respectively.
Now I know that they are still receiving and sending records to and from outside of the job, but that 0 tends to be very confusing to people. Is there a reason why this was chosen to be like this? Or a way make it not be 0?
For sinks in particular, if the serialization schema fails to serialize a message (and the error is captured and logged instead of causing the job to fail) you can't see the number the sink has actually output to reflect this. You just always see 0 and would assume everything made it through.
Answer: The reason is that we can't measure this in a generalized fashion and have to implement the measuring in each source/sink respectively for which we just haven't found the time yet. Another issue is that this would have to be done within user-defined functions, but the relevant metrics are not accessible from there (yet).
See https://issues.apache.org/jira/browse/FLINK-7286.
Comment: It still needs every source/sink to participate, which is being slowly rolled out afaik.
Comment: Do we have any solution on this yet ? I have tested on current latest flink version 1.15.1 and still, its not showing number of records written to file or DB in Sink on Records Sent Metric.


Trills, Tremolo and forearm movement on the piano

Question: I still don't understand what the proper way is to playing trills and tremolos, even though I've read a lot about them and watched a lot of videos. Worse it seems like all the people explaining it do them differently.
What confuses me is the movement of the forearm. I don't understand if the movement for a 2-4 trill or an octave tremolo solely comes from the forearm, meaning no movement of the finger muscles at all or if the movement comes from the finger with a little forearm rotation.
If I use only forearm rotation (the way I would rotate a door knob or change a light bulb), then I get extremly slow and watching other pianist doing tremolos or trills, it seems to me that the movemet comes from the finger and there is very little forearm rotation.
The second thing which I don't understand is the movement of the wrist. Especially when I trill on 2-4 and keep my wrist in motion then it feels very awkward to play a trill.
I know there are many questions about trills, but I still don't understand it after reading them.
Comment: Hint: the entire arm is often used to put energy into your finger**tips**, like a lever.
Answer: I don't have any direct experience in doing trills on piano but I have have experience in other musical areas which may relate to your problem.
When playing guitar I once used only my arm to strum. This bad technique caused lots of muscle pain after playing for long periods. I then was told to add in a twisting of my forearm in combination with the initial movement to decrease pain in my arm and sound better. This greatly helped me. Later when this good technique was learned I started to add in a finger movement that I had seen many Spanish guitarists use to achieve fast strumming.
I believe that theis will relate to you in the way that while you have to have a twisting of the forearm motion in piano trills, you also have to add in a finger movement to increase speed and technique.
Try this:
Extend your whole arm level with the floor in front of you. While keeping your fingers loose and untensed, twist your forearm back and forth as if you are doing a trill on a piano. Now do this same thing but have your fingers hitting a tabletop. Then move your fingers so they increase and decrease pressure on the tabletop after a period of ten or so forearm rotations.
Do this whole thing but with your fingers tensed. Does this feel more coordinated? It shouldn't.
Anyways, I hope you can understand what I am meaning. Good luck.   :)
Answer: I'm only an amateur jazz pianist, but I once told a professional jazz pianist that I couldn't do those octave trills that others seemed to be able to do easily.
When I showed him how I tried to do it (on a table), he said immediately: "I see what your problem is, you're not moving your fingers!"  So definitely a large part of the movement should come from the fingers, although the wrist/forearm should help.  He also noted that some finger independence is needed to do it well.
Answer: One thing that helped me was learning to make the keypress movements very small. Just considering the physics of it, it takes more energy to move a greater distance in the same amount of time. So, to use less energy (and therefore make it easier, and less tiring), you make the movement smaller. Translating that to piano playing, the fingers shouldn't lift too high off the keys, if at all. In fact, you can even play a trill without letting the keys return up to the full, at-rest height.
Comment: The key does not have to return to its full, at-rest height. Pianos are built with what is called a "double escapement". That mechanism allows for keys to be replayed without fully returning to the at-rest height.
Comment: Aaron: Yes, though not all pianos have that.
Comment: Fair enough. Upright pianos generally don't. Any grand piano built in the last 150 years does.
Comment: Are you therefore saying you should be using mostly - perhaps all - forearm rotation?
Comment: @Dekkadeci: For me, it depends on the fingers being used. If the thumb is involved, then mostly rotation, yes. For other fingers, not so much.


Verilog execution order

Question: I'm just starting to learn Verilog on my own after taking a course on VHDL. I'm having a trouble understanding the order in which behavioral statements are executed. Here is the code in question.
// This file is an experiment into the order in which verilog executes it's statements

module MainCircuit(clk, start);

    parameter cycles = 8;
    input clk;
    input start;
    //input [15:0] data;

    integer i;

    always @(posedge clk)
    begin
        if(start)
        begin
            i=0;

            repeat(cycles)
            begin
                @(posedge clk) $display("%d\ti = %d", $time, i);
                i = i + 1;
            end
        end
    end

endmodule

module tester;

    reg clk;
    wire start;

    assign start = 1'b1;
    initial clk = 1'b0;

    MainCircuit myMain(clk, start);
    initial repeat(40)
    begin
        #5 clk = 1'b1;
        #5 clk = 1'b0;
    end

endmodule

and here is the output:
                  15    i =           0
                  25    i =           1
                  35    i =           2
                  45    i =           3
                  55    i =           4
                  65    i =           5
                  75    i =           6
                  85    i =           7
                 105    i =           0
                 115    i =           1
                 125    i =           2
                 135    i =           3
                 145    i =           4
                 155    i =           5
                 165    i =           6
                 175    i =           7
                 195    i =           0
                 205    i =           1
                 215    i =           2
                 225    i =           3
                 235    i =           4
                 245    i =           5
                 255    i =           6
                 265    i =           7
                 285    i =           0
                 295    i =           1
                 305    i =           2
                 315    i =           3
                 325    i =           4
                 335    i =           5
                 345    i =           6
                 355    i =           7
                 375    i =           0
                 385    i =           1
                 395    i =           2

I don't understand why i isn't being reset to zero at each positive clock edge. Does myMain remember where it is in execution and continue from there each time clock is called? If so, where is it stopping?
And how would all this be synthesized?
Two other minor questions:
I tried to write
start <= 1'b01;

instead of
assign start = 1'b01;

in the second module, but it wouldn't work. Why not?
The second question is: what's with the weird spacing in the output?
Answer:
always @(posedge clk) doesn't automatically execute at every clock edge. An always block can only restart once it has reached the end of it's current execution (you can't simultaneously have two threads executing a block). Your always block doesn't reach end until after 8 clocks because it is stuck in your (repeat cycles) loop. Only after 8 posedge clocks can it finish the loop, hit the end of the always block, and then restart on the next posedge.
start <= 1'b1 is a nonblocking assignment and can only be executed inside an always block.
The $display is probably reserving enough space to print the max value of a 32bit decimal. If you don't want all the extra spaces try %0d instead of %d.
Comment: Thanks, its my first time posting here and I was worried that the verilog section wouldn't be very active.
1) So does the execution hang at`@(posedge clk) $display("%d\ti = %d", $time, i);`? Also, how is this synthesized to logic?
2) Which way is the standard way of  hard-wiring the input to a circuit? I thought that both assign and always were blocks of procedural code but I see hard-wiring as more of a gate-level thing.
Comment: @ChrisMorin Its probably less active than most sections but most questions look like they get at least one or two answers. Yes, the execution does pause on the display line. @(posedge clk) just means "wait here until the positive edge of the clock, then run the next statement". I'm not sure exactly how to answer 'how is this synthesized'... I guess it would just create a counter that runs up to 8 bits and then repeats, similar to your output. As for how to hard wire an input, there's nothing wrong with an assign statement to set a port on the DUT to a constant value.

Verilog execution order


Fingerpicking with my pinky finger

Question: For the past couple of years, I've adopted the following approach for fingerpicking folk rock/alternative music...
E - pinky finger
B - ring finger
G - middle finger
D - index finger
A - thumb
E - thumb
At this point, I'm super comfortable with using my pinky finger on the E. I personally think that it is the most ergonomic approach since I don't have to move my ring finger to reach the E (although I have to cover two strings with my thumb). I've started reading that the pinky is rarely used in picking. What are the pros/cons to this approach and should I forgo using the pinky in fingerpicking?
Comment: I liked all the answers, as it confirmed to me that using the pinky finger is fine. Thanks for all of the responses!
Answer: I'm also using my pinky a lot when finger picking. In this way there's not so much difference switching between pure finger picking and hybrid picking. So that's another benefit of this approach. With hybrid picking your index finger is not available, so there it's natural to use the pinky more. Plucking two adjacent strings feels more natural with the middle and ring finger rather than index and middle finger too.
Answer: Hard and fast rules will only guide you to what people have found worked for them. There is nothing wrong with changing to suit yourself. The thumb sounds good on the lowest two strings, as that's where the bass line often runs, so a fleshy sound is appropriate.A pattern I sometimes use involves only the top four strings, so I use thumb on 4 and 3, with top two strings being played with m and a usually.The pinky can and should be used - it's waiting for the opportunity ! Yes, it may be a bit weak, but soon it catches up with the others, given that chance.Playing a chord on top four, plucking simultaneously, can ONLY be achieved with all four fingers. Keep going, it's the end product that's more important than how you physically produce it.
Answer: As long as you feel comfortable with your pinky in the E string it's ok. As for advantages, you might find it easier to play arpeggios of 5 and 6 strings (since you have almost all strings covered), or as well play different melodies along the strings at the same time. It is not anything you couldn't do with the common finger position on the strings,  but it's all a matter of how comfortable you feel. In the list of disadvantages you should consider the fact that the pinky finger is the weakest finger, and it might make a difference on your E string picking strength and/or precision. But again, it all depends on your own preferences. Who knows, maybe you can go further with it and create a new technique!
Hope that helps, this is my very first answer (:
Answer: If you feel comfortable playing with your little finger, congratulations. You have the advantage. There's absolutely nothing wrong with it. After all, you use your (probably even weaker) left hand pinkie too. And pianists use their every finger.
Most classical guitarists play only with their four or even three first fingers because they find using their whole hand too hard. Basically there's two reasons for that:

Many players hold their plucking hand in a position where it is hard for little finger to reach the strings. Especially if it is relatively short compared to other fingers.
Classical players play mostly without amplification and find it easier to get a loud and fat sound with their strongest fingers.

Years ago I asked my teacher about this and he told that actually you can develop a better control for little finger because it has its own moving muscle unlike middle and ring fingers. He is a musician and not a physician so his explanation should probably be taken with a grain of salt.
Answer: I eased into right hand pinky use by playing songs finger-style using a chord-melody approach, mostly with full barre chords but these days adding in lots of "open" cords since I now know more what is where on the neck. It may not have been as quick compared to doing exercises but it was sure more fun.
Answer: I always say to people who are debating whether to play with the thumb and two fingers or thumb and three fingers that if they only use two fingers they are only using 75% of their available resources and will get a 75% result. Actually, I never considered using my pinky but by my same logic it is an available resource (although I do plant my pinky alot which gives me more control, especially with dynamics because the anchor gives you leverage without much hand movement). People also say that's wrong but I have been playing long enough to make an experienced educated assessment. I can play without it too.
The only other thing I would add is that you don't have to do either or or forego one for the other. You don't have to choose right from wrong. You can however, and maybe should, ALSO play without it. And ALSO be able to move across all strings with alternating index and middle fingers, classical style. It is ALL useful.
Comment: "classical style"?  i-m-a-m-i across all stings too.
Answer: I personally don't but if you are not experiencing and hand pain or tension then go for it, use it to your advantage.  In classical guitar the pinky is usually ignored but there is a modern trend started by Eliot Fisk (I think).  He recommends using the pinky in the Segovia scale exercises.  Even though it isn't used in performance it is believed that practicing to use it helps develop strength and independence of the ring finger.  I haven't tried it, I'm happy with the other fingers as is.
Keep using it.
Answer: I always teach my students to use all five fingers. You learn by assigning a finger to a string, thumb picks up the bass notes on the fifth and sixth.  Then enforce the discipline of only playing a note with the finger assigned to that string.  It's great for playing arrpeggioed chords and finger style. When you get used to it, you'll find that you always have a finger waiting for a note, without moving around so much. Give it a try. 50 year player. 22 year teacher.

Fingerpicking with my pinky finger