Inline entity form complex widget not saving child entities

Question: I'm using inline entity form on a node edit form. The target is a custom entity.
There are two possible form widgets to use: Simple or Complex.
With Simple (example) the child entity fields are just embedded in the parent form. It's not possible to collapse the child fields, nor is it possible to delete child entities, but it does save the child entities upon submitting the entire node edit form.
With Complex (example) the child entities fields are collapsible and the child entities can be deleted. However the child entity is only saved if the section of the form is not collapsed when the node edit form is submitted. Is this a bug?
I've discovered that using hook_inline_entity_form_entity_form_alter I can add a callback to the $form['#entity_builders'] array that is called when the child entity sub form is collapsed (and is meant to be saved).
In this callback I've added some super generic code to just save the child entity.
E.g.
function save_ief_child_entity($entity_type, $entity, $entity_form, $form_state) {

  $delta = $entity_form['#ief_row_delta'];
  $field_name = $entity_form['#parents'][0];
  $values = $form_state->getValue($field_name);

  // The location of the entity values changes depending on if it's a new save
  // or an update.
  if(isset($values['form']['inline_entity_form']['entities'][$delta]['form'])) {
    $values = $values['form']['inline_entity_form']['entities'][$delta]['form'];
  }
  else {
    $values =& $values['form']['inline_entity_form'];
  }

  if(empty($values)) {
    return;
  }

  // Loop form values to update entity
  foreach($values as $key => $value) {

    // Images are in the wrong format for some reason - fix it.
    foreach($value as &$part) {
      if(is_array($part) && isset($part['fids'])) {
        $part['target_id'] = $part['fids'][0];
      }
    }

    $entity->{$key} = $value;

  }

  $entity->save();

  // IEF takes care of creating the relationship between parent and child when the main form is submitted
}

Why do I have to do this / why doesn't IEF do this itself internally?
Comment: Did you get anywhere with this? Just found the same bug.
Comment: No - not revisited this since then I'm afraid.
Comment: Did this code snippet do the trick for you? Does it go in '.theme' file?
Comment: Yes, this snippet fixes the problem. This doesn't really have anything to do with theming so I would reccomend putting it in a custom module. You can put the hook inline entity form alter in there too.
Comment: Right on. This should be a patch.
Answer: If anyone would stumble on the issue of saving child nodes (entity) at inline entity form (ief) - newly added/created node not saved, here is a quickfix for that (D8/9):
function MODULENAME_inline_entity_form_entity_form_alter(&$entity_form, FormStateInterface $form_state) {
    $entity_form['#save_entity'] = true;
}


Combination for applicant pool

Question: The qualified applicant pool for six management trainee position consists of seven women and five men.
How many different groups of applicants consisting of at most two women can be selected for the position?
The answer I have obtained is 8 possible groups due to the following logic:
6C6 +7C6
6C6 represents 5 men and 1 women being chosen for the positions
7C6 represents 5 men and 2 women being chosen for the positions
Thou I am doubting this is the right answer please correct me
Comment: nCk is the number of ways to choose k applicants from a pool of n applicants. In this context, what do you mean by 6C6 and 7C6?
Comment: Pour idea to separate in groups of one woman and two women is good. But the rest is wrong.
Answer: If you choose no women, you have to choose 6 men and there aren't enough so you can't choose no women.
If you choose one woman, you have to choose all 5 men.  There are 7 ways to chose 1 woman and only 1 way to choose all 5 men so there are 7 ways to do this.
If you choose 2 women there are $7\choose2$ ways to do this.  That's $7\times\frac62 = 21$.  You must chose four men.  There are ${5\choose4} = 5$ ways to do this.  So there are $21\times5 = 105$ ways to do this.
In total there are $105 + 7 = 112$ ways to do this.
Answer: 7C6 is not correct, since you only need 4 men not 5 men to be chosen when there are 2 women being chosen already~
Comment: 8 is not the correct answer. For 6C6=$7\choose 1$, and for 7C6 (note there  are only 6 position for these people so you cannot have 7~)=$7\choose 2$x5.

Combination for applicant pool


How Can I Make A Chord Progression Sound Less Rhythmically Lame?

Question: When I'm playing piano as an accompaniment to singing, I pull up chord charts for the song and wing it. But I can't seem to figure out how to make the piano sound interesting.
For example, the song I'm playing at the moment is in 4/4 and has the chords: Cmaj7 F#7#11 Fmaj7 F/G F/Ab G7sus. The first three chords take a measure each, and the last three chords all together take up one measure. At the moment, I am just playing them vanilla. So I play the Cmaj7 and hold it for the full measure. Then I play the next chord and hold for a full measure, etc.
But when I hear people playing accompaniments, they play lots of notes in between the chords, with cool syncopations. And sometimes the notes they play aren't belonging to the chord, so they sound quite interesting. Are there some go-to rules I can use for making it sound better? Things like "a sixteenth note before playing the next chord, play the root of the current chord"? Improvisation and experimentation haven't worked for me, so I need help!
Comment: If it is, then simplest would be to just push every chord except the first by 1/16th. (This is not racist!) White guys push by 1/8, black guys by 1/16… that's the difference between Elton John & Stevie Wonder.
Comment: how about C,Cmaj7,C6,Cmaj ?
Comment: @Tetsujin interesting you mentioned Elton John, his rhythm section does very few pushes of either variety but his melodies are filled with 16th syncopations! Also your comment is not racist but is way too generalized. How about "Love And Happiness" by Al Green? 8th pushes galore. "Pick up the Pieces" by AWB, lots of 16th pushes.
Comment: @Tim nope it's Love on Top by Beyonce!
Comment: Does this answer your question? [How do I make piano chords sound interesting when playing along with popular songs?](https://music.stackexchange.com/questions/4904/how-do-i-make-piano-chords-sound-interesting-when-playing-along-with-popular-son)
Comment: @chasly-supportsMonica: yes that absolutely does answer it. Thanks!
Comment: @AlbrechtHügli, ehmm, I don't quite get what you mean... could you elaborate?
Answer: Arpeggios!  They are your friend.  The more you play them and the more chords whose arpeggios you play, the more often you will think to yourself "Hey, I've heard that before, played by someone good on a real record!"  Once you've got an arpeggio down, ascending and descending, play it starting on each note of the chord.  Also start on the top note, then ascending arpeggiate up from the bottom and vice versa.  Don't hesitate to make up your own drills.  This is exploring, and there is a whole universe to explore.
Comment: Thanks! So, I have played around with arpeggios and often they work. Elvis's Can't Help Falling in Love is a good example. My issue: arpeggios tell me what notes to play, but not when to play them. Elvis uses triplets. Arpeggios that play notes on the beats sound booooooring. Any advice on when to play the notes?
Answer: Are you the complete accompaniment (i.e. there isn't a bass player?)    Then your first job is to provide a strong, rhythmic bass line with your left hand.   Right hand can play chords, arpeggios, sometimes support the vocal melody by doubling it, invent a counter-melody...
Comment: Yep it's just me and the piano. The stuff you're saying around a rhythmic baseline in the left hand, and other stuff in the right. I am 100% on board, and that's what I do. I am wondering though, what rhythmic motifs can I use in my right hand to make it sound more interesting? At the moment I play the chord on the 1. Maybe also on the 3.  How can I get that sounding more interesting? You mentioned doubling the melody... personally I am not a huge fan of that, except for helping my vocal pitch accuracy from time to time. Reason being, it sounds rhythmically un-interesting.


Bartlett's paradox in Bayesian evidence

Question: I've come across Bartlett's "paradox" (not to be confused with Lindley's paradox, also known as the Lindley-Bartlett paradox) in Bayesian statistics. The paradox originates from Bartlett's 1957 paper,
A Comment on D. V. Lindley's Statistical Paradox
.
Bartlett's paradox is quite trivial. Suppose that with a Bayes-factor, one compares two models, $a$ and $b$, each with adjustable parameters. Model $b$ has an adjustable parameter $p$ that a priori could take on broad range of values $N$, for which a uniform distribution is an appropriate prior (suppose that it's a location parameter).
The Bayes-factor is
$$
\frac{p(D\mid M_a)}{p(D\mid M_b)} \propto N
$$
If a priori we know very little about the parameter $p$, it might be that we want to consider an improper prior $N\to\infty$ or at least very large $N$. In this case, the we ought to favor model $a$, almost regardless of the data (though here we must take care with the limit - if each $p(D\mid M)$ is normalized, $p(D\mid M_b) \ge p(D\mid M_a)$ for some $D$).
What are we to make of this? Is it paradox? How should we deal with this situation in which we have insufficient prior information to constrain a model parameter but want to make a model comparison? Maybe nothing has gone wrong, and we really should favour model $a$ in this situation?
Comment: This question might be better directed to Cross Validated ( http://stats.stackexchange.com/ ).
Comment: Alright, can it be migrated? @Eric
Comment: Hmm...  Seems we can't migrate a question that is > 60 days old...
Comment: This paper might be informative:  https://ideas.repec.org/p/kee/kerpuk/2004-03.html
Answer: It is a paradox, in the sense that the frequentist approach and Bayesian approach will give different results. This depends on the prior class you choose and the data distribution, but it will usually happen since we have the Central Limit Theorem, which guarantees the distribution of the statistic of interest to be Normal when the data sample size is relatively large, compare to the effective sample size of the prior.
So suppose $P(D|M_a)$ indeed gives the probability or probability distribution when the null hypothesis is true. When sample size $n$ is very large, you can imagine the standard error to be very small (proportional to $1/\sqrt{n}$). In this case, it's very likely that the frequentist approach will reject $M_a$. However, in the Bayesian approach, we favor $M_a$ due to the Bayes factor getting large.
One way to fix this is to also impose the precision (or the parameter that gives the effective sample size) some prior distribution, so that the joint prior distribution will have heavier tails, say, the Normal prior for $\mu \sim \mathcal{N}(\nu, 1/n_0)$ will become Cauchy, after imposing $n_0\sim \text{Gamma}$.

Bartlett's paradox in Bayesian evidence


How do I direct users to my custom search?

Question: I'm trying to use hook_search_execute to run a custom search inside my module:
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
    die; // just to see if we get called
    // lots of lines copied from the hook_search_execute doco
    return $results;
}

I can get the default Drupal search form inside my page.tpl.php with:
<?php print render(module_invoke('search', 'block_view', 'search')); ?>

But, when I click the "search" button on that form, my custom search isn't called.
I'm using D7. What's the appropriate way to actually force a search to get results from my custom search function?
Answer: I would use hook_form_alter() to alter the default search form to call your own submit function.
So, in your custom module do something like this:
// Alter regular search box
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form["#id"] == 'search-block-form') {
    // Add any additional fields or things you need here

    ...

    // Modify the submit handler that is called
    $form['#submit'] = array('YOUR_CUSTOM_search_submit');
  }
}

This actually modifies precisely that block search form, so including the search block just like you've described in the template file should work once you've implemented the form alter.


General linear model for counts which are "correlated"

