Método / Função que "pare aplicação somente se o usuário pressionar uma tecla" em C#

Question: Olá, eu estou praticando minha logica de programação no desenvolvimento de um app cronometro em C#... ele está contado os segundos, minutos e horas, até ai OK... porém eu quero criar a opção de o usuário "Pausar" o cronometro, tentei usar o método Console.ReadKey() mas o problema é que ele interrompe minha aplicação (parando de contar os segundos e minutos) esperando uma entrada do usuário, adoraria se alguém me desse alguma dica!!
<code>        static void Cronometro()
    {
        int tempo = 59;
        int minutos = 0;
        int horas = 0;
        int play = 0;
        int segundos = 0;

        Console.WriteLine("1 - iniciar ");
        Console.WriteLine("2 - Sair ");
        play = Convert.ToInt32(Console.ReadLine());

        if(play == 1)
        {
            do
            {
                //Função clear para limpar o console para nao ficar imprimindo infinitamente
                Console.Clear();
                Console.WriteLine("P - Pausar ");
                Console.WriteLine("S - Sair ");

                Console.WriteLine();
                segundos++;
                Console.WriteLine(segundos + " segundos");
                Console.WriteLine(minutos + " min");
                Console.WriteLine(horas + " horas");
                Console.WriteLine();

                    if (segundos == 59)
                    {
                        segundos = 0;
                        minutos++;
                    }
                    if (minutos == 59)
                    {
                        minutos = 0;
                        horas++;
                    }
                    //delay de 1s para a aplicação nao bugar, pois o time de leitura do codiog é mt rapido
                    Thread.Sleep(1000);
            }
            //aqui estou preso, pois a aplicação é interrompida a espera de uma interação com o usuario...
            while (Console.ReadKey().Key != ConsoleKey.P);
            Console.WriteLine("PAUSADO");
        }
        else if(play == 2)
        {
            Menu();
        }
    }
</code>
Answer: Talvez seja interessante você declarar um método por exemplo "Pause" fora do escopo "Cronometro" e declará-lo como público para que você possa chamar a função toda vez que durante a execução da estrutura condicional for receber um comando diferente do que está sendo sugerido pelo programa. Ex:
<code>static void Pause()
    {
        Console.WriteLine("Cronômetro pausado. Digite uma opção: ");
        Console.WriteLine("1 - Continuar a cronometragem.");
        Console.WriteLine("2 - Voltar ao menu inicial.");
        string pausar = string.Parse(Console.ReadLine());

        switch (pausar)
        {
            case 1: cronometrar; break;
            default: Menu(); break;
        }

    }

static void cronometrar()
    {
        Cronometro()
    }
 //E então dentro do seu código, declare uma estrutura condicional do tipo:
    if(play == 1 && cronometrar)
    {
        do
        {
            // continua o código de reprodução do crônometro.
        }
    }
</code>
Comment: Lembrando que você deve sempre se atentar sempre ao escopo onde você está declarando, para que posso fazer o uso posteriormente dentro de outros escopos.


load instance in a different appdomain

Question: Is it possible to create a new app domain and instantiate an instance of a type in that new domain or can you only load assemblies into app domains? Or possibly marshal an instance reference to another app domain?
Comment: @Rup for the same reason you're asking why, just curious.
Comment: Curiousity - why? Different set of static variables, or you don't trust the code, or something?
Comment: @Rup: One interesting side effect of doing this is that this is the only way to dynamically unload assembly and later be able to hot swap dll on the running managed process.
Answer:
Programming with Application Domains
AppDomain.CreateInstanceAndUnwrap
// Create a new application domain, create an instance
// of Worker in the application domain, and execute code
// there.
AppDomain ad = AppDomain.CreateDomain("New domain");
Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(
    Assembly.GetExecutingAssembly().FullName,
    "Worker");
remoteWorker.PrintDomain();

Comment: While I don't know his premise for using AppDomains, if Worker is a specific type it has now been loaded into both the Root Domain and the Child Domain meaning you can no longer dump it.
Answer: You can do all three.
Look up MarshalByRefObject on how to invoke an object created in one domain in your current domain.
You can also specify the ApplicationBase for the automatic Assembly Lookups.
There is also the Load method on a domain.
You have another option of using System.AppDomain.AssemblyResolve to do custom resolution. You can even stream an Assembly across the network that never existed on your machine before and have the Type resolving work with this event.
Cautions:
If your intent is to be able to unload a domain you have to make sure you do not load any Assembly or Type in your main AppDomain that you are instantiating in your child domain. This can be complicated because typically you'll want an interface between the Root AppDomain and it's children.
Answer: You can create a new app domain and instantiate an instance of a type there.  The type must be defined somewhere, but it doesn't have to be from a loaded assembly.  You could marshal a serializable type to another app domain.
You are probably aware of the issues of unloading an App Domain, but if not you should look into that if you care about unloading.
I don't have my code for this handy at the moment I'm afraid.
Answer: Yes you can:
 AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
 newDomain.Load("MyAssembly");

There are various overloads to Load, so check that out: http://msdn.microsoft.com/en-us/library/dwzhhcfk.aspx

load instance in a different appdomain


EM algorithm for mixture of Gaussians - is it ok to use my updated mu's in my new estimate of Sigma, within a single M-step?

