What do I need to know to integrate any rational function?

Question: My analysis book makes the following statement:

Every rational function with real coefficients can be integrated in terms of

rational functions,
logarithm functions,
arctangent functions.

Does it mean that after polynomial division, partial fraction expansion, completing the square, substituting where needed, and knowing that
\begin{align}
\\  \int \frac{dx}{(x-a)^n} &= -\frac{1}{n-1} \frac{1}{(x-a)^{n-1}} \ \ \ (n \neq 1)
\\  \int \frac{dx}{x-a} &= \log|x-a|
\\  \int \frac{dx}{x^2+1} &= \arctan x
\end{align}
one can  integrate any rational function?
Comment: In principle. In reality, you will often not be able to split the polynomials into irreducible factors.
Comment: You also need to be able to compute $$\int \frac{dx}{(x^2+1)^n}$$ for $n > 1$.
Comment: @mrf: I saw this one in many materials, yet I didn't quite understand why should we pay special attention to the integral if it can be quickly reduced to the 1st case after substitution and partial integration?
Comment: @Leo If you know complex numbers you can do it even without arctangent... You can just reduce it to the first and second formula (always).
Answer: You're in part right, as compared to this page. Yes, you need to know about polynomial division, but you also need to know about the degree of the numerator and the denominator, beacuse (and this comes from the link) the degree of the numerator and denominator determines what to do first. If the degree of the numerator is greater than that of the denominator, you do polynomial division, otherwise, you need to factor the denominator. Then you do partial fraction expansion (like you said). Yes, you may need to know the conditions you stated because the rational function could be of any of those forms.
This is the best thing I can say, but I hope this helps!
Answer: I just came across a very similar claim in my book's (Spivak's Calclus) solution manual. I think the following explanation is why you can find the integral of any rational functional (note: Spivak's book deals with $\mathbb R$, so the following comments are specific to polynomials whose coefficients are $\in \mathbb R$ and whose input is restricted to $\mathbb R$).
I will restrict my discussion to rational functions where the degree of the polynomial in the numerator is less than the degree of the polynomial in the denominator (note that if the degree of the numerator is greater than or equal to the degree of the denominator, then the fraction can be rewritten as some polynomial - possibly a constant - plus some new fraction where the degree of the numerator is less than the degree of the denominator...obviously, all polynomials can be easily integrated).

There are two theorems that Spivak provides (without proof here or in the book's text):

Theorem 1: Every polynomial function $q(x)=x^m+b_{m-1}x^{m-1}+\cdots+b_0$ can be written as a product of the form: $q(x)=(x-\alpha_1)^{r_1}\times\cdots\times(x-\alpha_k)^{r_k}\times(x^2+\beta_1 x+\gamma_1)^{s_1}\times\cdots\times(x^2+\beta_{\ell}x+\gamma_{\ell})^{s_{\ell}}$ where $r_1+\cdots+r_k+2(s_1+\cdots+s_{\ell})=m$

The results of the first theorem are ultimately used in the second theorem:

Theorem 2: If $n \lt m$ and $p(x)=x^n+a_{n-1}x^{n-1}+\cdots+a_0$, $q(x)=x^m+b_{m-1}x^{m-1}+\cdots+b_0$, then $\frac{p(x)}{q(x)}$ can be written as a sum of terms that take on one of the following three forms:

$\frac{a}{(x-b)^k}$

$\frac{a}{(x^2+bx+c)^k}$

$\frac{ax+b}{(x^2+cx+d)^k}$

(The full version of the theorem is written much more precisely...and I will include this at the bottom of the post...but, for the purpose of my answer, the above 3 forms are satisfactory).
One by one, we will consider how to approach integrating these fractions. A useful formula is the following (which can be proven using integration by parts):

$\displaystyle\int\frac{1}{(x^2+1)^n}dx=\frac{1}{2n-2}\frac{x}{(x^2+1)^{n-1}}+\frac{2n-3}{2n-2}\int \frac{1}{(x^2+1)^{n-1}}dx \quad (\dagger_1)$

First Expression
$\displaystyle\int \frac{a}{(x-b)^k}dx=a\int\frac{1}{(x-b)^k}dx$
We can perform $u$-substituion letting $u=x-b$, which gives us $a\int \frac{1}{u^k}du$. Of course, the integral of this is just $a \times\frac{1}{-k+1}\times u ^{-k+1}$ or $a\log(u)$ (depending on the value of $k$). Following the final substitution, we just have: $\frac{a}{-k+1}\frac{1}{(x-b)^{k-1}}$...or $a\log(x-b)$.

Second Expression
It is important to first see that the following expressions are all equivalent:
\begin{align} x^2+bx+c &= \left(x+\frac{b}{2}\right)^2+\left(c-\frac{b}{4}\right)\\&=\left(c-\frac{b}{4}\right)\left[\frac{\left(x+\frac{b}{2}\right)^2}{c-\frac{b^2}{4}}+1\right] \\&=\left(c-\frac{b}{4}\right)\left[\left(\frac{x+\frac{b}{2}}{\sqrt{c-\frac{b^2}{4}}}\right)^2+1\right]\end{align}
As such, consider next that $\displaystyle \int\frac{a}{(x^2+bx+c)^k}=a\int \frac{1}{\left(\left(c-\frac{b}{4}\right)\left[\left(\frac{x+\frac{b}{2}}{\sqrt{c-\frac{b^2}{4}}}\right)^2+1\right]\right)^k}dx=\frac{a}{\left(c-\frac{b}{4}\right)^k}\int\frac{1}{\left[\left(\frac{x+\frac{b}{2}}{\sqrt{c-\frac{b^2}{4}}}\right)^2+1\right]^k}dx$
We can now perform a $u$-substitution letting $u=\frac{x+\frac{b}{2}}{\sqrt{c-\frac{b^2}{4}}}$. Consistent with the notation of the $u$-substitution method, we would then write that $du=\frac{1}{\sqrt{c-\frac{b^2}{4}}}dx \iff \sqrt{c-\frac{b^2}{4}} du=dx $. We can therefore express our integral as:
$$\frac{a\cdot \sqrt{c-\frac{b^2}{4}}}{\left(c-\frac{b}{4}\right)^k} \int \frac{1}{\left(u^2+1\right)^k}du$$
You should notice that we can now apply our reduction formula $(\dagger_1)$ as many times as necessary (reduce it down to $\int \frac{1}{(u^2+1)^1}du$...which is just $\arctan(u)$). Substitute back in the appropriate value for $u$, and we are done.

Third Expression
To deal with expressions of the third form, consider the following:
If $g(x)=x^2+cx+d$, then $g'(x)=2x+c$. Compare $g'$ with the function $h(x)=ax+b$. We can describe $h$ in terms of $g'$ with the following trick:
$ax+b=\frac{\frac{2}{a}(ax+b)}{\frac{2}{a}}=\frac{1}{\frac{2}{a}}\left(2x+\frac{2}{a}b\right)=\frac{1}{\frac{2}{a}}\left(2x+\frac{2}{a}b+(c-c)\right)=\frac{1}{\frac{2}{a}}(2x+c)+\frac{1}{\frac{2}{a}}(\frac{2}{a}b-c)$...really, all this is saying is that one line ($2x+c$) can be made into another line ($ax+b$) through the action of scaling (changing the slope) and vertical translation. Using this trick, we can rewrite the third expression as:
\begin{align}\int\frac{ax+b}{(x^2+cx+d)^k}dx &= \int \frac{\frac{1}{\frac{2}{a}}(2x+c)+\frac{1}{\frac{2}{a}}(\frac{2}{a}b-c)}{(x^2+cx+d)^k}dx\\&=\frac{1}{\frac{2}{a}}\int \frac{2x+c}{(x^2+cx+d)^k}dx+\frac{1}{\frac{2}{a}}(\frac{2}{a}b-c)\int \frac{1}{(x^2+cx+d)^k}dx\end{align}
For the integral on the left, perform the $u$-substitution $u=x^2+cx+d$...which, as alluded to earlier, would give us $du=(2x+c)dx$. Therefore:
$$\frac{1}{\frac{2}{a}}\int \frac{2x+c}{(x^2+cx+d)^k}dx=\frac{1}{\frac{2}{a}}\int \frac{1}{u^k}du$$
Of course, this integral has an established form that we previously referenced in the First Expression section. For the integral on the right, well...we have already addressed how to determine this integral in the Second Expression section.
All done!

Theorem 2: If $n \lt m$ and $p(x)=x^n+a_{n-1}x^{n-1}+\cdots+a_0$, $q(x)=x^m+b_{m-1}x^{m-1}+\cdots+b_0$, which, by Theorem 1, is equal to $(x-\alpha_1)^{r_1}\times\cdots\times(x-\alpha_k)^{r_k}\times(x^2+\beta_1 x+\gamma_1)^{s_1}\times\cdots\times(x^2+\beta_{\ell}x+\gamma_{\ell})^{s_{\ell}}$, then $\frac{p(x)}{q(x)}$ can be written as \begin{align}\left [\frac{a_{1,1}}{x-\alpha_1} +\cdots+\frac{a_{1,{r_1}}}{(x-\alpha_1)^{r_1}} \right] &+\cdots \\+\left[\frac{\alpha_{k,1}}{x-\alpha_k}+\cdots+\frac{\alpha_{k,r_k}}{(x-\alpha)^{r_k}}  \right] \\&+\left[\frac{b_{1,1}x+c_{1,1}}{x^2+\beta_1x+\gamma_1} +\cdots+\frac{b_{1,s_1}x+c_{1,s_1}}{(x^2+\beta_1x+\gamma_1)^{s_1}} \right]+\cdots \\+\left[\frac{b_{\ell,1}x+c_{\ell,1}}{x^2+\beta_{\ell}x+\gamma_1} +\cdots+\frac{b_{\ell,s_{\ell}}x+c_{\ell,s_{\ell}}}{(x^2+\beta_{\ell}x+\gamma_{\ell})^{s_{\ell}}} \right]\end{align}


How to make all my external jquery files load properly for the Dom effects in partials to work in angular routing

Question: Hi I am working on a project where I have a web template theme which contains a lot of jquery files. I want to use angular in it. When I apply the angular routing by making partials out of its contents these jquery effects in my page are failing to work properly. So how to do angular routing the right way where a html page into which a partial is loaded contains a lot of external jquery files.
I have tried using ocLazyLoad and Requirejs etc etc non of those are working which I found as solutions from stackoverflow.
Can any one tell the steps how to do it right way routing for it.
Answer: This questions lacks of some details so i'll try to handle some possible case that might not concern you :

If you use script tag in a template loaded by ngRouter it won't work.
If you're jQuery is triggering whenever document (the javascript object) is Loaded, it won't work, because partials as not loaded yet.

So how to do angular routing the right way where a html page into which a partial is loaded contains a lot of external jquery files.

Well since it's still a braod way of describing what you have i can only give you some generals way :

Listen for route events to trigger your jQuery at the right time : $routeChangeSuccess will be your friend
Wrap jQuery in directives. For instance, i don't use ui-bootstrap so i wrapped the bootstrap component that i needed like this :

module.directive('ngToggle', ['$log', function($log){
    return {
        restrict: 'A',
    link: function(scope, element, attrs){
         if (attrs.ngToggle=="tooltip"){
                $(element).tooltip();
              }
         ...
       }
    }


How do I wrap a view row inside a ?

Question: I have bad-designed a view, and the result is that I have the following scheme:

Field 1: Category (taxonomy)
Field 2: Node title
Field 3: Image
Field 4: Other data (PHP processed).

The problem is that I need field 1 to appear just once for a group of nodes and not always. As I had to redo all the View, I have made the following process, please tell me if there is a better solution.
Instead of not displaying field 1, grouping by that, etc., as I have some PHP process on it, I do the following:
In views-view-fields.tpl.php I identify the category, and prepend [[BEGIN]]. I identify the last field and append [[END]].
In views-view-unformated.tpl.php I replace [[BEGIN]] and [[END]] with
 wrappers; depending on the valued inside (preg_match), I make the category title  appear just once at the beginning of the list of products.
Please tell me if that is a valid approach (it works) or it should be more desirable to re-draw the view (hours of changing fields, logic, etc.).
The string replacement outputs an additional
 which wraps all the complete row of fields. This I had in the view as the field 1 was just another field and did not encapsulate anything. Maybe even if I would set it as grouping field it didn't encapsulate anything. The result I want (and get) is:

 divs and HTML stuff from the view

The only easy and fast way of doing a
 encapsulation of the row is using those delimiters in the template files.
Comment: Can you also post your expected output?
Comment: Added at the end of the edited answer. Basically I get a warping div with some codification that I can not get by any other means, but surely there must be a (far) better way of doing this.
Comment: do you want to wrap the div in all views row or each rows? just want to clarify before answering it.
Comment: All views rows til the end is marked. In fact, I put just a unique delimited [BEGIN] as it does not always appear (category is not shown, php logic). When I find [BEGIN] I wrap inside an additional div. By using counters I take care of the closing div tags.
Comment: You want field 1 to appear in row 1 only? Is that your question?
Comment: Well, there is a mixture of things I do because of bad design. I put a field which in the Views appears always, and with preprocess php code, I set it to appear just once. Later when it appears I mark it with a tag which later use to warp inside a div, enclosing a bunch of rows. It is clearly bad desing, I am sure that the enclosing div could have been set at the View GUI. By not grouping there or something I have the category field, which must appear just once, appearing in all rows, and I have to do all the logic commented.
Answer:
Add field and Exclude from Display.
Add Global: Text area in the header.
Check Use replacement tokens from the first row
Enter the row pattern
Use css to make it look part of the first row

That will output the first row's field in the header.
Comment: I don't see how the Header will be repeated after a few rows, when the Category changes, it seems something that goes just once at the very beginning of the View. Also, I have used the replacement tokens, and get "Content: Category" literally written when I use [field_category]. I would have expected the full pattern text be replaced by the category name, and not by the literal "Content: Category".
Comment: Ah ok, I thought you only mentioned grouping as a way to give the field.. Didn't realise there were multiple types.
Comment: And what about the literal "Content: Category" being shown? What is its value? May it be a bug?
Comment: What happens with [title] or [nid] ?
Comment: Title is the only one that behaves as expected (see replacement by Cold fusion of [title]: [Content: Category]">[Content: Category] Title: Cold fusion NID: [nid]
Comment: And you have the fields added to the view? Sounds weird..
Comment: My fault, I had set the replacement in the own field besides the Global Area. Now it is working right, but this will not work because of the multi-rows.
Comment: Do you know how many groupings there will be? Could just do attachment views and filter each by category.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/44291/discussion-between-cesar-and-niall-murphy).

How do I wrap a view row inside a ?


Offset cells in Excel on different Sheets

Question: I have an exported data and I'm trying to move it arount so it's easier for my boss to read. The exported data are on 3 lines per record so it looks like this:
Name    A    Date    Total
        B
        C

And I need it to look like this:
Name  A  B  C  Date   Total

So I've created a second sheet and am using a formula in cell A4 =Sheet1!B9
refering to the Name and then I have manually done it so it increases by 3 for each record (person). But it's a pain in the butt to do for all 6 columns. I know there has to be a way to do it using OFFSET, but I can't figure it out.
Is there a way to tell Excel to take the cell that is next to a referenced cell? i.e. if cell A4 on Sheet2 is pointed as above to B9, is it possible to use OFFSET or some other function to tell cell A5 to point to one cell down from that cell by pointing at A4, instead of having to link it directly?
Thanks!
Answer: If the data is as shown below, and the desired result as well the solution is beneath the picture.

Below are the OFFSET formulas for the first row in the RESULT area. They can be copied down to produce the result shown in picture.
For Name, A's, Date, Total the formula looks like this:
=OFFSET($A$1;(ROWS($E$1:$E1)-1)*3;0), the only part that changes is the first argument, ex. $A$1-For Name; $B$1-For A's; etc.
For B's the formuka looks like this:
=OFFSET($B$1;(ROWS($E$1:$E1)-1)*3+1;0)-notice the +1
For C's the formula looks like this:
=OFFSET($B$1;(ROWS($E$1:$E1)-1)*3+2;0)-notice the +2


Node unable to leave cluster for eJabberd upgrade

Question: Environment

ejabberd version: 20.04
Erlang version: Erlang (SMP,ASYNC_THREADS)(BEAM) emulator version 9.2
OS: Linux (Debian)
Installed from: source

Errors from crash.log
2022-02-08 22:42:45 =CRASH REPORT====
crasher:
initial call: pgsql_proto:init/1
pid: <0.27318.6018>
registered_name: []
exception exit: {{init,{error,timeout}},[{gen_server,init_it,6,[{file,"gen_server.erl"},{line,349}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
ancestors: ['ejabberd_sql_vhost1.xmpp_12','ejabberd_sql_sup_vhost1.xmpp',ejabberd_db_sup,ejabberd_sup,<0.87.0>]
message_queue_len: 0
messages: []
links: []
dictionary: []
trap_exit: false
status: running
heap_size: 376
stack_size: 27
reductions: 997
neighbours:
Bug description
I am trying to upgrade from eJabberd 20.04 to 20.07. My cluster setup has three nodes. The rolling upgrade on two nodes were successful. When node1 is trying to leave cluster for upgrade, it gives the following error:
Failed RPC connection to the node 'firstname.lastname@example.com: timeout
When I try ejabberdctl status, the following was returned:
The node 'email@example.com' is started with status: started
Failed RPC connection to the node 'firstname.lastname@example.com': {'EXIT',
{timeout,
{gen_server,call,
[application_controller,
which_applications]}}}
On Erlang shell, the node is still shown part of the cluster
nodes().
['firstname.lastname@example.com','firstname.lastname@example.com']
Could you please help me in resolving this issue.
Comment: This same question was silently cross-posted in https://github.com/processone/ejabberd/issues/3764
Answer: This may be a dumb comment, but just in case it gives you some idea:
You are running the leave_cluster command in one of the nodes, and it doesn't connect correctly to the other one.
You could try to run the command in the other node.
If that doesn't help, maybe there's some internal way to attempt to remove a node from the cluster...
But you should update your question and clarify what are the node names, where you attempt to perform the admin task, and what exactly is the method you are attempting.
Answer: Thanks for your reply and sorry for the late response. The issue happened in the first node after successfully completing upgrade of two nodes. The first node became unresponsive after in the last two nodes. We found the reason for failure of node 1 was too many failed SQL queries completing rolling upgrade in the last two nodes. We found the reason for failure of node 1 was too many failed SQL queries due to connection issues.
The node names are email@example.com firstname.lastname@example.com email@example.com
To resolve the issue we had to kill the unresponsive eJabberd processes and restart eJabberd on first node. We are continuing with further upgrades.


problem in prime algorithm in C

Question: Following the answer from @neal aise here to get prime factors:
I did:
/*neal aise's  code*/
printPrimeFactors(int num) {
  int i;
  for (i = 2; i < sqrt(num); i=next_prime(i)) {
     if (num %i){
        printf("%d", i);
     }
  }
}

/*my code*/
int next_prime(int p){
   int prime_found = 0;
   while (!prime_found){
    if (p <= 1)/* if low number comes in, then */
       p = 2; /* next prime is always 2 (first prime) */
    else
          if ((p % 2) == 0) /* no even primes */
              p++;      /* make the number odd before test */
          else
              p += 2;       /* get next odd numero to test */
    prime_found = is_prime(p); /*check if number is prime*/
    }
    return (p);
}

int is_prime(int p){
    int curr_num = 2;                  /* start divisor at 2 */
    float stop_num = sqrt((float) p);  /* no divisor > sqrt of number needed */
    while(curr_num <= stop_num){
        if ((p % curr_num) == 0)      /* not prime if evenly divisible */
            return (0);
        else
            curr_num++;              /* increment divisor */
    }
    return(1);                         /* not evenly divisible, return prime */
}

How do I moddify the code in function

printPrimeFactors()

so it works as desired?
Comment: Try adding some `cout << ` statements into your code. They always helped me debug things like this.
Comment: What does your `is_prime()` function do?
Comment: can you post your code for `is_prime()`?  Also, input/output code...
Comment: First bug: `if(num%i)` will activate only when num is not divisible by i.  If you want the prime factors of num, then you should negate this, or more meaningfully change it to `if(num%i!=0)`
Comment: Edited c code, is_prime, tells if number is a prime
Comment: @Jon, added is_prime() function
Answer: There are a couple of logic errors:
if (num%i) // Change this to...
if ((num%i)==0) // num%i == 0 when i divides num, this 'i' is a prime factor.

Also, you will only print out roughly half of the prime factors by stopping at <sqrt(num). Either change the exit condition of the for loop to be i <= num:
for (i = 2; i <= num; i=next_prime(i)) { // note the <=
  if (num %i){
     printf("%d ", i);
  }
}

Or the alternative, more efficient method. Note the factors will not be in order:
for (i = 2; i <= sqrt(num); i=next_prime(i)) {
  if (num %i){
     printf("%d %d ", i, num/i); // Print out the pair, since we stop at i<=sqrt(num)
  }
}

Answer: If you want "prime number generator", interfaces is ok to me. But your code limit the number of prime numbers.
meaningless interfaces is not valuable. it can write more simply.
#include <stdio.h>

int main() {
  int n, m;
  for (n = 1; n < 1000 /* specify your max */; n++) {
    for (m = n-1; m > 1; m--)
      if (n % m == 0) break;
    if (m == 1)
      printf("%d\n", n);
  }
  return 0;
}

Comment: and what about the prime factors?, Dou you see the code feasible?
Answer: Instead of x = sqrt(n_limit) and if(n < x), you can do it like if(n*n < n_limit). No need for expensive sqrt(), floats or casts.

problem in prime algorithm in C


Alternate way to load javascript counter script

Question: I am trying to load the statcounter script from my custom js file. The original script looks like this:

...

...

...

The code seems to set the variables, then loads the counter script which reads the values of the variables and does its job.
I'm trying to call the counter script like this:
// file: counters.js
function CounterFromStatCounter() {
  sc_project=11111111;
  sc_invisible=1;
  sc_partition=11111111;
  sc_click_stat=1;
  sc_security="11111111";

  var oHead = document.getElementsByTagName('HEAD').item(0);
  var oScript= document.createElement("script");
  oScript.type = "text/javascript";
  oScript.src="http://www.statcounter.com/counter/counter_xhtml.js";
  oHead.appendChild( oScript);
}

 // main page

...

...

...

...

The code seems to work: the script element that references the statcounter script appears in the head section as it should, but no visits are recorded - this means that the variables set in my script cannot be accesed by the counter script.
What am I doing wrong?
Answer: You are doing a couple of things wrong.
1) You likely have not validated your code.  Go to http://jslint.com and validate your JavaScript.
2) Do not write JavaScript into your HTML.  That has a tendency to force all code bits into the global namespace, which is very likely to produce collisions with any other JavaScript code.
3) Only reference external JavaScript files directly prior to the closing body tag.  Script interpretation blocks parallel downloads in IE.
Accomplish those three and then come back for more help.
Comment: @alexandrul - The proper way to ensure all the necessary code get executed upon loading of the page is to put all the function names that you need loaded into another function.  The use the onload event in the body tag and reference this new function.  Everything inside the new function will get executed the moment the page has completely loading.
Comment: 2) what other options do I have considering that the statcounter script runs when loaded and needs to acces the sc_* variables?
Comment: 1) JSLint gives only one error: "Implied global: sc_project 2, sc_invisible 3, sc_partition 4, sc_click_stat 5, sc_security 6, document 8,9" when no option is selected. With "The Good Parts" options selected, it just hurts all my little feelings.
Comment: JSLint validation passes if using "/*global document, sc_project: true, sc_invisible: true, sc_partition: true, sc_click_stat: true, sc_security: true */". The only problem seems to be how to set the sc_* variables in my script in order to be accesed from the statcounter script which is later loaded by my script.
Comment: #2 is nonsense. Inline scripts and scripts included over HTTP have exactly no difference in terms of how they relate to the global scope. And both allow the use of closures to avoid polluting the global scope.
Comment: @eyelidlessnes - You are wrong.  Code declared inline to the HTML without being wrapped in a function is executed as it is interpreted, which does contaminate the global namespace exactly as implied globals variables of external script files.  That problem is solved by always using functions as containers, always declaring variables inside functions using the var command, and always placing that code in external script files.
Answer: Define the variables globaly and write some js like below.
window.attachEvent('onload', function() {
   document.write('


How to fix the drum part's staff in the correct form in Sibelius?

Question: I wrote the drum part in DAW, exported the midi and imported it to Sibelius. It recognized this track in this form:

How can I quickly transform it into the correct form and remove these polyphony?
Such as this:

It is reproduced correctly, i.e. all sounds (bass drum, cymbals) are in the correct positions
Comment: If some of those are bass drum parts and some of those are not (i.e. some of them are played with your feet and some of them are played with your hands), I personally highly recommend **not removing the polyphony**. However, I have seen some metal drumming sheet music for sale with the polyphony removed (makes the drum part harder to read, IMO).
Comment: @Dekkadeci I have more of a question about the form of notes, not polyphony, but thanks for the advice
Answer: I suggest you just re-write the drum stave in Sibelius, using the imported stave as a guide.   There's just so MUCH to fix between an import from DAW import and a readable drum part that any automatic solution would probably be more trouble.
Comment: Thanks for the answer. I suspect it is really easier to write everything with hands. But I have a lot of score pages. I think there may still be a function that can change the note symbol at a certain pitch, for example, to make all the notes of the hi-hat with crosshairs or something like that


How many combinations are possible, if fare is 50 paisa?

Question:
Sherlock Holmes and Dr Watson travel from X to Y via metro.
They have enough coins of 1,5,10,25 paisa. Sherlock Holmes agrees to pay for
Dr Watson only if he tells all possible combinations of coins that can be used to pay for the ticket.

Q1 How many Combinations are possible,if Fare is 50 paisa.
Q2 How many combinations are possible if they get an international discount of 10% i.e fare of 45p.
My Approach:
These are all the different combinations of coins I found.
Case1:(1,10) paisa coins with 1 paisa 10 coins and 10 paisa 4 coins
Case2:(1,5) paisa coins with 1 paisa 5 coins and 5 paisa 9 coins
Case3:(1,25) paisa coins with 1 paisa 0 coins and 25 paisa 2 coins(may be)
Case4:(5,10) paisa coins with 5 paisa 2 coins and 10 paisa 4 coins
Case5:(5,25) paisa coins with 5 paisa 0 coins and 25 paisa 2 coins(may be)
Case6:(10,25) paisa coins with 10 paisa 0 coins and 25 paisa 2 coins
Case7:(1,5,10) paisa coins with 1 paisa 5 coins and 10 paisa 4 coins and 5 paisa 5 coins
Case8:(1,5,10,25) paisa coins with 1 paisa 5 coins and 10 paisa 3 coins and 5 paisa 3 coins
Q Is this a good approach to solve this problem? What are the other combinations if I could not found it.
Comment: Are you sure you are supposed to do this without a computer? Because there are a lot of possible solutions...
Comment: @5xum yes we had to do
Comment: Why negative votes?
Answer: If we had only 1er coins, then there'd always be exactly one way to pay.
If we have only 1er and 5er coins, then to pay $5n$ paisa, we have $n+1$ ways: Use between  $0$ and $n$ (inclusive) 5ers and fill with 1ers.
To pay $5n$ paisas with 1ers, 5ers and 10ers, there are (cf. above) $n+1$ ways without a 10er, $n-1$ ways (if that is still $\ge0$) with one 10er, $n-3$ ways (if $\ge0$) with two 10ers, and so on. So if $n=2k$ is even, this is $(2k+1)+(2k-1)+(2k-3)+\ldots +5+3+1=(k+1)^2$ and if $n=2k-1$ is odd, it is $2k+(2k-2)+(2k-4)+\ldots +6+4+2=k(k+1)$.
Finally, to pay $50=5\cdot 10$ paisas with 1ers, 5ers, 10ers, 25ers, we can use no 25er in $(5+1)^2$ ways, one 25er in $3\cdot 4$ ways, two 25ers in exactly $1$ way. In total: $49$ ways.
On the other hand, to pay $45=5\cdot 9$ paisas with 1ers, 5ers, 10ers, 25ers, we can use no 25er in $5\cdot 6$ ways, or one 25er in $(2+1)^2$ ways. In total: $39$ ways.
Comment: How n-1 with one 10er.Does that mean we did not need 1er?
Comment: How we get n+1 ways(given in second line)Can you please elaborate?
Comment: @justintakro There are $n+1$ numbers from $0$ to $n$ (inclusive). - And if we use one10er, we effectively replace $5n$ with $5(n-2)$ to be payed with 5ers and 1ers, so effectively adding a 10er decreases $n$ y two, which is why $n+1$ becomes $(n-2)+1=n-1$ and so on.
Answer: If you want to list the combinations, I'd suggest being a bit more systematic.  Use tables.
$$\boxed{\begin{array}{l|llll}50\text p & 25\text{p}&10\text{p}&5\text{p}&1\text{p}
\\\hline & 2
\\ & 1 & 2 & 1
\\ & 1 & 2 & & 5
\\ & 1 & 1 & 3
\\ & 1 & 1 & 2 & 5
\\ & 1 & 1 & 1 & 10
\\ & 1 & 1 &  & 15
\\ & 1 & & 5
\\ \vdots & & \ddots & & \vdots
\\ & & & & 50
\end{array}}\;\boxed{
\begin{array}{l|llll}45\text p & 25\text{p}&10\text{p}&5\text{p}&1\text{p}
\\\hline & 1 & 2
\\ & 1 & 1 & 2
\\ & 1 & 1 & 1 & 5
\\ & 1 & 1 &   & 10
\\ & 1 &   & 2 &
\\ & 1 &   & 1 & 5
\\ & 1 &   &   & 10
\\ &   & 4 & 1
\\ \vdots & & \ddots & & \vdots
\\ & & & & 45
\end{array}}$$
Comment: Thats great But How to analyze that I don't miss any cases.The method can cause errors


exhaustive search over a list of complex strings without modifying original input

Question: I am attempting to create a minimal algorithm to exhaustively search for duplicates over a list of strings and remove duplicates using an index to avoid changing cases of words and their meanings.
The caveat is the list has such words  Blood, blood, DNA, ACTN4, 34-methyl-O-carboxy, Brain, brain-facing-mouse, BLOOD and so on.
I only want to remove the duplicate 'blood' word, keep the first occurrence with the first letter capitalized, and not modify cases of any other words. Any suggestions on how should I proceed?
Here is my code
def remove_duplicates(list_of_strings):
""" function that takes input of a list of strings,
uses index to iterate over each string lowers each string
and returns a list of strings with no duplicates, does not modify the original strings
an exhaustive search to remove duplicates using index of list and list of string"""

list_of_strings_copy = list_of_strings
try:
    for i in range(len(list_of_strings)):
        list_of_strings_copy[i] = list_of_strings_copy[i].lower()
        word = list_of_strings_copy[i]
        for j in range(len(list_of_strings_copy)):
            if word == list_of_strings_copy[j]:
                list_of_strings.pop(i)
                j+=1
except Exception as e:
    print(e)
return list_of_strings

Comment: `list_of_strings_copy = list_of_strings` is not making a copy.  https://nedbatchelder.com/text/names.html
Answer: Make a dictionary, {text.lower():text,...}, use the keys for comparison and save the first instance of the text in the values.
d={}
for item in list_of_strings:
    if item.lower() not in d:
        d[item.lower()] = item

d.values() should be what you want.
Answer: I think something like the following would do what you need:
def remove_duplicates(list_of_strings):
    new_list = [] # create empty return list
    for string in list_of_strings: # iterate through list of strings
        string = string[0].capitalize() + string[1:].lower() # ensure first letter is capitalized and rest are low case
        if string not in new_list: # check string is not duplicate in retuned list
            new_list.append(string) # if string not in list append to returned list
    return new_list # return end list

strings = ["Blood", "blood", "DNA", "ACTN4", "34-methyl-O-carboxy", "Brain", "brain-facing-mouse", "BLOOD"]
returned_strings = remove_duplicates(strings)
print(returned_strings)

(For reference this was written in Python 3.10)


show existence of a finite set $\{K_{j_1},....K_{j_m}\}$ with empty intersection

Question: Let $\{K_\alpha\}$ be a family of compact sets in the Hausdorff topological space $X$, such that $\cap_{\alpha\in I}{K_\alpha}=\emptyset$...
Is there necessarily a finite set $\{K_{j_1},....K_{j_m}\}$ such that $\cap_{n=1}^m{K_{j_n}}=\emptyset$? if so... why? I can see why it is true on metric spaces, but cannot conclude it for general topology....
Comment: Look up [Finite intersection property](https://en.wikipedia.org/wiki/Finite_intersection_property)
Answer: Pick $j_0\in I$. Then the open sets $X-K_\alpha$ cover $K_{j_0}$. Hence there is a finite sub-cover:
$$K_{j_0}\subseteq \bigcup _{n=1}^m(X-K_{j_n}).$$
But then
$$ K_{j_0}\cap \bigcap _{n=1}^mK_{j_m}=\emptyset.$$


Preserve term association when migrating nodes

Question: Actually I can migrate nodes depending on their type, and the author comes with node import like this in d2d :
$this->addFieldMapping('uid', 'uid');

but I don't know how to do the same to keep terms attached to nodes..I believe that in Drupal6 source, terms are frequently assigned from the core system, not via the content taxonomy module that represent the Drupal7 way.
Do you think I can do that actually, or do I need to modify the source and adopt the content taxonomy way before migrating nodes or generally upgrading from Drupal 6 to Drupal 7 ?
Thanks
EDIT: my migration class code
class NodesPageInnovationsMigration extends DrupalNode6Migration {
/* ==============================================================================
* -- Pour limiter l'import aux nodes créés aprés la date indiquée --
*
* ==============================================================================
*/
//protected function query() {
//    $query = parent::query();
//    $query->condition('created', strtotime('28-03-2013'), '>');
//    return $query;
// }
public function __construct(array $arguments) {
    parent::__construct($arguments);
    //Le nom machine de la migration de nodes associée comme dépendances
     // $this->dependencies[] = 'D2D_RostandNodes_PageInnovations';

    //On défini la source et la cible depuis les infos de base
      $this->source = new MigrateSourceSQL($this->query(),
      $this->sourceFields,NULL, $this->sourceOptions);

// We're replacing the legacy field_published, which was a text field, with a new date field
    $this->addFieldMapping('field_publish_date', 'field_published');

    //Préservation du NID des nodes importés
     $this->addFieldMapping('field_legacy_nid', 'nid')
         ->description('We have a common field to save the D6 nid');

    /* ==============================================================================
     * -- Mappage de la taxonomie --
     * Assigned terms are represented in Drupal 6 by their vid, migrate to the new term
     * reference field, translating the tid from the legacy value.
     * ==============================================================================
     */
     //$this->addFieldMapping('field_NomduChampCible', 'VidSource')
    //La taxonomie via champs custom ou du core (D6)
   // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    $this->addFieldMapping('taxonomy_vocabulary_1', '1')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    $this->addFieldMapping('taxonomy_vocabulary_2', '2')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

   //$this->addFieldMapping('field_taxo_vdl', 'field_taxo_vdl'); inutile car dans D7 taxo est un champ

    /* ==============================================================================
     * -- Mappage des champs custom CCK --
     * $this->sourceFields['NomChampSource'] = t('DescriptionChampSource');
     * ==============================================================================
     */
//   $this->sourceFields['field_fichier_joint_lycee'] = t('Joindre un fichier');
//   $this->sourceFields['field_lien_page_lycee'] = t('Liens utiles');
//   $this->sourceFields['field_video_lycee'] = t('Ajout galerie Flickr');

   $this->addFieldMapping('field_video_externe', 'field_video_externe');
   $this->addFieldMapping('field_fichier_joint_innovation', 'field_fichier_joint_innovation');
   $this->addFieldMapping('field_fiche_action_innovation', 'field_fiche_action_innovation');
   $this->addFieldMapping('field_date_evenement', 'field_date_evenement');

   //Les champs custom pour les contenus VDL
   $this->addFieldMapping('field_illus_vdl', 'field_illus_vdl');
   $this->addFieldMapping('field_video_vdl', 'field_video_vdl');
   $this->addFieldMapping('field_galerie_image_vdl', 'field_galerie_image_vdl');
   $this->addFieldMapping('field_choix_galerie_vdl', 'field_choix_galerie_vdl');
   $this->addFieldMapping('field_liens_vdl', 'field_liens_vdl');

   //Correspondance des utilisateurs
   $this->addFieldMapping('uid', 'uid');
   //$this->addFieldMapping('tnid', 'tnid'); traduction du terme

}
/* ==============================================================================
     * -- Manipulation et mise en forme des données des champs mappés --
     *
     * ==============================================================================
     */
public function prepareRow($row) {
// Always include this snippet, in case our parent class decides to ignore the row
if (parent::prepareRow($row) === FALSE) {
   return FALSE;
}
//ici le code pour formatter les data
}
}

Comment: @MyPalDrupal use `drupal_write_record` to write the node object with the nid set, prior to save. i.e       `drupal_write_record('node', $node); drupal_write_record('node_revision', $node);node_save($node);` - this will preserve the nid
Comment: @MyPalDrupal no, if you've already migrated with that module, I assume it's created the nids for you. Maybe you can reset them after that, but that would all require custom code.
Comment: Can you not preserve the same nid during migration?
Comment: no,actually nodes are imported with a new nid
Comment: @DavidThomas preserving nids is one of Drupal Unicorns, I'm afraid. webmaster pf - could you link what d2d is?
Comment: this is d2d : https://drupal.org/project/migrate_d2d  perhaps mapping the nid like other fields could be the fix ?
Comment: @molot, yes it can be a tricky thing to do, but there are ways. I just finished a migrate from D5 to D7, about ~10,000 migrated, preserving the nid and tid relationships. However, I don't use the migrate module...
Comment: @DavidThomas Can you pls. share how you achieved this ?
Comment: @DavidThomas Thanks a lot, you did not used the migrate module. I am a starter so can you pls. tell how exactly you used this ? and can this be done after using the migrate module for other migration jobs (migrate node, terms etc. ?
Answer: Check out all the examples for migrations in the migrate d2d handbook.
There is documentation on taxonomy term migrations and node migrations.
Put these together with the documentation for migrate.
Also, the migrate, migrate extras, and migrate d2d modules all have example modules in them, which have very useful example code.
Specifically check out the example module in migrate_d2d, it has an example of this.
There is a lot of documentation there but that is because migration is a complicated task.
The more you read and the better understanding you have the easier it is and the better the result.
After you have done a couple of migrations it gets much easier.
For nodes and their taxonomies, you migrate the terms first, then the nodes.
The migrate module will keep track of the mapping of the old term id to the new term id, then when it comes to the nodes it will use that mapping for the terms attached to the nodes.
This is how you map a taxonomy field:
When you register your hooks:
// Each migration being registered takes an array of arguments, some required
// and some optional. Start with the common arguments required by all - the
// source_connection (connection key, set up in settings.php, pointing to
// the Drupal 6 database) and source_version (major version of Drupal).
$common_arguments = array(
  'source_connection' => 'legacy', // This is the name of a connection in your settings.php file.
  'source_version' => 6, // This is the source drupal version.
);

// Other migration registration here, like users & files.

// For vocabulary migrations, source_vocabulary and destination_vocabulary are
// required arguments. Note that in Drupal 6 vocabularies did not have machine
// names, so we use the vocabulary ID to uniquely identify them.
$vocabulary_arguments = array(
  array(
    'description' => t('Migration of Tags terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Tags', // Migration machine name
    'source_vocabulary' => '5',  // Source vocabulary ID
    'destination_vocabulary' => 'tags', // Destination vocab machine name.
  ),
  array(
    'description' => t('Migration of Category terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Category', // Migration machine name
    'source_vocabulary' => '6',  // Source vocabulary ID
    'destination_vocabulary' => 'category', // Destination vocab machine name.
  ),
  // More migrations for other vocabs.
);

// We're using the migrate_d2d class directly for all of the above.
// You can put other common params here.
$common_vocabulary_arguments = $common_arguments + array(
  'class_name' => 'DrupalTerm6Migration',
);
foreach ($vocabulary_arguments as $arguments) {
  $arguments += $common_vocabulary_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

// Node migrations.
$node_arguments = array(
  array(
    'class_name' => 'PageMigrationClassName', //  The class name for this migration as we are extending a built in one.
    'description' => t('Migration of page nodes from Drupal 6'), // Description for this migration.
    'machine_name' => 'Page', // Machine name of this migration.
    'source_type' => 'page', // The node type in the old site.
    'destination_type' => 'page', // The node type in the new site.
    // Dependencies. This means this won't run until after the Tags & Category migrations have run.
    'dependencies' => array('Tags', 'Category'),
  ),
  // Other nnode migrations here.
);
foreach ($node_arguments as $arguments) {
  $arguments += $common_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

Now in your page node migration code you would do:
class PageMigrationClassName extends DrupalNode6Migration{
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Note that we map migrated terms by the vocabulary ID.
    // This is for the Tags vocab.
    // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    // This is how it is stored on the row, eg. $row->5
    $this->addFieldMapping('field_tags', '5')
         ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    // And for the category vocab.
    $this->addFieldMapping('field_category', '6')
         ->sourceMigration('Category')
         ->arguments(array('source_type' => 'tid'));
  }
}

If you want to map the data to data that is already in the new system and wasn't migrated with the migrate module, there is probably a bunch of ways to do it.
One way is to use the migrate API methods.
You can implement prepareRow() in your node migration class and do this:
public function prepareRow($row) {
  // Always include this fragment at the beginning of every prepareRow()
  // implementation, so parent classes can ignore rows.
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // The node's terms are in an array under their vocab ID.
  if (!empty($row->{5})) {
    foreach ($row->{5} as &$tid) {
      // Code here to map term IDs from old to new.
      // Set $tid to the corresponding new site tid.
      // You could call a separate mapping function to do this if you have
      // a lot of terms or complex mapping requirements or something.
    }
  }
  return TRUE;
}

Alternatively, you can put the new tids somewhere else on the $row, like:
$row->mapped_tids_tags = array(3, 7, 4, 8, 6);

Then for your field mapper you have:
$this->addFieldMapping('field_tags', 'mapped_tids_tags')

Instead of:
$this->addFieldMapping('field_tags', '5')

Comment: great explanation, but i did upgrade before import nodes via migrate d2d.so terms and vocabulary are already in the db.your second code could help me i guess,and i'm reading about examples include into the module folder.but actually i met troubles after updating modules (2.6 for migrate and 2.1 for d2d).
Comment: i get this error : `Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column f.field_fichier_joint_innovation_description' in 'field list'`
Comment: this error come from after updating the d2d module,it's a known issue
Comment: I have added a part about manually mapping tids.
Comment: ok;i'm reading about the utility of prepareRow in my case and appear it's something needed to achieve nodes migration .But for now the error disallow me to run test so i run test onto my files migration
Comment: Do you have a field called "field_fichier_joint_innovation_description"? Usually the field's column name will have _value at the end. - Also, does this help at all: http://drupal.stackexchange.com/q/50138/10729
Comment: this error is fixed : https://drupal.org/node/2021413


Como atualizar  html sem precisar dar refresh na pagina inteira?

Question: Minha pagina web deve tocar um audio diferente a cada 1 minuto, sem dar refresh na pagina inteira. O audio pode ficar em uma div, mas ele precisa ser atualizado a cada 1 minuto, mas da forma que está, o navegador sempre pega o primeiro audio tocado, e sempre que mudo o audio e salvo o arquivo, o navegador sempre pega audio pelo qual a pagina foi carregado a ultima vez.
Resumindo, preciso atualizar o audio em uma div.
Segue meu código:
HTML E PHP
<?php

include("config/conn.php");
$seguntos=2; //segundos
?>

<audio id="audio" style="display:none">
<source src="sons/aero.wav" type="audio/wav" />
</audio>

FUNÇÃO JAVASCRIPT AUDIO

FUNÇÃO JAVASCRIPT VERIFICA A SITUAÇÃO E DA O PLAY

Answer: Pagina do audio

<input id="idInput" type="hidden" value="0">

<audio id="audio">
<source id="qqid" src="https://s3.amazonaws.com/Syntaxxx/bigger-picture.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

atualizaAudio.php
//vindo via post
$numAudio=$_POST['numAudio'];

//array auxiliar com mumeração igual a quantidade de audios
$numero = array(1, 2, 3, 4);

//condicional que incrementa a variável $numAudio até a quantidade de áudios no array
$numAudio < 4 ? $numAudio++ : $numAudio=1;

//seta o audio de acordo com a variável $numAudio
switch ($numAudio) {
    case 1:
        $audio="tarantella.mp3";
        break;
    case 2:
        $audio="esera.mp3";
        break;
    case 3:
        $audio="deo.mp3";
        break;
    case 4:
        $audio="to_nem_ai.mp3";
        break;
    default:
        $audio="https://s3.amazonaws.com/Syntaxxx/bigger-picture.mp3";
}

//resultado a passar para processar na pagina do audio
echo $audio."|".$numAudio;

Como desenvolvedor, você pode alterar o comportamento da política de reprodução automática do Google Chrome localmente para testar seu website.

Pode optar por desativar completamente a política de reprodução automática, definindo o sinalizador do Chrome "Autoplay Policy" para "No user gesture is required" em chrome://flags/#autoplay-policy . Isso permite que você teste seu website como se o usuário estivesse fortemente envolvido com seu site e a reprodução automática sempre fosse permitida.

Alterações na Política de Reprodução Automática (ingles)
Google tradutor - Alterações na Política de Reprodução Automática
Answer: Sem fazer refresh na página, você precisa atualizar todo o elemento audio.
Faça o seguinte, inclua o audio em um span com um id:

   <audio id="audio">
      <source src="sons/aero.wav" type="audio/wav" />
   </audio>

Na função play(), altere o HTML do span com o próprio HTML, fazendo com que o navegador puxe novamente o arquivo wav, mas é preciso também modificar o nome do arquivo. Não precisa alterar o nome original, basta acrescentar um parâmetro qualquer para que o navegador pense que é um novo arquivo, algo como sons/aero.wav?12321321.
Para gerar esse parâmetro você pode usar a data do sistema. Veja o código:
audio = document.getElementById('audio');

function play(){
   var src = "sons/aero.wav";
   var param = new Date().getTime();
   src += "?"+param;
   $("#audio source").attr("src", src);
   $("#audiocontainer").html($("#audiocontainer").html());

   audio.play();
   audio.stop();
   audio.pause();
}

Comment: Essa tag audio não funciona com style="display:none"  e nem reproduz automaticamente no Chrome e no Opera. No Safari não funciona nada.
Comment: pq vc negativou minha resposta?
Comment: Foi eu não.. rss
Comment: Já que não foi vc, pq vc acha que negativaram? veja perguta do AP `Minha pagina web deve tocar um audio diferente a cada 1 minuto, sem dar refresh na pagina inteira.`
Comment: Xiii, acho que descobri, era pra ser 1 minuto e botei 15 segundos, aff
Comment: Não faço ideia. Tem gente por aí que sai negativando mesmo.
Comment: Já percebi isso, tenho pena deles!


Using Bootstrap theme and anonymous user, ajax form submit results in "call to undefined function bootstrap_form_process"

Question: Context
We have a subtheme based on the Bootstrap theme and we're rendering a form inside of a modal. The submit button uses an ajax callback to handle form submission.
Problem
When logged in as an admin in Chrome, the form submits perfectly.
When logged out (accessing the site as an anonymous user) in Chrome, submitting the form results in a 500 Server error.
The server logs are reporting "Call to undefined function bootstrap_form_process()".
Research
It seems that this might be related (https://www.drupal.org/node/2156371) but I'm not sure what to do to fix it.
I have a hard time following issue discussions on drupal.org. I have a decent amount of Drupal knowledge, but still struggle to figure out what they are saying.
Things I've Tried
Some people in the thread linked above got around the issue by setting max_input_vars to 2000, so I gave that a shot. It didn't help.
I thought maybe I needed to increase it even more, so I set it to 5000, but still no change. I then switched it back to the default 1000.
I also tried adding "drupal_static_reset('element_info');" to my theme's template.php file, but it didn't seem to do anything.
Answer: This is similar to https://www.drupal.org/node/2369635, i.e. you need to include /path/to/bootstrap/includes/process.inc in your codebase.  The easiest way IMHO is in a hook_init() somewhere.


Https/BotAuthentication breaking botframework bot?

Question: I am having an issue with trying to create a bot. Everything seems to work fine when I am using Http. I can deploy my application to my website and interact with the bot via the emulator or botframework.com.
Unfortunately, when I try to use HTTPS, I get a 401 error from the emulator and nothing shows up when I try to use botframework.com.
Just so that I am crystal clear, the only things that I changed are:
1. Added the [BotAuthentication] attribute to my ApiController like so:
<code>[BotAuthentication]
public class MessagesController : ApiController
</code>

Updated the URL in the emulator/botframework.com from http://mywebsite.com/api/messages to https://mywebsite.com/api/messages

Web.config is all set up with the appId and AppSecret. My site already has an SSL certificate.
Is there anything that I am missing? Although I have never used basic authentication before I am assuming there is nothing else that I need to set up, right?
Comment: For those reading this later, it turns out that my IIS instance was setting Basic Authentication to enabled. This seemed to get in the way of the BotAuthentication attribute as described by T Laird-McConnell below. My solution was to remove basic auth in the web.config
Answer: I hit your endpoing and IIS is responding to the basic auth and getting in the way.
Basic Auth is works the following way:
There is a header  which contains the UserId:Password encoded as base64
If the server doesn't see the header it returns a 403 with a "basic" to signal that the web site requires auth token. For a web browser that means it will popup a stock user/password dialog and then it will do submit the request again with the header.
If the header is provided but the user/password is wrong the server returns 401.
Normally basic auth is used to look up in a database, but in our case there is only 1 user, it is the bot appid/appsecret.  All the BotAuthorization attribute does is to add an inspector to the request pipeline to look for the header with appid/appsecret in it to make sure that only approved callers can call your bot.
If you don't care about that you can simply remove the attribute.  Regardless, you don't want IIS sticking it's nose into the process.
Make sense?
Answer: This theoretically should work based on your description of the changes you've made. This is the emulator talking to your cloud service or to the bot on localhost?  And you get this error as well from the Bot Framework test control in the portal?
If you send me your BotId to email@example.com I can check our logs to see if there's anything interesting (or DM me at @jameslew on twitter).


Página de Contato funciona em GitHub Pages?

Question: Ao elaborar um simples protótipo de página para contato, eu lembrei que existe a possibilidade do projeto ser hospedado pelos servidores do GitHub.
Exemplo

Mas também lembrei que a hospedagem com o GitHub somente da suporte a processamento Front-End ou seja, esse formulário de contato não funcionará já que dele deveria ser feito com uma linguagem que roda no lado do servidor, como o PHP por exemplo.
Dúvida
É possível fazer funcionar um formulário de contato desses mesmo ele sendo hospedado no GitHub Pages?
Caso não seja possível, existe alguma alternativa com custo zero para resolver esse problema?
Comment: Até onde sei o github pages hospeda apenas conteúdo estático(html, js, css), portanto, você não vai conseguir executar nada relacionado a backend. Você pode combinar github pages (caso você não queira gastar com domínio) com uma máquina ec2 dentro do free tier(1 ano grátis) da AWS(ou hospedar tudo lá mesmo). Na AWS você também consegue soluções permanentes com o custo bem baixo(AWS Lambda + API Gateway + S3).
Comment: Esse custo bem baixo da pra chegar a zero? realmente não queria ter gasto com hospedagem e nem com nome de domínio, na verdade eu estou propondo entregar o projeto com custo zero. É possível?
Comment: O free tier da aws te da 1 ano com o custo zero. Você pode montar uma api e hospedar em uma máquina ec2, daí você faz requests através do js da sua página no githubpages pra mandar email. Já rodei aplicações com a stack serverless(api gateway + lambda) da aws com custo mensal extremamente baixo (menos de $3). Da uma olhada em outros provedores de cloud, devem oferecer free tier ou custo bem baixo também.
Comment: Eu creio que sim, seja de algum modo possível fazer, sem nem precisar de lado servidor. Baseando-se na capacidade de se editar um arquivo do próprio GitHub através da API deles. Ou então mandar mensagem via `Messenger` para si mesmo usando a API do Facebook. O problema é que, como é tudo servido estaticamente, então o processamento precisa ser feito no browser e, portanto, a informação precisa estar disponível para quem baixar a página (claro, pode estar criptografado, mas você também precisa fornecer como descriptografar também)
Answer: O propósito do GitHub Pages é servir de repositório para documentação de códigos hospedados no GitHub, utilizando-se de arquivos markdown, que são transformados em arquivos estáticos.
A ideia não é ter um espaço para homologação de uma aplicação e nem mesmo hospedagem de uma, mesmo sendo possível fazere uma usando SPA, Single Page Application.
Se você está desenvolvedo uma aplicação e que validá-la, use alguns dos serviços de nuvem tais como Azure ou AWS, que oferecem pelo período de um ano, para novas contas, um valor mensal para ser consumidor. O primeiro pode ser acesso por este link azure.com/free.
Se for muito complicado neste momento, existem serviços ainda mais simplestas, por exemplo: heroku.com.
Comment: Muito boa a dica, agradeço pelos links =) na verdade, como os projeto são estáticos eu pensei que pudesse usar o páginas do github, não existe nenhum tipo de processamento, até eu lembrar que existe a páginas de contato.


Probability of getting at least 1 red or green ball

Question: I am working on the following problem:

We have 2 bags that each contain 3 yellow, 4 blue, 5 red, 6 green and
  2 black balls.   In a simultaneous draw what is the chance of getting
  at least 1 red or 1 green ball?

My approach:
Find probability of getting at least 1 green ball:
$(\frac{14}{20})^2 = (\frac{7}{10})^2= \frac{49}{100}$ is the probability of not getting a green ball in the draw hence $1 - \frac{49}{100} = \frac{51}{100}$ is the probability of getting at least 1 green ball.
Find probability of getting at least 1 red ball:
$(\frac{15}{20})^2 = (\frac{3}{4})^2 = \frac{9}{16}$ is the probability of not getting a red ball in the draw hence $1 - \frac{9}{16} = \frac{7}{16}$ is the probability of getting at least 1 red ball.
Therefore what we are looking for is the sum of these probabilities i.e.
$\frac{51}{100} + \frac{7}{16} = \frac{816 + 700}{1600} =\frac{1516}{1600} = \frac{379}{400}$
But my notes say $\frac{319}{400}$
Is this a typo or is my solution wrong?
Comment: Where do you get $14\over20$ from? Also those events aren't mutually exclusive so you can't add them together. If 1 bag had all greens and the other had all reds, then you'd end up with 2 as your answer.
Comment: Remember that the probability of $A$ or $B$ is the sum of the individual probabilities *minus* the joint probability of $A$ and $B$. There's an easier way to do this, though.
Comment: In probability questions which say something similar to 'find $P(A)$ where $A$ is the event of getting at least 1 XXX', then you should almost always consider if $P(A^C)=1-P(A)$ is easier to find.
Comment: @Shuri2060 That's where the $\frac{14}{20}$ came from, it's the complement of getting a green ball.
Comment: @browngreen Yeah - didn't realise at first (and there's a typo on that line), but as others have mentioned, getting no reds and no greens is the way to go
Answer: Your solution is wrong because you forgot to subtract the joint probability of drawing a red ball and a green one. However, here's the best way to do this problem.
The probability of at least $1$ red or green ball is $1$ minus the probability of no red or green ball on either draw. Thus:
$1-(\frac{9}{20}\cdot\frac{9}{20}) = 1-\frac{81}{400}=\frac{319}{400}$
Does that make sense?
Comment: I think I got you. I got confused by the fact that we are counting as distinct combinations red from bag1, green from bag2 and red from bag2 and green from bag1. So the "at least 1 green" includes both these 2 combinations right? That's why we care about the order?
Comment: Somehow I got confused now. Why doesn't the `1 minus the probability of no red or green ball on either draw` includes the probability of drawing a red ball and a green one right? So how come we don't need to subtract it?
Comment: Because you're not double counting it this way. When you add the probability of getting a red to the probability of getting a green, you're counting the event of getting both red and green twice. That's why you have to subtract in that case, to make up for the double counting.
Comment: A selection that has a red and a green is acceptable right? So the probability to get at least 1 green indeed has the case of red + green included. And the probability to get at least 1 red indeed has the option of red + green included. So if I remove from each these cases (like mentioned by browngreen) won't I be removing completely the case of red + green from counting it? But it is an acceptable condition no?
Comment: That's why you don't remove it from both cases. You only subtract it once.
Comment: I thought $\frac{30}{400} + \frac{30}{400}$ is subtracting it completely. Somehow I got stuck on this. Could you please help me understand it?
Comment: The first $\frac{30}{400}$ is the probability of getting red from bag 1, and green from bag 2. The second is the probability of getting green from bag 1 and red from bag 2. Together, those make up the probability of getting both red and green. The whole $\frac{60}{400}$, is counted both in the "at least 1 green" and in the "at least 1 red" cases. If you subtracted it twice, you'd have to subtract $\frac{120}{400}$.
Comment: It sounds like you got it.
Answer: You can use counting by complement to greatly simplify this problem. The original statement asks for at least 1 red ($\geq 1$ red) OR at least 1 green ($\geq 1$ green).
Condition:
$\geq 1$ green OR $\geq 1$ red
Negating this, we get cases where this condition is violated (by DeMorgan's Law):
$0$ green AND $0$ red
There are $20$ choices in total for each bag. If you eliminate red and green selections, you are left with $9$ balls to choose from each bag for a probability of $\frac{9}{20}$ * $\frac{9}{20}$ = $\frac{81}{400}$.
The cases where this is NOT violated, then, is $\frac{400-81}{400}$ = $\frac{319}{400}$
Answer: You must subtract the probability of getting exactly one green ball and one red ball, since this was counted twice.
The probability of Ball 1 being green and Ball 2 being red is $\frac6{20}\cdot\frac5{20}=\frac{30}{400}$
The probability of Ball 2 being green and Ball 1 being red is the same, so in total you are subtracting $\frac{60}{400}$.
Comment: Why are we counting the probability of Ball1,Ball2 as distinct from Ball2,Ball1 and we add to get the $\frac{60}{400}$?
Comment: I am confused on this a bit. Why are we counting the sequence ball1, ball2 plus ball2,ball1 for getting a red and green?
Comment: @Jim There are two distinct ways to get one green and one red, each with a probability of $30\over 400$. (Ball1-green, Ball2-red) is a different scenario from (Ball1-red, Ball2-green) so you have to add the probabilities.


Performance: is preferable to use Rules or node_presave/node_save/other hook ?

Question: we know that via hook_* we can make everything, but my question is about the use of Rules vs hook_. At high level performance programming  hook_ is better that rules, but if we consider a normal level performance ?
In a site where you have installed rules (like a commerce) is better to use hook_* or I can create a rule that exec an PHP function? In the first way (hook_*) I need to remember in which module an FooBar thing happen (say does something before node's saving, hook_node_presave) but I have max performance; second way is  via Rules module where I have all rules in one path and I can crete a Rules that is "called" when "condition" "before saving new node of node type XYZ" appair.
Which is better in a normal site ? Or in a site more than normal ?
M.
PS: sorry for my bad english.
Answer: In practice, it is far easier to debug a hook than a rule that includes a PHP function.  So, not only are hooks faster, they are easier to maintain and less likely to present security risks.
You do not need to remember "in which module foo happens" if you put all your hooks in a single custom module for the site.  Unless you have an extremely large number of tweaks, using a single module (and version controlling it!) is probably the easiest way to do this.
Regardless of the size of the site, if you want to write custom PHP, you should use a custom module, not rules.
Comment: What, no attack on the PHP filter in general? I'm disappointed...;)


Reserve one http slot for /server-status?

Question: I have an Apache server which is hanging for some reason. When I normally want to check on the load of an Apache server, I tend to use mod_status via the URL at http://webserver1.example.org/server-status or from the commandline like service httpd fullstatus.
However today, the Server is refusing all new connections. Some mysterious problem is causing connections to stall, which means that number of connections fills up all available connections (e.g. The number of connects exceeds the MaxClients setting), and therefore neither http://webserver1.example.org/server-status nor service httpd fullstatus can return anything.
Is it possible to configure Apache to reserve one or two slots for the mod_status pages?
Comment: You could kill one of httpd processes and immediately try to get status.
Comment: Great idea! Unfortunately even something like `kill PID && service httpd fullstatus` is failing to grab the status.
Comment: You may want to wait a second before trying. Sending a signal does not immediately end a process. Also check if this process really exited.
Comment: I also tried waiting a second or more. In the logfile I see that another request from elsewhere was accepted over mine, so maybe it's just a crapshoot and if I tried enough times I'll eventually get the session.
Answer: Please see this related question and the linked answer by @covener. There are two options you could take to approach your problem.

check mod_backdoor (description and source) which provides a special port offering the scoreboard, even when all slots are in use.
Use a ScoreBoardFile which provides the scoreboard via shared memory. You will have to use a tool (i.e. Apache2-ScoreBoardFile or ftss) to parse the binary data though.

Both solutions are quite involved but with option 2 allowing even realtime access due to shared memory.
Additionally I opened a bug report at apache bugzilla.
Answer:
The number of connects exceeds the MaxClients setting

If this isn't being caused by high traffic to the server or a MaxClients setting that's way too low (the defaults are usually fine), then the problem is probably being caused outside of Apache, which server-status won't help troubleshoot much.
That said, I've seen the exact behavior you're describing happen when the root filesystem is out of free space. Try a df -h to see if you're out of disk space.
Comment: /server-status is just a convenient tool which lets me see which the client IP, HTTP request, path, and various performance statistics. While much of that info is already availalbe in the logs, logs don't provide a quick glance at a server's health, I like the convenience of a command like `service httpd fullstatus`.


Reconhecimento de voz não funciona

Question: Recentemente formatei meu notebook e tive que reinstalar tudo, só que agora meu projeto de TCC está com erro que no caso antes não tinha.
Nesse trecho de código:
<code>SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new CultureInfo("pt-BR"));
</code>
O Erro que aparece:

An unhandled exception of type 'System.ArgumentException' occurred in System.Speech.dll
Additional information: Nenhum reconhecedor da identificação necessária encontrado.

Aqui e o print da linguagem instalada....
Comment: Será que [esta resposta](http://pt.stackoverflow.com/a/68686/20615) lhe ajuda?
Comment: pergunta simples para outra linguagem ele funciona?
Comment: Não compreendi sua pergunta...
Comment: se você colocar "en-US" seu programa compila sem erros ?
Comment: Não funciona, já tentei :/
Comment: é claro eu presumo que você tenha instalado o SpeechPlatformRuntime e as linguagens que você queira como suporte ....
Comment: Sim, editei ali e coloquei o print
Comment: O sistema operacional é o mesmo ou você alterou?
Comment: é o mesmo, senão me engano só troquei a versão dele, mas ambos é Windows 10
Comment: pq vc tem versão 64bits e 32bits instalado? será que isso não está gerando algum conflito !?
Comment: Posso tentar deixar uma só, é que no desespero instalei todos os possiveis. E a banca final do tcc esta chegando, e preciso concertar isso logo
Comment: deixei uma versao, mas o erro ainda persiste
Answer: Não posso afirmar com exatidão como resolver o problema, mas o erro ocorre porque falta algum componente, no caso o que faz o reconhecimento em português, que claramente não vem por padrão no Windows. Veja o que precisa instalar.
Sempre que encontrar um erro, consulte a documentação para entender melhor o que ocorre.
Answer: Há algumas soluções que resolvem este problema. Dentre as mais usadas:
1 - Verifique a versão do .NET Framework que está a usar e veja na documentação da DLL se suporta a mesma.
2 - Adicione uma referência (Via DLL) ao framework da ferramenta que deseja usar.
Caso nenhuma dê certo, verifique a documentação do framework.

Reconhecimento de voz não funciona


Can't submit form/log-in to Nike.com using headless browser in python

Question: I am currently trying to do some QA/form submissions using a headless browser in python, and I don't think my libraries are able to submit/complete the form. What am I doing wrong here?
import mechanize
import cookielib

cj = cookielib.LWPCookieJar()

br = mechanize.Browser()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

response1 = br.open("http://www.nike.com/us/en_us/")

assert br.viewing_html()
print br.title()
print response1.geturl()

html = response1.read()

for forms in br.forms():
    print forms

# Select the second (index one) form
br.select_form('login-form')

# User credentials
br.form['email'] = 'email@example.com'
br.form['password'] = 'test-password'

br.submit

If I try robobrowser, this is my error:
Traceback (most recent call last):
  File "/Users/cmw/PycharmProjects/Nike_Bot/nike_bot_py.py", line 44, in <module>
    browser.submit_form(signin_form)
  File "/Library/Python/2.7/site-packages/robobrowser/browser.py", line 341, in submit_form
    response = self.session.request(method, url, **payload.to_requests(method))
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 553, in send
    adapter = self.get_adapter(url=request.url)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 608, in get_adapter
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'javascript:void(0);'

Answer: The website you are trying to access runs javascript to submit forms: action="javascript:void(0);". Your mechanize library is trying to mimic that without actually being able to understand javascript and fails. If you just submit the content of the form with a POST then that may work unless they are using request authentication, in which case you are out of luck.
Comment: So I'm guessing I need to use a headless browser that submits these forms as if I'm literally clicking them?
Comment: I'm not aware of any programmable browser that runs javascript. Just try to send a request that acts as if you filled out the form without actually navigating the page.


Proving the infinite sum of $1/2^i$ without induction

Question: Prove
$$\sum_{i=1}^n \frac{i}{2^i} = 2-\frac{n+2}{2^n} $$
Pretty trivial to do with induction, but as a practice problem for solving recurrences we have to do this only by repeating $\sum_{i=1}^n (1/2^i) = 1-1/2^n$ and summing the diagonals of the resulting lower triangular matrix.
So for example the first few rows of the matrix..
$1/2$
$1/2^2, 1/2 ^2$
$1/2^3, 1/2 ^3, 1/2^3$
.....
$1/2^n, .............1/2 ^n$
When you sum the diagonals you get $\sum_{k=1}^n (\sum_{i=k}^n 1/2^i)$, but this is basically back where we started. Now what?
Comment: See [Why $\sum_{k=1}^{\infty} \frac{k}{2^k} = 2$?](http://math.stackexchange.com/q/337937) and many other posts [linked there](http://math.stackexchange.com/questions/linked/337937).
Comment: The title and text are different - the former refers to a general term of $2^{-i}$ while the latter has a term of $i2^{-i}$.
Answer: You have
$$ \sum_{i=k}^n (1/2)^{i} = \frac{(1/2)^{k}-(1/2)^{n+1}}{1-1/2} = (1/2)^{k-1}-(1/2)^n $$
Then the outer sum is
$$ \sum_{k=1}^n \left( (1/2)^{k-1}-(1/2)^n \right) = - n (1/2)^n + \sum_{k=1}^{n} (1/2)^{k-1} = - n (1/2)^n + \frac{1-(1/2)^n}{1-1/2} = 2 - \frac{n+2}{2^n} $$
Answer: $$\begin{align}
\sum_{i=1}^n \frac{1}{2^i} &= \frac12 + \left(\frac12\right)^2+ \left(\frac12\right)^3+\cdots + \left(\frac12\right)^n\\
\frac12 \sum_{i=1}^n \frac{1}{2^i} &= 0 + \left(\frac12\right)^2+ \left(\frac12\right)^3+\cdots + \left(\frac12\right)^n+\left(\frac12\right)^{n+1}
\end{align}$$
Subtracting these we see
$$\begin{align}
\frac12 \sum_{i=1}^n \frac{1}{2^i} &= \frac12-\left(\frac12\right)^{n+1}
\end{align}$$
from which
$$\begin{align}
\sum_{i=1}^n \frac{1}{2^i} &= 1-\left(\frac12\right)^{n}
\end{align}$$
Similarly,
$$\begin{align}
\sum_{i=k}^n \frac{1}{2^i} &= \left(\frac12\right)^{k-1}-\left(\frac12\right)^{n}
\end{align}$$
Then, perform the outer sum similarly for the first term (i.e., sum a geometric progression).
Answer: Although Chappers' answer is good, an alternative approach might be to consider $$\sum_{i=1}^{n} \frac{x^i}{2^i}$$ which you can express with the usual formula for a geometric sum. Then if you take the derivative of both expressions and evaluate them at $x=1$, you will get the same answer without any induction.
Comment: I'll note that the other ways are probably better for this type of problem to get you more acquainted with series, but this technique is useful for more difficult problems.
Comment: Not the method I was looking for, but this is very clever too I will try it. I suppose it sort of fits with the point of "only using the series and properties of the series" to solve the question.


Analysis of data given as intervals instead of points

Question: I have a set of data that is not given as $ \boldsymbol{x} = x_1, \dots, x_n,$ but as pairs $\boldsymbol{x}_{interval} = (x^{(start)}_1, x^{(end)}_1), \dots, (x^{(start)}_n, x^{(end)}_n). $ For each pair $(x^{(start)}_i, x^{(end)}_i),$ the true $x_i$ lies in the interval $(x^{(start)}_i, x^{(end)}_i), $ but it is not known where.
In context, this means that we have intervals in which we know an event $x_i$ occured, which tells us that it happened after $x^{(start)}_i,$ but before $x^{(end)}_i$.
The goal of the analysis is to model this data or in some way approximate the distribution. Initially, I'll start with trying to use the information contained in the intervals to fit a normal distribution to the distribution of the unobserved events  $\boldsymbol{x}$ .
I'm having a very hard time finding any information about this type of problem. Is this a known field of research, of statistical interval analysis?
Comment: There is a tag on this site for interval-censoring, perhaps some of the answers there may help you?
Comment: It is a little like double sided censoring in survival analysis.  But it is not a time censoring and you have several intervals with only one observation per interval.  If I were to put a distribution for the unknown x in each interval I would use the uniform distribution because I think you have no reason to favor any particular points in the intervals over others.
Comment: It is conceivable that *how* the intervals are generated could be informative.  As such, I would be reluctant to apply some omnibus "interval-censoring" technique to the analysis of these data until I had a better understanding of what these intervals actually represent.  Could you elaborate on that?  For instance, many digital meters truncate measurements to some nearest power of 10, whence all intervals have a common width with predefined endpoints. In other cases the interval widths might vary with the measurement due to properties of the measurement itself.
Answer: The data are censored, specifically interval-censored. Censoring, especially right-censoring (start but no end), is a common feature of time-to-event data and dealt with under survival analysis (Medicine) or reliability analysis (Engineering).
For parametric modelling of such data the key insight is that contributions to the joint likelihood from uncensored data are of the form $$f(x_i)$$ while those from censored data are of the form $$F\left(x_i^\mathrm{(end)}\right)-F\left(x_i^\mathrm{(start)}\right),$$ where $f(\cdot)$ is the density & $F(\cdot)$ the distribution function. Under the assumption of independent censoring—which you shouldn't leap to—these are the only part of the likelihood needed for inference as the censoring times contain no additional information about the parameters. If a normal distribution seems appropriate start off with a contour plot of the likelihood against the mean & variance parameters, then improve initial maximum-likelihood estimates numerically.
Comment: Thanks so much for the connection to the term censoring, and interval-censoring. The likelihood contribution as a difference between the two CDFs was indeed my hunch, but it's great to see it makes sense. Thanks again!
Answer: A good starting for examining the univariate distribution would be to look at the Non-Parametric Maximum Likelihood Estimator (NPMLE). This is a generalization of the Kaplan-Meier curves (which itself is a generalization of the Empirical Distribution Function), which will give you a non-parametric estimate of the cumulative distribution function. Interestingly, this estimate is not unique (unlike the EDF or Kaplan Meier curves), but rather known up to an interval. So you will get a pair of step functions that bound the NPMLE, rather than a single step function.
While this estimator is good for examining the shape of a distribution, it can be a bit unstable, i.e. high variance in the estimates. One can fit standard parametric models, but it is still recommended to use the NPMLE at least for model checking.
Many of the standard survival regression models are available (proportional hazards, accelerated failure time and proportional odds, for example). Interestingly, although the NPMLE has high variance for the estimates of the survival curve, the regression parameters in a semi-parametric model which uses the NPMLE for the baseline distrubtion do not suffer from the instability. So semi-parametric regression methods are quite popular for inference.
@Scortchi and @whuber bring up important points about the generation of the beginning and end of the observation intervals ($x_i^{start}, x_i^{end}$ as defined by the OP). A standard simplifying assumption (which should be carefully considered) is that there are a set of inspection times $C_0 \leq C_1 \leq, ..., \leq C_k$ that are generated independently of the actual event time / outcome $t$ of interest (equality occurs when we observe the event time exactly). Then, all we observe is the interval $C_j, C_{j+1}$ such that $t \in C_j, C_{j+1}$. But if it seems plausible that the event time could strongly influence inspection time, care must be taken in the analysis. As an example, suppose our event of interest was onset of tooth decay and our inspections were dentist visits. If we go to the dentist fairly regularly, then the assumption of independence seems reasonable. But if we very rarely go to the dentist except when our tooth hurts a lot, then $t$ is definitely influencing $C_j$!
A brief tutorial for using these models in my R-package icenReg can be found here.


A bound of Cesàro mean of the Fourier series of bounded function

Question: Let $f: \mathbb{T} \to \mathbb{R}$ with $m \leq f(x) \leq M$ for some $m, M \in \mathbb{R}$ and all $x \in \mathbb{T}$. We have, the $k$-th Cesàro mean of the Fourier series $f$:
$$\sigma_k[f](x) = \int_{-\pi}^{\pi}F_k(t)f(x-t)\ dt,$$
where $F_k(t)$ is the Fejér kernel.
To show: $m \leq \sigma_k[f] \leq M$ for all $x \in \mathbb{T}$ and $k \in \mathbb{N}$.
I thought because $m \leq f(x) \leq M$ , then $m \leq f(x-t) \leq M$, by the periodicity of $f$. Using $\int_{-\pi}^{\pi}F_k(t)\ dt = 1$, it is clear that $m \leq \sigma_k[f] \leq M$. Then I'm starting to doubt whether I can take such conclusion. I think this reasoning will work if $f(x) \geq 0$ for all $x \in \mathbb{T}$. Any comments or tips would be appreciated.
Answer: Hint: Note that Fejér kernel is an approximate to identity, and  $$F_k(t)=\frac{1}{k+1}\left(\frac{\sin\frac{(k+1)t}{2}}{\sin\frac{t}{2}}\right)^2\geq 0.$$ So, $$m=\frac{m}{2\pi}\int_{-\pi}^\pi F_k(t)\ dt\leq\sigma_k(f)(x)=\frac{1}{2\pi}\int_{-\pi}^\pi F_k(t) f(x-t)\ dt\leq \frac{M}{2\pi}\int_{-\pi}^\pi F_k(t)\ dt= M.$$

Note that there is another alternative formulation of Fejér kernel
given by $$F_k(t)=\sum_{\ell=-k}^k\left
 (1-\frac{|\ell|}{k+1}\right)e^{i\ell\theta}.$$ But, we do not need this
here.
Comment: No, you don't need to consider this special case as Fejér kernel is non-negative, as I have written.
Comment: Maybe you mean $m = m\int_{-\pi}^{\pi}F_k(t)\ dt$? Since the integral of the Fejér kernel is 1, right?
Comment: Yes, the integral of the Fejér kernel is $1$, some use the factor $\frac{1}{2\pi}$, some not. It depends on the definition of Fejér kernel, in order to make it an approximate to identity we have to multiply it by suitable constant.
Comment: So we don't have to worry that $f(x)$ could be negative?
Comment: What do you mean with "it's an approximate to identity"?
Comment: Besides, how do you conclude those inequalities?


MutableLiveData: Cannot invoke setValue on a background thread from Coroutine

Question: I'm trying to trigger an update on LiveData from a coroutine:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
    AddressList.value = listOf()
    GlobalScope.launch {
        AddressList.value = getAddressList()
    }
    return AddressList
}

but I get the following error:

IllegalStateException: Cannot invoke setValue on a background thread

Is there a way to make it work with coroutines?
Comment: Is there a reason you don't want to use postValue?
Comment: @RedDeckWins. No, I just didn't take it into account but it is definitely the way to update MutableLiveData from a coroutine.
Answer: Use liveData.postValue(value) instead of liveData.value = value. It called asynchronous.
From documentation:

postValue - Posts a task to a main thread to set the given value.
Answer: You can do one of the following :
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
    AddressList.value = listOf()
    GlobalScope.launch {
        AddressList.postValue(getAddressList())
    }

return AddressList
}

or
fun getAddressesLiveData(): LiveData<List<Address>> {
    AddressList.value = listOf()
    GlobalScope.launch {
        val adresses = getAddressList()
        withContext(Dispatchers.Main) {
            AddressList.value = adresses
        }
    }
    return AddressList
}

Comment: Actually, I think this is the perfect `postValue()` usage scenario. There is no need to force Main Thread context.
Comment: Read the documentation for `GlobalScope`. Avoid using `GlobalScope`.
Answer: I just figured out that it's possible by using withContext(Dispatchers.Main){}:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
    GlobalScope.launch {
        withContext(Dispatchers.Main){ AddressList.value = getAddressList() }
    }
    return AddressList
}

Comment: Don't call `getAdresseList()` inside the `withContext(Dispatchers.Main)` block because this will be run on the main thread.
Call it outside so it's properly dispatched by `Dispatchers.Default` and use only the result on the main thread
Comment: You just literally return your heavy task to run in UI thread
Comment: Avoid using `GlobalScope`. https://developer.android.com/kotlin/coroutines/coroutines-best-practices#global-scope
Answer: Although others have pointed out that, in this case, the library provides its own method to post an operation to the main thread, coroutines provide a general solution that works regardless of a given library's functionality.
The first step is to stop using GlobalScope for background jobs, doing this will lead to leaks where your activity, or scheduled job, or whatever unit of work you invoke this from, may get destroyed, and yet your job will continue in the background and even submit its results to the main thread. Here's what the official documentation on GlobalScope states:

Application code usually should use application-defined CoroutineScope, using async or launch on the instance of GlobalScope is highly discouraged.

You should define your own coroutine scope and its coroutineContext property should contain Dispatchers.Main as the dispatcher. Furthermore, the whole pattern of launching jobs within a function call and returning LiveData (which is basically another kind of Future), isn't the most convenient way to use coroutines. Instead you should have
suspend fun getAddresses() = withContext(Dispatchers.Default) { getAddressList() }

and at the call site you should launch a coroutine, within which you can now freely call getAddresses() as if it was a blocking method and get the addresses directly as a return value.
Answer: If you want to updated UI by using Coroutines, there are 2 ways to achieve this
GlobalScope.launch(Dispatchers.Main):
GlobalScope.launch(Dispatchers.Main) {
    delay(1000)     // 1 sec delay
    // call to UI thread
}

And if you want some work to be done in background but after that you want to update UI, this can be achieved by the following:
withContext(Dispatchers.Main)
GlobalScope.launch {
    delay(1000)     // 1 sec delay

    // do some background task

    withContext(Dispatchers.Main) {
            // call to UI thread
    }
}

Comment: Avoid using `GlobalScope`. https://developer.android.com/kotlin/coroutines/coroutines-best-practices#global-scope
Answer: In my case, I had to add Dispatchers.Main to the launch arguments and it worked fine:
 val job = GlobalScope.launch(Dispatchers.Main) {
                    delay(1500)
                    search(query)
                }

Answer: The Answer from @Amir Hossein Ghasemi is good. Just to add to it.
liveData.value = value is used to update the value of a LiveData only on the main thread. Usually used for RxJava
Whereas liveData.postValue(value) you can call it from any thread, including the main thread and background threads (asynchronous). Usually used for coroutines
Answer: I was facing this error when I called a coroutine inside runBlockingTest for a test case
TestCoroutineRule().runBlockingTest {

}

I got it fixed by adding the instantExecutorRule as a class member
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()

Answer: Below code worked for me for updating livedata from thread:
 val adresses = getAddressList()
 GlobalScope.launch {
     messages.postValue(adresses)
 }


Deploy environment variables to Firebase hosting

Question: I use Firebase in React and when initializing Firebase, I use environment variables fetched from my .env file with dotenv. I want to build and deploy my React app to Firebase hosting, I use GitHub Actions with the following .yml workflow file:
name: Deploy
on:
  push:
    branches:
      - master

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@master
      - name: Install Dependencies
        run: npm install
      - name: Build
        run: npm run build
      - name: Archive Production Artifact
        uses: actions/upload-artifact@master
        with:
          name: public
          path: public
  deploy:
    name: Deploy
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@master
      - name: Download Artifact
        uses: actions/download-artifact@master
        with:
          name: public
      - name: Deploy
        uses: w9jds/firebase-action@master
        with:
          args: deploy --only hosting
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

However, my build step fails (i.e. npm run build) because the environment variables are not found. If I hardcode the values instead of using my environment variables, the workflow is successful.
Do I need to do add my environment variables to GitHub secrets similar to how I added FIREBASE_TOKEN in my deploy step and add them to the workflow to be something like:
name: Deploy
on:
  push:
    branches:
      - master

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@master
      - name: Install Dependencies
        run: npm install
      - name: Build
        run: npm run build
        env:
          FIREBASE_API_KEY: ${{ secrets.FIREBASE_API_KEY }}
          FIREBASE_AUTH_DOMAIN: ${{ secrets.FIREBASE_AUTH_DOMAIN }}
          FIREBASE_DATABASE_URL: ${{ secrets.FIREBASE_DATABASE_URL }}
          FIREBASE_PROJECT_ID: ${{ secrets.FIREBASE_PROJECT_ID }}
          FIREBASE_STORAGE_BUCKET: ${{ secrets.FIREBASE_STORAGE_BUCKET }}
          FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.FIREBASE_MESSAGING_SENDER_ID }}
          FIREBASE_APP_ID: ${{ secrets.FIREBASE_APP_ID }}
      - name: Archive Production Artifact
        uses: actions/upload-artifact@master
        with:
          name: public
          path: public
  deploy:
    name: Deploy
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@master
      - name: Download Artifact
        uses: actions/download-artifact@master
        with:
          name: public
      - name: Deploy
        uses: w9jds/firebase-action@master
        with:
          args: deploy --only hosting
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

I receive the same error, saying that it can't find the API token.
When I browse workflow files in other firebase-based React apps, I can't see anyone adding these environment variables like I have suggested. What is the proper way of handling environment variables in apps deployed to Firebase? Do they belong in the build or deploy step?
Comment: Did you get any solution?
Comment: To be clear, have you added your API key as a github secret, or just in an env file? Can you be a bit more specific about what the errors were, and the example file when it worked.
Answer: Your custom env variables must start with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name.
Please take a look at this article Adding Custom Environment Variables.
As an additional note you can also run the npm run build along with your env variables passed as parameters like this:
REACT_APP_FIREBASE_APIKEY=${{ secrets.REACT_APP_FIREBASE_APIKEY }} REACT_APP_FIREBASE_AUTHDOMAIN=${{ secrets.REACT_APP_FIREBASE_AUTHDOMAIN }} REACT_APP_FIREBASE_DBURL=${{ secrets.REACT_APP_FIREBASE_DBURL }} npm run build

Answer: Instead of adding a .env file you can easily add the secrets to github secrets.

Once the secrets are added to github secrets you can add them to env at the build process as follow in your workflow.
name: Firebase Deployment
on:
  push:
    branches:
      - master
      - feature/secrets_fix

env:
  API_KEY: ${{ secrets.FIREBASE_API_KEY }}
  APP_ID: ${{ secrets.FIREBASE_APP_ID }}
  AUTH_DOMAIN: ${{ secrets.FIREBASE_AUTH_DOMAIN }}
  MESSAGE_SENDER_ID: ${{ secrets.FIREBASE_MESSAGE_SENDER_ID }}
  PROJECT_ID: ${{ secrets.FIREBASE_PROJECT_ID }}
  STORAGE_BUCKET: ${{ secrets.FIREBASE_STORAGE_BUCKET }}
  TOKEN: ${{ secrets.FIREBASE_TOKEN }}

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: firstname.lastname@example.com
      - name: Install Dependencies
        run: npm install
      - name: Build
        env:
          CI: false
        run: npm run build
      - name: Archive Production Artifact
        uses: actions/upload-artifact@v2
        with:
          name: build
          path: build
  deploy:
    name: Deploy
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: email@example.com
      - name: Download Artifact
        uses: actions/download-artifact@v2
        with:
          name: build
          path: build
      - name: Deploy to Firebase
        uses: w9jds/firebase-action@master
        with:
          args: deploy --only hosting
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

secrets.${YOUR_GITHUB_SECRET_NAME}
Once they are mapped as above under env, you can easily retrieve them from react application using
process.env.YOUR_ENV_VARIABLE_NAME_HERE
Following is a example on firebaseConfig
const firebaseConfig = {
    apiKey: process.env.API_KEY,
    authDomain: process.env.AUTH_DOMAIN,
    projectId: process.env.PROJECT_ID,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MESSAGE_SENDER_ID,
    appId: process.env.APP_ID
};

Hope this will help someone.
Answer: Correct, you should add your env parameters to Github Secrets (https://github.com/your-project-name/settings/secrets/actions) and address them in YAML file, setting them up in the beginning of the file. Here's an example:
name: Deploy to Firebase Hosting on merge
'on':
  push:
    branches:
      - main
env:
  REACT_APP_API_KEY: ${{ secrets.REACT_APP_API_KEY }}
  REACT_APP_FIREBASE_AUTH_DOMAIN: ${{ secrets.REACT_APP_FIREBASE_AUTH_DOMAIN }}
  REACT_APP_FIREBASE_PROJECT_ID: ${{ secrets.REACT_APP_FIREBASE_PROJECT_ID }}
  REACT_APP_FIREBASE_STORAGE_BUCKET: ${{ secrets.REACT_APP_FIREBASE_STORAGE_BUCKET }}
  REACT_APP_FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.REACT_APP_FIREBASE_MESSAGING_SENDER_ID }}
  REACT_APP_FIREBASE_APP_ID: ${{ secrets.REACT_APP_FIREBASE_APP_ID }}
  REACT_APP_FIREBASE_MEASUREMENT_ID: ${{ secrets.REACT_APP_FIREBASE_MEASUREMENT_ID }}
  REACT_APP_FIREBASE_DATABASE_URL: ${{ secrets.REACT_APP_FIREBASE_DATABASE_URL }}

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [17.4.0]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
      - run: |
              npm install
              npm ci && npm run build --if-present
      - uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_APPNAME }}'
          channelId: live
          projectId: APPNAME