Question: The typical general linear model (GLM) for count data uses the Poisson link function. The counts there are assumed to be "independent". Now suppose the counts are not "independent" in a sense illustrated by the following toy example.
There are data points on 2100 students who each take 7 courses. The response is the number of "A" grades they earn. The histogram below illustrates the observed "A" count. I'm interested in a GLM for this kind of response distribution with some predictors (for example, # hours spent studying + household income).
From a modeling perspective, it is reasonable to believe that students who get an "A" in one course are likely to get an "A" in other courses (and vice versa). So I am unsure as to what an appropriate link function would be for a GLM. It is clear that the responses don't follow a Poisson distribution in this example. But would a logarithmic link function (i.e. Poisson regression) still be valid in this scenario? Any thoughts would be much appreciated.
Answer: If you treat "student" as a random effect (e.g. by including a random "intercept" to represent the student effect), that's one way of modelling this sort of dependence.
Given a GLM to begin with, this would result in a generalized linear mixed model (GLMM) on which topic you can find quite a few posts here.
Answer: Your histogram looks a lot like a zero-inflated Poisson (ZIP) distribution.  In short, the ZIP is a mixture of a Bernoulli (which in this case would model something like probability a student has the potential to get an A) and a Poisson (which would model the number of A's a student receives given they have the potential to get one).  If 7 is the maximum number of classes, however, a zero-inflated Binomial model would be more appropriate.
Comment: I have a question about getting significance of a predictor in ZIP models. Suppose $Y_i$ is a response. I want to model a single predictor $X_i$ in both the "binomial" and "Poisson" parts of the model. That is, there are two parameters $\beta_{Bin}$ and $\beta_{Pois}$ corresponding to $X_i$ in this ZIP model (Q1.) Is this valid to use the same predictor in both parts of the model?
Comment: (Q2) Fitting the ZIP model here gives an estimate and standard error for $\beta_{Bin}$ and $\beta_{Pois}$. Is there way to combine them to get a total $p$-value corresponding to the significance of $X_i$? Is there an analytical way? For example, $F$-tests or linear restrictions of some sort.
Comment: For the first question, you should be able to use the same x-variable in both parts, as they would be estimating the effect of that predictor on two different processes.  I rarely use p-values for statistical inference (I tend to prefer bayesian estimation), so I am not able to directly answer  your second question. However, I'm not sure why it wouldn't be preferable to look at the significance of the two $\beta$ coefficients separately.


Sketching $|z-i|= k|z-2i|$ in Complex Plane

Question: Given the set $|z-i|= k|z-2i|$ when $k>0$
I don't understand how to sketch this set.
Help me please. Thank you.
............................
edit
From $|z-i|= k|z-2i|$
I have $\sqrt{x^2+(y-1)^2} = k\sqrt {x^2+(y-2)^2}$
I have $ x^2+(y-1)^2 = k^2(x^2+(y-2)^2)$
Thus, $x^2+y^2-2y+1 = k^2(x^2 +y^2-4y+4)$
Suppose $k=\frac{1}{2}$ , I have $x^2+(y-\frac{2}{3})^2 = \frac{4}{9}$
Suppose $k=1$ , I have $y=\frac{3}{2}$
Suppose $k=2$ , I have $x^2+(y-\frac{7}{3})^2 =\frac{19}{6} $
Suppose $k=3$ , I have $x^2+(y-\frac{17}{8})^2 = \frac{9}{64}$
Now, I think when I suppose $k\geq{3}$ I have circles small than $k=2$
Can I sketch this set from equation $x^2+(y-\frac{7}{3})^2 =\frac{19}{6} $ ?
Comment: I reopened this question since the author has added their work.
Comment: Have you tried plotting a few points? Fix $k$ and find some simple values for $z$, then see what happens.
Comment: You might try looking at this as $\left|\,\frac{z-i}{z-2i}\,\right|=k$ which means that $\frac{z-i}{z-2i}=ke^{i\theta}$.
Comment: Solving for $z$ gives the parameterization $z=\frac{2ke^{i\theta}-1}{ke^{i\theta}-1}\,i$
Comment: thank you sir. @robjohn
Comment: @user1729 Thank you, could you check my edit for me.
Comment: [Here](http://i.stack.imgur.com/7uCkn.png) is what these look like.
Comment: Wow! Fantastic! Thank you very much. @robjohn
Comment: Ehhh..I am not very sure about when k converge approch to 1 ex. 10000/10201 this circle greater than 3/4 .
Comment: @Zera: when $k\to1$, the circle tends to the line $y=\frac32$.
Answer: Continue with $x^2+y^2-2y+1 = k^2(x^2 +y^2-4y+4)$ to obtain the general expression,
$$x^2+\left(y-\frac{2k^2-1}{k^2-1}\right)^2 = \left(\frac k{k^2-1}\right)^2$$
So, for any $k>0$ and $k\ne1$, the set is of a circle with center $(0,\frac{2k^2-1}{k^2-1})$ and radius $\frac k{k^2-1}$. For example, if $k=2$, the circle becomes,
$$x^2+\left(y-\frac{7}{3}\right)^2 = \left(\frac 2{3}\right)^2$$
which is sketched here, showing that the distance from $z$ to (0,i) is twice as that from $z$ to (0,2i).


$\sum_{n=1}^\infty a_n$ is convergent $\iff \lim_{k\to \infty}[\sum_{n=k}^\infty a_n]=0$. Is this right?

Question:
$\displaystyle \sum_{n=1}^\infty a_n $ is convergent $\iff $ $\displaystyle \lim_{k\to \infty}\bigg[\displaystyle \sum_{n=k}^\infty a_n\bigg ]=0$

I don't know whether this statement is true or not. I think I'm sure that the from left to right statement is right, and here is my thought:
$\displaystyle \sum_{n=1}^\infty a_n $ is convergent, and suppose $\displaystyle \sum_{n=1}^\infty a_n=A$. Then $\displaystyle \lim_{k\to \infty}\bigg[\displaystyle \sum_{n=k}^\infty a_n\bigg ]=A-\lim_{p\to \infty}\displaystyle \sum_{n=1}^p a_n=A-A=0$. Thus from left to right is right.
However, I'm not sure about the other side. My intuition tells me the other side might be right. By the same expression, $\displaystyle \lim_{k\to \infty}\bigg[\displaystyle \sum_{n=k}^\infty a_n\bigg ]=\displaystyle \sum_{n=1}^\infty a_n-\lim_{p\to \infty}\displaystyle \sum_{n=1}^p a_n$. If the $\displaystyle \sum_{n=1}^\infty a_n$ isn't convergent. Then the result should not exist instead of being zero, but I'm not sure.
Any help on this? Thanks!
Comment: The statement is true whenever it is a well-defined sentence (i.e., the sum $\sum_{n=k}^{\infty} a_n$ exists for all $k$.) It is risky to make a statement about some expressions that may be undefined in some instances.
Comment: A similar statement which is true, and doesn't involve possibly undefined terms is: $\sum_{n=1}^\infty a_n$ is convergent if and only if $\lim_{k,\ell\to\infty} \sum_{n=k}^\ell a_n = 0$ (where the right hand side means: for every $\varepsilon > 0$ there exists $N$ such that whenever $k,\ell \ge N$, then $\left| \sum_{n=k}^\ell a_n \right| < \varepsilon$).
Comment: @Yink I don't see what letting $\ell = k + p$ has to do with anything.  Otherwise, that's precisely the point: the condition implies the sequence of partial sums is Cauchy almost directly (with just the small wrinkle that $S_{\ell} - S_k = \sum_{n=k+1}^\ell a_n$ if $\ell > k$ or $-\sum_{n=\ell+1}^k a_n$ if $\ell < k$).
Comment: What kinds of objects are the $a_n$ and infinite series thereof? For example, if we're restricted to the metric space $\Bbb Q$, then some Cauchy series seem not to converge, and that's because they really converge to an irrational number, which motivates Cauchy completion as a rival to Dedekind cuts to define $\Bbb R$.
Comment: Just $a_n \in \mathbb R$, and each $a_n$ is either positive, negative, or zero
Comment: @311411 Why this is true?
Comment: In epsilon-n, it said that $\forall \epsilon, \exists N\in \mathbb N: n>N...$. This $N$ is a fixed value, so if after $N$, and for $p=1,2,...$ $|a_n+...+a_{n+p}|<\epsilon$, this can mean that there are infinitely many terms, and their sum is smaller than epsilon, and the finitely many terms before them won't affect the convergence and divergence. This time we can say a series is convergent. But now $k$ isn't a fixed value, it is approaching infinity. Shouldn't this mean that there will be infinitely many terms before $k$ as $k \to \infty$?
Comment: @Daniel Schepler I think I kind of understand your statement. By your statement, I can just let $l=k+p$ for $p\in \mathbb N$. Then when $l,k\to \infty$, the right side statement will just be the Cauchy criterion which implies that the series is convergent, right?
Comment: @311411 Do you mean that as $k\to infty$ I can fix $k$ for each time. When $k=1,2,3,...$. Then since the terms after $k$ gives 0 and the terms before it just $a_1+a_2+...,+a_{k-1}$, so the series is convergent?
Answer: Yes, the theorem is true for real series. As already noted, a series converges iff its partial sums sequence converges (to a finite limit, to be crystal clear). Thus, we put
$$S_n:=\sum_{k=1}^n a_k\;,\;\;\text{so that}\;\;\sum_{k=1}^\infty a_k\;\;\text{converges}\;\iff \lim_{n\to\infty}S_n=S\in\Bbb R$$
and by the very definition of limit we get:
$$\left\{S_n\right\}_{n=1}^\infty\;\;\text{converges to a number}\;\,S\,\;\iff \forall\,\epsilon>0\;\;\exists\,N\in\Bbb N\;\;s.t.\;n>N\implies |S-S_n|<\epsilon$$
But the last inequality is just
$$\epsilon>|S-S_n|=\left|\sum_{k=n+1}^\infty a_k\right|$$
Thus we get that
$$\;\sum_{k=1}^\infty a_k\;\;\text{converges}\;\; \iff \;\lim_{n\to\infty}\sum_{k=n+1}^\infty a_k=0$$
In fact, the above is just the definition of (finite) existence of limit after using
Cauchy's condition for the sequence of partial sums.
Comment: Wrong answer. See the answer below.
Comment: @KaviRamaMurthy What *exactly* in the above answer is wrong, in your opinion? Just to state "wrong" doesn't seem serious.
Comment: What is the meaning of $\sum_{n=k}^\infty a_n$ on thn right side? You cannot use this meaningless sum  unless you know convergence already.  You should delete your answer.
Comment: That is the series tail or however you want to call it, and it converges to zero . Haven't you seen this? then you should study it. And it is **always** possible to talk about this even if a series diverges. Its behavior could be different, of course...but it is always defined as far as the series.
Comment: What does $\sum a_n$ denote if the partial sum sequence is $\{1,-1,1,-1,...\}$? It neither denotes  a real number nor $\pm \infty$. It has no value associated with it.  You have over 200K reputation points and youngsters assume that you know basic Mathematics.
Comment: I didn't talk about "sums" just like that. From the beginning it is *a converging series* that is being discussed. Partial sums are *always* defined . You have almost 300K reputation points, one could assume you actually understand what you're trying to write about...A pity.
Answer: The main issue with your formula is that, in the right-hand side, we are confronted with an expression $\sum_{n=k}^{\infty} a_n$ that is undefined in some instances.
1. To make an analogy, consider the following formula:
$$ \forall x \in \mathbb{R} \ : \ x > 0 \iff 1/x > 0 \tag{1} $$
For the formula $\text{(1)}$ to have a truth value in formal logic, the function symbol $1/x$ must always have a value, even when $x = 0$. Of course, this is not the case under the usual definition of the division. So, how is this formula dealt with in logic? One solution is to say that $\text{(1)}$ is true iff it is true in any possible interpretation of the symbol $1/x$ (i.e., any assignment of value to the expression $1/0$). However, it is easy to see that the truth value of $\text{(1)}$ depends on the interpretation of $1/0$.
To make amend of this situation, we might tweak $\text{(1)}$ and instead consider
$$ \forall x \in \mathbb{R} \ : \ x > 0 \iff (x \neq 0 \text{ and } 1/x > 0). \tag{1'} $$
This statement is now true in arbitrary interpretation of the symbol $1/0$, hence we can serenely consider it true.
2. In the same spirit, we may modify your formula as:
$$ \sum_{n=1}^{\infty} a_n \text{ converges in } \mathbb{R} \quad \iff \quad \left\{\begin{gathered} \sum_{n=k}^{\infty} a_n \text{ exists in } \overline{\mathbb{R}} \text{ for all } k \text{ and} \\\lim_{k\to\infty} \sum_{n=k}^{\infty} a_n = 0\end{gathered}\right\} $$
where $\overline{\mathbb{R}}=[-\infty,\infty]$. Then it is easy to check that this statement is true, as extensively discussed by other users.
Comment: To a downvoter: Please let me know why do you not like about this answer, so I can improve it.
Answer: Note that convergence of series is usually defined as follows
$$\sum_{k=1}^{\infty}a_k \text{ is convergent } :\Leftrightarrow \left(\sum_{k=1}^n a_k\right)_{n} \text{ is converging}$$
Note that convergence of the term on the right hand side means: Let $\varepsilon>0$ there exists $N\in \mathbb{N}$ such that for all $n\geq N$ it holds $\left|\sum_{k=n+1}^{\infty}a_k\right|\leq \varepsilon$. Then you have
$$ \left|\sum_{k=1}^{\infty} a_k -\sum_{k=1}^n a_k\right|=\left|\sum_{k=n+1}^{\infty}a_k\right|\leq \varepsilon.$$
Since $\varepsilon$ is arbitrary it follows $\sum_{k=1}^n a_k\to \sum_{k=1}^{\infty} a_k$ so that $\sum_{k=1}^{\infty}a_k$ is converging.
Comment: I think you regard the series as a sequence of partial sum and use the Cauchy criterion, but in fact, in my problem, the $\textbf{lower}$ index is approaching infinity instead of the upper one, so I think maybe this won't be helpful or did I miss something in your answer?
Comment: Yeah assume $\lim_{n\to \infty} \sum_{k=n}^{\infty} a_k=0$. This means that for any $\varepsilon$ you can choose $N\in \mathbb{N}$ so that $|\sum_{k=n}^{\infty} a_k|<\varepsilon$. But in order to show that the series is converging you have to show that the partial sums are converging. But substracting the series from the $n$-th partial sum gives exactly $|\sum_{k=n}^{\infty} a_k|$ so that the series is converging.
Comment: Note that in my writings I changed $n$ and $k$ so thats maybe why you misunderstood me.


How to show login page outside the layout using vue js 3?

Question: I want to show login page outside the layout but unfortuntly i see the sidebar and header on login page sidebar and header should not be on login page  please help me how can i resolve that thank u ?

App.vue

    <template>

        <Layout></Layout>

        <RouterView />
    </template>

router\index.js
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/DashBoard.vue')
    },

  ]
})