Question: Here is a screenshot from an assignment I am currently working on - these are the Expectation-Maximization update rules for the parameters $\omega$ (latent component "responsibilities"), $\mu$, and $\Sigma$ for a mixture of multivariate Gaussians.
To clarify notation (though this isn't actually too important, my question is for general E-M):

$p(m|x_t;\theta)$ is the probability of latent component m given an $x_t$ (and there are a total of $T$ such $x_t$'s in the entire dataset $X$)
$\theta$ is a parameter which holds $\omega$, $\mu$, and $\Sigma$

Within a single M-step, the updates for $\mu$ occur before the updates for $\Sigma$ (as in, the literal line of code for the $\mu$ update gets executed earlier).
So as I code this I am wondering: Is it kosher to use my updated $\mu$ in my calculation of the $\Sigma$ update, within the same "M-step"?

On one hand, I would think that theoretically, all of these parameter updates are supposed to happen "instantaneously" and at the same time as each other - meaning, I should use the old, un-updated $\mu$ from just before my update.
On the other hand, the updated $\mu$ is supposed to converge towards the "correct" value, so my updated $\mu$ should be "closer" to the truth - meaning that if I use the new $\mu$, it ought to give me a more "accurate" $\Sigma$ update.

Can anyone comment? Thank you!

Small edit: re the (very reasonable!) comment below that the notation should be more explicit in specifying $\theta^{current}$ vs $\theta^{update}$ - I completely agree that the notation as provided from the assignment is not at all clear, and hence the impetus for this question.
I've simplified, but in code my updates look something like this, and this performs reasonably well:
theta.omega = update_omega(theta, X)
theta.mu = update_mu(theta, X)
theta.Sigma = update_Sigma(theta, X)

While the provided notation can be considered "bad", it does translate nicely to code, so perhaps the professor was just trying to help. If I weren't thinking too hard it would be easy to miss the fact that an updated theta is being fed into each sequential step.
I'm asking this question because I am curious about whether this is standard practice for implementing EM (as it seems to be in the sklearn GaussianMixture class - I believe that within a single M-step they take a freshly updated mu and feed it right into the covariance update), or whether this is technically a "different" approach (as the third comment may suggest!).
Comment: This approach is called ECM for Expectation-Conditional-Maximisation, see [Meng and Rubin (1993)](http://tinyurl.com/meng-rubin-pdf).
Comment: There is a notation issue: EM requires _two_ sets of parameters,one,  $\theta^\text{cur}$, being the current value of the parameter, obtained at the previous M step, the other being a free $\theta$ that is the variable of the next optimisation step.
Comment: @Xi'an - thanks for the suggestion, I didn't know about the `self-study` tag and it has been added. I agree that the notation provided is unclear; if it had been explicit then I wouldn't need to ask this question (though I'll add a little edit above). Thanks for linking the paper as well, I will read it.
Answer: In short, updating the parameters all at once in the M step or one by one with the other being fixed are both justified by the same argument that both approaches do increase the (observed) likelihood at each step. See Meng and Rubin (Biometrika, 1993) for more details.
Comment: If the definition of the M step is that it should maximize the likelihood, then one should use the updated mu to update the sigma, right? It might still work when using the old mu, but it won't maximize the likelihood.
Comment: It works if one runs one M step at a time with only one parameter to optimise and it works if one runs a single M step with all parameters changed at once.
Comment: Yes; my comment was rather terminological: I wanted to say that "vanilla" EM is the one that optimizes all parameters inside one M step (which in this case means using new mu to compute new sigma).
Answer: Yes, and it's easy to see why if we look at it the right way.
Forget about the M-step; in fact, forget the fact that we're inside an iterative algorithm at all. Forget about the past and that you ever had other estimates for $\vec{\mu}$ or $\mathbb{\Sigma}$. And forget that there are other classes, and just focus on one class. And forget that the weights can be interpreted as $p(m|\vec{x}_i;\theta)$ and just think of them as sample weights, origin unknown, called $w_i$. For convenience let's also assume that these weights are normalized, e.g. $\sum w_i = 1$.
What remains is a sample of $n$ (instead of $T$ so I can reserve $T$ for "transpose") observations $\vec{x}_i$ with weights $w_i$ which we believe came from a multivariate distribution $\mathcal{N}(\vec{\mu}, \mathbb{\Sigma})$. What is the procedure for estimating $\vec{\mu}$ and $\mathbb{\Sigma}$? Well, it's to first calculate the mean, subtract it off, then average over the outer products:
$$ \vec{\mu}= {1 \over {n}}\sum_{i=1}^n w_i \vec{x}_i \tag{1} $$
$$ \mathbb{\Sigma} = \frac{1}{n} \sum_{i=1}^n w_i ( \vec{x}_i - \vec{\mu} )(\vec{x}_i - \vec{\mu})^T \tag{2} $$
This is the ML estimate. Note that the $\vec{\mu}$ in (2) is exactly the same as the $\vec{\mu}$ in (1) - this is a closed form solution, not an iterative algorithm! Any other estimate for $\vec{\mu}$ and $\mathbb{\Sigma}$ will have lower likelihood, by definition.
Now we can lift our self imposed amnesia and recall that we are using E-M to numerically approximate the maximum likelihood of a GMM. For that one particular M step, we held all other parameters constant and maximized the likelihood with respect to just $\vec{\mu}$ and $\mathbb{\Sigma}$. Because we used the closed form solution of (1) and (2), we didn't take a "step" towards that maximum - we jumped straight to the maximum within that subspace. In particular we can guarantee that likelihood either increased or stayed the same. We need this property because it is necessary for the convergence of the E-M algorithm as a whole. Using the closed form ML estimate for the multivariate distribution is by easiest way to prove it, and any other procedure for updating $\vec{\mu}$ and $\mathbb{\Sigma}$ - such as using the $\mu$ left over from the previous step - would require a separate proof.
One good resource on GMM and the EM algorithm I used was this Stanford Lecture by Andrew Ng. I've linked to the part of the lecture where he shows this update step in particular but the whole lecture is worth watching.
Comment: +1 Very nice answer.


How to read lyrics and music without getting lost?

Question: I can read music enough to follow a vocal line but have never sung from music before. I've ended up in a festive choir and am finding aside from the problems of singing something that's not the tune, having to read the bass line while looking at the lyrics is a problem. I keep getting lost in the music or missing the lyrics when I look at the music!
Can anyone offer any tips?
Comment: You need to train your peripheral vision.
Answer: The biggest thing is simply practice and experience: the more you do it, the easier it gets. It doesn't help so much for the present, but it means that if you do this again next year, it will be easier. But here are a few tricks for this year.

Highlight your part. That way, it stands out from the others, so it
takes less concentration to find it when you are switching between
the lyrics and the notes. Yellow is usually best because it is very
visible, but also very easy to read what's beneath. And it usually
disappears under a photocopier.
Rewrite the lyrics. If part of the problem is that the notes and lyrics are too far from
each other, you can rewrite the lyrics by hand closer to the notes.
This one is a pain, and I only do it when the original music is very
badly formatted. But when that's the case, it's a huge help.
Stand next to better singers in your part. If you have other, more experienced singers also singing the same
part as you, make an effort to stand next to them. It makes it easier
to hear and follow your part. My experience is in amateur groups of
very mixed abilities, but I've always found the experienced musicians
are willing to help out this way. Before the rehearsal starts, go up
to the best singer in your part, and ask if you can sit next to them
because you are having trouble holding your own part, and you could
do better if you could follow them. Then they'll probably even help
save you a spot.
Become familiar with your part. Even halfway memorizing your part goes a long ways towards
solving your problem, because there will be a lot less to read.
Answer: Usually with SATB the lyrics are just under the dots.That's because the same words may not always be sung at the same time in each voice. Learning the lyrics as in a poem means there is one fewer thing to look at - then the notes can be followed more easily.
If you can find recordings of the pieces, them listen to them while following the sheet music.Eventually singing your part along with them.If you could find someone to play only your part, or even better, your part while the recording is being played, you could, again, sing along to that. All this is obviously 'homework' - I wouldn't recommend you asked for that to happen in a full rehearsal. Some choirs will have a time when each voice can be taken separately. I don't know whether 'Music Minus One' has recordings of this sort of stuff, but if so, it would be very useful to you and others.
Comment: Learning the parts would obviously remove the need for music and would be preferable - I have the parts recorded - but I don't think it's possible (for me) in the time available to learn so many things. Same with lyrics - verse one is fine generally but then it goes wrong. And under the stress of singing unfamiliar tunes, even words I know go out of my head!
Comment: So I was more hoping for some sort of tips/tricks in the interim :)
Answer: The same way people read piano scores that have 2 clefs that are being played at the same time: You practice and practice and you'll get there.
At first, it is hard for everyone to follow two different things simultaneously (in your case, a bass line and lyrics), but if you keep doing it, you'll be able to follow both the lyrics and the music without losing it.
If you find one of those parts easier to memorize than the other, memorize it and follow/read the other one when you sing. That way you won't have to read two things at the same time.
You can also practice them separately. If one of the lines is hard to be read while you sing, practice each one of them separately and then when  you feel comfortable with them, put them together, it'll be easier.


How to avoid smoothing to 0 at edges of R density plot

Question: When using the density function in R, it includes smooth transitions down to 0 at both ends of the data. Is there a way to prevent this? As a trivial example, suppose I am calculating the density function for 1000 uniformly spaced points between 0 and 1. What I'd like is a straight line from 0 to 1. Instead, I get a straight line from about 0.2 to 0.8 with smooth transitions down to 0. (Numbers are a little different for non-default kernels but the same general idea.) Of course, I know the density in this example, but not in real examples. I can shrink these end caps using bw or adjust, but that causes an undesirable reduction in smoothing within the interval.

Is there an option to truncate the kernel at the boundaries of the region, so that it estimates the density using only points inside the region? I have worked around this by mirroring all of my points about the two ends and then keeping only the part in the middle, but that seems like a crazy hack for something that should be simple. Is there a simpler way to do this?
Comment: Almost a duplicate:  https://stats.stackexchange.com/questions/121744/kernel-density-estimation-on-bounded-support
Answer: In general, you need a routine which is told of any hard minimum and/or maximum for a variable and does somehow the right thing near those boundaries. The right thing could be mapping to a different space; estimating the density on a transformed scale, and then back-transforming; or reflecting probability mass backwards at a boundary.
Such routines are not common and the problem isn't even widely mentioned, so far as I know.
Otherwise put, no routine knows about a boundary unless it is told about it. Or, the software user must take extra care to do an equivalent calculation. Not the answer you seek, but for such data I think you are better off plotting the cumulative distribution function, or equivalently the quantile function. In this example, either would be a straight line for a uniform distribution, naturally. It's a broader issue, but my own prejudice is that density estimation is somewhat oversold, whereas quantile plots are still undersold. Density estimation smooths away trivial noise, to be sure, but for many very common situations, particularly highly skewed and/or bounded distributions, density estimation defaults often work poorly.
I am not well informed about density estimation code in R and don't know what adjust does. In any case this has been migrated to CV as essentially a statistical question. It seems clear that changing the kernel type or width is no kind of solution here, unless the kernel adapts at the boundaries, which is perhaps the nub of the question.
Answer: If it is ok for you to use a different smoother, you could try P-splines in these cases. The method I am referring to is presented in Eilers and Marx (1991).
Edit - how does this help?
Quoting Eilers and Marx,

the P-spline density smoother is not troubled by
boundary effects, as for instance kernel smoothers
are.

In general, P-splines combine B-splines and finite difference penalties. The density smoothing problem is a special case of GLM. So we just need to parameterize our smoothing problem accordingly.
The R-code below reproduces an example similar to the one proposed in the original question. The same code and a short explanation of the method can be found here: Kernel density estimation and boundary bias
(Edit: N=60 in analogy with the other example)
# Simulate data
set.seed(1)
N = 60
x = runif(N)

# Construct histograms
his = hist(x, breaks = 60, plot = F, prob = T)
X = his$counts
u = his$mids

# Prepare basis (I-mat) and penalty (1st difference)
B = diag(length(X))
D1 = diff(B, diff = 1)
lambda = 1e6 # fixed but can be selected (e.g. AIC)
P = lambda * t(D1) %*% D1

# Smooth
tol = 1e-8
eta = log(X + 1)
for (it in 1:20)
{
mu = exp(eta)
z = X - mu + mu * eta
a = solve(t(B) %*% (c(mu) * B) + P, t(B) %*% z)
etnew = B %*% a
de = max(abs(etnew - eta))
cat('Crit', it, de, '\n')
if(de < tol) break
eta = etnew
}

# Plot
plot(u, exp(eta) / diff(u)[1] / sum(exp(eta)), ylim = c(0, max(his$density)), type = 'l', col = 2)
lines(u, his$density, type = 'h')

The results look like this (you will notice there is no boundary bias):
Answer: This problem is discussed in Venables & Ripley MASS (the book) writes:
Most density estimators will not work well when the density is non-zero at an
end of its support, such as the exponential and half-normal densities. (They are
designed for continuous densities and this is discontinuity.) One trick is to reflect
the density and sample about the endpoint, say, a. Thus we compute the density
for the sample c(x, 2a-x) , and take double its density on [a, ∞) (or (−∞, a]
for an upper endpoint). This will impose a zero derivative on the estimated density at a, but the end effect will be much less severe. For details and further tricks
see Silverman (1986, §3.10).

The cited book is here. Then they go on to mention boundary kernels, which did not exist in R/S-plus at that time. But now they do, see the following simple example:
library(bde)
set.seed(7*11*13) # My public seed
testdata <- runif(60)
bde.estimate <- bde::bde(testdata, estimator="boundarykernel")

Comment: The graph is not  a good advertisement for the method...
Comment: I did look at the y axis and before I posted my comment...
Comment: This is a useful answer (+1) albeit somewhat oddly worded. With `N=10000` as the other methods, the resulting plot looks fine. The `bde` package is quite literally designed for density estimation in bounded domains; it is the tool for the job.
Comment: IT is not---until you looks at the y-axis.


better way to validate input?

Question: I have a bit of code that takes 5 grades from user input and checks to see if a grade is 0 to 100 or if the input is a non-numerical value and keeps trying until you give it valid input.
def main(x):
    counter = 0
    grade = x
    grades = [0] * 5
    incount = ["first", "second", "third", "fourth", "fifth"]
    average = 0
    restart = ""

    # try 5 times to validate input and set the 5 grades if valid
    while counter < 4:
        try:
            grade = int(grade)
            if grade > 100 or grade < 0:
                print("Please enter a number from 0 to 100!")
            else:
                grades[counter] = grade
                counter = counter + 1
        except:
            print("Please enter a valid numerical value.")
        grade = input("Enter the " + incount[counter] + " grade. ")
    grades[counter] = grade

The problem is on the 5th grade if it does not validate. What could I change to make sure the 5th one validates and can also start using this module
def start():
    grade = 0
    print("To get a grade average, please enter five grades one by one from
    0 to 100.")
    grade = input("Enter the first grade. ")
    main(grade)

EDIT:
    while counter < 5:
        try:
            grade = int(grade)
            if grade > 100 or grade < 0:
                print("Please enter a number from 0 to 100!")
            else:
                grades[counter] = grade
                counter = counter + 1
        except:
            print("Please enter a valid numerical value.")
        if counter < 5:
            grade = input("Enter the " + incount[counter] + " grade. ")
    grades[counter - 1] = grade

I took the advice to loop an extra time but I did not want to add a decision statement to avoid another input on the last loop. It seems to be a cheap fix for the last loop but I can't figure out how to get all 5 values validated without taking another input otherwise.
Comment: Can you reformat this to be valid Python code, so that we can see the concrete problems with your implementation? Pseudocode can not be tested, and the question should not be tagged `python` unless it actually is related to Python.
Answer: You're only iterating 4 times in your while loop since your condition is a strict inferiority.
counter takes only the following values : 0, 1, 2, 3, 4. But for 4 it doesn't output TRUE to the condition
You should change the max value from 4 to 5 OR change your operator from < to <=
Comment: I would also have to stop taking input on the 5th loop and that takes up another decision, maybe that is my only option
Comment: Can you be clearer about that? I'm not sure I understand
Comment: At the end of each loop, another input is taken. On the 5th loop, at the end another input would be taken giving 6 input values and producing an error.
Comment: No, it only asks you five times to input a grade.
Comment: no on the 5th run it asks for input again just look at code
Comment: it asks for input again but it is the 5th request not the 6th
Comment: the last thing the loop does is ask for input, think about it. before the loop starts it already has input, so on the 5th run (not the 6th) a 6th INPUT record would be taken. therefore i put a check before the input is taken to see if it is the last run, do you understand?
Comment: Well no. On the 5th run, you store your grade, then you increment `counter`, then you check if `counter` is less than 5 (which is False because `counter = 5` at this time), so you don't enter the `if` and you don't ask for another input.
Comment: no, at the end of each loop input is taken. you are completely wrong
Answer: I have diverged from your preferred solution direction and decided to go with a self calling function with some checks for call counter and grades length
There is also a custom exception for numbers < 0 or > 100 that is raised and caught to give the desired user flow.
# coding: utf-8
class InvalidIntError(Exception):
    ''' our custom exception '''
    pass

def average_grade(grades_marks, grade_title, counter):
    grades = ['first', 'second', 'third', 'fourth', 'fifth']

    # for the first loop use the original grades list
    if counter > 0:
        # for subsequent calls to this function always start looping grades from passed grade_title
        current_index = grades.index(grade_title)
        new_grades = grades[current_index:]
        print(
            f'The current index {current_index} , the current grades {new_grades}'
        )
        grades = new_grades

    try:
        print(f'Counter {counter}, using grades :> {grades}')

        for grade_title in grades:
            grade = int(input(f'Enter the {grade_title} grade :> '))
            if grade > 100 or grade <= 0:
                raise InvalidIntError(
                    f'Your grade is < 0 or > 100.Enter the {grade_title} grade :> '
                )
            grade = int(grade)
            grades_marks.append(grade)
            print(grades_marks)
            counter += 1
        print('Gotten grade values calculating the average')
        average = sum(grades_marks) / len(grades_marks)
        print(f'grades given as {grades_marks},\n the average is :> {average}')
    except ValueError as e:
        # means we have given a non integer, so rerun function
        print('error ', e)
        average_grade(grades_marks, grade_title, counter)
    except InvalidIntError as e:
        # an int < 0 or > 100
        print('error ', e)
        average_grade(grades_marks, grade_title, counter)

if __name__ == '__main__':
    grades_marks = []
    average_grade(grades_marks, 'first', 0)

Sample run
$ python infinite_validation.py
Counter 0, using grades :> ['first', 'second', 'third', 'fourth', 'fifth']
Enter the first grade :> 20
[20]
Enter the second grade :> f
error  invalid literal for int() with base 10: 'f'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> g
error  invalid literal for int() with base 10: 'g'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> f
error  invalid literal for int() with base 10: 'f'
The current index 1 , the current grades ['second', 'third', 'fourth', 'fifth']
Counter 1, using grades :> ['second', 'third', 'fourth', 'fifth']
Enter the second grade :> 20
[20, 20]
Enter the third grade :> 40
[20, 20, 40]
Enter the fourth grade :> 12
[20, 20, 40, 12]
Enter the fifth grade :> 9000000000000221211
error  Your grade is < 0 or > 100.Enter the fifth grade :>
The current index 4 , the current grades ['fifth']
Counter 4, using grades :> ['fifth']
Enter the fifth grade :> 40
[20, 20, 40, 12, 40]
Gotten grade values calculating the average
grades given as [20, 20, 40, 12, 40],
 the average is :> 26.4

NB: You can remove some of the excessive print debug statements.
Comment: can you explain why i would want to do this? seems like a way overcomplicated way of doing a rather simple task
Comment: this is just an alternative, it might work or not work for you , it uses one function also it captures specific exceptions as opposed to a general except statement, finally it passes much more control to the caller by introducing those three parameters.

better way to validate input?


How do I mass update entities?

Question: How do I perform mass updates for entities? Suppose I want to publish 50 nodes at once. How should I do that?
Comment: But what rows? Values in multi-value field? Many entity instances? Please be more specific about your setup.
Answer: You can perform most of the mass updates in Admin > Content page.
If you require any advanced actions, sorting, filtering, I'd suggest you use Views and Views Bulk Operations modules.
Answer: You can use Views bulk operations module which support the mass update on the Drupal site.

This module augments Views by allowing bulk operations to be executed
  on the displayed rows. It does so by showing a checkbox in front of
  each node, and adding a select box containing operations that can be
  applied. Drupal Core or Rules actions can be used.

As you said that you want to update the number of nodes, so there is already module in Drupal Administration Views which replace administrative pages with views.

Features

Filter all administrative views via AJAX.
Perform any kind of bulk/mass operations on items in administrative views.
Filter content by title, node type, author, published status, and/or vocabulary.
Filter comments by title, author, node title, or published status.
Filter users by name, ban/blocked status, or user roles.

Or, if you want to update using code, you can follow harshal's answer.
Answer: If you have a big number of nodes that need to be updated (say, 10,000 or more), the best option available for you is to use DRUSH (Drupal Shell).
With drush you can perform bulky tasks very fast.
Comment: The pro of drush is that it doesn't depend from a browser, and that the PHP timeout is changed to allow longer operations. Other alternatives would require to use a Drupal queue, and a module that run its cron tasks.

How do I mass update entities?


Maximal area of a triangle

Question: What would be the most elementary proof of the following:
A triangle has been drawn inside the circle with radius $r$ and its area is as large as possible. Prove that the triangle is equilateral.
I mean, can we avoid topology and compactness to prove that the maximal triangle can be found? And can we avoid derivatives and trigonometry to find the maximal area?
Answer: How about this for a simple proof? Let $A, B, C$ be the vertices of the triangle on a circle.
Fix a side, say $AB$, and then we see that the area is maximised by having $AC = BC$ (the base is fixed, height would be maximised if $C$ is on the perpendicular bisector and at the farthest point).
As we can choose any side for the base and the other two sides must equal for maximum area, unless the triangle is equilateral we can always find a better triangle...
Comment: This is a good argument but is this an entirely rigorous proof that the equilateral triangle has maximum area? We can consider a sequence of areas of triangles undergoing these symmetrizing transformations, $S_k$, and we can say that this sequence is monotonically growing and it is bounded (less than the circle area). So it has a limit (the Weierstrass theorem of calculus). But how do we prove that this limit is equal to the area of equilateral triangle?
Comment: @MaximUmansky the answer given implies if there is a maximum, it has to be reached when the triangle is equilateral.  That there is such a maximum is stated in the problem statement, so this suffices.  $$ $$ Of course, if we had to also show that there exists such a maximum, there would be more work to do.
Answer: Suppose a triangle with vertices $A,B,C$ lie inside a circle whose area is maximaum among all the triangles. Without loss of generality assume $A,B,C$ lie on the circle. Suppose $ABC$ is not equilateral. Then there exist a vertex (say $A$) such that the straight line passing through $A$ and parallel to $BC$ cuts the circle at point $E$ different from $A$. Choose a point $P$ on the line $AE$ which is different from $A$ and $E$. Then the triangle $BPC$ has same area as $ABC$. Suppose now extended $BP$ meets the circle at $F$. Then we have got a triangle, namely $BCF$, whose area is strictly larger than $ABC$ and this is a contradiction.
Answer: Suppose we an angle $\;\theta\;$  of the triangle $\;\Delta ABC\;$ with sides $\;a,b,c\;$ and respective opposite angles $\;\alpha,\beta,\gamma\;$ and inscribed in a circle of radius $\;r\;$ . The sinus law tells us that
$$\frac a{\sin\alpha}=\frac b{\sin\beta}=\frac c{\sin\gamma}=2r$$
If we now use the area formula
$$S(r,\alpha,\beta):=S_{\Delta ABC}=\frac12ab\sin\gamma=\frac12(2r\sin\alpha)(2r\sin\beta)\sin\gamma=$$
$$=2r^2\sin\alpha\sin\beta\sin(\alpha+\beta)$$
$$\begin{align*}\text{I}\;\;S'_r&=4r\sin\alpha\sin\beta\sin(\alpha+\beta)\stackrel ?=0\\
\text{II}\;\;S'_\alpha&=2r^2\sin\beta\underbrace{\left[\cos\alpha\sin(\alpha+\beta)+\sin\alpha\cos(\alpha+\beta)\right]}_{\sin(2\alpha+\beta)}\stackrel ?=0\\
\text{III}\;\;S'_\beta&=2r^2\sin\alpha\underbrace{\left[\cos\beta\sin(\alpha+\beta)+\sin\beta\cos(\alpha+\beta)\right]}_{\sin(\alpha+2\beta)}\stackrel ?=0\end{align*}$$
Since we can assume $\;r,\sin\alpha,\sin\beta\neq 0\;,\;\;0<\alpha\,,\,\beta <\pi\;$ (why?) , we get
$$\begin{align*}\text{II}\implies&\sin(2\alpha+\beta)=0\iff 2\alpha+\beta=\pi\\
\text{III}\implies&\sin(\alpha+2\beta)=0\iff\alpha+2\beta=\pi\end{align*}$$
Solving the above easy linear system we get
$$3\beta=\pi\implies \beta=\frac\pi3$$
and etc....

Maximal area of a triangle


Can Drupal built-in search or Apache Solr find comments on the site made with Disqus?

Question: I'm evaluating comment systems and although I see disqus used in many cases I'm not sure if it is the best choice for me as I am uncertain that my site's own search system could show comments in search results.
Can Drupal built-in search or Apache Solr find comments on the site made with Disqus ?
Research I have shown so far is that Disqus has Search Engine Optimisation (SEO) -- for external search engines e.g. Google:-

http://wordpress.org/plugins/disqus-comment-system/
http://www.quora.com/Do-search-engines-index-Disqus-content

But what about your own search system on your site, or using Solr for example. I'd prefer not to use Custom Google Search to search my site as I want control over how my results are shown.
So I'm looking for 2 answers for searching Disqus comments: 1) for the basic built-in Drupal search and 2) for SOLR.
Thank you.
Comment: Yea, I meant Disqus generally. I disliked the idea of my comments way outside my control and gave it up pretty quickly. Thus I can't help you much here beside sharing what little I know (and even that in form of a question as I'm not 100% sure).
Comment: As far as I know, Disqus comments are downloaded and rendered using javascript, aren't they? If so, they are never on the server hosting your site, and no server-side tool will know about them.
Comment: Thanks Mołot - what about the Disqus APIs? Is there a means to access the comment content via this? My initial search results indicated that this feature is not available, but if you know this possible I'd be pleased to know (and the references) but I'll try to keep digging.
Comment: Never managed to find it, but I used it just once, on my test site, and it's not like I particularly cared, so maybe there is.
Comment: Thanks again Mołot - when you say "it" - you mean disqus generally (not an API to searching the content)? Once I've worked out that it's not possible with Disqus I can justify (to the client) that this is a dead-end and move onto something else, like Drupal's own system (and theme it or extend it) - as I would be able to include this in searches. I'll continue to look into it, thanks for your inputs :)
Comment: +1 for "I disliked the idea of my comments way outside my control". And no problem! Thanks for the info that you can help with, it has been useful. I will try to follow up later with a definitive answer about searching Disqus comments.
Answer: Looks like it may be possible on the server side via the Disqus API PHP wrapper - I widened my answer outside of Drupal to get more input: https://webmasters.stackexchange.com/a/52159/3738
Though I still have concerns about not fully controlling the comment data and if the API changes. I'd have to see real benefits for our situation for Disqus to be able to outweigh these potential issues. Another issue is that of usability (UX/User Experience): having already logged in to the Drupal site, the user has to log in yet again to use disqus, unless the well supported Facebook login to the Drupal site can be "carried" into the Disqus login automatically. Though some user testing has revealed some would prefer the Disqus approach to be simpler.


How convert string array with hexadecimal values to array of digit numbers in Python?

Question: I have the array:
array_h = "'0x5a','0x20','0x29','0x1','0x1','0x59eb5e8e'"

I need to convert it to this:
array_i = [41, 15 ,41, 1, 1, 1508444575]

How can I do it in Python?
Comment: link another question them, pls
Comment: Please see: [How do I avoid misusing tags?](https://meta.stackoverflow.com/questions/354427/how-do-i-avoid-misusing-tags)
Comment: I understand now
Answer: iteratively convert each hexstring to integer:
array_i = []
for eachHexString in array_h:
    array_i.append(int(eachHexString, 16))

Comment: i try and the out : invalid literal for int() with base 16: 'x'
Comment: i resolve with split first in the array str for remove ',' and after this work it
before : array_t = array_h.split(',')


Detectar navegador e redirecionar o usuário

Question: Estou com um problema de animações no Safari e gostaria de saber como restringir o uso do Safari de todas as versões sem ter que listar uma por uma, por exemplo se eu fosse redirecionar uma versão do Internet Explorer seria:


How can I study the convergence of the improper integral $\int_{2}^{\infty} \frac{\arctan(x+1)+x}{2^x+3^x}\, \mathrm dx$?

Question: I need to study the convergence of the following improper integral:
$$\int_{2}^{\infty} \dfrac{\arctan(x+1)+x}{2^x+3^x}\, \mathrm dx$$
I did the following:
$$ -\dfrac{\pi}{2} < \arctan(x+1)  < \dfrac{\pi}{2}   \\
\implies -\dfrac{\pi}{2} + x < \arctan(x+1) +x < \dfrac{\pi}{2} +x   \\
\implies   \dfrac{-\dfrac{\pi}{2} + x}{2^x+3^x} <  \dfrac{\arctan(x+1) +x}{2^x+3^x}  < \dfrac{\dfrac{\pi}{2} + x}{2^x+3^x}   \\
$$
I planned to integrate the inequality and then using the comparison criterion to proof its convergence. However, the idea did not work for me.
Comment: $\arctan$ is globally bounded and since $$\int_2^\infty \frac1{2^x+3^x}<\infty,$$ you only need to look at $$\int_2^\infty\frac{x}{2^x+3^x}$$
Comment: @MaximilianJanisch you should submit that as an answer!
Answer: Just observe that RHS is less than $$\frac{\frac{\pi}{2}+x}{3^x}$$Since $$\int_2^\infty\frac{1}{3^x} \,dx$$clearly converges, it is enough to show that$$\int_2^\infty\frac{x}{3^x} \,dx$$ converges which can be done using limit comparison test (with $g(x)=\frac{1}{e^x}$).
Answer: The function $x\mapsto \lvert\arctan(x+1)\rvert$ is globally bounded by $\frac\pi2$ so your integral is bounded in absolute value by $$\int_0^\infty \frac{\frac\pi2+x}{2^x+3^x}\,\mathrm dx<\infty.$$
Note that the last integral is finite because $$\int_0^\infty \frac{P(x)}{b^x}\,\mathrm dx$$ is finite for all polynomials $P$ and numbers $b>1$. This can be proven for example by noting that $$b^x\geq 1+C x^{\mathrm{deg}(P)},$$ where $C=\frac{\ln(b)^{n+2}}{(n+2)!}$ and $\mathrm {deg}(P)$ is the degree of the polynomial $P$.
Answer: You have a polynomial function over an exponential one.  This dies fast enough at $\infty$ to integrate there.
Comment: $x$ is not bounded :)