export default router

Answer: Use conditional rendering to hide/show elements based on the current route
<Layout v-if="route.path !== '/'"></Layout>

Also, not sure why you have two script tags.  You don't need to register components with the Composition API (script setup), so you can/should remove the second script


ServeStatic not defined - pure node.js

Question: It is my first day coding nodejs. This is a code example from a book called node.js in action. It's a nice book with some great information about how to code node.js as a beginner. but already after 1 day, i run into an error. I have copied the code and tried everything but nothing seems to work. This is the code I can't get to work.
My error when trying to run: ReferenceError: serveStatic is not defined

I have now installed the module and required it in my file.
Now i get a new error: "TypeError: root path must be a string"

Now it says
TypeError: root path must be a string
    at serveStatic (/Applications/XAMPP/xamppfiles/htdocs/learningmern/chatapp1/node_modules/serve-static/index.js:44
   var http     =   require("http");
    var fs      =   require("fs");
    var path    =   require("path");
    var mime    =   require("mime");

    var cache = {}

// Helper functions
function send404(res){
    res.writeHead(404,{"Content-Type":"text/plain"});
    res.write("error 4o4");
    res.end();
}

function sendFile(res, filePath, fileContents){
    res.writeHead(200, {"Content-Type": mime.lookup(path.basename(filePath)) });
    res.end(fileContents);
}

function serveCache(res, cache, absPath){
    if (cache[absPath]){
        readFile(res, absPath, cache[absPath]);
    } else {
        fs.exists(absPath, function(exists){
            if (exists){
                fs.readFile(absPath, function(err, data){
                    if (err){
                        send404(res);
                    } else {
                        cache[absPath] = data;
                        fs.readFile(res, absPath, data);
                    }
                })
            } else {
                send404(res);
            }
        })
    }
}

//run server
var server = http.createServer(function(req, res){
    var filePath = false;

    if (req.url == "/"){
        filePath = "public/index.html";
    } else {
        filePath = "public" + req.url;
    }

    var absPath = "./" + filePath;
    serveStatic(res, cache, absPath);
});

server.listen(3000, function(){
    console.log("server started at port 3000");
});

Thanks
Answer: You need to install the package. Run this:
npm install serve-static

Also require it. Put this at the top require section.
var serveStatic = require('serve-static')

Comment: Okay thanks. Now it says "TypeError: root path must be a string"
Comment: TypeError: root path must be a string
    at serveStatic (/Applications/XAMPP/xamppfiles/htdocs/learningmern/chatapp1/node_modules/serve-static/index.js:44
Comment: Your book is likely showing how to use an older version of serveStatic. Please check out the usage here: https://github.com/expressjs/serve-static for the current version. It should only take two parameters, your example shows 3. Utilize console.log debug what various variables are and keep trying.
Answer: After you have installed server-static npm, here is the solution to the error you are dealing with. You are calling the variables before you define them so you'd change your code to
   var http     =   require("http");
    var fs      =   require("fs");
    var path    =   require("path");
    var mime    =   require("mime");
    var serveStatic = require('serve-static');

    var filePath = ""; //define filePath here for the functions to not run an error
    var absPath = "./" + filePath;
    var cache = {};
    var server = http.createServer(function(req, res){

    if (req.url == "/"){
        filePath = "public/index.html";
    } else {
        filePath = "public" + req.url;
    }

    serveStatic(res, cache, absPath);
   });

// Helper functions
function send404(res){
    res.writeHead(404,{"Content-Type":"text/plain"});
    res.write("error 4o4");
    res.end();
}

function sendFile(res, filePath, fileContents){
    res.writeHead(200, {"Content-Type": mime.lookup(path.basename(filePath)) });
    res.end(fileContents);
}

function serveCache(res, cache, absPath){
    if (cache[absPath]){
        readFile(res, absPath, cache[absPath]);
    } else {
        fs.exists(absPath, function(exists){
            if (exists){
                fs.readFile(absPath, function(err, data){
                    if (err){
                        send404(res);
                    } else {
                        cache[absPath] = data;
                        fs.readFile(res, absPath, data);
                    }
                })
            } else {
                send404(res);
            }
        })
    }
}

//run server

server.listen(3000, function(){
    console.log("server started at port 3000");
});

Comment: it now says : "TypeError: root path must be a string
    at serveStatic "
Comment: change `res` object to `"/"` also check out this link https://www.npmjs.com/package/serve-static
Comment: TypeError: root path must be a string
    at serveStatic (/Applications/XAMPP/xamppfiles/htdocs/learningmern/chatapp1/node_modules/serve-static/index.js:44

ServeStatic not defined - pure node.js


Faster xgb.cv for large data set

Question: I have a record of data that contains 1.1 millions observations and 14 variables. The response is 0 or 1. It was suggested to me that I use Gradient Boosted Trees to build my logistic model.
Using xgb.cv from xgboost in R, I'm attempting to estimate the best hyperparameters on a holdout of 2/3 of the data. However, the code takes forever to run. It took me 13 hours for learning rate = 0.5, depth = 7, number of folds = 5 and number of trees = 10000. I can't imagine the time it will take to loop over different learning rates and depths.
How could I make the process faster? I guess that reducing the number of trees to 2500 would make sense, based on my error curve. Will reducing the number of folds help? Is it really necessary to do bootstrapping?
My current code looks like this, for reference :
etas = c(0.75,0.5,0.1)
max.depths = c(11,9,7,5,3)
fitAssessmentLst = list()
lstPos = 0
for(eta in etas){
  for(max.depth in max.depths){
    lstPos = lstPos + 1
    x = xgb.cv(params = list(objective="binary:logistic", eta=eta,
        max.depth=max.depth, nthread=3),
        data = train_data.xgbdm,
        nrounds = 10000,
        prediction = FALSE,
        showsd = TRUE,
        nfolds = 5,
        verbose = 0,
        print.every.n = 1,
        early.stop.round = NULL
        )
    fitAssessmentLst[[lstPos]] = list(eta = eta, max.depth = max.depth, assessmentTbl = x)
  }
}

Comment: related: http://stats.stackexchange.com/questions/193306/optimization-when-cost-function-slow-to-evaluate/193310#193310 also, you probably have way more trees than are necessary. and row subsampling can dramatically improve training time and create a more robust model
Comment: You should be using `early.stop.round` along with a hold out or cross validation so that the algorithm will stop short of your `10000` trees.  This is a very nice feature of xgboost you should utilize.
Comment: Row subsampling doesn't speed xgboost up much at all, I think because it bins IVs upfront for large data. Column subsampling does however have a huge and pretty much linear impact.
Comment: I couldn't agree more with the General. A learning rate of 0.5 and 10000 trees seems a bizarre setup. Have you checked the learning curves? Are the 9900 last trees really needed? I would recommend a learning rate of 0.3, 100 trees and features engineering.
Comment: Also I would be interested in knowing which version of XGBoost you are using. I have seen some performance differences between the master branch and old versions...
Comment: One point of boosting is that it doesn't need initial learners to produce good end results.  You may find that stumps (depth =1) produces very good results.
Comment: @GeneralAbrial Thanks for that suggestion, there is a very detailed example in the `rBayesianOptimization` package that uses `xgb.cv`. I'll give it a shot.
Comment: @AdrienRenaud The error seemed to stabilize after 2000 trees, with a learning rate of 0.5. The version of xgboost is 0.4-4
Comment: @MatthewDrury I forgot to mention that I am using a 2/3 holdout, I added it to the question. What would be a reasonable `k` to use for `early.stop.round`?
Comment: @Sycorax How does row subsampling make a more robust model? I am running `xgb.cv` using 1/10 of my data, which seems to really decrease the runtime, but I'm worried that my hyperparamaters won't translate well to the full dataset. I tried Bayes Optimization and it was still slow as hell. Around 100 minutes per iteration using 2500 rounds.
Comment: @jgadoury It can increase robustness in a manner analogous to how it works in random forest -- shaking up how the trees get built. The point isn't to identify hyperparameters and then fit a model without subsampling but to use subsampling as part of the model construction. Bayesian opt doesn't make model estimation faster, it just makes hyper-parameter tuning intelligent. Grid search doesn't use info from other models to make decisions about where to go next; BO does.
Comment: @Sycorax How does one do row subsampling in `xgb.cv`? I tried to find an option that I don't see it. Do you recommend using `sample` before each iteration?
Comment: I don't know how the R package works.
Answer:
It took me 13 hours for learning rate = 0.5, depth = 7, number of folds = 5 and number of trees = 10000.

The quickest & easiest way to make this faster is to use xgboost's early stopping feature, as suggested in the comments. The way it works is that you supply a hold-out set to the model, and specify a positive integer. The integer specifies the number of rounds to continue boosting even if the loss increases on the hold-out data. For example, if you specify 3, boosting rounds will continue if the loss increases for 2 rounds on the hold-out, but then decreases on the third round. But if the loss increases for three consecutive rounds, boosting terminates. (Boosting will also terminate if you exhaust the number of boosting rounds - in your case, 10000.)
The reason that this is useful is that it provides a principled - in the sense that it stops when hold out performance declines - way for you to terminate training without having to specify the number of boosting rounds ahead of time. The procedure is a little arbitrary in that choosing different integers can dramatically change the number of boosting rounds.
The reason that you specify an integer as part of the procedure is that it's often true that the loss on the holdout data will transiently increase before decreasing again. This pattern persists until the loss consistently increases, where "consistent" is defined in the rather ad hoc manner of the positive integer.
It's not a perfect system, but it works well enough in practice.
As an aside, with a learning rate as high as 0.5, it's often true that early stopping will terminate training in maybe a dozen rounds of boosting. The sweet spot for the learning rate is somewhere between 0.05 and 0.2 in my experience. A decrease in the learning rate often increases the number of boosting rounds (when you're using early stopping) and yields an improved out-of-sample loss. So there's a little bit of a trade-off between how long you want to wait for results, and how many trees you want (more trees makes the model size larger, so it's not always a trivial concern) and how good the model is.

To answer the titular question, I've heard from colleagues that LightGBM is a faster gradient boosted tree package. I don't have any definitive evidence to substantiate that claim.
Answer: Try to make your numeric features categorical by digitizing them. If you digitize the features, you can also one-hot-encode them. By that you will get rid of unnecessary floating point as well as having a sparse dataset which will enable you considerable efficiency.
LightGBM is swifter by its natural depth-wise tree approach compared to XGBoost's level-wise approach and thanks to its booster: Gradient-One-Sided-Sampling[1]. Moreover, if you have a sparse dataset, its Effective-Feature-Bundling (EFB) skill will boost the computation efficiency sharply[1]. I recommend you to try LightGBM, it solves speed without losing accuracy[1].
Here is your evidence (also experimented but nevermind):
https://papers.nips.cc/paper/6907-lightgbm-a-highly-efficient-gradient-boosting-decision-tree][1]
Have fun.

Faster xgb.cv for large data set


Convert cert .cer to .pem via OpenSSL plus using SHA-256

Question: This might be me having done it wrong. I recently used OpenSSL to convert a .cer to .pem using this -
openssl x509 -inform der -in certificate.cer -out certificate.pem

(And then loaded the .pem onto the loadbalancer)
However the client browser (chrome) reports it's SHA-1 and although it works, (connectivity wise) it doesn't look good. Plus SHA-1 is old/being phased out.
Is this because of the openssl command I used? Should I have used -sha256 in my openssl command (from a quick googling around)
As you can tell, bit new to certificates!
Answer: The "SHA-1" or "SHA-256" mentioned in Chrome is the hash that was used by the CA (Certification Authority) to create the signature on the certificate.  The command you ran doesn't change the certificate at all, it merely changes the file format used (.cer is just the raw ASN.1 encoded certificate data; .pem is a base64-encoded form of the same ASN.1 data).  The hashing scheme used for the signature is unrelated to the file formats.
If you want a SHA-256 certificate, you'll need to have one issued by a CA.  These days, it's pretty much guaranteed that you'll get a SHA-256 certificate, because SHA-1 is very, very deprecated (hence why Chrome is warning you about it).
Comment: Server 2003 is out of security support.  Anyone running a CA on that now needs to have their head examined.
Comment: Touchè, sir.  Touchè.
Comment: Ah thanks. That confirms what we've just heard from the chaps issuing the CA - that their Server 2003 CA can only issue SHA-1.  Which isn't ideal... but it puts the issue in their hands rather than ours!


Qual modo correto de fazer UPDATE

Question: Amigos este erro (SQLSTATE[HY093]: Invalid parameter number: parameter was not defined), qual a forma correta de aplicar o UPDATE conforme o código abaixo?
Campos DB
id_seguradora
nome_seguradora
cnpj_seguradora
tel_seguradora
cep_seguradora
rua_seguradora
numero_seguradora
bairro_seguradora
cidade_seguradora
estado_seguradora
responsavel_seguradora
email_seguradora
quemcadastrou
quematualizou
data_hora_cadastro

Código
$nome_seguradora = trim($_POST['nome_seguradora']);
    $cnpj_seguradora = trim($_POST['cnpj_seguradora']);
    $tel_seguradora = trim($_POST['tel_seguradora']);
        $cep_seguradora = trim($_POST['cep_seguradora']);
        $rua_seguradora = trim($_POST['rua_seguradora']);
        $numero_seguradora = trim($_POST['numero_seguradora']);
        $bairro_seguradora = trim($_POST['bairro_seguradora']);
        $cidade_seguradora = trim($_POST['cidade_seguradora']);
        $estado_seguradora = trim($_POST['estado_seguradora']);
    $responsavel_seguradora = trim($_POST['responsavel_seguradora']);
    $email_seguradora = trim($_POST['email_seguradora']);
    $quematualizou = $userRow['nome_funcionario'];
        $data_hora_cadastro = trim($_POST['data_hora_cadastro']);
    $error = FALSE;

    if (!$error) {

            date_default_timezone_set('America/Maceio');
            $datahora = date('Y-m-d H:i:s');

     $sql = "UPDATE `seguradoras` SET `nome_seguradora` = :nome_seguradora, `cnpj_seguradora` = :cnpj_seguradora, `tel_seguradora` = :tel_seguradora, `cep_seguradora` = :cep_seguradora, `rua_seguradora` = :rua_seguradora, `numero_seguradora` = :numero_seguradora, `bairro_seguradora` = :bairro_seguradora, `cidade_seguradora` = :cidade_seguradora, `estado_seguradora` = :estado_seguradora, `responsavel_seguradora` = :responsavel_seguradora, `email_seguradora`        = :email_seguradora, `quematualizou` = :quematualizou, `data_hora_cadastro` = '$datahora' WHERE `id_seguradora` = :id_seguradora ";

      try {
        $stmt = $DB->prepare($sql);

        // bind the values
        $stmt->bindValue(":nome_seguradora", $nome_seguradora);
        $stmt->bindValue(":cnpj_seguradora", $cnpj_seguradora);
        $stmt->bindValue(":tel_seguradora", $tel_seguradora);
                $stmt->bindValue(":cep_seguradora", $cep_seguradora);
                $stmt->bindValue(":rua_seguradora", $rua_seguradora);
                $stmt->bindValue(":numero_seguradora", $numero_seguradora);
                $stmt->bindValue(":bairro_seguradora", $bairro_seguradora);
                $stmt->bindValue(":cidade_seguradora", $cidade_seguradora);
                $stmt->bindValue(":estado_seguradora", $estado_seguradora);
        $stmt->bindValue(":responsavel_seguradora", $responsavel_seguradora);
        $stmt->bindValue(":email_seguradora", $email_seguradora);
        $stmt->bindValue(":quematualizou", $quematualizou);
                $stmt->bindValue(":data_hora_cadastro", $data_hora_cadastro);

        // execute Query
        $stmt->execute();
        $result = $stmt->rowCount();

Comment: deve ter alguma coisa errada com o parâmetro `data_hora_cadastro`... Confira tudo sertim....
Comment: Coloquei assim: `data_hora_cadastro` = :data_hora_cadastro, olha o erro: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Answer: Você passou id_seguradora = :id_seguradora ", mas esqueceu de dar o bindValue   para ele:
$nome_seguradora = trim($_POST['nome_seguradora']);
        $cnpj_seguradora = trim($_POST['cnpj_seguradora']);
        $tel_seguradora = trim($_POST['tel_seguradora']);
            $cep_seguradora = trim($_POST['cep_seguradora']);
            $rua_seguradora = trim($_POST['rua_seguradora']);
            $numero_seguradora = trim($_POST['numero_seguradora']);
            $bairro_seguradora = trim($_POST['bairro_seguradora']);
            $cidade_seguradora = trim($_POST['cidade_seguradora']);
            $estado_seguradora = trim($_POST['estado_seguradora']);
        $responsavel_seguradora = trim($_POST['responsavel_seguradora']);
        $email_seguradora = trim($_POST['email_seguradora']);
        $quematualizou = $userRow['nome_funcionario'];
            $data_hora_cadastro = trim($_POST['data_hora_cadastro']);
        $error = FALSE;

        if (!$error) {

                date_default_timezone_set('America/Maceio');
                $datahora = date('Y-m-d H:i:s');

         $sql = "UPDATE `seguradoras` SET `nome_seguradora` = :nome_seguradora, `cnpj_seguradora` = :cnpj_seguradora, `tel_seguradora` = :tel_seguradora, `cep_seguradora` = :cep_seguradora, `rua_seguradora` = :rua_seguradora, `numero_seguradora` = :numero_seguradora, `bairro_seguradora` = :bairro_seguradora, `cidade_seguradora` = :cidade_seguradora, `estado_seguradora` = :estado_seguradora, `responsavel_seguradora` = :responsavel_seguradora, `email_seguradora`        = :email_seguradora, `quematualizou` = :quematualizou, `data_hora_cadastro` = :data_hora_cadastro WHERE `id_seguradora` = :id_seguradora ";

          try {
            $stmt = $DB->prepare($sql);

            // bind the values
            $stmt->bindValue(":nome_seguradora", $nome_seguradora);
            $stmt->bindValue(":cnpj_seguradora", $cnpj_seguradora);
            $stmt->bindValue(":tel_seguradora", $tel_seguradora);
                    $stmt->bindValue(":cep_seguradora", $cep_seguradora);
                    $stmt->bindValue(":rua_seguradora", $rua_seguradora);
                    $stmt->bindValue(":numero_seguradora", $numero_seguradora);
                    $stmt->bindValue(":bairro_seguradora", $bairro_seguradora);
                    $stmt->bindValue(":cidade_seguradora", $cidade_seguradora);
                    $stmt->bindValue(":estado_seguradora", $estado_seguradora);
            $stmt->bindValue(":responsavel_seguradora", $responsavel_seguradora);
            $stmt->bindValue(":email_seguradora", $email_seguradora);
            $stmt->bindValue(":quematualizou", $quematualizou);
                    $stmt->bindValue(":data_hora_cadastro", $data_hora_cadastro);
            $stmt->bindValue(":id_seguradora ", $id);

            // execute Query
            $stmt->execute();
            $result = $stmt->rowCount();

Isso é um erro muito comum, lembre-se sempre de conferir se passou todos os parametros informados na query.
Faltou algo o tipo:
  $stmt->bindValue(":id_seguradora ", $id);

Coloquei só id, porque nao sei como voce esta armazenando o id, que deseja atualizar.
Edit
Voce errou nessa linha do sql tambem
data_hora_cadastro = '$datahora'

Voce passou a variavel direta, sendo que passou ela no bind.
Deve ficar assim
`data_hora_cadastro` = :data_hora_cadastro

Comment: Apareceu este erro: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Comment: @MauroSantos Voce colocou o id correto que deseja atualizar?
Comment: Sim coloquei...
Comment: vou revisar aqui
Comment: @MauroSantos editei, olha agora
Comment: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/51775/discussion-between-mauro-santos-and-localhost).

Qual modo correto de fazer UPDATE


Can we Combine two convergent infinite series as follows

Question: Given two infinite series $S_0 = \sum_{n=1}^{\infty}\frac{1}{F(x, n)^{p}}$ and $S_1 = \sum_{n=1}^{\infty}\frac{1}{F'(x, n)^{p}}$.
Let both of these series be 'convergent' to the same real value $K$ for some values of $x$.
Assuming for $x = x_0$ this is the case. Thus,
$S_0 = \sum_{n=1}^{\infty}\frac{1}{F(x_0, n)^{p}} = K$
$S_1 = \sum_{n=1}^{\infty}\frac{1}{F'(x_0, n)^{p}} = K$
Now, can we claim that for new series used by combining the corresponding terms of $S_0$ and $S_1$ are also convergent, i.e.:
$S_2 = \sum_{n=1}^{\infty}(\frac{1}{F(x_0, n)^{p}}) - (\frac{1}{F'(x_0, n)^{p}}) = 0$
$S_3 = \sum_{n=1}^{\infty}(\frac{1}{F(x_0, n)^{p}}) + (\frac{1}{F'(x_0, n)^{p}}) = 2K$
I assume this is true, but I am not certain.
Comment: If $S_n \to S $ and $T_n \to T$ then $S_n - T_n \to S -T$. Letting these denote your partial sum sequences we see its OK.
Answer: Yes, since your $x_0$ is fixed anyway we can just use the standard rule of adding two convergent series:
$$
\sum_{n=1}^\infty (a_n + b_n) = \sum_{n=1}^\infty a_n + \sum_{n=1}^\infty b_n.
$$
Comment: For division you'd need that the divisor doesn't converge to $0$. It also works for complex number. The proofs of these facts are pretty standard and shouldn't be too hard to find.
Comment: Thank you. I assume by extension its also true for multiplying and division too? And also were $x$ is a complex number too ?
Comment: Thanks again. I am just beginning in analysis as a self-interest. my background is CS.


Ansible shell command fails under sudo when it should succeed

Question: I have an Ansible task based on https://github.com/al3x/sovereign/blob/master/roles/tarsnap/tasks/tarsnap.yml#L2 that keeps failing when it should succeed.
I used to run the role with ansible_ssh_user=root, but recently switched to using a non-root user that has passwordless sudo rights and then calling become in my playbooks.
However, now the Ansible task fails even though I've specified become=true. Tarsnap is already installed, but the task still returns stderr: /bin/sh: tarsnap: command not found. I think it's because of something around sudo that I don't quite understand.
When I manually ssh into the server as this non-root user and run sudo tarsnap --version | grep 1.0.35 --color=never, I get sudo: tarsnap: command not found. But if I SSH in as root, that same command gives me tarsnap 1.0.35.
Similarly, when I run sudo -i tarsnap --version | grep 1.0.35 --color=never (note the -i), I get tarsnap 1.0.35.
I am using CentOS 7.
1) Why are the results different for sudo vs sudo -i?
2) How do I fix my Ansible task?
Answer: Point to tarsnap with a fully-qualified path, or set your PATH explicitly so it can find tarsnap.  You can find the missing path element by logging in as root and executing which tarsnap
You don't mention what flavour of Linux you are using, so bear in mind that /bin/sh may very well not be the same as /bin/bash (eg. ~/.bashrc and ~/.bash_profile may not be read).
sudo -i will give you an 'interactive' shell. You should see the manual page for bash (if indeed you are using bash) to find out what 'interactivemeans (ie. which files are consulted). I think you'll find thatsudo -iwill read in ~/.bashrc, while justsudo(without-i`) will not.
Comment: Thought so. The shell is interpreting `sudo echo $PATH` before sudo is run. Change the `$PATH` to `\$PATH`
Comment: Thanks, fully qualified fixed it. Using Centos 7. What's weird is if I do `sudo -i which tarsnap` I get `/usr/local/bin/tarsnap`; but then I run `sudo echo $PATH` and `:/usr/local/bin:` is part of the path so I don't get why a normal non-interactive `sudo` can't find tarsnap since it should be checking that path.
Comment: Please show a verbatim transcript of how you determined what PATH was.
Comment: 1) SSH in as my non-root user. Using the default CentOS bash shell. 2) Run `sudo echo $PATH` 3) Result: `/usr/lib64/ccache:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/non-root-user/.local/bin:/home/non-root-user/bin` <-- result contains `/usr/local/bin`


RXJS Get Current Value of a ReplaySubject

Question: I am trying to pull the current value from a ReplySubject on login. On subscribe in the current flow, the previous value is returned instead of a the current value. So the stuff received is the previous stuff at login and not the current stuff. Is there a way to get the current value of the observable on subscribe in the ReplaySubject without having to resort to a BehaviorSubject?
stuff.service.ts:
 private _stuffSubject = new ReplaySubject<any>();
 private _stuff$: Observable<any> = this._someSubject.asObservable();

  get stuff$ () {
   return this._stuff$;
  }

  private fetchStuff () {
    return this.http.get('/stuff/current')
      .map(data =>  {
        return data.json()
      })
      .catch(err => {
        console.debug(this.constructor.name, 'handled error ->', err.message);
        return Observable.of(false);
      })
      .map(stuff => {
        this._stuffSubject.next(stuff);
      })
  }

stuff.component.ts:
this.stuffService.stuff$
  .subscribe(({stuff1, stuff2, stuff3}) => {
    this.stuff1 = `${stuff1}`;
    this.stuff2 = `${stuff2}`;
    this.stuff3 = `${stuff3}`;
  });

Comment: You can always subscribe to `_stuffSubject` to get its current buffer but you won't be able to tell when it emitted all its items.
Answer: You can set the buffer size to 1:
private _stuffSubject = new ReplaySubject<any>(1);

Comment: Its actually not quite the same, ```BehaviorSubject``` will resolve with a value for the first time even if its an undefined value and ```ReplaySubject``` will not resolve until value is emitted
Comment: `ReplaySubject(1)` is like `BehaviourSubject()`, but I think that it buffers the first and throws away subsequent (until subscribed, then the buffer is able to take another)?
Comment: Hi @asmmahmud, you are quite correct the buffer stores the last value.
Comment: ReplaySubject allows you to buffer [n] number of previous values: const mySubject = new Rx.ReplaySubject(2) will buffer 2 previous values...


Converting datetime format to text format in excel

Question: I have an excel file which has data like "04 17" (right aligned) but the format is showing as DateTime i.e 4/1/2017.
My C# Production code is written in such a way that it recognizes if that is mentioned as text format (left aligned).
In the below screenshot all data in "Project Start Date" column need to be left aligned (like I manually wrote in 3rd line).
I am new to excel & macro, please give some clue how to convert these values. I have around 6000 lines, so cant re enter all the columns manually.
Comment: So you c# code is reading the sheet? (not generating it) and do you want to do this as a one off fix? or is this something you want to write a program to do?
Comment: Yes, C# code is just reading it & I am trying to provide a fix without any code change as that's already in production.
Answer: Set "Custom" format on column S, enter "MM YY" in the 'Type' slot (without the quotes) ... then set left alignment for the whole column from the menu.
If you need the text version, enter this formula in an adjacent column, let's say column T, row 6:
=TEXT(S6,"MM YY")
Extend the formula in the column to fill the 6000 row range.  You can optionally lock in the text values by copying the column and then doing a 'Paste Special - Values' into a new column.
Comment: Thanks for the hint. It worked with "mm yy" format which I was missing when I tried initially.


Fire a rule only when a specific webform has been submitted

Question: I am using the latest version of both drupal 8 and webform 8
Here is my use case:
I have on my drupal 8 website 3 different webforms (webform A, Webform B and Webform C)
Now, I want to fire a rule ONLY when "Webform A" is submitted.
I understand that we should use condition to limit the rule to one webform only.
For example in drupal 8 if i want to show a message on the website when a new content of type article is saved, i do the below:
1) EVENT: After saving new content (rules_entity_insert:node)
2) CONDITION: Node is of type; Node is of type: node; Content Types: article
3) ACTION: Show a message on the site.
And it is working pretty good when saving a content of type ARTICLE.
Now, i want ot do the same but using a webform instead of a node.
Here what i did so far:
1) EVENT: After saving a new webform submission (rules_entity_insert:webform_submissiom)
2) ACTION: Show a message on the site.
After saving a new webform submission, the message is indeed showing on the website which is perfect.
However, the problem is that the message is showing for any SUBMITTED WEBFORM.
In order to limit the rules to be fired only when the webform A is sumbitted, a condition should be added to the rule in question.
I have used the below conditions
"Entity is of type"
"Node is of type"
"Webform"
"Webforms"
trying to limit the rule for only one webform and all above conditions resulted an error on the site after trying to submit any webform:
(The website encountered an unexpected error. Please try again later)
And when i remove the condition added, the site work properly again.
Any idea what is going on ?
Or maybe i am using the wrong condition to specify only one webform ?
Main question:
What is the condition to be used in order to fire a rule ONLY when one specific webform has been submitted.
Thank you in advance,
Answer: I got this to work but i don't know if my answer will be the best approach for what i need:
Let's say, we want the rule to be fired ONLY for the webform ID: "contact"
1) EVENT: After saving a new webform submission (rules_entity_insert:webform_submission)
2) CONDITION: Data Comparision;
Data to compare: webform_submission.webform_id.target_id;
Operator: ==
Value: contact
3) ACTION: Show a message on the site.
Hope it will help somebody else as well, especially that there is no documentaion yet for rules 8.
Cheers,


Python API call pagination issue

Question: I am stuck on the following issue: I have the code below for an API call. In and of itself, the API call is fine, no server issues, I have checked it in Postman:
{
    "@odata.context": "https://api.channeladvisor.com/v1/$metadata#Orders",
    "value": [
        {....}
    ],
    "@odata.nextLink": "https://api.channeladvisor.com/v1/Orders?refresh_token=xxx&$skip=100"
}

I am new to all of this, so please bear with me. All I want to do is save all of the records into a data frame at the end, not just the first 100 records. Channel Advisor's documentation is not really helpful, either, and I haven't been able to find what I need when searching on Google.
I found a post here that I massaged to add on the "while" loop, and I had to modify it to fit my requirements.
Code version 1 (full):
import requests
import pandas as pd
import os
import json

def get_access_token():
    url = 'https://api.channeladvisor.com/oauth2/token'
    headers = {'Authorization': 'Basic xxxxx'}
    post_body = {'grant_type': 'refresh_token', 'refresh_token': 'xxxxx'}
    response = requests.post(url, headers=headers, data=post_body)
    return response.json()['access_token']

access_token = get_access_token()

url = 'https://api.channeladvisor.com/v1/orders'
headers = {
    'Authorization': 'bearer ' + access_token,
    'accept': 'text/plain',
    'Content-Type': 'application/json'
}

response = requests.get(url, headers=headers)
response_data = response.json()['value']
response_nextlink = response.json()['@odata.nextLink']

#create list to store the values
data = []
data.extend(response_data)

while True:
    if '@odata.nextLink' in response_nextlink:
        response = requests.request('GET', response_data['@odata.nextLink'], headers=headers)
        response_data = response.json()['value']
        data.extend(response_data['value'])
        response_nextlink = response.json()['@odata.nextLink']
    else:
        break

This code only runs once, likely because the while loop is not set up correctly.
So, I added some error handling:
Code version 2:
while True:
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        print("Error occurred. Status code: ", response.status_code)
        print("Content: ", response.content)
        break
    response_data = response.json().get('value')
    if not response_data:
        break
    data.extend(response_data)
    if '@odata.nextLink' in response.json():
        url = response.json()['@odata.nextLink']
    else:
        break

The result of this is a Status code 400 runtime error. Again, the server is fine when I try the call on Postman.
So, I modified the while loop again:
Code version 3:
while True:
    response = requests.get(url, headers=headers)
    response_data = response.json()['value']
    data.extend(response_data)
    if '@odata.nextLink' in response.json():
        url = response.json()['@odata.nextLink']
    else:
        break

This produces the following error:
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [80], in <cell line: 25>()
     24 while True:
     25     response = requests.get(url, headers=headers)
---> 26     response_data = response.json()['value']
     27     data.extend(response_data)
     28     if '@odata.nextLink' in response.json():

...................

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I am otherwise stuck. What am I doing wrong?
Answer: Since I dont have API access I can only guess that you confused the break condition in the while loop
import requests
import pandas as pd
import os
import json

# start session to store cookies / authentications
s = requests.Session()

url = 'https://api.channeladvisor.com/oauth2/token'
headers = {'Authorization': 'Basic xxxxx'}
post_body = {'grant_type': 'refresh_token', 'refresh_token': 'xxxxx'}
response = s.post(url, headers=headers, data=post_body)
access_token = response.json()['access_token']

url = 'https://api.channeladvisor.com/v1/orders'
headers = {
    'Authorization': 'bearer ' + access_token,
    'accept': 'text/plain',
    'Content-Type': 'application/json'
}

# use session for requests
response = s.get(url, headers=headers)

# parse response only once
json_response = response.json()

response_data = json_response['value']

#create list to store the values
data = []
data.extend(response_data)

while True:
    if '@odata.nextLink' in json_response:
        response = s.request('GET', json_response['@odata.nextLink'], headers=headers)
        print("request returned status", response.status_code, response.text)
        if not response.ok:
            break
        json_response = response.json()
        data.extend(json_response["value"])
    else:
        break

Comment: Thank you for responding! I tried out your code, and I get this error:
Comment: `....---> 34 response = requests.request('GET', response_data['@odata.nextLink'],
 headers=headers)

     35 json_response = response.json()

     36 data.extend(json_response["value"])

TypeError: list indices must be integers or slices, not str`

Sorry about the formatting; I tried mini markdown, but this is what came out.
Comment: From what I understand, and that's as far as I got, `response_data = json_response['value']` sets that variable to, well, the second part of the json response here: `{
    "@odata.context": "https://api.channeladvisor.com/v1/$metadata#Orders",
    "value": [
        {....}
    ],
    "@odata.nextLink": "https://api.channeladvisor.com/v1/Orders?refresh_token=xxx&$skip=100"
}`
But that part does not have the `response_data['@odata.nextLink']` information in it.
Comment: Oh, my bad, there was one wrong line. I updated my code accordingly...
Comment: No worries. :) You're trying to help, and that is very much appreciated. I'll try the code out soon and give you feedback.
Comment: I tried out your code and this line in the `while` loop throws an error: `json_response = response.json()`. The error message is: `JSONDecodeError: Expecting value: line 1 column 1 (char 0)`. Within the Traceback is this block: `UnicodeDecodeError: Wrong UTF codec detected; usually because it's not UTF-8but some other 8-bit codec.  This is an RFC violation, and the server didn't bother to tell us what codec *was* used.` That part is precisely where I got stuck myself and couldn't get past it. Any ideas?
Comment: i updated a few lines that might help you find the error. Maybe you can post the result again?
Comment: The revised `while` loop now returns this response: `request returned status 400`.
Comment: I updated a line to output the error text
Comment: This is the "pretty" response: `Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.` The rest of it talks about how to make a custom error page. BTW, when I click on the link in Postman at the bottom of the JSON response and then send the new request, I get an "authorization has been denied" error.
Comment: i have an idea, one moment
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/252488/discussion-between-dolunaykiz-and-klops).
Comment: Update: @klops code works with a different endpoint, so I am assuming that the errors I am seeing are related to the server itself.

Python API call pagination issue


Area of triangle inscribed in a circle with a specific position

Question: Triangle $ABC$ inscribed in a circle. Versine (green)are drawn from the midpoints of the sides of the triangle perpendicular to them. They have lengths as shown in this figure.

find the area of $\Delta ABC$
honestly, I got stuck on this problem and I was far from geometry for years. Please show me a clue or guide me to get over on this problem. Thanks in advance.
I just find out the lines(green) must cross at one point, because of the middle and perpendicularly. but not go more ...
Comment: Hint: The perpendicular bisetors of a triangle concur at the circumcenter. In other words ... extend your green lines to meet at the center of the circle.
Comment: Alright, but how can I use it ...$R=20+x=16+y=13+z$ ?
Comment: It is easy to find the value of $R$ numerically and then prove it to be the exact result, but I wonder if it is posssible to find the value analytically.
Comment: @user:Can you turn a light to the numerical solution?
Comment: @user: Can you start answer, but not full solution?
Answer: Let $\alpha, \beta, \gamma = 16,20,13$ be the heights of circular segment opposite to vertices $A,B,C$.
Let $R$ be the circumradius. It is easy to see
$$\alpha = R(1-\cos A),\quad \beta = R(1-\cos B) \quad\text{ and }\quad \gamma = R(1-\cos C)$$
Notice for any $3$ angles $A,B,C$ which sums to $180^\circ$, we have the trigonometry identity:
$$1 - \cos^2A - \cos^2 B - \cos^2 C - 2\cos A \cos B \cos C = 0\\
\iff 2(1-\cos A)(1-\cos B)(1-\cos C) = (1- \cos A - \cos B - \cos C)^2$$
In terms of $\alpha,\beta,\gamma$, this leads to
$$2\frac{\alpha\beta\gamma}{R^3} = \left(\frac{\alpha+\beta+\gamma}{R} - 2\right)^2
\quad\iff\quad (2R - (\alpha+\beta+\gamma))^2 R - 2\alpha\beta\gamma = 0
$$
Plug back the values of $\alpha,\beta,\gamma$, this becomes
$$R(2R - 49)^2 - 8320 = (2R-65)(2R^2 - 33R + 128) = 0$$
This cubic equations has $3$ real roots. However, the two roots from the quadratic factor is too small (both $\le 20$). This leaves us with $R = \frac{65}{2}$.
Apply intersecting chord theorem to side $BC$ and its perpendicular bisector, we find
$$\left(\frac{a}{2}\right)^2 = \alpha(2R - \alpha) \implies
a = 2\sqrt{\alpha(2R-\alpha)} = 2\sqrt{16(65-16)} = 56$$
By a similar argument, we find
$$b = 2\sqrt{20(65-20)} = 60\quad\text{ and }\quad c = 2\sqrt{13(65-13)} = 52$$
By Euler's formula between a triangle's area, circumradius and sides, the desired area equals to
$$ \verb/Area/(ABC) = \frac{abc}{4R} = \frac{56\cdot 60 \cdot 52}{2\cdot 65} = 1344$$
Answer: Hint: One can easily check that $R=\dfrac{65}2$ is the only solution of the equation
$$
\arccos\left(1-\frac{13}R\right)+\arccos\left(1-\frac{16}R\right)+\arccos\left(1-\frac{20}R\right)=\pi.
$$


EventTarget is not able to access classList

Question: I am trying to make an expansion panel expand only when clinking the arrow, but when I try to compile it, this function
private _isExpansionIndicator(target: EventTarget): boolean {
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return (target.classList && target.classList.contains(expansionIndicatorClass) );
  }

returns the following error:
"Property 'classList' does not exist on type 'EventTarget'"

Any clues how do I get past this error or do you know any other workaround to acheive the same functionality?
I got it working on stackblitz with no errors...
https://stackblitz.com/edit/basic-material-e6sh1r
Comment: Can you please show the relevant portion of your template?
Comment: No. The thing is working on stackblitz, but it doesn't compile locally....
Answer: Using console.log({event}); and console.log({target});, you can see the following :

The EventTarget is actually MouseEvent, and the target property is not of a fixed type. You can see this post to know more on the subject : SO Post
Since the target element is a span, you can use with TypeScript the HTMLSpanElement type to help you for that.

Here is imo a cleaner solution of what is proposed as an alternative answer :
  expandPanel(matExpansionPanel: any, event: MouseEvent) {
    console.log({event});

    if (!this._isExpansionIndicator(event.target as HTMLSpanElement)) {
      matExpansionPanel.close();
    }
  }

   private _isExpansionIndicator(target: HTMLSpanElement): boolean {
    console.log({target});
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return (target.classList && target.classList.contains(expansionIndicatorClass) );
  }

Comment: In fact, I like your approach better than what I currently have... I think I will go with that! Thank you!
Comment: @gothaf I also think this is more appropriate, IMO you should remove accepted from my answer and mark this answer as accepted. upvoted this answer.
Comment: Ok @Plochie.. Only because you say so... :)
Comment: Thank you guys!! I appreciate your help!
Answer: You need to typecast 'EventTarget' to Element, change function as follows,
private _isExpansionIndicator(target: EventTarget): boolean {
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return ((<Element>target).classList && (<Element>target).classList.contains(expansionIndicatorClass) );
}


percorrer uma lista ate chegar em determinada posição Golang

Question: preciso percorrer uma lista que contem 11 itens mas quero parar no item 9. Esse é o meu codigo até o momento porem ele percorre toda a lista.
n = 10
for i := range lista{
        total += lista[i] * n
        n -= 1
    }

tentei fazer algo como mostrado abaixo, porem não deu certo!
n = 10
for i := range (len(lista) - 2){
        total += lista[i] * n
        n -= 1
    }

Answer: Definimos o limite de vezes que queremos passar no loop na variável stopIndex, comparamos o index atual com nossa variável e chegamos no momento de stop loop.
O comando break é acionado e seguimos o fluxo normal.
Existem diversas maneiras de fazer o caso solicitado, acredito que essa é uma forma simples e de rápido entendimento.
package main

import "fmt"

func main() {
    list := []string{
        "Cereais", "Tangerina", "Castanha", "Banana", "Repolho",
        "Cogumelos", "Pepino", "Manga", "Nozes", "Batatas",
        "Alcachofra",
    }

    stopIndex := 9

    for index, item := range list {
        //Are we at index 9?
        if stopIndex == index {
            break
        }

        fmt.Println(item)
    }

}

Answer: O range deve ser usado num array ou slice. Diferente de outras linguages (como Python), o range não pode ser usado como valor númerico (como de 0...10).
Sua pergunta não define o que é uma "lista", já que slices e arrays são distintos. Irei assumir que seja um slice.

Você pode fazer isso de várias formas, ambas com o for:
for (i := 0; i < 9; i++) {
   total += lista[i] * n
}

Você também pode criar um "novo slice" redimencionado:
for _, item := range lista[:len(lista)-2] {
   total += item* n
}

Note que, neste caso estamos criando um novo slice usando lista[:len(lista)-2] ou pode usar lista[:9]. Quando eu digo "um novo slice", você não está copiando os dados, lembre-se que os slices possuem uma referencia interna, portanto está apenas criando novos 24 bytes, sendo eles: o ponteiro para o dado original, o tamanho (que definiu usando o :len(lista)) e a capacidade.
Note que deve verificar o tamanho do slice antes de ambos os for, uma vez que pode causar um out-of-bound.

Se quiser redimencioanr a capacidade, pode também usar lista[:9:9], mas isso não é necessário. Caso queria "avançar", pode definir isso no inicio, como lista[1:9], isso fará ignorar o primeiro item. ;)


I have created a python library and importing one python file from other in that file but I get import error?

Question:
I am trying to import lr_finder.py inside training.py as
from lr_finder import LRFinder, LRFinder is class inside lr_finder.
But I get import error for lr_finder.py
Comment: Never add `.py` to your imports
Answer: Try this
from .lr_finder import LRFinder

Also have a read about absolute vs relative imports.


How to make jQuery .click function more scaleable

Question: I am having a little trouble getting this to work. I have several anchor tags on a page that use scrollTop for its animation. HTML example
link
What are your terms of service?

and the target

and the jquery
$('a#TOS').bind('click',function() {
     var pos = $('#Svc').offset().top;
     $('html,body').animate({scrollTop : pos}, 500);
     return false;  //stops navigation from adding the id to the url
   });

Now this gets quite bloated having 30+ of these on the same page. Could I modify the code to apply a class to the anchor and make a variable out of the url like so
$('.foo').bind('click', function() {
var href = (this).attr('ID');
var pos = href.offset().top;
$('html,body').animate9{scrollTop : pos}, 500);
return false;
});

the issue Im having is targeting the anchor ID inside the href var and then placing that inside the pos var...thx
Answer: You can give all those links the same class, like this:
What are your terms of service?

Then make your function bind to that class, like this:
$('a.scrollTo').bind('click',function() {
  var pos = $(this.hash).offset().top;
  $('html,body').animate({scrollTop : pos}, 500);
  return false;
});

This binds to all the links but uses the .hash of the link you clicked on to get the scrollTop destination.
Comment: You know, for all the JS/html I do... I never once thought to use the `hash` property of an anchor.
Comment: @mway - It has the `#` already, so it makes a great ID selector...and degrades gracefully with JS disabled to boot, win-win :)
Comment: I recommend using `event.preventDefault()` instead of `return false`. More about why here: http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false
Answer: If I understand correctly what you mean, yes you can. You have to use the hash function in javascript.
So for your markup, if you have
What are your terms of service?

This JS will alert "#Svc" :
$('a.foo').click(function() {
     alert(this.hash);
   });

So in your example, use it to make :
$('a.foo').click(function() {
  var pos = $(this.hash).offset().top;
  $('html,body').animate({scrollTop : pos}, 500);
  return false;
});

By the way, you can use
.click(function() {});

as a shortcut for
.bind('click', function() {});

More details here
Answer: I haven't used the ID for that kind of thing before but maybe you could try using title instead? And then you would just use it in the selector like $(my_title).offset().top. Hope that helps.
Answer: You have to find the element by Id first:
$('.foo').bind('click', function() {
  var href = $(this).attr('ID');
  var pos = $('#'+href).offset().top;
  $('html,body').animate({scrollTop : pos}, 500);
  return false;
});

adding $('#element') around the href should do it, no?
Answer: Try this:
$('a[ID]').bind('click', function() {
var href = $(this).attr('href');
var pos = $(href).offset().top;
$('html,body').animate({ scrollTop : pos}, 500);
return false;
});

Worked for me.  I adjusted the href var.  Pretty sure that was it.  a[ID] as a selector targets any anchors with IDs.


When has the driver who won most races in a season not been champion?

Question: This season could be interesting if Hamilton wins the final race of the season and Rosberg finishes 2nd or 3rd as you would have the unusual situation where the driver with most wins during the season isn't champion.  Hamilton would have 10 wins to Rosberg's 9.
What I want to know is has this happened in previous seasons and can you give me some more detail?
I am aware of 2008 when Hamilton won the title with 5 wins to Massa's 6 - but Hamilton actually won the Belgian GP that year but was given a penalty that handed Massa the win, so you could argue he won the most races that season.  Or at least he saw the chequered flag most times.
Answer: A similar case happened during the 1982 season, where five drivers (Didier Pironi, John Watson, Alain Prost, Niki Lauda, Rene Arnoux) shared the most number of wins with two wins each, while the eventual champion (Keke Rosberg) only had one.
The circumstances behind the championship were quite bizarre, though, as Pironi suffered a career-ending accident during the German GP, five races before the end of the season. Before then, he was leading the championship comfortably.
Compared to the multiple retirements and non-scoring finishes shared between the multiple race-winners, a consistent points haul throughout the season by Rosberg played a huge part in his title victory.
Answer: It happened in 1967.
Jim Clark won four of the eleven Grands Prix but Denny Hulme was the eventual champion with only two wins.
This is in part due to Jim Clark failing to finish four races, while Denny Hulme only failed to finish twice and scoring points in all nine other races.
Answer: It happened a surprising number of times in the 1980s. In addition to 1982, as cited already, it also happened in:
1983 (Prost 4 wins; Piquet champion with 3 wins);
1984 (Prost 7 wins; Lauda champion with 5 wins);
1986 (Mansell 5 wins; Prost champion with 4 wins);
1987 (Mansell 6 wins; Piquet champion with 3 wins);
1989 (Senna 6 wins; Prost champion with 4 wins).
Going much further back in history to what has long been the most famous example, in 1958 Stirling Moss scored 4 wins but Mike Hawthorn took the title with just 1 win.
In addition to scoring the most wins without taking the title in 1967, as cited previously, the great Jim Clark also did so in 1964, with 3 wins compared to the 2 of John Surtees, who won the title.
Comment: Welcome to SE.Sport. Can you add ay references to confirm your written?
Comment: Certainly, ale; here are the relevant references:
Comment: https://en.wikipedia.org/wiki/1958_Formula_One_season
Comment: https://en.wikipedia.org/wiki/1964_Formula_One_season       https://en.wikipedia.org/wiki/1983_Formula_One_season        https://en.wikipedia.org/wiki/1984_Formula_One_season     https://en.wikipedia.org/wiki/1986_Formula_One_season     https://en.wikipedia.org/wiki/1987_Formula_One_season     https://en.wikipedia.org/wiki/1989_Formula_One_season
Answer: In addition to the various instances I cited above, I forgot another one that has been regarded for many years as a classic example: 1977, when Andretti scored 4 wins but Lauda took the title with 3. It's seen as a classic example because Andretti was in the season's outstanding car (the Lotus 78, Colin Chapman's first foray into ground effect, which he would perfect the following year with the Type 79), but he also had a large number of reliability issues and in fact would ultimately finish only third in the championship, while Lauda concentrated on racking up the points in his less advanced but more reliable Ferrari 312T2. https://en.wikipedia.org/wiki/1977_Formula_One_season
Answer: Across all these examples, there are basically two distinct types: first, the ones such as Lauda in '77 where a driver is not in the best car but gets the maximum possible out of it and wins the title through stealth (the absolutely supreme example of this is usually considered to be Prost in '86, when his McLaren MP4/2 was a three-year-old design but he beat the drivers of the dominant Williams-Honda to the title). The other, less well-regarded type is where the world champion takes the title with fewer wins than his own team-mate. The reasons are variable but reliability usually plays a part. In this respect, Lauda's '84 title was less impressive than his '77 one, as he had 2 wins fewer than his McLaren team-mate Prost, but fewer reliability issues. The worst example is probably Piquet in 1987, who only won half the number of GPs won by his Williams team-mate Mansell but had considerably fewer reliability issues and also got away with various mid-race spins and other driving errors. Even the three wins Piquet managed were all inherited, despite having the most dominant car, but he still took arguably the luckiest title in F1 history! It puts the arguments about Rosberg's this year into perspective although Nico's title does undoubtedly fall into this second less impressive category.
Answer: Not sure if he is the one winning more races without being champion, but Nigel Mansell won 7 races in 1986 to lose the title to Alain Prost because, at the last race, in Adelaide, he had a bad rear wheel puncture at approximately 300 Kph on a straight line that he luckily and skillfully saved to end into a huge crash.
Comment: Mansell only won five races that year, not seven - but you're right, he did win the most races that year.
Answer: The existing answers mostly mention one or two examples, but there has yet to be a comprehensive answer that mentions every example. So, from the top:

1958: Mike Hawthorn won the title but Stirling Moss won the most races (4 to Hawthorn's 1). 3rd-placed Tony Brooks also won more races (3) than Hawthorn.
1964: John Surtees won the title but Jim Clark won the most races (3 to Surtees' 2).
1967: Denny Hulme won the title but Jim Clark won the most races (4 to Hulme's 2).
1977: Niki Lauda won the title but Mario Andretti won the most races (4 to Lauda's 3).
1979: Jody Scheckter won the title but Alan Jones won the most races (4 to Scheckter's 3).
1982: Keke Rosberg won the title, but no less than five drivers (Didier Pironi, John Watson, Alain Prost, Niki Lauda, and René Arnoux) won more races than him (2 to Rosberg's 1).
1983: Nelson Piquet won the title but Alain Prost won the most races (4 to Piquet's 3).
1984: Niki Lauda won the title but Alain Prost won the most races (7 to Lauda's 5).
1986: Alain Prost won the title but Nigel Mansell won the most races (5 to Prost's 4).
1987: Nelson Piquet won the title but Nigel Mansell won the most races (6 to Piquet's 3).
1989: Alain Prost won the title but Ayrton Senna won the most races (6 to Prost's 4).
2008: Lewis Hamilton won the title but Felipe Massa won the most races (6 to Hamilton's 5).
2016: Nico Rosberg won the title but Lewis Hamilton won the most races (10 to Rosberg's 9).

As Lister Jaguar noted, this was very common from the late 70s through to the late 80s, due to a combination of increased competitiveness and lower reliability.


My array loop is way really slow. Is there any way to improve this?

Question: I am looping through each cell in my data to see if it matches specific string. If it matches, then it will terminate the loop and ask the end user to review the data. The thing is, this is still taking way too long if I have a lot of data. Is there a way to improve the speed of this? Thank you!
  Dim Keywords As Variant
    Dim SearchRange As Range
    Dim iRange_Col As Integer
    Dim lRange_Row As Long
    Dim vArray As Variant
    Dim lCnt As Long
    Dim lRowCnt As Long
    Dim keyw As Variant
    Dim val As String
    Dim found As Boolean

    Keywords = Array(Chr(34), "'", ",")
    lastrow2 = ThisWorkbook.Worksheets("Data").Range("A" & Rows.Count).End(xlUp).Row
    Set SearchRange = ThisWorkbook.Sheets("Data").Range("A1:BK" & lastrow2)
    iRange_Col = SearchRange.Columns.Count
    iRange_Row = SearchRange.Rows.Count
    ReDim vArray(1 To iRange_Row, 1 To iRange_Col)
    vArray = SearchRange

    For lRowCnt = 1 To iRange_Row
        If ThisWorkbook.Worksheets("Import").Range("D16") = "Revised!" Or _
           ThisWorkbook.Worksheets("Import").Range("D15") = "Revised!" Or _
           ThisWorkbook.Worksheets("Import").Range("D17") = "Revised!" Then
            Exit For
        End If
    For lCnt = 1 To iRange_Col
        If ThisWorkbook.Worksheets("Import").Range("D16") = "Revised!" Or _
           ThisWorkbook.Worksheets("Import").Range("D15") = "Revised!" Or _
           ThisWorkbook.Worksheets("Import").Range("D17") = "Revised!" Then
            Exit For
        End If
        Application.StatusBar = lCnt
        val = vArray(lRowCnt, lCnt)

       For Each keyw In Keywords
           found = InStr(1, val, keyw) <> 0
           If (found) Then
               Exit For
           End If
       Next

    If found Then
        If keyw = "," Then
            ThisWorkbook.Worksheets("Import").Range("D15") = "Revised!"
        Else
            If keyw = Chr(24) Then
                ThisWorkbook.Worksheets("Import").Range("D17") = "Revised!"
            Else
                If keyw = keyw = "'" Then
                    ThisWorkbook.Worksheets("Import").Range("D16") = "Revised!"
                End If
            End If
        End If

    End If

    Next lCnt
 Next lRowCnt

Comment: If you're interested in a fuller review of your code, this might be a good candidate for [CodeReview](http://codereview.stackexchange.com/)
Comment: You seems to be exiting the routine as soon as you've found a single "problem" character.  Wouldn't you (and your end-users) be better-off if you highlight all "problem" cells ? Maybe set the cell font red if it contains one of the characters?
Comment: If you dump the range into a `Variant` array it will be much faster, see for example here: http://stackoverflow.com/questions/8178161/what-is-the-most-efficient-quickest-way-to-loop-through-rows-in-vba-excel
Comment: Turning off the screen-updating with `Application.ScreenUpdating = False` should improve it.
Comment: You have a typo in there: `Chr(34)` but then later you have `Chr(24)`   How much data do you have?
Comment: @TimWilliams Yeah I noticed the typo too. Fixed that. Data could get as big as 100k. I would love to highlight all "problem" cell. But if that causes the code to run even slower, I would rather not.
Comment: @loannis: I tried changing searchrange into a variant instead. But the code crashes when i tried running it. Did I do it wrong?
Comment: @AndyG I did. It did run a little faster. but still pretty slow when it comes to large data set.
Comment: I would first change the name to something like `vSearchRange` and then do `vSearchRange = ThisWorkbook.Sheets("Data").Range("A1:BK" & lastrow2).Value2`. No `ReDim` is necessary. Then instead of `SearchRange.Rows.Count` we need `Ubound(vSearchRange, 1)` and `SearchRange.Columns.Count` should become `Ubound(vSearchRange, 2)`. I would also store the values of `D16:D18` so that you do not have to poke the `Worksheet` object in each iteration.
Comment: I guess my point about listing all errors is that if I were *using* this code I'd not be very happy with continually having to run it just to find the single next problem and then run it yet again after that one was fixed. If you think it's already too slow, then just running it *once* seems like a better option. I guess it all depends on what you expect the "error rate" in the data will be....
Comment: You have another typo ,`Dim lRange_Row As Long`, and later you're referencing `iRange_Row = SearchRange.Rows.Count`.  That's why it's important to have `Option Explicit` at the top of every module.
Answer: One thing that speeds things up is commenting out the Application.StausBar line.  In my case, processing 40,000 rows went from 2.5 minutes to just under 7 seconds.  Also, as Ted Williams suggested, this routine highlights ALL flagged cells in one shot.  Hope this is helpful.
Sub findHilite()

    Dim Keywords As Variant
    Dim SearchRange As Range
    Dim vArray As Variant
    Dim lCnt As Long
    Dim lRowCnt As Long
    Dim keyw As Variant
    Dim val As String
    Dim lastrow2 As Long
    Dim rBld As Range

    Keywords = Array(Chr(34), "'", ",")
    lastrow2 = ThisWorkbook.Worksheets("Data").Range("A" & Rows.Count).End(xlUp).Row
    Set SearchRange = ThisWorkbook.Sheets("Data").Range("A1:BK" & lastrow2)

    SearchRange.Interior.ColorIndex = xlNone

    vArray = SearchRange

    For lRowCnt = 1 To SearchRange.Rows.Count 'rows loop
        For lCnt = 1 To SearchRange.Columns.Count 'columns loop
'            Application.StatusBar = lRowCnt 'display row count
            val = vArray(lRowCnt, lCnt)

            For Each keyw In Keywords
                If InStr(1, val, keyw) <> 0 Then
    '               build range consisting of flagged cells
                    If Not rBld Is Nothing Then
                        Set rBld = Union(rBld, SearchRange(lRowCnt, lCnt))
                    Else
                        Set rBld = SearchRange(lRowCnt, lCnt)
                    End If
                    Exit For
                End If
            Next

        Next lCnt
    DoEvents
    Next lRowCnt
    On Error Resume Next
    rBld.Interior.ColorIndex = 3 'hilite flagged cells in one step, saves time
    On Error GoTo 0

End Sub


insert value in a table from another table

Question: Plase someone help me in adding a value from table to another table in sql server
I have one table with columns (reserve,name,price)
and another table with columns (name,price)
i want to insert into table1(price) value from table2(price)
Comment: check this: http://sqlandme.com/2013/06/18/sql-server-update-table-with-inner-join/
Answer: INSERT INTO TABLE1(Price)
(
    SELECT Price FROM TABLE2
)

Answer: posting as answer:
If you are trying to update price column in Table1 to values in Table2(Price):
UPDATE TBL1
SET    TBL1.Price = TBL2.Price
FROM   Table1 TBL1
INNER JOIN Table2 TBL2 ON TBL1.name = TBL2.name

Answer: using (SqlConnection con= new SqlConnection(connectionString))
{
 MySqlCommand cmd = new MySqlCommand("INSERT INTO table2(name,price) SELECT name,price from table1", con);
 con.Open();
 cmd.ExecuteNonQuery();
}

Answer: Query: Inserting data from one table to another
1) Using Insert into :  It is used when table is already created in the database earlier and data is to be inserted into this table from another table also having same schemas
 insert into tb1 (name,price) select name,price from tb2;

2) Using Select into:  It is used only if the table specified in the INTO clause does not exist. It will create  new table same data types as selected columns.
select name,price into tb3 from tb2;

DEMO SQL FIDDLE
Answer: insert into table1(price) select price from table2


Neural Network Forward Propagation

Question: I'm trying to solve this neural network problem found here:

How do I go ahead and calculate the forward propogate in this example? I've see examples of how to calculate the expected output but that is given here, and I'm note quite sure what I even need to do or start doing to calculate the forward propagate
Comment: Please paste in whatever context is necessary to understand your question so that it is self-contained. People aren't going to want to download & read something to understand your question. (You can still leave a link to the full pdf for more context for those who want it.)
Comment: @EngrStudent what difference does that make?
Comment: This looks like homework.
Answer: Forward propogation is simply multiplying input with weights and add bias before applying activation fuction (sigmoid in here) at each node. There is no bias in this question.
$ W^{(1)}*x = z^{(1)} = \begin{bmatrix}
       \ W_{11}^{(1)} & \ W_{12}^{(1)} \\[0.3em]
       \ W_{21}^{(1)} & \ W_{22}^{(1)}
     \end{bmatrix} * \begin{bmatrix}
       \ x_1  \\[0.3em]
       \ x_2
     \end{bmatrix} = \begin{bmatrix}
       \ 0.5 & \ 0.1 \\[0.3em]
       \ 0.25 & 0.75
     \end{bmatrix} \begin{bmatrix}
       \ 1  \\[0.3em]
       \ 0
     \end{bmatrix}  = \begin{bmatrix} \ 0.5  \\[0.3em] \ 0.25  \end{bmatrix}$
$ a^{(2)}= sigm(z^{(1)}) = sigm(\begin{bmatrix} \ 0.5  \\[0.3em] \ 0.25  \end{bmatrix}) = \begin{bmatrix} \ 0.6225  \\[0.3em] \ 0.5622 \end{bmatrix}   $
$ W^{(2)}*a^{(2)} = z^{(2)} = \begin{bmatrix}
       \ W_{11}^{(2)} & \ W_{12}^{(2)}
     \end{bmatrix} * \begin{bmatrix}
       \ a^{(2)}_1  \\[0.3em]
       \ a^{(2)}_2
     \end{bmatrix} = \begin{bmatrix}
       \ 0.95*0.6225 + 0.5622*1.0
     \end{bmatrix} = 1.1536 $
$ a^{(3)}= sigm(z^{(2)}) = sigm(1.1536) =  0.7602  $
This is your output, and assume that your cost function is
$ C = \frac{1}{2}(a^{(3)} -y )^2$
where y is expected output = 0.5, and output error term derived as,
$ δ^{(3)} = \frac{dC}{dz^{(2)}} = (a^{(3)} -y ).* a^{(3)}.*(1-a^{(3)}) = (0.7602 - 0.5) .*0.7602.*(1-0.7602) = 0.0474$
where '.*' is element-wise product and $a^{(3)}.*(1-a^{(3)})$ comes from derivation of sigmoid. I've assumed that error term calculated with respect to $ z$,not $ a$. If that is the case the derivation changes a little bit. Now back propogate $ δ^{(3)}$, to find $ δ_{2}^{(2)}$
$ δ_{2}^{(2)} =  \frac{dC}{dz^{(2)}} * \frac{dz^{(2)}}{dz_{2}^{(1)}} =  δ^{(3)} * \frac{dz^{(2)}}{dz_{2}^{(1)}} $
let's drive the second term before we continue
$ \frac{dz^{(2)}}{dz_{2}^{(1)}} = W_{12}^{(2)}.*a_{2}^{(2)}.*(1-a_{2}^{(2)})$ from $ z^{(2)}= W^{(2)}*sigm(z^{(1)}) $
now we can evaluate previous equation,
$ δ_{2}^{(2)} =  \frac{dC}{dz^{(2)}} * \frac{dz^{(2)}}{dz_{2}^{(1)}} =  δ^{(3)} * W_{12}^{(2)}.*a_{2}^{(2)}.*(1-a_{2}^{(2)}) = 0.0474 * 1.0 * 0.5622 * (1-0.5622) = 0.0117 $
You can see that how error term diminishes quickly during back propogation if we use sigmoid activation(or hyperbolic tangent).

Neural Network Forward Propagation


Change ASP .NET CORE Identity default email address under the Username column

Question: ASP .NET CORE Identity stores email address as default under the Username column. How do i change it from storing the email address as a Username to a custom name as a username ?
Answer: This is just how the default UI handles it. If you want to do it another way, then you'll need to scaffold the Register page into your project and change it. Specifically, you're looking for this line in Register.cshtml.cs:
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);

There, you'll simply change Input.Email to something like Input.UserName. Of course you'll need to add a UserName property to the page model so that you can collect this information in the first place, and add an input to the view accordingly.
Answer: You can always change scaffolded register page to have both username field and email field. The model already have both.
More importantly if you willing to have separate username field you have to be more careful on places where you retrieve users by email address. If the email address is not unique, then you got to be in trouble if you do not pay attention to those places. Specially on pages like reset password page.
I faced a similar kind of situation. Our application originally built to have email as username. Therefore in the db both username and email were same. So throughout the application there were lot of pages where we retrieved user by email. Then client wanted to have non email usernames. After supporting it,  reset password was not working, because email address was not unique and had multiple users with same email.
To fix the issue what I could do is change the reset password Uis or make email as unique field.
To make email unique in asp. Net core identity you can use options.User.RequireUniqueEmail = true;  in identity service Startup.cs file.
Even though it is too late to  answer this question, I thought to answer this today because this can be helpful to some one in 2021
Answer: When you scaffold Identity and register a user, the OnPostAsync handler in Register.cshtml.cs has following code to create the user which decides the value of UserName column.
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);

You could cahnge UseName = Input.Email to your custom name.


Eclipse Indigo Outline (PHP Mode, Subclipse) is flickering with large classes

Question: my Eclipse Indigo Outline is flickering when i click around
the code of large php classes.
I think it has something to do with subclipse because after the flickering ends the revision number & date is displayed.
Does anyone know a solution to this problem ?
My eclipse looks like this:
<code>  Android DDMS  18.0.0.v201203301601-306762

  Android Development Tools 18.0.0.v201203301601-306762

  Android Hierarchy Viewer  18.0.0.v201203301601-306762

  Android Traceview 18.0.0.v201203301601-306762

  CollabNet Merge Client    3.0.8

  Eclipse SDK   3.7.1.M20110909-1335

  PHP Development Tools (PDT) SDK Feature 3.0.0.v201201110400-77-184_2BEICRgM_fMVcz0M4Va9O

  Subclipse (Required)  1.8.9

  Subclipse Integration for Mylyn 3.x (Optional)    3.0.0

  Subversion Client Adapter (Required)  1.8.2

  Subversion JavaHL Native Library Adapter  188.8.131.52

  Subversion Revision Graph 1.1.1
</code>
Thank you,
Lucian
Answer: An update to "Eclipse SDK Version: 3.7.2 Build id: M20120208-0800"
solved my problem ! The outline doesnt blink anymore.
Lucian
Comment: It seems that i also forgot to switch from JAVA to PHP Mode while editing large PHP classes, which could also have caused the blinking...