ISLR book ridge/lasso regression cross-validation

Question: I work with the book 'Introduction to statistical learning with R', link. I got a question about the cross-validation for ridge and lasso regressions (ellipsis indicate that part of the original code was omitted for brevity. The code can be found here).
x=model.matrix(Salary~.,Hitters)[,-1]
y=Hitters$Salary

# Ridge Regression

library(glmnet)
grid=10^seq(10,-2,length=100)
ridge.mod=glmnet(x,y,alpha=0,lambda=grid)
...

set.seed(1)
train=sample(1:nrow(x), nrow(x)/2)
test=(-train)
y.test=y[test]
...

set.seed(1)
cv.out=cv.glmnet(x[train,],y[train],alpha=0)

My question is: what is the reason for applying the cross-validation to the train subset of the original data? Doesn't it already include splitting data into the training and test sets? In Chapter 5 Lab the cross-validation is performed on the entire data set.
EDIT. Let me rephrase the question: why would you use the cross-validation on the train subset in the example above as opposed to using it on the entire set like this:
cv.out=cv.glmnet(x,y,alpha=0)

What are the advantage of subsetting if the aim is finding the best model fit?
Comment: I believe you are using CV in this context to select appropriate parameters for glmnet.  So you would do that on the training data first, but then once you've picked an appropriate parameter, you'd fit glmnet using that parameter, and then use the hold out sample (the test data) to see how the mode performs.
Comment: To repeat @michaeloberst, glmnet is using k fold cross validation on the training data to find the best regularisation parameter by minimising "validation set" error. To then get an unbiased estimate of generalisation you need a hold out set,  the test set,  or you can use nested cross validation on the whole data set,  splitting the data repeatedly into test and "train/validation" ,  then splitting train data repeatedly into train and validation
Answer: In a single sentence: in order to evaluate your final model on truly unseen data.
Deeper explanation
One big reason to only use your training data while trying different models is to leave some portion of your data totally untouched and unexplored to validate your results on. This way, you can evaluate your final model on completely unseen data.
While the point of cross-validation is to have a better method of evaluating your model than a single train/test split, if you're using cross-validated model training on your full dataset then there technically isn't any truly unseen data by the end, and you might make decisions about which model to go with based on noise in the data that you slowly fit to over the course of many model iterations.
Conclusion
I haven't seen research on this question exactly, so it might not actually be an issue. It's not the worst thing to use your whole dataset in your training if you're using cross-validation, but there may be small changes of not generalizing well to new data—I personally try to leave out a test set that I don't look at until I have my final model. I'd love to see research on the answer.
Note: This answer also discusses this question: Do we need a test set when using k-fold cross-validation?


Prove by induction for the sum of $\sum_{k=1}^{2n-1} (-1)^{k-1}(k-1)(k+1) = 2n^2 - n - 1$

Question: I'm trying to prove following equation with induction:
$$
\sum_{k=1}^{2n-1}  (-1)^{k-1}(k-1)(k+1) = 2n^2 - n - 1
\\~~\\
$$
First step is the base case, which for $ n = 1$ is true.
$$
(-1)^{0}(0)(2) = 0 = 2(1)^2-1-1
$$
Then we can assume that the equation is true for $n$, therefore we want to prove that it's also the case for $n+1$
$$
\sum_{k=1}^{2(n+1)-1}  (-1)^{k-1}(k-1)(k+1) = \\ (\sum_{k=1}^{2n-1} (-1)^{k-1}(k-1)(k+1) ) + (-1)^{2(n+1)-1}(2(n+1)-2)(2(n+1))
$$
That means for the right side of the equation:
$$
2n^2-n-1 + (-1)^{2(n+1)-1}(2(n+1)-2)(2(n+1))
$$
Removing the brackets results in:
$$
2n^2-n-1+(-1)^{2n}(2n)(2n+2) = \\~\\2n^2-n-1+(-1)^{2n}(4n^2+4n)
$$
I'm not sure if I am allowed to make an assumption, but I did:
$$
\forall n \epsilon \mathbb{N} :(-1)^{2n} = 1
$$
Since it's equivalent to:
$$
((-1)^n)^2 =  ((-1)^2)^n
$$
By replacing it with $1$, the last step is summing it up:
$$
6n^2+3n-1
$$
Which is wrong ... Am I allowed to make the assumption? And where did I make the mistake? (Hint preferred)
Comment: What do you mean by "$\sum_{k=1}^{2n-1}=(-1)^{k-1}(k-1)(k+1)$"? I have doubts as to whether you understand the summation notation...
Comment: Oops, sorry, didn't mean to put the equal sign there ^^
Answer: When you substitute $n+1$ into the upper limit of summation (above the $\sum$ symbol), you get there $2(n+1)-1$. But you should simplify this expression: $2(n+1)-1=2n+1$.
Now, this sum ranges from $k=1$ up to $k=2n+1$. You did exactly the right thing by extracting the sum that goes from $k=1$ up to $k=2n-1$. But how many more terms are there, after $k=2n-1$? Hint: more that one.
Answer: First of all, correct notations is
$$\sum_{k=1}^{2n-1}(-1)^{k-1}(k-1)(k+1) = 2n^2 - n - 1$$
Then, what you did in the base case is correct. After that, if we suppose $n \ge 2$ and argument holds for all $n$, for $n+1$ we have
$$\sum_{k=1}^{2(n+1)-1}(-1)^{k-1}(k-1)(k+1)$$
Notice that we can write this sum as $\sum_{k=1}^{2n-1}(-1)^{k-1}(k-1)(k+1) + $ [the expression for $k = 2n$] $+$[the expression for $k = 2n+1$], which yields:
$$= \sum_{k=1}^{2n-1}(-1)^{k-1}(k-1)(k+1)+(-1)^{2n-1}(2n-1)(2n+1)+(-1)^{2n}(2n)(2n+2)$$
$$= 2n^2-n-1-(4n^2-1)+(4n^2+4n)$$
$$= 2n^2+3n$$
$$ = 2(n+1)^2-(n+1)-1$$
Answer: $$[(k+1)^2-1]-[k^2-1]=2k+1$$
For the rest you can just telescope.


What's an invariant metric of $(\mathbb{C}^*,\cdot)$?

Question: The Birkhoff–Kakutani theorem gives the necessary and sufficient conditions for a topological group $(G,\cdot)$ to be metrizable. It gives a construction of a metric $d$ on $G$, and proves that it is also left invariant, in the sense that $d(x,y)=d(g\cdot x,g\cdot y)$ for all $g,x,y\in G$.
In particular, it implies that there exists a metric $d$ on $\mathbb{C}^*$ such that it generates the same topology and $d(x,y)=d(zx,zy)$ for all $x,y,z\in\mathbb{C}^*$, but it doesn't give an explicit example.
How would such a metric look?
I tried doing this for $(\mathbb{R}_+,\cdot)$ by defining $d(x,y):=\left\vert\log(x)-\log(y)\right\vert$, and since the map $\log:\mathbb{R}_+\rightarrow\mathbb{R}$ is both a group isomorphism and a homeomorphism, it is quite clear that it would work. However, I'm not so sure the same trick would work here since $\log:\mathbb{C}^*\rightarrow\mathbb{C}$ has different branches and everything that arrises from $z\mapsto e^z$ not being injective in $\mathbb{C}$.
Does this work?
Thanks in advance to anyone who answers.
Answer: The group $\mathbb{C}^*$ is the direct product of the groups $\mathbb{R}_+$ and the group $S^1$ of complex numbers of absolute value $1$.  The Euclidean metric is already an invariant metric on $S^1$, so you can just combine it with your logarithmic metric on $\mathbb{R}_+$.  Explicitly, you can define a metric $d$ on $\mathbb{C}^*$ by $$d(ru,sv)=|\log(r)-\log(s)|+|u-v|$$ where $r,s\in\mathbb{R}_+$ and $|u|=|v|=1$.
Or, more directly along the lines you suggest, you can get an invariant metric by defining $d(z,w)=|\log(z)-\log(w)|$ where the right-hand side means the smallest possible value ranging over all possible logarithms of $z$ and $w$.  This amounts to taking the imaginary part of $\log(z)-\log(w)$ to be the arc length distance along the unit circle between $z/|z|$ and $w/|w|$.
Comment: No, I mean the Euclidean metric restricted from $\mathbb{C}$.  Of course the arc length metric would also work.
Comment: By "Euclidean metric on $S^1$", you mean the arc length metric right?
Comment: I don't know what I was thinking, of course the restriction of the Euclidean metric also works. Sorry about that.


What online resources should I use to learn harmony and musical analysis?

Question: I had some harmony courses and I want to learn some more about it.
Ideally, I am looking for is a KhanAcademy-like website about harmony and musical analysis. If that doesn't exist, where else should I go ?
Comment: Here's a [related question](http://music.stackexchange.com/q/623/120). It seems IMSLP has many freely available treatises on harmony.
Answer: Edward Sarath's Music Theory Through Improvisation is available online, thanks to google books. The subtitle of the book ("A New Approach to Musicianship Training") seems to address your situation directly. You may also find my posts about another book and about chord functions useful.
Answer: hmmm, big topics...
Ya seen http://www.dolmetsch.com/theoryintro.htm ?
also http://www.musicarrangers.com/star-theory/p01.htm  ( menu on the right...:/ )
and  http://www.songtrellis.com/
Answer: This site provides something Khan academy like: Dave Conservatoire.
Also, try searching for harmony treatises on IMSLP. They've got some good stuff like a short treatise on harmony by Peter Tchaikovsky.
Answer: Coursera has some courses about music including this one: How music works. You have to enroll and you can only follow the course when it starts. No date is announced yet.

About the Course
Designed as a course for all students, regardless of background, "How
  Music Works" is appropriate for anyone with a love of music and a
  curiosity about how it functions.  Prior experience with music is
  welcome but not required, and music reading ability is not needed in
  order to participate.  Topics covered include: rudiments of musical
  notation and analysis, psychoacoustics, meaning in music, and the
  interaction of the basic building blocks of sonic art such as rhythm,
  melody, and harmony.  Activities include examinations of musical
  examples from a variety of cultures and time periods, in-class music
  making, and readings that address the techniques of musical creation
  and the power and importance that music has in all human societies.


Cantor's theorem and countable additivity of Lebesgue measure

Question: In this book, with more than 300 pages, the author claims that Cantor was wrong:
Transfinity, Wolfgang Mückenheim
https://www.hs-augsburg.de/~mueckenh/Transfinity/Transfinity/pdf
In particular, the author lists in more than 100 pages authors that had concerns about Cantor's argument. He even cites Sharon Shelah who wrote

Of course, the most severe skeptics will even deny the mathematical
content of Cantor's theorem ($2^{\aleph_0} > \aleph_0$). To these we
have nothing to say at all, beyond a reasonable request that they
refrain from using the countable additivity of Lebesgue measure.

CARDINAL ARITHMETIC FOR SKEPTICS, Shelah
https://arxiv.org/pdf/math/9201251.pdf
Is there any chance that indeed Cantor's theory is inconsistent? In the paper above, Shelah refers to concerns about "consistency" in Cantor's theory - how far may these concerns eventually reach?
Comment: Shelah does not have concerns about the correctness of Cantor's theorem. The comment you quoted is about the people (like Mückenheim) who are unable or unwilling to understand Cantor's proof. Shelah says that he has nothing to say to  those people. If they don't understand even Cantor's quite easy proof, they certainly won't understand Shelah's far more advanced work.
Comment: The value of that book cannot be understated. There is nothing of substance there beyond the author's implicit conviction that mathematics must be relevant to the necessarily-finite physical universe, and the author frequently distorts the meaning of the people he quotes (I'm quoted there, for example, without my statements being remotely understood).
Comment: Shelah's comment is actually quite witty. I imagine its humour was lost on Muckenheim.
Comment: *you find a huge number of authors that also had concerns* --- To me this is a huge red flag that one might be reading crank literature. In this case, however, I know who Mückenheim is, and don't need to look for red flags. However, if I didn't know who he was, I would definitely be thinking "crank possibility" based on the huge number of author quotes.
Comment: You want us to list all the errors in a 300 page book!
Comment: @Tyma Gaidash: See [De Morgan's book](https://archive.org/details/budgetofparadoxe02demorich) (1800s cranks) ***AND*** [Dudley's book](https://www.amazon.com/dp/0883855070) ([a precursor paper](https://web.mst.edu/~lmhall/whattodowhentrisectorcomes.pdf) to Dudley's book) ***AND*** [Martin Gardner's **Fads and Fallacies**](https://www.amazon.com/dp/0486203948) ***AND*** [MSE *Spotting crankery*](https://math.stackexchange.com/q/157250/13130) ***AND*** [blog post *Ten Signs a Claimed Mathematical Breakthrough is Wrong*](https://scottaaronson.blog/?p=304) **(continued)**
Comment: ***AND*** [Academia SE *What is the best way to deal with cranks?*](https://academia.stackexchange.com/q/111413/49593) ***AND*** [MSE *Refuting the Anti-Cantor Cranks*](https://math.stackexchange.com/q/527248/13130). And you can easily google for more $\ldots$
Comment: @NoahSchweber . Dorothy Parker once wrote in a review "This is not a book to be taken up lightly. It should be hurled with great force."
Comment: Shelah is just an example. In the PDF above you find a huge number of authors that also had concerns about Cantor's arguments
Comment: @Angina Seng: That's what I was thinking also, since one is not going to accomplish much (unique to Lebesgue integration) without using countable additivity.
Comment: @DaveL.Renfro What is a crank and who is Muckenheim? I came across the name in a review post, but did not know about it.
Comment: @DaveL.Renfro Wow! Thanks for the large list of sources.
Answer: Well, the answer to the question "What is wrong in that book?" is "practically everything." Moreover, the mathematical errors (as opposed to situations where he misunderstands quoted arguments of others) are not at all original to Mückenheim, but rather are the general cranky arguments against the infinite in mathematics - with seemingly one exception, which may be instructive and which is the reason I'm writing this answer.
(To clarify: the prospects for inconsistency in various set theories is actually an interesting topic, but Mückenheim's book does not form a serious contribution to it. If you're interested, one relevant term is "consistency strength.")
First, let me briefly summarize what's not original. The bulk of Mückenheim's book is a reiteration of the standard arguments-from-incredulity, that set theory displays "bad" features and is therefore clearly inconsistent (although Mückenheim either misunderstands or deliberately misuses the technical term "inconsistent" - he conflates formal inconsistency and inconsistency with physical reality). For example, there is the "paradox" of the banker who at day $n\in\mathbb{N}$ gains $10$ dollars but spends $1$ dollar, and yet winds up "at the end of the day" completely broke based on which dollars they chose to spend. The "paradoxes" of this general flavor are completely resolved once we uncover the implicit assumptions that the relevant set-theoretic operations are well-defined and continuous in the appropriate senses, which they aren't; basically, the justification for the arguments against these situations boils down to trying to lift results about finite sets to infinite sets without justifying their continued validity.
The following error, however, does seem original to Mückenheim. (See here if you can view deleted posts.) Consider two different set-theoretic implementations of the natural numbers: as the von Neumann numerals $$0_V=\{\}, 1_V=\{\{\}\}, 2_V=\{\{\}, \{\{\}\}\}, 3_V=\{\{\}, \{\{\}\}, \{\{\}, \{\{\}\}\}\}, ..., (i+1)_V=i\cup\{i_V\}, ...$$ versus the Zermelo numerals $$0_Z=\{\}, 1_Z=\{\{\}\}, 2_Z=\{\{\{\}\}\}, 3_Z=\{\{\{\{\}\}\}\}, ..., (i+1)_Z=\{i_Z\}, ...$$ Now take an appropriate "set-theoretic limit of the natural numbers" in each sense: we have $$\limsup_{i\in\mathbb{N}}i_V=\{i_V: i\in\mathbb{N}\}\not=\emptyset$$ but $$\limsup_{i\in\mathbb{N}}i_Z=\emptyset.$$ Aha! says Mückenheim, we have here a contradiction. Well, no, we don't - what we have is two different implementations which behave differently with respect to a set-theoretic operation. But that set-theoretic operation is not meaningful at the level of the structure being implemented itself! This is basically the same error as looking at two programs which compute the same function and being confused about how one is longer than the other: "the length of the program" is not a property of a bare function.
So this mistake reveals the need to distinguish between the thing being implemented and the choice of implementation, and more importantly between operations/relations defined on the level of the thing being implemented vs. the implementation framework.  There are indeed interesting things to say about this (the relevant logical term is "interpretation") ... but Mückenheim doesn't. However, since this does appear to be an original confusion and is vaguely related to something interesting it seems worth mentioning.
Comment: Here's a possible analogy to the argument you discuss in the second half of your answer. Let $x$ be a real number that has a terminating decimal expansion, and thus $x$ has both a terminating decimal expansion and a non-terminating decimal expansion (e.g. $2.43000\ldots \;= \; 2.42999\ldots).$ Define $x_T(n)$ be the $n$'th digit to the right of the decimal point of the terminating expansion of $x,$ and let $x_N(n)$ be the $n$'th digit to the right of the decimal point of the non-terminating expansion of $x.$ **(continued)**
Comment: Then $\lim_{n \rightarrow \infty} x_T(n) = 0$ and $\lim_{n \rightarrow \infty} x_N(n) = 9.$ So decimal expansions involve a contradiction, and thus cannot exist.
Comment: @DanielS. Crap, that was a really nasty typo! I meant to say "totally implementation-**independent.**" My apologies, that was about the most misleading typo I could have made. "The $n$-th decimal digit of $r$ is ambiguous, as pointed by Dave above, right?" Only if you define it wrong - we can specify the "right" decimal expansion as the one which doesn't eventually consist only of $9$s (and we can do this purely algebraically - no reference to implementation here).
Comment: Re: non-originality of errors, I can't help but mention this famous passage: ["This paper, whose intent is stated in its title, gives wrong solutions to trivial problems. The basic error, however, is not new."](https://mathscinet.ams.org/mathscinet-getitem?mr=39515)
Comment: Different representations impact implementation but not the thing being implemented.  However, can we build an argument similar to Cantor's diagonal that is representation independent? Is the Cantor's diagonal argument representation independent?
Comment: @NoahSchweber if Cantor argument is implementation-dependent, isn't it a weakness of the argument?  The $n$-th decimal digit of $r$ is ambiguous, as pointed by Dave above, right?


How to normalize multiple values

Question: I have three values, two of them are from $0 - 144$ and one is from $0 - 24$. I want to normalize these values and end up with a value from $0 - 1$ or $0 - 100$. I wanted to know if I can use the following equation to do this? And if so, how to go about it.
$$
z_i=\frac{x_i-\min(x)}{\max(x)-\min(x)}
$$
where $x=(x_1,...,x_n)$ and $z_i$ is now your $i^{th}$ normalized data.
Applying this to my example, if I have three values to get an overall number from $0-1$ or $0-100$ do I have to do put each value individually though this equation and then add them or can I add the values together and use this as the max and do it this way? Also for min wouldn't this always be zero ?
Answer: If you want to scale your values with range $[\min,\max]$ to the new range $[a, b]$ the formula is:
$$
z_{i} = \frac{(b - a)(x_{i} - \min(x))}{\max(x) - \min(x)} + a
$$
Apply this formula for each of your original values. Here is an example: Say you have three values $x_1, x_2, x_3$. The first two values have a range of $[0, 144]$ and the third has a range of $[0, 24]$. You want to transform all three to have a new range of $[0, 100]$. Let's say your values are: $x_1 = 133.43, x_2 = 51.65, x_3 = 6.91$. The corresponding transformations are thus:
\begin{align}
z_1 &= \frac{(100 - 0)(133.43 - 0)}{144 - 0} + 0 = 92.66 \\
z_2 &= \frac{(100 - 0)(51.65 - 0)}{144 - 0} + 0 = 35.87 \\
z_3 &= \frac{(100 - 0)(6.91 - 0)}{24 - 0} + 0 = 28.79 \\
\end{align}
Comment: Thank you for your answer. To clarify, this has scaled the values to the data set I have correct. Also this is a bit of a different question, but if I add the three values outputted and put it over the total (eg. 144+144+24) would this represent the percentage of these values over the dataset or is it just an arbitrary number?
Comment: @dmnte Yes, this has rescaled the three values. About the second question: I don't think adding them is useful in this context.

How to normalize multiple values


On the splitting field of $f(X)$, when $\deg f =2$

Question: Let $F$ be a field, $f(X)\in F[X]$ with $\deg f=2$ and $E$ is its splitting field.
We want to show that there are no proper intermediate fields in the extension $E/F$.
My thought. We know that $f$ has at most $2$ roots in its splitting field. Let $\alpha,\beta$ be its roots. Then, is is $E=F(\alpha,\beta)$. So, we have the  Tower of Fields
$F \leq F(\alpha)\leq F(\alpha,\beta)=E$. So, from the Tower Law,
$$[F(\alpha,\beta):F]=[F(\alpha)(\beta):F(\alpha)][F(\alpha):F].$$
Since $f(\alpha)=0_F$, we have
$$m_{(\alpha,F)}(X)|f(X) \implies \deg m_{(\alpha,F)} \leq \deg f \iff [F(\alpha):F]\leq 2.$$
Now, consider the extension $F \leq F(\alpha)$. Then, we have $m_{(\beta,F(\alpha))}|m_{(\beta,F)}$.
But like before, since $f(\beta)=0_F$, we have
$m_{(\beta,F)}(X)|f(X) $. So,
$$\deg m_{(\beta,F(\alpha))} \leq \deg m_{(\beta,F)} \leq \deg f \implies [F(\alpha,\beta):F(\alpha)]\leq 2.$$
Therefore, $[E:F]\in \{1,2,3,4\}$. If it is $1$, trivially our claim holds and if $[E:F]\in \{2,3\}$, since $2,3$ are prime, there are no proper intermediate fields in $E/F$. So, we take the case that $[E:F]=4$. By above the only possible case is  to consider $[F(\alpha)(\beta):F(\alpha)]=[F(\alpha):F]=2$
But how can we continue from that? Is this proof right/in the correct direction?
Thank you.
Comment: Doesn't this immediately follow from the fact that for each intermediate $L$, we have $[E:F]=[E:L][L:F]$ and $[E:F]=2$?
Comment: Thank you for your comment. Why $[F(\alpha, \beta) :F] =2$?
Comment: Yes sorry. We have $[E:F]=2$ if $f$ is irreducible and $1$ otherwise.
Answer: It seems like the easier approach is to note that if $x^2-ax+b=(x - \alpha)(x - \beta)$, then $a=\alpha+\beta$ (and $b=\alpha \beta$) so $a \in F \subseteq F[\alpha]$ and $\alpha \in F[\alpha] \Rightarrow \beta = a - \alpha \in F[\alpha]$ and $E=F[\alpha]$.
Comment: @Chris If $K\subseteq F\subseteq E$ is a tower of extensions, then $[E:K]=[E:F]\cdot [F:K]$. So we have a factorization of $[E:K]$. If $[E:K]$ is a prime number...
Comment: Thank you for your answer. So, $F(\beta)\subseteq F(\alpha)$. But how do we conclude that there are no intermediate fields from this claim? Is that
  because $[F(\alpha):F]\leq 2$?
Comment: Got it. If $[F(\alpha):F]=1\iff F(\alpha)=F$ and if $[F(\alpha):F]=2$, since it is a prime, there are no proper intermediate fields. Right?


Ajuda em javascript

Question: Como faço para esse script executar em 10 segundos ??

A ideia seria colocar um countdown nele, alguém sabe ?
Comment: @CaioFelipePereira Isso faria ele executar imediatamente, só o resultado (`undefined`) seria passado pro `setTimeout`. Melhor seria `setTimeout(function() { simulateClick(1176,435); }, 10000);`
Comment: `setTimeout(simulateClick(1176,435), 10000);`
Comment: @mgibsonbr verdade, isso que da escrever na pressa. Escreve uma resposta aí pra ganhar pontos de internet ;)
Comment: @mgibsonbr funcionou perfeito, valeu
Comment: @CaioFelipePereira Blz, fiz isso. E ainda aprendi uma coisa nova rsrs (não sabia que o `setTimeout` aceitava argumentos adicionais - nos *browsers* recentes pelo menos)
Answer: A função setTimeout pode ser usada para invocar uma função após X milissegundos:
var timeoutID = setTimeout(simulateClick, 10000, 1176, 435);

O primeiro parâmetro é a função que será chamada, o segundo o número de milissegundos a esperar (10s = 10000ms). Os parâmetros adicionais são passados diretamente à função, ou seja, é quase o mesmo que fazer:
setTimeout(function() { simulateClick(1176,435); }, 10000);

(Nota: caso você queira dar suporte ao IE9 ou anterior use sempre esse segundo formato, pois o primeiro não é suportado)
O valor de retorno pode ser ignorado, se você não precisar dele. Ele é usado caso se queira cancelar a chamada da função antes que ela ocorra, via clearTimeout(timeoutID).

Ajuda em javascript


Arranging tab menus created by views module

Question: I've created 3 different view and added them to a tab menu.
now these 3 menu items are sorted alphabetically and the default tab menu is printed as middle item .
I wanted to sort them using menus but tab items doesn't exist there .

How can I reorder tab items created by views module?
Answer: You can provide a weight while editing the Views tab:
. Higher weights will be moved to the back of the order. But since you cannot see the weights of the other tabs this can take quite a while to get right.
Better is to have a look at Tab Tamer

Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.
Comment: totally forgot tab tamer ..
Comment: after these many years of this answer, it helped me to save me my time. changing the weight works for me...  Thank You :)
Answer: You can adjust the weight in hook_menu_local_tasks_alter:
<code>/**
* Implements hook_menu_local_tasks_alter()
*
* @param $data
* @param $router_item
* @param $root_path
*/
function HOOK_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'admin/content') {
    // You add #weight here on item level not link level
    $data['tabs'][0]['output'][0]['#weight'] = '1000';
  }
}
</code>
For more code you can also look here: Altering menu local task title
Comment: isn't there any solution without coding? anyway thanks for help
Answer: I know that this is 2 years ago, but this will help somebody looking for similar problem.
here you can see full code for creating menu tabs with weight. (just put weight in $items array under key)
<code>$items['processing'] = array(
    //'title' => t('Create Menu Tab'),
    'access callback' => TRUE,
    'access arguments' => array('dn_release'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_release_form'),
  );

  $items['processing/order/release'] = array(
    'title' => 'Release orders',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'access arguments' => array('dn_release'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_release_form'),
    'weight' => 1,
  );

  $items['processing/order/labels'] = array(
    'title' => 'Print labels',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('dn_wawi'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_generate_tracking_form'),
    'weight' => 2,
  );
</code>


Using the "call" function without evaluating it

Question: I am trying to add a call entry to the object cb.fit.
cb.fit = CoxBoost(
    time=clin.mut$SurvMetastasis_Time,
    status=clin.mut$SurvMetastasis_Event,
    x=as.matrix(clin.mut[,-c(1,4,5)]),
    stepno=1000,
    penalty=100
)

cb.fit$call = call(
    "CoxBoost",
    time=clin.mut$SurvMetastasis_Time,
    status=clin.mut$SurvMetastasis_Event,
    x=as.matrix(clin.mut[ ,-c(1,4,5)]),
    stepno=1000,
    penalty=100
)

though
> class(cb.fit$call)
[1] "call"
> names(cb.fit$call)
[1] ""        "time"    "status"  "x"       "stepno"  "penalty"

cb.fit$call is actually computed values, not an expression.
What did I do wrong?

I do not see anything wrong, but if I call the method, then I get true long list values.
I define a generic function and method with
  predictSurvProb = function (x, ...) {
                      UseMethod("predictSurvProb", x)
                      }
  predictSurvProb.iCoxBoost = function(x) predict(x, newdata=clin.mut[ ,2:500], type="logplink")

> a = call("predictSurvProb", cb.fit)
> class(predictSurvProb)
[1] "function"
> a = call("predictSurvProb", cb.fit)
> class(cb.fit)
[1] "iCoxBoost" "CoxBoost"
> class(a)
[1] "call"
> a[[1]]
predictSurvProb
> class(a[[2]])
[1] "iCoxBoost" "CoxBoost"
> names(a[[2]])
 [1] "time"             "status"           "stepno"           "penalty"
 [5] "xnames"           "n"                "p"                "event.times"
 [9] "coefficients"     "linear.predictor" "meanx"            "sdx"
[13] "standardize"      "Lambda"           "scoremat"         "logplik"
[17] "call"             "formula"          "terms"            "cause"
> a[[2]]$time
 [1]  146   40  242   69 2749  627  422 2274 2668   67 1695 1554 1839 1699  391
[16]  981   69 1279 1461 1328 1211 1223 1063   34  362 1082  204  765   67  480
[31]  236  301   90 8747  687 5897  366 1558  247 3817 1533 4104  125 1566 3884
[46] 3915   70   48  223 3903 3655   43 3729 3736 2306 3677 1615 3628 3518 3479
[61] 1000 3228   28

and so on. All entries in the call object, has actual values.
Comment: Can you show the code where you actually add the call to cb.fit?
Comment: It is in the original post, but the code is formatted in strange way.

cb.fit$call = call("CoxBoost", time=clin.mut$SurvMetastasis_Time, status=clin.mut$SurvMetastasis_Event, x=as.matrix(clin.mut[ ,-c(1,4,5)]), stepno=1000, penalty=100)
Comment: "the code is formatted in a strange way". You formatted it. Take a look at  https://stackoverflow.com/help/formatting
Comment: It's unclear what you are trying to achieve.
Comment: cb.fit is "CoxBoost" object.
I am trying to use it as input to pec function in pec package. In order to do so, I need to add an entry "call".
But the call I added is not expression, but actual long list of numbers.

for instance,
a=10.1
call("round", a)
should be round(10.1)
but in my case, some how it is computed, and gives 10
Answer:
cb.fit$call is actually computed values, not an expression.

No, it isn't. It's the unevaluated call expression, as your class(cb.fit$call) shows. The names you show are the argument name of the function call expression.
To use your simplified round example:
〉 a = 10.1
〉 (x = call("round", a))
round(10.1)
〉 eval(x)
[1] 10

— Nothing is evaluated until you actually force evaluation.
… that is, unless you have somewhere overwritten the call function in another part of your code. Verify that call actually resolves to its original definition, i.e.
function(name, ...) .Primitive("call")

Comment: @Haiying Don't give analogs then, give *actual* examples. And make them as simple as possible. As it stands, it's **impossible** to know what you are talking about.
Comment: I am saying with analog. Of course, if I run
> call("round", 10.1)
round(10.1)
I am saying that in the more complicated function, I am actually getting 10 as output if I analog to this case.
Answer: You can use the function match.call within a function to return the exact call that was used to call that function.
So calling match.call() within the function someFun(a = b + c, 1234) will return a call object with that exact content.
You can use this to create a wrapper around the function you want, and return the call along with the actual output of the function:
addCall <- function(fun, ...){
  call <- match.call()[-1]

  return(list(call = call, result = fun(...)))
}

Which results in the following:
> addCall(sum, 1:5)
$call
sum(1:5)

$result
[1] 15

> addCall(sum, 1 + 2 + 3 + 4 + 5)
$call
sum(1 + 2 + 3 + 4 + 5)

$result
[1] 15

The match.call()[-1] takes the call, and removes the first element. So it would be addCall(sum, 1 + 2 + 3 + 4 + 5), but if you are only interested in the exact call used to fun, the [-1] removes the first element (addCall), and the second element (fun) takes its place.
Comment: I could not fully understand your code. But could you please take a look at my code. I do not see anything wrong, but if I call the method, then I get true long list values.
Comment: The difference is that you construct the call like this `call(function, arguments)`, which evaluates arguments before creating the call, while I do it within the function itself using `match.call`, which creates a call object without evaluating the arguments.


Testing if a proportion is different between groups

Question: I have data on the status of a treatment in approx 800 hospitals. For example:
Hosp    N   Given   C.I Refuse  Age.Group
1       5      3     0    0      A
1       11     5     1    1      B
1       21     15    2    1      C
1       32     24    1    1      D
1       111    70    3    1      E
2       10     7     1    0      A
2       25     12    2    0      B

etc. Please note these data are made up.
Each row represents one of 5 age group within a hospital. N is the number of patients with a particular condition. Given is the number of patients, out of N, receiving the treatment, C.I. is the number of patients, out of N, who were contraindicated for the treatment, and Refuse is the number of patients, out of N, who refused the treatment
I need to test whether these proportions are different between the age groups
Given / N
C.I / N
Refuse / N
Is it appropriate to do a binomial regression for each ratio, with Age.Group as the explanatory variable ?
What alternative ways are there to do this ?
Answer: Is your question materially focussed on the hospital element? Or are you really interested in the age group element, and it just so happens that the hospitals are providing a sampling framework?
[EDIT: after writing this answer, I just saw the comment by whuber about "Grouping hospitals is tantamount to an assumption of homogeneity that ought to be checked." which is what I'm suggesting you address here.]
If the latter is the case, then you might consider taking an approach that is based around having clustered data, wherein the results from individual clusters (hospitals) are then combined to come up with an "overall" pattern of results.
Before I waffle on about clustering, given the huge number of hospitals you have these following methods may not majorly influence the results obtained compared to ignoring hospital (pooling results across all hospitals by age group, and then analysing as though all from a single sample.) This approach would in part depend on the relative sizes of the different hospitals (e.g. if there is a hospital serving a massive population that has quite different practices to other hospitals, then this hospital will dominate the results obtained).
Conceptually you could think of this as being a meta-analysis of the age -> treatment relationship, where each hospital is treated as a unique "study".
In practice, one could:

run some kind of multilevel model for this,
use tools designed for analysing clustered survey data (and specifying hospital as a cluster unit, with the regression model then looking at the age -> treatment decision relationship,)
calculate summary statistics within each cluster (hospital) -- for example, odds ratios between age groups -- and then use the mean and standard deviation of these odds ratios across all 800 hospitals to construct a confidence interval for the odds ratios. One could similarly calculate proportions per age group per hospital, then use similar methods to get some descriptive statistics around the proportions.

The following link (from Martin Bland) talks about randomised controlled trials, but most of the principles still apply to observational data:
http://www-users.york.ac.uk/~mb55/talks/clusml.htm
Two outstanding points: You'll probably still run into problems with zero-counts or sparse cells in each hospital/age-group combination if your actual data look like the example (you will have odds ratios comparing groups on a per-hospital basis that are zero or infinity). There is also a second issue around treating the given/contraindicated/refused as independent outcomes -- I might have to pass on addressing this part for the moment.
Comment: Thank you. This is helpful. I am interested primarily in the age group element, but please note that for each hospital-age group combination, I only have aggregated data.
Comment: Data aggregated as per your example (i.e. summarised for each age group at each hospital) is all you need for this analysis. If you're doing a summary-statistics analysis, then you can do it directly off that original data (e.g. proportion given treatment in Age Group A in Hospital 1 is 3/5 = 0.6, for same Age Group in Hospital 2 is 7/10 = 0.7.)
Comment: Note that depending on your stats package, if you want to take a regression-like model approach (survey approach or multi-level analysis), you may need to make line listed data (e.g. create 10 lines for Hospital 1 with a binary variable called TREATMENT, 6 of which have a 1 and 4 given a zero, and an indicator variable for HOSPITAL.) This is relatively simple to do, programmatically speaking (e.g. in R, SAS, Stata.)


replace column in data frame with elements from another column - python

Question: df = pd.DataFrame({'c1':['g1','g1','g1','g2','g2','g2'], 'c2':['x','y','z','x','y','z'], 'v':[72,44,13,53,97,32]})

Is there a way to transform df in a way that v is replaced by the values g1 and g2 from column c1?
This is the output I'm trying to achieve:
    c2   g1   g2
0   x    72   53
1   y    44   97
2   z    13   32

Answer: use pivot_table() for that:
In [58]: df.pivot_table(index='c2', columns='c1', values='v').reset_index()
Out[58]:
c1 c2  g1  g2
0   x  72  53
1   y  44  97
2   z  13  32

Comment: That's great! It works perfectly! Thank you very much for your help!


SSH X11 Forwarding XInputExtension missing

Question: When trying to open a GUI-program on a SSH-Session with X11-Forwarding (both client and server have X11Forwarding activated) I get this error:
Xlib:  extension "XInputExtension" missing on display ":4".
Application asked to unregister timer 0x8000003 which is not registered in this thread. Fix application.
VNC to this server is working correctly.
OS: Ubuntu Server
Thanks!
Answer: Try using
<code>ssh -Y
</code>
to connect to the box as explained in this post
Comment: I'm still getting this error: Xlib: extension "RANDR" missing on display
Comment: Seems like something has changed.
The RANDR extension could be needed if the app needs to go full screen. Try launching it in a window if you can.
Alternatively you could use standard X Display configuration with those commands:
`xhost +`
`ssh remotebox`
`export DISPLAY=local.box.ip.address:0`
`gui-program`
After making sure your X server is listening on a TCP port (don't remember which file under /etc/ controls this, though)
Comment: after installing libxrandr2 ssh -Y worked


Pegar apenas uma div de outra página via jQuery

Question: Pegar conteúdo de outra página por javascript ou jquery
Em outra pergunta eu queria saber como pegar conteúdo de uma página.
Neste eu queria através deste código pegar apenas uma
 ao invés do conteúdo inteiro. Vamos supor que eu queria pegar todo conteúdo de uma
 chamada teste.
Como pegar apenas uma
?
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="estilo.css">
    <title></title>

Answer: Eu utilizaria o método .find no conteúdo da resposta da sua requisição.
Pode parecer estranho a princípio, isso funciona perfeitamente.
Veja:
$.ajax({
    url: 'http://agenciaroadie.com.br/loja.php',
    type: 'GET',
    success: function(res) {
        var headline = $(res.responseText).find('#id_da_div_que_eu_quero');
        $("#cabecalho").html(headline);
    }
});

Repare que não é necesário o .text. Isso muito útil caso você queira, por exemplo, selecionar elementos de uma classe específica.
Exemplo:
$(function(){

    // Suponhamos que esse é o conteúdo de outra página

    var html = '
\

1
\

2
\

Não é uma li
\

';

    // Quero somente as LI

    var $lis = $(html).find('li');

    $('#element').html($lis);
})

Veja isso no JSFIDDLE
Exemplo com classes:
$(function(){

        var html = '
\

1
\

2
\

3
\

4
\

';

    // Quero somente os pares

    var $lis = $(html).find('li.par');

    $('#element').html($lis);
})

Veja no JSFIDDLE
Obtendo elementos filtrados de um conteúdo externo
Suponhamos que nós temos duas páginas:

index.html - A página onde estamos trabalhando
externo.html - A página externa, onde vamos procurar os elementos

Veja como funcionaria, de maneira prática, baseando-se nesse cenário:
Conteúdo externo:
#externo.html

A página onde incuiremos o conteúdo de outra página
#index.html

<!DOCTYPE html>

    <title>Testando</title>

Comment: Muito bom, tem como buscar tags ou classes também? Ou tags dentro de de uma ID?
Comment: Sim, eu citei isso acima, porém não coloquei no exemplo ^_^
Comment: @Wallace neste exemplo a var html seria o endereço do site? exemplo var html = www.google.com ?
Comment: Não. Seria o conteúdo retornado pelo AJAX. A resposta da função `$.ajax` sempre cai no primeiro parâmetro da função  `success`, que é representado pela variável `response`. Vou postar exemplo.
Comment: Neste assunto ai Eu fiquei boiando mesmo e não entendi, você se importa em postar um exemplo completo ai por favor, retirando do site http://www.pauloroberto.info a div  wb_element_instance10, para Eu ver este negócio funcionando, pois isso muito me interessa e ja desisti disso no passado por não ter compreendido...Se não for tomar muito o seu tempo.
Comment: Uma última pergunta, como eu faço para acessar o segundo li no último elemento, supondo que tenha dois li?
Comment: var $lis = $(html).find('#conteudo > ul > li'); se eu quiser pegar o segundo li
Comment: `var $lis = $(html).find('#conteudo > ul > li').eq(1)`. Pois a contagem das `` é a partir de `zero`.
Comment: Valeu, não achei nenhum tutorial sobre isto, vai ajudar muito.
Answer: Podes usar o load do Jquery
$("#cabecalho").load("loja.php #teste");

jQuery Load
Comment: +1. Simples, bonito e objetivo.
Comment: Exactamente, para o que pretende penso que seja o mais prático.
Comment: A diferença é que, com o ajax, temos `beforeSend`, ou poderiamos setar o método de requisição como `POST` e outras coisas. Eu não sei se tem como fazer pelo `load`. :)
Comment: Veja os últimos exemplos da página do jQuery. Mas para ter mais controlo sobre o que se está a fazer também prefiro .`$.ajax`
Comment: ótimo isso mesmo ja sana a maldita duvida e em uma linha de código rsrs  obrigado @azyFox


"Create new account" Block in drupal

Question: I am working on a Drupal project where I require a "Create new account" form on a content page. Can anybody help me out with this? Is there any module or any alternative to get "Create new account" as a block?
Answer: Use this module http://drupal.org/project/formblock
Download and install the module. Navigate to admin/structure/block You can see Registration form as a block and choose the region to appear.

User Registration to appear in a block taken from this source.
Answer: You can can create block programmatically. And create your own callback function where you can call drupal_get_form and render user_register_form.
For example your callback function will look like this:
Basic example
/**
 * Implements hook_block_info().
 */
function yourmodule_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );

  return $blocks;
}
function hook_block_view($delta = '') {
    switch ($delta) {
    case 'my_block':
          $block['subject'] = t('Register form');
          $block['content'] = yourmodule_block_register_callback();
     }
}

function yourmodule_block_register_callback() {
   $reg_form = drupal_get_form('user_register_form');
   $output = drupal_render($reg_form);
   return $output;
}

If you are not familiar with the creation of custom modules - read this.
Comment: Is it not possible through modules or something which is not so programmatic.
Comment: it's not as difficult as it seems
Answer: https://drupal.stackexchange.com/a/21553/23871
Create a new block, copy/paste this code in the body:
<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

Make sure the block is set to PHP filter

“Create new account” Block in drupal


XGBoost - Linear Tree

Question: I've been reading about linear tree models particularly the linear-tree package and the option to use linear trees in LightGBM if one sets the parameter linear_tree to True. However I am confused by XGBoost's gblinear booster. Previous resources I found on stats.exchange haven't been helpful and there is very little out there on gblinear. Does gblinear mean that the leaves have linear models making it a linear tree model?
Answer: The gblinear booster is an ensemble of generalised linear regression models that is trained using (variants of) gradient descent. As such the concept of a leaf or leaves is inapplicable in the case of a gblinear booster as it uses linear functions only. Effectively a gblinear booster is an elastic net GLM as we primarily control the L1 and L2 regularisation parameters, it does not have any tree structure associated with it.
What you describe where "leaves have linear models" is essentially the methodology of Cubist (or M5) where a tree is grown such that the terminal leaves contain linear regression models. As you note, LightGBM's linear_tree does that if one wants to experiment with it further.
Comment: I tried to when you first responded but I got the message "You need at least 15 reputation to cast a vote, but your feedback has been recorded". Thank you for the help though @usεr11852
Comment: Got it, thanks @usεr11852. If XGBoost's `gblinear` is a GLM, why does it have the letter "b" in it. Makes it seem like it is a GBM where the "_leaves have linear models_". It's confusing because then the [linear-tree package](https://github.com/cerlymarco/linear-tree), "a python library to build Model Trees with Linear Models at the leaves", has their own Linear Boosting available. In addition, LightGBM has their `linear_tree` option.
Comment: Because a `gblinear` object is fitted sequentially by combining GLM and then combines them together, it is a booster. Just combing GLMs still gives you a GLM. (Hm, I will clarify this point in answer.)
Comment: BTW, if this post is useful for you, you can upvote it, and it resolves your ask you consider accepting it as an answer.
Comment: Oh, right, no worries. I mentioned it because sometimes new users don't immediately understand the voting concept. Go forth and boost! :)

XGBoost - Linear Tree


Filter all rows with word next to a specified word in R

Question: I have a column with string content
temp <- c(NA, NA, "grocery pantry all offers", NA, "grocery offers today low price",
"grocery offers today low price", "tide soap", "tide soap bar",
"tide detergent powders 2kg", NA, "tide", "tide detergent powders 2kg",
"liquid detergent tide brand")

My intention is to create a bigram with words which are next to Tide. For this I would need to filter out words which are next to tide. Either left or right side. For ex in above output would be
tide soap
tide soap
tide detergent
tide detergent
detergent tide
tide brand

Any help ?
Answer: If you use the quanteda package, this is straightforward. You specify which word you want to target and decide how many words on left/right side of the target you want.
library(quanteda)

kwic(x = temp, pattern = "tide", window = 1) %>%
as.data.frame

  docname from to       pre keyword      post pattern
1   text7    1  1              tide      soap    tide
2   text8    1  1              tide      soap    tide
3   text9    1  1              tide detergent    tide
4  text11    1  1              tide              tide
5  text12    1  1              tide detergent    tide
6  text13    3  3 detergent    tide     brand    tide

Comment: @akrun No worries. I think there are similar cases on SO and you would come across `kwic()`. Quanteda is very useful if you dig text.
Answer: Is this what you want?
library(stringr)

str_extract(temp, "(tide [:alnum:]*)|([:alnum:]* tide)")

It basically says extract the strings that are either "tide" followed by a whitespace  and then a combination of letters and numbers ([:alnum:]) of any length (*) or (|) the other way around ([:alnum:]* tide).
Btw: if you want to, afterwards you can remove the NAs with
x <- str_extract(temp, "(tide [:alnum:]*)|([:alnum:]* tide)")
x[!is.na(x)]

Comment: Thanks could you please edit it so that it includes both words from last word it currently gives only tide detergent, can it also give tide brand?  Also, is it possible using pairwise_count? I was trying to do it using pairwise_count but unfortunately its not possible without a group as I found
Answer: You can use the tidytext package to split the text into bigrams and filter for tide.
library(tidytext)
library(dplyr)
library(tibble)

temp %>%
  enframe(name = "id") %>%
  filter(str_detect(value, "tide")) %>%
  unnest_tokens(bigrams, value, token = "ngrams", n = 2) %>%
  filter(str_detect(bigrams, "tide"))

# A tibble: 6 x 2
     id bigrams
  <int> <chr>
1     5 tide soap
2     6 tide soap
3     7 tide detergent
4    10 tide detergent
5    11 detergent tide
6    11 tide brand

Answer: This is another option just using tidyverse that grabs anything before and/or after 'tide'.
stringr::str_match_all(temp, "(\\w+)?\\s?tide\\s?(\\w+)?") %>%
   purrr::reduce(rbind) %>%
   as.data.frame %>%
   dplyr::filter_all(dplyr::any_vars(!is.na(.)))

                    V1        V2        V3
1            tide soap      <NA>      soap
2            tide soap      <NA>      soap
3       tide detergent      <NA> detergent
4                 tide      <NA>      <NA>
5       tide detergent      <NA> detergent
6 detergent tide brand detergent     brand

Answer: Here is a base R solution
r <- unlist(Filter(length,
                   t(do.call(cbind,
                             lapply(c("\\w+\\stide","tide\\s\\w+"),
                                    function(p) regmatches(temp,gregexpr(p,temp)))))))

such that
> r
[1] "tide soap"      "tide soap"      "tide detergent" "tide detergent" "detergent tide" "tide brand"


What if the intermediate point is $c=(0,0)$ in the MVT?

Question:
Let $f: \Bbb R ^2 \to \Bbb R$ be differentiable everywhere. Assume $f(-\sqrt 2, -\sqrt 2) = 0$ and also that
$$ \left| \frac {\partial f} {\partial x} (x,y) \right| \le | \sin (x^2 + y^2) | \\
\left| \frac {\partial f} {\partial y} (x,y) \right| \le | \cos (x^2 + y^2) |$$
for each $(x,y) \in \Bbb R ^2 \setminus \{ (0,0) \}$. Prove that $|f(\sqrt 2, \sqrt 2)| \le 4$.

So by Mean Value Theorem there is a point $c$ in the straight line segment that joins $(\sqrt{2},\sqrt{2})$ and $(-\sqrt{2},-\sqrt{2})$ such that,
$\|f(\sqrt{2},\sqrt{2})-f(-\sqrt{2},-\sqrt{2})\|\leq |\nabla f(c)| \;\|(\sqrt{2},\sqrt{2})-(-\sqrt{2},-\sqrt{2})\|$.
This implies $\|f(\sqrt{2},\sqrt{2})\|\leq |\nabla f(c)| 4$. Now if $c\neq (0,0)$ then by the given inequalities we can show the result. But, what if $c=(0,0)$? Because $(0,0)$ is a point on the line segment.
Comment: Break the direct path from $(-\sqrt{2},-\sqrt{2})$ to $(\sqrt{2},\sqrt{2})$ into two subpaths, the first from $(-\sqrt{2},-\sqrt{2})$ to $(\epsilon,-\epsilon)$ and the second from $(\epsilon,-\epsilon)$ to $(\sqrt{2},\sqrt{2})$. (Here $\epsilon>0$ is small, and will eventuallly be sent to $0$.)
Answer: Write
$$f(\sqrt 2,\sqrt 2) = f(\sqrt 2,\sqrt 2) - f(0,0) + f(0,0) - f(-\sqrt 2,-\sqrt 2).$$
Use the mean value theorem on each segment; recall the MVT doesn't require differentiability at the end points.
Answer: The problem is $f$ may be discontinuous at $0$.
However we can evade $(0,0)$ and follow two line segments.
Call A = $(\sqrt{2},\sqrt{2})$.
Fix $\epsilon>0$ and call E = $(0, \epsilon)$.
Take the path -A to E to +A. Then by making $\epsilon$ arbitrarily small we can approach 4 as closely as needed. Hence $f(A)$ must be $\le 4$.
Comment: Actually $f$ is differentiable everywhere, hence continuous everywhere.
Comment: f is continuous at $(0,0)$ since it is differentiable everywhere.
Comment: Right - I missed that. But in that case we know the $\nabla f(0,0)$ has to be the only value that can maintain continuity of $\nabla f$ around the origin, i.e. it has to be $(0, 1)$.