Permission denied: user=basi, access=WRITE, inode="/":

Question: Im a fresher in hadoop and pig.i have installed pig in my local user in ubuntu and hadoop as hduser.Pig working fine in local mode for small datasets.started pig in mapreduce mode and tryng to implement wordcount but getting permission denied error as below.
Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException): Permission denied: user=basi, access=WRITE, inode="/":hduser:supergroup:drwxr-xr-x
started hadoop in psudomode
statrted pig in local user:pig -x mapreduce
   grunt> A = LOAD '/Wordcount.txt' AS (line:Chararray);
   grunt> B = FOREACH A GENERATE FLATTEN(TOKENIZE(line)) AS word;
   grunt> grouped = group B by word;
   grunt> wc = FOREACH grouped GENERATE group, COUNT(B);
   grunt> DUMP wc

/Wordcount.txt is file in hdfs
Answer: Its not clear how you loaded /Wordcount.txt into the root folder, but the error is saying you're trying to write into the root directory, which is only possible as the hduser account, not basi, your local user.
One option - switch to the other user.
Otherwise, don't use the root of HDFS as the dumping ground for all files; use your dedicated /user directory
Answer: It is not Pig but Hadoop related. It happened to me with Spark. Probably you installed your Hadoop manually. You need to create supergroup and add hduser into supergroup.
sudo groupadd supergroup
sudo usermod -aG supergroup hduser

Then try again.
Answer: proceed as below
chmod 777 /Wordcount.txt

chmod change the permission of text file as rwxrwxrwx for owner group and other respectively
and then provide complete location of text file in the load command similar to below
grunt> A = LOAD '/directory/abc/Wordcount.txt' AS (line:Chararray);

then run the code again...
hopes this will help you out.
Answer: In Pig, DUMP command would first write its output to /tmp/temp.... and then the client reads from it.  My guess is, your cluster does not have /tmp.   If that is the case, please try creating the /tmp directory (usually with permission 1777).
(Edited: Reading answers of others, I think the one about /user makes sense.  Without it, you won't even be able to submit any jobs.)


Como fechar um select ao clicar fora dele?

Question: Estou construindo um select customizado com autocomplete e para isto estou usando algumas
's, um <input> e jQuery.
Eu gostaria que ele tivesse o mesmo comportamento padrão de um select HTML de quando se clica fora do mesmo, ele se fecha.
Meu HTML, em linhas gerais, está assim:

    <input id="my-input" type="text" value="" onkeyup="myAutocomplete(this);">

Estou usando a função JavaScript myAutocomplete() para fazer todo trabalho de auto complete e manipular as divs com sucesso, meu único problema é fazer a div my-options-container se fechar ao clicar fora do select.
A função myAutocomplete() é a seguinte:
function autocomplete_region(obj) {
    var value = $(obj).val();

    // Only executes if there is some text on search input
    if (value) {
        // Mount request URL
        var url = '/options/' + value + '/';

        // Send the request to server
        $.get(url,
            function (response) {
                // Continues only if there is a response
                var options = (response["options"] == undefined) ? response : response["options"];

                if (options.length > 0) {
                    // Clear old options
                    $('#my-options-container').html('');

                    // Populate items
                    for (var i = 0; i < options.length; i++) {
                        var href_value = '/?code=' + options[i].code + '/';
                        var item = '
' + options[i].text + '
';

                        $('#my-options-container').html($('#my-options-container').html() + item);
                    }

                    // Shows options div
                    if ($('#my-options-container').is(':hidden'))
                        $('#my-options-container').show();

                } else {
                    $('#my-options-container').html('Ops! Nenhuma opção disponível.');

                    // Shows options div
                    $('#my-options-container').show();
                }
            });
    } else {
        // Hides options div
        $('#my-options-container').hide();

        // Empty options div
        $('#my-options-container').html('');
    }
}

Comment: @hugocsl Achei desnecessário colocar a função `myAutocomplete()` na pergunta porque ela ficou relativamente grande por fazer outras coisas como pegar as opções em uma API além de apenas mostrar e esconder a `` que mostra as opções.
Comment: Cara coloca o se script ai na pergunta tb, facilita para te responder e para similar a situação ai
Comment: Queres fechar o select quando o input perder o `focused` ou como o nativo quando clicares fora?
Comment: @Sergio Quando perder o `focused`seria melhor.
Comment: Vc tá usando algum componente para criar o select ou está fazendo na mão mesmo?
Comment: @Sam Na mão mesmo.
Comment: Coloque na pergunta a função (ou funções) e/ou o CSS que abre o select. Só assim dá pra saber como fazer o reverso (fechar o select).
Comment: Vou colocar então, um minuto.
Comment: Coloca aí que eu ajusto a minha resposta com mais exatidão.
Comment: @hugocsl Coloquei o script.
Comment: @Sam Veja se melhorou a pergunta.
Comment: Então. Vc vai colocar no `else` da minha resposta o mesmo `else` da função autocomplete. Esse `else` onde tem `// Hides options div`.
Answer: Clicar no document esvaziar e esconder a div.#my-options-container. Basta verificar no click no document se o local do click não é a div.my-select-container:
$(document).on("click", function(e){
   if($(e.target).closest(".my-select-container")[0]){
      e.stopPropagation();
   }else{
      $('#my-options-container').hide().empty();
   }
});

O e.stopPropagation(); irá cancelar o click no document se o clique foi feito dentro da div.my-select-container.


A standard way of marking alternate tunings for classical guitar?

Question: I'm writing a piece that needs to have a drop D tuning- how do I mark the guitar's tuning at the top of the score? Is there a standard? Something like "E = D" or just "DADGBE"? Maybe a chord fingering chart type thing with the letters at the nut of the guitar?
I'm fine with "Tuning = DADGBE", but if there's a standard, I'm interested in what it is.
Comment: That's called "scordatura" in the classical world. You might do a web search on that.
Answer: In Behind Bars, Elaine Gould writes that "scordatura"  is indicated as "<string number> to pitch", with <string number> circled (pp. 388–89).

Indicate the different tunings above the first staff.

See the image below for her example, from Walton's Five Bagatelles, No. 3.
Comment: Exactly, see Capricho Arabe by Tarrega for instance.
Answer: I just got some rep with exactly that tuning. It says:
6 = D
at the top, but with the 6 inside a circle.
You don't have to specify the other strings are in standard tuning. Just that the sixth string is D.
Comment: There is a ⓺ character (DOUBLE CIRCLED DIGIT SIX) but I don't know if that renders correctly in all browsers.
Comment: It can also show words "muta in" (change to). Like "6ª muta in Ré" etc. etc.
Comment: @NotLegato What happens is we develop scordatura muscle memory. We also have to decide where on the neck to play and we have to adjust our analyses for scordatura also. It's kinda like doubling on banjo or mandolin where we change how the notes on the page translate to our hands.
Comment: ```6 = Re``` is also pretty common
Comment: Is it customary to notate the sounding pitch or just write D as an E in the case of (6) = D? I understand the latter is the case when using an explicit scordatura staff, as seen in Yuxi L's answer.
Comment: @NotLegato Not sure about other strings but they are probably like guitar in that you have to write the sounding pitch. If you want a low D you notate a D on the score. The reason is that most notes can be played in more than one place and the guitarist has to figure out the fingering. If you don't give them the actual pitches it's a hopeless task.
Comment: @ToddWilcox I presumed writing transposed pitches would be easier due to habit and muscle memory; a certain arpeggio may naturally fall on the hands as a CV barré. But noted.
Answer: I agree with all the answers above. An alternate way, in case you ever get crazy tuning schemes, is to notate your alternate tuning with the staff. The advantage with this method is that you don't get confusions over which octaves the alternative tuning notes are in.
An example from Carlo Domeniconi's Koyunbaba:
Answer: I've seen your last sentence written way more than anything else. It makes immediate sense, and is unequivocal.
Tab may be different, in that the 6 strings would be notated DADGBE on the start of the tab.
Comment: Which sentence are you referring to?
Comment: @JohnKugelman - since my answer is to OP, the OP's last sentence.
Comment: As in, "I'm fine with 'Tuning = DADGBE'..."? Why then add "Tab may be different..."?
Comment: @JohnKugelman - basically, I'm trying to be a little more thorough than necessary?


Creating Hyper-V VM fails with failed to load a library error

Question: I am trying to create a Ubuntu 18 VM with Hyper-V under Windows 10 Enterprise.
In particular, I want to increase the disk space.
I get an error pop-up box with the following message.
<code>Failed to load a library required by Hyper-V Manager. To resolve the problem, close Server Manager, then open Server Manager again, and then open Hyper-V Manager again.
</code>
I am running Hyper-V quick create as an Administrator.
The Hyper-V Manager is already running.
I have tried closing and re-opening Hyper-V Manager, but still get the same error.
Hyper-V Manager gives version as 10.0.17134.1
Windows 10 gives version as 1803 (OS Build 1714.1967)
Answer: This was due to configuring more than one SCSI controller entry. In theory, this should not prevent the VM from being created, but nevertheless it does.


$span\{s+v\} = span\{s\} + span\{v\}$?

Question: span{s+v} = span{s} + span{v}
Does the above statement always hold true?
In addition, what is the difference between span {s} $\cup$ {v} = span{s} + span{v} and the above statement?
Comment: Are $s$ and $v$ vectors or sets of vectors? If they are sets, how are you defining $s+v$? If they are vectors, how are you defining $s\cup v$?
Comment: Do you mean span {$s$}$\cup${$u$}=Span{$s$}+span{$v$}?
Comment: Hey i edited the question. Hope it is clear now.
Answer: No. Consider the set {$(1,0)+(0,1)$} $=$ {$(1,1)$}.
The span of {$(1,1)$} is just a straight line through the origin in $\mathbb{R}^{2}.$
While the span of {$(0,1)$,$(1,0)$} is all of $\mathbb{R}^{2}$.
On the other hand
span({$s$} $\cup$ {$v$}) $=$ span{$s$} + span{$v$} holds.

$span\{s+v\} = span\{s\} + span\{v\}$?


CLT theorem and Berry–Esseen bounds for this special case of sampling

Question: Consider a finite set $S=\{s_1,s_2,..s_n\}$, where $a \leq s_i\leq b$ are integers. Each element in $S$ can be chosen to a subset $S'$ in probability $p$.
We consider $n$ to be very large.
My question: How is there a way to messure how the mean element in $S'$ (i.e., $(s'_1+s'_2...+s'_{n'})/n'=s'$, where $n'$ is the number of elements in $S'$) to the mean element in $S$ (denoted by $s$)?
Formally, this means, given an error parameter $\alpha$, and mean values $s, s'$ I am trying to find the probability that
$Pr(|s-s'|< \alpha)$.
Since $n$ is large, I consider to use the  central limit theorem and use Berry–Esseen theorem to approximate the error, which depends on $n$. But I cannot express the problem as a sum of independent random variables, since this not a "standard way" of using sampling with replacement.
What can I do to approximate error?
Note: I did not found how to express the problem cannot as sum of independt RVs. For example, suppose we denote $X_i$ if element i is chosen or not- then
$$s'=(\sum_{i=0}^{n} X_i *s_i )/(\sum_{i=0}^n X_i).$$
And this cannot be expressed a a sum of independent RVs, as done in CLT or Berry Essen Thorems.
Comment: In what sense is the arithmetic mean a measure of "closeness"??
Comment: +1 Why can you not express $s^\prime$ as the sum of independent random variables?  After all, it is explicitly constructed in terms of such a sum!
Comment: What kinds of objects are the $s_i$ and how do you measure closeness?
Comment: Every object is an integer between $a$ and $b$.
Comment: the average=mean. i.e., sum of all elements divided by number of elements.
Comment: @whuber - since the number of elements in S' is random.
Comment: For example: suppose X_i denotes if element i is chosen or not- then s'=(\sum_{i=0}^{n} X_i *s_i )/(\sum_{i=0}^n X_i). This cannot be expressed a a sum of independent RVs.
Comment: Let me check my understanding of "chosen to a subset ... with probability $p.$" Their sum can be expressed in terms of $n$ *independent* random variables $X_1,\ldots,X_n$ where $X_i=s_i$ with probability $p$ and $X_i=0$ otherwise. The sum of the chosen elements equals the sum of the $X_i.$
Comment: Yes, but you need to divide the sum by the number of elements in S', which is a random varible (and not constant).
Comment: @whuber This is why classic CLT and Berry-Esseen cannot be applied to this case
Comment: That is correct, and I think it gets to the heart of the matter.  But doesn't it take only a slight modification to handle the random denominator?  As $n$ grows large , $n^\prime$ approaches $pn$ sufficiently rapidly.
Comment: Hmmm... maybe it will work for some cases. If $a$ and $b$ are equal, then there is still an error depends only on $n$. I think there should be a better bound in such case.
Answer: First of all, I want to ensure whether I have understood the question correctly or not. $n$ is 'very large' and $S=\{s_1,\dots, s_n\}$.
Now with probability $p\in(0,1)$, each $s_i$ is chosen to form the collection $S'$ (where $X_i:=I_{s_i \in S'}$).
Then
$$s'=\frac{\sum_{i=0}^n s_i I(s_i \in S')}{\sum_{i=0}^n I(s_i \in S')}=\frac{\sum_{i=0}^n s_i X_i}{n'}$$
and $s=\sum_{i=0}^n s_i/n$. (We have to keep in our mind that $n'$ and $s'$ are random and $p$ is fixed.)
Also let $m:=min\{|a|,|b|\} \le |s_i|\le max\{|a|,|b|\}=:M.$
Now, this might help you:
\begin{align}
&\frac{\sum_{i=0}^n s_i I(s_i \in S')}{n'} - \frac{\sum_{i=0}^n s_i}{n} \\
&= \frac{1}{\sum X_i} \left(\sum_{i=0}^n s_i X_i - \frac{n'}{n} \sum_{i=0}^n s_i\right) \\
&= \frac{n}{n'} \cdot \frac{1}{n}\left(\sum_{i=0}^n s_i X_i - p \sum_{i=0}^n s_i\right) - \left(\frac{n'}{n}-p\right)\frac{\sum s_i}{\sum X_i}
\end{align}

Now, for the first part, you need a weighted version of CLT - check Lyapunov CLT condition (or Lindeberg condition).
Lyapunov CLT with variables $Y_i=s_i X_i$ will give you $$\frac{\sum s_iX_i - p \sum s_i}{p(1-p)\sqrt{\sum s_i^2}} \to N(0,1)$$ as $n\to \infty.$ (I have not checked thoroughly though, please check them - you might need boundedness of the random variables.)
$m\sqrt{n}\le \sqrt{\sum s_i^2}\le M\sqrt{n}$ - for simplified calculations, you have to assume $m>0$ - though this assumption can be relaxed.
For the other part, note $\sqrt{n}\left(\frac{n'}{n}-p\right) \to N(0,1)$.
$$\frac{\sum s_i}{\sum X_i} = \left(\frac{\sum s_i}{n}\right)\frac{n}{n'} \to \left(\frac{\sum s_i}{pn}\right)$$ Now $s_i$ are bounded which gives you required consistency from here.

For CLT type result, I would tweak the previous part in this way,
\begin{align}
&P\left(\sqrt{n}|\frac{\sum_{i=0}^n s_i I(s_i \in S')}{n'} - \frac{\sum_{i=0}^n s_i}{n}|>\epsilon\right) \\
&\le P\left(\sqrt{n}|\frac{n}{n'} \cdot \frac{1}{n}\left(\sum_{i=0}^n s_i X_i - p \sum_{i=0}^n s_i\right)|>\epsilon/2\right) + P\left(\sqrt{n}|\left(\frac{n'}{n}-p\right)\frac{\sum s_i}{n'}|>\epsilon/2\right) \\
&= P\left(\frac{n}{n'} \cdot \frac{1}{\sqrt{n}}|\left(\sum_{i=0}^n s_i X_i - p \sum_{i=0}^n s_i\right)|>\epsilon/2\right) + P\left(\frac{\sum s_i}{n} \cdot \frac{n}{n'} \cdot \sqrt{n}|\left(\frac{n'}{n}-p\right)|>\epsilon/2\right)
\end{align}

You can use Slutsky's theorem with $\frac{n'}{n}\to p$ and the normality you got from the Lyapunov CLT here.
For the second part, use boundedness of $\sum_1^n s_i/n$ and a Slutsky theorem type approach will give you some bound.

Sorry for the mess.
Edit:
There should be another condition on the values of $s_i$'s. These values should be such that $\sum_{i=0}^n s_i/n \to c$ for some constant $c$ as $n \to \infty$


Getting 415 Unsupported media type when executing from address line in browser provifing JSON as parameter for route in .NET Core 3

Question: I'm executing the URL

https://localhost:44310/api/Licensee/{"name":"stan"}

in address field of my browser, getting the error

"title": "Unsupported Media Type", "status": 415

which is described as

... the origin server is refusing to service the request because the payload
is in a format not supported by this method on the target resource.

The suggested troubleshot is

... due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data ...

I can't really control what header the browser provides. Due to intended usage, I can't rely on Postman or a web application. It needs to be exected from the URL line. The parameter will differ in structure, depending what search criteria that are applied.
The controller looks like this.
[HttpGet("{parameters}")]
public async Task<ActionResult> GetLicensee(LicenseeParameters parameters)
{
  return Ok(await Licensee.GetLicenseeByParameters(parameters));

}

I considered decorating the controller with [Consumes("application/json")] but found something dicouraging it. I tried to add JSON converter as suggested here and here but couldn't really work out what option to set, fumbling according to this, not sure if I'm barking up the right tree to begin with.
services.AddControllers()
  .AddJsonOptions(_ =>
  {
    _.JsonSerializerOptions.AllowTrailingCommas = true;
    _.JsonSerializerOptions.PropertyNamingPolicy = null;
    _.JsonSerializerOptions.DictionaryKeyPolicy = null;
    _.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
  });

My backup option is to use query string specifying the desired options for a particular search. However, I'd prefer to use the object with parameters for now.
How can I resolve this (or at least troubleshoot further)?
Comment: You can't pass JSON in the url like that. You have to use querystring params
Comment: But I really want to... The reason is that there might be a **loooot** of parameters and I don't want to refactor the controller's signature each time. I guess passing the parameters in body might be an option. But how do I pass a body from URL line? Is it possible at all? Also, do you have a reference on where it says that JSON can't be used that way, please? I'd like to angrily read it.   :)
Comment: You cant do things that are not supported, no matter how much you want to do them.  JSON is supported in request.body however.
Comment: @JK. Not on GET. I will have to switch to POST. Then I have to learn the very rookie testers to use Swagger... Sight...
Comment: Well of course not. When doing HTTP GET, there is no request body.
Answer:
The reason is that there might be a loooot of parameters and I don't want to refactor the controller's signature each time

Actually, you don't have to change the controller's signature each time. ASP.NET Core Model binder is able to bind an object from query string automatically. For example, assume you have a simple controller:
[HttpGet("/api/licensee")]
public IActionResult GetLicensee([FromQuery]LicenseeParameters parameters)
{
    return Json(parameters);
}

The first time the DTO is:
public class LicenseeParameters
{
    public string Name {get;set;}
    public string Note {get;set;}
}

What you need is to send a HTTP Request as below:
GET /api/licensee?name=stan&note=it+works

And later you decide to change the LicenseeParameters:
public class LicenseeParameters
{
    public string Name {get;set;}
    public string Note {get;set;}

    public List<SubNode> Children{get;set;} // a complex array
}

You don't have to change the controller signature. Just send a payload in this way:
GET /api/licensee?name=stan&note=it+works&children[0].nodeName=it&children[1].nodeName=minus

The conversion is :  . represents property and [] represents collection or dictionary.
In case you do want to send a json string within URL, what you need is to create a custom model binder.
internal class LicenseeParametersModelBinder : IModelBinder
{
    private readonly JsonSerializerOptions _jsonOpts;

    public LicenseeParametersModelBinder(IOptions<JsonSerializerOptions> jsonOpts)
    {
        this._jsonOpts = jsonOpts.Value;
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var name= bindingContext.FieldName;
        var type = bindingContext.ModelType;
        try{
            var json= bindingContext.ValueProvider.GetValue(name).FirstValue;
            var obj = JsonSerializer.Deserialize(json,type, _jsonOpts);
            bindingContext.Result = ModelBindingResult.Success(obj);
        }
        catch (JsonException ex){
            bindingContext.ModelState.AddModelError(name,$"{ex.Message}");
        }
        return Task.CompletedTask;
    }
}

and register the model binder as below:
[HttpGet("/api/licensee/{parameters}")]
public IActionResult GetLicensee2([ModelBinder(typeof(LicenseeParametersModelBinder))]LicenseeParameters parameters)
{
    return Json(parameters);
}

Finally, you can send a json within URL(suppose the property name is case insensive):
GET /api/licensee/{"name":"stan","note":"it works","children":[{"nodeName":"it"},{"nodeName":"minus"}]}

The above two approaches both works for me. But personally I would suggest you use the the first one as it is a built-in feature.


Hosting service with WordPress auto-install

Question: I recently started a WordPress blog on MyDomain (which offers WordPress auto-installation). Being a newbie to hosted blogging, I prefer using a host service that will have WordPress auto-installation.
I'm very disappointed with MyDomain because of two key issues they failed me on:

I have no access to .htaccess files so I can't use "nice" permalinks.
The WordPress application can't access WordPress.com or akismet, so I'm very limited in the plugins I can use.

I'm considering switching a hosting service to get better WordPress service. Is there any service that "plays nicely" with auto-installed WordPress out of the box?
On WordPress.org they mention BlueHost, DreamHost and some others, however these are (I assume) paid featured hosts, so although I would like to support WordPress.org, I don't trust these commercials.
What's the best option for me?
Thanks
Comment: Are you only going to use WordPress on your host?  Why not just get sign up at WordPress.com?
Comment: @squillman: I want more flexibility
Answer: I have hosting in a few different hosting companies, one of which is DreamHost. There are some horror stories about them, but I've never had an issue with them. And their WordPress auto-installation is very smooth.
Comment: Regarding their WordPress hosting - do you know if they provide access to .htaccess files and allow for outbound connections? Thanks
Comment: Yes, yes they do.
Comment: I didn't choose them because of the minimal required payment. I thought it to bee too much (50$ to be able to pay monthly or pre-pay 1 year in advance)
Answer: I use Hostmonster.com  .  It has the newest version of cPanel Pro  and it has the latest version of many of the most popular web softwares, including WordPress.    They charge $5.95 a month for UNLIMITED space and bandwidth.   Also, they have Live Chat with support on their site so you can easily ask questions about the service.   http://www.hostmonster.com/
Comment: Is that really unlimited, or "unlimited" bandwidth?
Comment: they have a few hundred "shared servers" and so you get all the bandwidth you need.  they dont charge you for going over any limit.
Answer: If you just want wordpress hosting go with wordpress.com
Comment: it you go with auto-hosting a blog, i'd say typepad.com is good also.
Answer: Eventually I chose JustHost that were quite cheap and recommended by WordPress.org. Meanwhile everything is okay, thanks for all the answers.


Show $1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots+\frac{1}{1999}-\frac{1}{2000} =\frac{1}{1001}+\frac{1}{1002}+\ldots+\frac{1}{1999}+\frac{1}{2000}$

Question: I am trying to show that
$$
1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots+\frac{1}{1999}-\frac{1}{2000}
=\frac{1}{1001}+\frac{1}{1002}+\ldots+\frac{1}{1999}+\frac{1}{2000}.
$$
It seems there is some sort of generalizable pattern here, so I will verify it for smaller numbers:
$$
\begin{align*}
\text{Say, }n=4 \hspace{35pt} 1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}&=\frac{1}{3}+\frac{1}{4}\\
\frac{12}{12}-\frac{6}{12}+\frac{4}{12}-\frac{3}{12}&=\frac{4}{12}+\frac{3}{12}\\
\frac{7}{12}&=\frac{7}{12}
\end{align*}
$$
So, my guess on the general formula is
$$
 1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots+\frac{1}{n-1}-\frac{1}{n}=\frac{1}{n/2+1}+\ldots+\frac{1}{n-1}+\frac{1}{n}.
$$
This really seems like I am getting somewhere, but how can I finish off the proof? Is induction viable?
Answer: Let $$S(n) = 1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \cdots + \frac{1}{2n-1} - \frac{1}{2n}.$$
Then notice if we add $$T(n) = 2 \left(\frac{1}{2} + \frac{1}{4} + \cdots + \frac{1}{2n}\right)$$ to $S(n)$, all the negative terms become positive and we get a nice sum:
$$S(n) + T(n) = 1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{2n} = H(2n),$$ where $H(n) = 1 + 1/2 + \cdots + 1/n$ is the $n^{\rm th}$ harmonic number.
But notice that $T(n)$ is itself a harmonic number:  just distribute the $2$:  $$T(n) = \frac{2}{2} + \frac{2}{4} + \cdots + \frac{2}{2n} = 1 + \frac{1}{2} + \cdots + \frac{1}{n} = H(n),$$ so they are actually the same.  Therefore,
$$S(n) = H(2n) - H(n).$$  And from here it is easy to see that
$$S(n) = \left(1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{2n}\right) - \left(1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{n}\right) \\
= \frac{1}{n+1} + \frac{1}{n+2} + \cdots + \frac{1}{2n},$$
which proves the claim.
Answer: Proceed with induction. We seek to show, in essence, for all $n$ sufficiently large,
$$\sum_{k=1}^{2n} \frac{(-1)^{k-1}}{k} = \sum_{k=n+1}^{2n} \frac{1}{k}$$
We have a base case. So let's try to show that - assuming the above holds for $n$ - that it holds for $n+1$ too. We have
$$\begin{align*}
\sum_{k=1}^{2(n+1)} \frac{(-1)^{k-1}}{k}
&= \frac{(-1)^{2n}}{2n+1} + \frac{(-1)^{2n+1}}{2n+2} + \sum_{k=1}^{2n} \frac{(-1)^k}{k} \\
&= \frac{1}{2n+1} + \frac{-1}{2n+2} + \sum_{k=1}^{2n} \frac{(-1)^{k-1}}{k} \\
&= \frac{1}{2n+1} + \frac{-1}{2n+2} + \sum_{k=n+1}^{2n} \frac{1}{k} \\
\sum_{k=(n+1)+1}^{2(n+1)} \frac{1}{k}
&= \sum_{k=n+2}^{2n+2} \frac{1}{k} \\
&= \frac{1}{2n+2} + \frac{1}{2n+1}+ \sum_{k=n+2}^{2n} \frac{1}{k} \\
&= \frac{1}{2n+2} + \frac{1}{2n+1} - \frac{1}{n+1} + \sum_{k=n+1}^{2n} \frac{1}{k} \\
\end{align*}$$
It is trivial to show that
$$\frac{1}{2n+1} + \frac{-1}{2n+2} = \frac{1}{2n+2} + \frac{1}{2n+1} - \frac{1}{n+1}$$
so the induction follows and the original equation holds for $n \ge 4$. In particular, $n=1000$ gives you your desired result.
Answer: above, both are excellent answers. This is another way to look at it.
$1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots+\frac{1}{1999}-\frac{1}{2000} =\frac{1}{1001}+\frac{1}{1002}+\ldots+\frac{1}{1999}+\frac{1}{2000}$
After cancelling out positive matching terms on both sides and moving negative matching terms to RHS, we get:
$1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\ldots+\frac{1}{999}-\frac{1}{1000} =\frac{1}{501}+\frac{1}{502}+\ldots+\frac{1}{999}+\frac{1}{1000}$
Continuing the descent, we will end up with:
$1-\frac{1}{2}+\frac{1}{3}=\frac{1}{2}+\frac{1}{3}$
which is true.
Comment: Ah, I see, very nice.


Armazenar quantidade de valores em um txt PHP

Question: Possuo as informações abaixo em um arquivo txt.
500038;204932;61312;FTE GAV EDIT LACAVA TOTAL LARGXALTX15 GAV. NORMAL;LACA BLU FOSCO#996#335;5;78101922;xxxxxxx;0204932005
500038;204932;61312;FTE GAV EDIT LACAVA TOTAL LARGXALTX15 GAV. NORMAL;LACA BLU FOSCO#696#166;12;xxxxxxx;0204932012
100398;204932;50384;CJTO OPC LAT DIR/ESQ ARMARIO 30XALTXPROF;MDF BP LEGGERO#1040#340;74;78728780;xxxxxxx;0204932074
100398;204932;50385;CJTO OPC BASE SUP/INF RETA ARM LARGX30XPROF;MDF BP LEGGERO#769#340;71;78728777;xxxxxxx;0204932071
100398;204932;61108;FTE GAV EDIT ALCA LARGXALTX18 GAV. QUAD;LEGGERO#696#164;77;78728783;xxxxxxx;0204932077
100398;204932;50057;PAI OPC EDIT LARGXALTX15;LEGGERO#2610#100;39;78728745;xxxxxxx;0204932039

Peguei essas informações e armazenei em um array.
Após isso peguei somente o número dos pedidos e armazenei em outro array.
$file_name = "IMP.txt";

$file = fopen("ArquivoOrig/".$file_name, "r") or die ("Arquivo não encontrado!");
$file_output = fopen("ArquivoImp/Output_".$file_name, "w") or die ("Arquivo não criado!");

    while(!feof($file)){
      $strAnalise =  fgets($file);
      $strAnaliseArray = explode(";", $strAnalise);
    if(trim($strAnaliseArray[7]) != ''){
        $ArrayChaveNome[$strAnaliseArray[1]] = trim($strAnaliseArray[7]);
    }
    $strArrayDados[] = $strAnaliseArray;
}

foreach ($strArrayDados as $key => $value) {
    if(trim($value[7]) == ''){
        if(array_key_exists($value[1], $ArrayChaveNome)){
            $strArrayDados[$key][7]= $ArrayChaveNome[$value[1]];
        }
    }
}

for ($i=0; $i < count($strArrayDados); $i++) {
    $arrayTemp[$i] = $strArrayDados[$i][0];
}

var_dump($arrayValor);

//Monta arquivo
foreach ($strArrayDados as $key => $value) {
    $dataAtual = date('dmY');
    fwrite($file_output, $dataAtual.";");
    $resultPontoVirgulaToTxt = implode(";", $value);
    fwrite($file_output, $resultPontoVirgulaToTxt);

}

fclose($file_output);
fclose($file);

Usei a funçao array_count_values para contar os números de pedidos, sendo que possue 2 pedidos com o número 500038 e 4 pedidos com o número 100398.
$arrayValor = array_count_values($arrayTemp);

Retorno:
Array
(
    [500038] => 2
    [100398] => 4
)

Agora a pergunta é, como eu coloco esses valores ao lado do número de pedido de forma dinâmica, pois os números de pedidos podem váriar e a quantidade também. Isso é o que tem que estar no txt, não imprimir na tela.
Como preciso que fique:
2;500038;204932;61312;FTE GAV EDIT LACAVA TOTAL LARGXALTX15 GAV. NORMAL;LACA BLU FOSCO#996#335;5;78101922;xxxxxxx;0204932005
2;500038;204932;61312;FTE GAV EDIT LACAVA TOTAL LARGXALTX15 GAV. NORMAL;LACA BLU FOSCO#696#166;12;xxxxxxx;0204932012
4;100398;204932;50384;CJTO OPC LAT DIR/ESQ ARMARIO 30XALTXPROF;MDF BP LEGGERO#1040#340;74;78728780;xxxxxxx;0204932074
4;100398;204932;50385;CJTO OPC BASE SUP/INF RETA ARM LARGX30XPROF;MDF BP LEGGERO#769#340;71;78728777;xxxxxxx;0204932071
4;100398;204932;61108;FTE GAV EDIT ALCA LARGXALTX18 GAV. QUAD;LEGGERO#696#164;77;78728783;xxxxxxx;0204932077
4;100398;204932;50057;PAI OPC EDIT LARGXALTX15;LEGGERO#2610#100;39;78728745;xxxxxxx;0204932039

Answer: O seu valor saiu um pouco diferente do que citou, aqui apareceu assim:
array(2) {
  ["500038;204932"]=>
  int(2)
  ["100398;204932"]=>
  int(4)
}

Acho que tem várias maneiras de fazer isto, uma que pode usar é o explode como limitador, ou um simples str_replace:
<?php
$valoresStr = '500038;204932
500038;204932
100398;204932
100398;204932
100398;204932
100398;204932';

$arrayTemp = explode(chr(10), trim($valoresStr));

$arrayValores = array_count_values($arrayTemp);

var_dump($arrayValores);

foreach ($arrayValores as $valor => $soma) {
    $valoresStr = str_replace($valor, $soma . ';' . $valor, $valoresStr);
}

echo PHP_EOL;

echo $valoresStr;

Veja que troquei $valor por $soma . ';' . $valor, isso quer dizer que adicione o prefixo como sendo o valor da soma, claro que isto irá funcionar para o seu exemplo, agora não sei afirmar se haverá variações após o ; disto 500038;204932, por exemplo isto 500038;2000001
Exemplo online: http://ideone.com/wDGpXc
Comment: Antes de armazenar já dei um `explode` nos delimitadores que são `;`. Esqueci de mencionar. Por isso que já saiu assim `Array
(
    [500038] => 2
    [100398] => 4
)`
Comment: @Kevin.F posta então o código na pergunta de maneira que possamos entender, por favor
Comment: Sua resposta não deu a resposta para mim mas eu consegui fazer, sua resposta clareou as coisas.
Comment: @Kevin.F não deu certo porque o exemplo na sua pergunta esta incompleto, se colocar completo eu conseguirei formular da maneira que você precisa. Teu exemplo atualizado continua saindo diferente
Comment: Então, coloquei todo meu código e toda as informações que possui o `txt` vê se agora está melhor para entender.
Comment: @Kevin.F agora ficou melhor, vou tentar ajustar o exemplo.


Sum function for power series

Question: I have the series $\sum_{n=0}^{\infty}\frac{n}{n+1}x^n$. It is convergent for $-1<x<1$.
I want to find the sum function. I've tried the following:
\begin{align*}
\sum_{n=0}^{\infty} x^n &\sim \frac{1}{1-x}\\
\sum_{n=0}^{\infty} \frac{x^{n+1}}{1+n}&\sim -\log(1-x)&\text{Integrating both sides}\\
\sum_{n=0}^{\infty} \frac{x^{n}}{1+n}&\sim-\frac{\log(1-x)}{x}&\text{Divide with $x$}\\
\sum_{n=0}^{\infty}\frac{nx^{n-1}}{1+n}&\sim\frac{1}{(1-x)x}+\frac{\log(1-x)}{x^2}&\text{Derivative with respect to $x$}\\
\sum_{n=0}^{\infty}\frac{nx^{n}}{1+n}&\sim\frac{1}{(1-x)}+\frac{\log(1-x)}{x}&\text{Multiply by $x$}
\end{align*}
I can't decide on what to do from this point. I seem to miss the $n$ in the nominator, but changing index does not really help med out. Can you point me in the right direction?
Edit: I used the tips and finished it. Thank you.
Comment: Seems like a good start.  divide by $x$ to get $-\frac {\log (1-x)}x=\sum \frac {x^n}{1+n}$.  Now differentiate and correct the power of $x$.
Comment: Differentiate first, multiply by $x$, then integrate.
Comment: Thank you for the tips.
Comment: Another one: https://math.stackexchange.com/q/2217289.
Answer: If your function is $f(x)$, then $xf(x)=\sum_{n=1}^\infty\frac n{n+1}x^{n+1}$ and therefore its derivative is$$\sum_{n=1}^\infty nx^n=x\sum_{n=1}^\infty nx^{n-1}=x\left(\sum_{n=1}^\infty x^n\right)'.$$Can you take it from here?

Sum function for power series


Por que Python tem números tão grandes?

Question: Qual seria o maior número em python? Python mostra o resultado de expressões como:
>>> 8**150000

O resultado teve 135465 dígitos! Queria saber a linguagem consegue fazer isso.
Comment: https://www.reddit.com/r/Python/comments/2bbbvk/how_does_python_handle_bignum_arithmetic/
Answer: Python é uma linguagem de script, portanto o que importa para ela é ser fácil, é entregar o que o programador pede sem criar dificuldades. Não importa eficiência ou qualquer outro aspecto.
O computador precisa de espaço determinado para representar tipos porque a memória é um local de armazenamento com espaço delimitado. É física, para poder colocar algo em algum lugar precisa saber o tamanho a ser reservado.
Para ser eficiente uma linguagem precisa ter tipos que ocupam pouco espaço porque grande parte das operações exigem bem pouco. Ao mesmo tempo precisa ter tipos diferentes que ocupam muito espaço porque algumas operações precisam de dados muito grandes.
Quando a eficiência não importa, uma das técnicas possíveis é só ter um tipo que ocupa muito espaço podendo armazenar grandes números, mesmo que não use na maioria das vezes.
Mas por mais que você reserve espaço ainda pode faltar em certas situações, e a reserva de algo muito grande pode inviabilizar o uso, não só tornar ineficiente. Então precisa de uma outra técnica que aceite números pequenos e grandes de forma flexível, elástico.
Da mesma forma que Python criou uma infraestrutura para lidar com variáveis que podem ter dados de tipos diferentes (tamanhos arbitrários), apesar disso não ser possível de forma direta no computador, a linguagem também criou uma forma do número aceitar tamanhos arbitrários. Há um mecanismo que controla isso e vai aumentando o tamanho do número possível conforme vai tendo necessidade. Obviamente que isso tem um overhead de memória e de processamento, mas não importa para a linguagem. Isso se dá com alguma forma de indireção.
Enquanto em muitas linguagens a tipagem é eficiente e simples, igual ao que o computador precisa, obrigando o programador lidar com o tipo certo de acordo com o que precisa, em Python tem algo complexo internamente para facilitar a vida do programador.
Na verdade as outras linguagens costumam ter em sua biblioteca uma infra semelhante para lidar com números de tamanho arbitrários, mas você só usa se precisar, em Python você paga o preço dele sempre.
Mecanismo
A técnica mais usada para obter isso é semelhante de um array, ou uma string, que não deixa de ser um array. O número é decomposto em partes, então cada elemento do array vai sendo uma das partes.
Vamos dizer que a estrutura interna fosse um array de bytes (pode usar algo maior para mais eficiência, eu usaria um long ou talvez um int mas provavelmente não), até 256 inteiros precisa só de 1 byte (mais o custo extra para controlar o tamanho e possivelmente outras questões), se for até 65536 precisa de 2 bytes, até cerca de 16 milhões precisa de 3 bytes, e 4 bilhões precisa de 4, e por volta de 1 trilhão precisa de 5, e assim por diante. E vai lidar se tem sinal, sem tem parte decimal e quantas.
Todas operações matemáticas consideram essa construção complexa e olha tudo isso quando faz a conta.
Deve imaginar que se o número mudar e o seu tamanho, também é necessário copiar ele para outro lugar para caber o novo número, mas como há uma indireção, o acesso é feito normalmente sem dificuldades, apenas tem um processamento a mais.
Conclusão
Um dos segredos da programação é criar abstrações em cima de coisas complexas. Você usa o simples enquanto tem todo um maquinário por baixo do capô. Nada de errado nisso em certos cenários, mas quando a pessoa não entende essas coisas acaba-se criando uma horda de pseudo programadores, que não é um problema para a maior base de usuários de Python.
Se tiver interesse pode ver o código fonte que cuida disso tudo.
Coloquei no GitHub para referência futura.

Por que Python tem números tão grandes?


Getting none-English character from query string

Question: I have this in my querystring - sug_zehut=ז
(ז is a Hebrew letter)
Although I'm well aware that this is bad practice, I have to receive it like so in my query string (not my code..)
When I write it to a hidden I get sug_zehut=%EF%BF%BD as a part of the querystring, and when I try to put it in a string and put that in a hidden, I get � (I found here that those two are the same).
Anyhow, the question is - How do I get the value ז to my variable?
(I'm using .net version 4)
Thanks.
Comment: May this help you:

http://stackoverflow.com/questions/2742852/unicode-characters-in-urls
Comment: _"When I write it to a hidden"_ - You really should post some code. Are you working between Unicode in JavaScript and UTF-8? There are built in ways of handling this `encodeURIComponent` but it depends on from where to where. If you want an answer, post a snippet of code which reproduces the problem.
Answer: %EF%BF%BD is the code of � sumbol. That's mean your server don't know this character because of you sent symbol in one encoding and try get it as UTF-8.
Try to set up utf-8 encoding in every place (at least for testing of the problem):

In web.config
http://msdn.microsoft.com/en-us/library/ydkak5b9(v=vs.71).aspx
In the page
<meta charset="utf-8"> vs <meta http-equiv="Content-Type">
Change real file encoding if you directly set up your symbol (.cs,
.cshtml, .aspx, .js, ...)

If it's not working that please tell me how do you get this url and navigate on it?
Comment: It also looks like , as OP is talking about hidden field , browser is also needs to be set to UTF-8 Encoding I guess , right ?
Answer: Here's a small function to convert your character to an HTML encoded version (ז in this case). HtmlEncode won't do it for you in most versions of .net, unfortunately.
<code>private static string UnicodeConvertChar(char input)
{
    if (input > 159)
    {
        return "&#" + ((int)input).ToString() + ";";
    }
    else
    {
        return input.ToString();
    }
}
</code>
You can convert it before setting it in your hidden field, and then when you get it back, you can simply read it by using HttpUtility.HtmlDecode.
Here's a dotnetfiddle for you to play around with it:
https://dotnetfiddle.net/jbDY0V


Creating dummy from multiple xts objects

Question: I have multiple xts objects which are all indicators if a stock is above or below a certain median value. These list are structured the following way the size variable is S or B the value variable is H or L and the momentum variable is D or U. This is what part of my three xts objects look like
 `         NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 "B"  "B" "B"  "S"  "S"  "B"  NA
1990-01-01 "B"  "B" "B"  "B"  "S"  "B"  NA`

           NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 "H"  "L" "L"  "H"  "L"  "L"  NA
1990-01-01 "H"  "H" "L"  "H"  "L"  "L"  NA

          NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 "D"  "U" "U"  "D"  "D"  "D"  NA
1990-01-01 "D"  "U" "D"  "D"  "D"  "U"  NA

Now i want to generate a new list which takes these three lists into account so that I can create a dummy variable equal to 1 when for example a stock is in S, L and D. The result would look something like this:
           NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 NA  NA   NA   NA   1    NA   NA
1990-01-01 NA  NA   NA   NA   1    NA   NA

I have tried the following:
SLD_dummy <- ifelse(big_small=="S" & high_low=="L" & up_down=="D",1,NA)

However, I get the following error:
Error in `[.xts`(x, i, which.i = TRUE) : subscript out of bounds

Does anybody know how I can get the desired results? Thanks in advance for your help.
Answer: You could use replace on your xts object:
library(xts)
library(magrittr)
big_small <- as.xts(read.table(text='       NESN ROG NOVN ZURN ABBN UBSG LONN
                   1989-12-01 "B"  "B" "B"  "S"  "S"  "B"  NA
                   1990-01-01 "B"  "B" "B"  "B"  "S"  "B"  NA'))

high_low <- as.xts(read.table(text='       NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 "H"  "L" "L"  "H"  "L"  "L"  NA
1990-01-01 "H"  "H" "L"  "H"  "L"  "L"  NA'))

up_down <- as.xts(read.table(text='        NESN ROG NOVN ZURN ABBN UBSG LONN
1989-12-01 "D"  "U" "U"  "D"  "D"  "D"  NA
1990-01-01 "D"  "U" "D"  "D"  "D"  "U"  NA'))

m <- big_small=="S" & high_low=="L" & up_down=="D"
replace(m, m==T, 1) %>% replace(., m==F, NA)
#>            NESN ROG NOVN ZURN ABBN UBSG LONN
#> 1989-12-01   NA  NA   NA   NA    1   NA   NA
#> 1990-01-01   NA  NA   NA   NA    1   NA   NA

Created on 2021-05-22 by the reprex package (v2.0.0)
(or do m[m==TRUE] <- 1; m[m==FALSE] <- NA)
Comment: Thank you this is exactly what I was looking for I didn't know that you could combine xts objects with an &
Answer: We could also do this with Map/Reduce in base R (used R 4.1.0)
library(xts)
Map(`==`, list(big_small, high_low, up_down), c('S', 'L', 'D')) |>
    {\(x) Reduce(`&`, x)}() |>
    {\(x) NA^(!x)}()

-output
#          NESN ROG NOVN ZURN ABBN UBSG LONN
#1989-12-01   NA  NA   NA   NA    1   NA   NA
#1990-01-01   NA  NA   NA   NA    1   NA   NA

data
big_small <- structure(c("B", "B", "B", "B", "B", "B", "S", "B", "S", "S",
"B", "B", NA, NA), .Dim = c(2L, 7L), .Dimnames = list(NULL, c("NESN",
"ROG", "NOVN", "ZURN", "ABBN", "UBSG", "LONN")), index = structure(c(628491600,
631170000), tzone = "", tclass = c("POSIXct", "POSIXt")), class = c("xts",
"zoo"))

high_low <- structure(c("H", "H", "L", "H", "L", "L", "H", "H", "L", "L",
"L", "L", NA, NA), .Dim = c(2L, 7L), .Dimnames = list(NULL, c("NESN",
"ROG", "NOVN", "ZURN", "ABBN", "UBSG", "LONN")), index = structure(c(628491600,
631170000), tzone = "", tclass = c("POSIXct", "POSIXt")), class = c("xts",
"zoo"))

up_down <- structure(c("D", "D", "U", "U", "U", "D", "D", "D", "D", "D",
"D", "U", NA, NA), .Dim = c(2L, 7L), .Dimnames = list(NULL, c("NESN",
"ROG", "NOVN", "ZURN", "ABBN", "UBSG", "LONN")), index = structure(c(628491600,
631170000), tzone = "", tclass = c("POSIXct", "POSIXt")), class = c("xts",
"zoo"))


Interpreting overlapping arrows on a PCA biplot: does it mean that the variables are redundant?

Question: I'm new in principal component analysis (PCA) and I don't really understand the biplot representation of its results, so I would really appreciate some guidance. Having the example of the illustration shown below. Could I say that variables x1 and x2 are telling me the same, and so there is no need to record the values of one of the two?
In my case variables are geometrical deviations of a part where the points measured are close to each other. Therefore, I would like to know if based on the PCA biplot I could stop measuring the values for x2 if I already measured x1 values.
Comment: This Q asks a specific question about variable redundancy. I don't think it's a duplicate.
Comment: I think it is a duplicated question, can you check this [post](http://stats.stackexchange.com/questions/66926/what-are-the-four-axes-on-pca-biplot/218839#218839)
Comment: http://stats.stackexchange.com/q/224204/3277 is theoretically a similar question (see).
Answer: X1 and X2 are "redundant" in the sense of linear duplicates of each other if they correlate perfectly ($r=1$). Then the two variable vectors must coincide, be collinear in the space (that space - where variables are drawn as vectors, arrows - is called "subject space").
But from the plot, without knowing the variable correlations, you can't tell if the vectors coincide in the space - because the plot is only 2-dimensional whereas the space spanned by the four variables is potentially 4-dimensional (or 3-dimensional, in case X1 and X2 do coincide). The plot's plane defined by the first two PCs is the subspace within that 4 (or 3) dimensional space. For what we see as arrows on the plane are just the projections of the true variable vectors on it, shades cast on it by them. What I'm saying is expressed more graphically and with formulas here. Thus, having only your plot, the question whether X1 and X2 coincide or not is yet open.
But, suppose a case that the two PCs explain lion's share of the variability (say, 80% or more of the overall variance). That will mean that the subsequent dimensions (defined by PC3 and PC4) are shallow, so the space is not far to be just the plane you showed. Then the angle between X1 and X2 (which cosine is their correlation) won't be able to be wide. But this is to say that the two variables are not far from being collinear anyway. If so (i.e. little variance left unexpained by PC1+PC2), you may regard X1 and X2 as reasonably redundant.
Finally, if they do coincide or near coincide and therefore redundant for you, could I stop measuring the values for x2 if I already measure x1 values? - you ask. That depends on what you are going to do next after the deletion of one of the two variables. If, for example, you delete the one and go to redo PCA - the PCs will change despite that you deleted a "redundant" measurement.


Laravel Upgrading To 5.2.0 From 5.1 error

Question: Getting the error on composer update command.

My composer.json file is:
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "illuminate/html": "^5.0",
        "barryvdh/laravel-debugbar": "~2.0",
        "spatie/laravel-paginateroute": "^2.0",
        "darkaonline/l5-swagger": "~2.0",
        "yajra/laravel-datatables-oracle": "~5.0",
        "phpoffice/phpexcel": "^1.8"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1",
        "symfony/dom-crawler": "~3.0",
        "symfony/css-selector": "~3.0"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "files": ["app/Helpers/helpers.php"],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

Answer: You need to remove this outdated package (taken out of the core and no longer supported):
"illuminate/html": "^5.0",

When you remove it, you need to also remove its service providers / aliases. So, if you open up config/app.php, you will see a providers and aliases section. Remove these lines of code if you haven't done so already.
'Illuminate\Html\HtmlServiceProvider'

'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',

In place of it, you should install the Laravel collective package. To install that, replace the illuminate/html package with this:
"laravelcollective/html": "5.2.*"

Then in your config/app.php file, add this to your providers array:
Collective\Html\HtmlServiceProvider::class

and this to your aliases array:
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,

The docs can be found here: https://laravelcollective.com/docs/5.2/html
Comment: If you are still getting errors, just put a caret before the version number:
`"laravelcollective/html": "^5.4.6"`
Comment: where do i put "laravelcollective/html": "^5.4.6" ?
Answer: Look at this
https://laracasts.com/discuss/channels/laravel/call-to-undefined-method-illuminatefoundationapplicationbindshared
Quote "bindShared has been renamed to $app->singleton()"
[Edit]
I think you have something is your own custom code what need to be changed from : $this->app->bindShared() to: $this->app->singleton().
Answer: I solved it by the steps mentioned in Link1 Link2
After the upgrade please make sure all the Deprecations mentioned in Link2 are corrected in your current app. For me Illuminate\Contracts\Routing\Middleware had to be removed from all the Middlewares.
Also I had to install latest version of certain packages like "yajra/laravel-datatables-oracle": "~6.1.1",


searching from database with zend search lucene

Question: I am developing a social network kind of web application. I want to enable my users to search for people. As I am using Zend framework, Zend search lucene looks like a nice choice to create search functionality but there is no tutorial on web that can suit my needs. Is zend search written for searching from web pages only? Should I use Zend search or I should use simple like query and create the entire functionality my self?
Answer: Zend_Lucene is meant for every possible data . When you got raw data (like from database without in a special format .html or .doc) then you need to build your own document yourself . Which is good thing since it gives you lot more options
consider you got User table
<code><<User>>
*user_id
*email
*first_name
*last_name
*password

$userTb = new Default_Model_DbTable_User();
$index = Zend_Search_Lucene::create('/data/my-index');
$users = $userTb->fetchAll();
foreach($users as $user)
{
  $doc = new Zend_Search_Lucene_Document();
  $doc->addField(Zend_Search_Lucene_Field::Text('email', $user->email)); //here field = ur database column
  $doc->addField(Zend_Search_Lucene_Field::Text('first_name',$user->first_name));
  $index->addDocument($doc);

}
</code>


plotly with Python - limits of Gantt Chart

Question: I have a dataframe like this which is an application log:
+---------+----------------+----------------+---------+----------+-------------------+------------+
|  User   | ReportingSubId | RecordLockTime | EndTime | Duration | DurationConverted | ActionType |
+---------+----------------+----------------+---------+----------+-------------------+------------+
| User 5  |             21 | 06:19.6        | 06:50.5 |       31 | 00:00:31          | Edit       |
| User 4  |             19 | 59:08.6        | 59:27.6 |       19 | 00:00:19          | Add        |
| User 25 |             22 | 29:09.4        | 29:37.0 |       28 | 00:00:28          | Edit       |
| User 10 |             19 | 28:36.9        | 33:37.0 |      300 | 00:05:00          | Add        |
| User 27 |             22 | 13:27.7        | 16:54.9 |      207 | 00:03:27          | Edit       |
| User 5  |             21 | 11:22.8        | 12:37.3 |       75 | 00:01:15          | Edit       |
+---------+----------------+----------------+---------+----------+-------------------+------------+

I wanted to visualize the duration of adds and edits for each user, ad Gantt Chart seemed ideal for me.
I was able to do it for a sample dataframe of 807 rows with the following code:
data = []

for row in df_temp.itertuples():
    data.append(dict(Task=str(row.User), Start=str(row.RecordLockTime), Finish=str(row.EndTime), Resource=str(row.ActionType)))

colors = {'Add': 'rgb(110, 244, 65)',
          'Edit': 'rgb(244, 75, 66)'}

fig = ff.create_gantt(data, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True)

for i in range(len(fig["data"]) - 2):
    text = "User: {}
Start: {}
Finish: {}
Duration: {}
Number of Adds: {}
Number of Edits: {}".format(df_temp["User"].loc[i],
                                                                                df_temp["RecordLockTime"].loc[i],
                                                                                df_temp["EndTime"].loc[i],
                                                                                df_temp["DurationConverted"].loc[i],

                                                                                counts[counts["User"] == df_temp["User"].loc[i]]["Add"].iloc[0],
                                                                                counts[counts["User"] == df_temp["User"].loc[i]]["Edit"].iloc[0])
    fig["data"][i].update(text=text, hoverinfo="text")

fig['layout'].update(autosize=True, margin=dict(l=150))
py.iplot(fig, filename='gantt-group-tasks-together', world_readable=True)

and I am more than happy with the result : https://plot.ly/~pawelty/90.embed
However my original df has more users and 2500 rows in total. That seems to be too much for plotly. I get 502 error.
I am a huge fan of plotly but I might have reached it's limit. Can I change something in order to visualize it with Plotly ? Any other tool I could use?
Comment: Have you tried running it on your computer rather than sending it to plotly for the visualization?
Comment: Hmm I run it in Jupyter Lab and got the same result.
Comment: What module are you using that is being called `ff`?
Comment: I am following https://plot.ly/python/gantt/ the section about grouping tasks. The module is called plotly.figure_factory
Comment: I can't find any limits on the functions within the [source code](https://github.com/plotly/plotly.py/blob/master/plotly/figure_factory/_gantt.py). Would you happen to know if you are using any part of the plotly API? If you are getting a 502 error, it seems like it might be on plotly's side. I'd check out matplotlib as an alternative. See [this answer](https://stackoverflow.com/questions/31820578/how-to-plot-stacked-event-duration-gantt-charts-using-python-pandas).
Comment: Yeah but with Matplotlib I lose all the interactivity and sharing possibilities. Thanks for your help anyway.
Comment: Can it be a limitation of a free account?
Answer: I started using plotly.offline.plot(fig) to plot offline and it worked much faster and I got less errors. I also have the problem that my graph doesn't get displayed or sometimes only in fullscreen mode...
I import plotly instead of plotly.plotly though, otherwise it doesn't work.


How do I add default header and footer regions to my site?

Question: i have added regions in my theme.info file. now i want to add default header and footer with logo in all the pages of my site.This is my page.html.twig

    {{ page.header }}

  {{ page.primary_menu }}
  {{ page.secondary_menu }}

  {{ page.breadcrumb }}

  {{ page.highlighted }}

  {{ page.help }}

    {# link is in html.html.twig #}

      {{ page.content }}

{# /.layout-content #}

    {% if page.sidebar_first %}

        {{ page.sidebar_first }}

    {% endif %}

    {% if page.sidebar_second %}

        {{ page.sidebar_second }}

    {% endif %}

  {% if page.footer %}

      {{ page.footer }}

  {% endif %}

{# /.layout-container #}

I have placed files region--header.html.twig and region--footer.html.twig .Please help me how to place logos and other contents in header and footer
Answer: You define a region in your theme's info file and then print it in your page.html.twig. Content to each region is added via blocks. You only add your own region templates when you need to make some changes to the markup.

OK, so you added the regions in your info file, and printed them in your page template, fine. First of all, delete your region--header.html.twig and region--footer.html.twig again. Then in the backend of your site go to Structure > Blocks. Your newly added regions should appear there. Now place some blocks in your newly added regions. Save, flush cache and visit your frontend again. Your regions should be populated now.
And regarding the region--YOURREGION.html.twig templates you should have deleted by now, these only will be picked up when these regions are populated – with blocks. Otherwise these regions simply won't get printed at all.


Angularjs + UnitTest BeforeEach Inject not Executing

Question: I am trying to write an angularjs spec, but the beforeEach Inject block is not being executed, leaving my test services undefined
describe 'VodAssetsTriageController', ->
  $charterModal = null
  controller = null
  FieldService = null
  $q = null
  $rootScope = null
  $scope = null
  VodAssetsService = null
  PidService =
    getPids: _.noop
  AdiSearchService =
    getHeadEnds: _.noop

  beforeEach module('alphonso', ($provide) ->
    $provide.factory 'AdiSearchService',
      $get: -> AdiSearchService
    $provide.factory 'PidService',
      $get: -> PidService
  )

  beforeEach inject ($controller, _VodAssetsService_, _VodAssetsFieldService_,            _$charterModal_, _$q_, _$rootScope_, _AdiSearchService_, _PidService_) ->

     controller = $controller
     $charterModal = _$charterModal_
     VodAssetsService = _VodAssetsService_
     FieldService = _VodAssetsFieldService_
     $q = _$q_
     $rootScope = _$rootScope_
     $scope = $rootScope.$new()
     AdiSearchService = _AdiSearchService_
     PidService = _PidService_

     result =
      content: []
     spyOn PidService, 'getPids'
      .and.returnValue $q.when(result)
     spyOn AdiSearchService, 'getHeadEnds'
      .and.returnValue $q.when(result)

     controller = controller 'VodAssetsTriageCtrl',
      VodAssetsService: VodAssetsService,
      VodAssetsFieldService: FieldService,
      $scope: $scope,
      $charterModal: $charterModal

     installPromiseMatchers()

  describe 'controller.paginate.onChange()', ->
    result = null
    searchDeferred = null

    beforeEach ->
      page =
        size: 1000
        totalElements: 179000
      response =
        content: []
        number: 0
        page: page
      result =
       response: response
      searchDeferred = $q.defer()
      spyOn VodAssetsService, 'getAll'
        .and.returnValue searchDeferred.promise
      $scope.searchVm =
        doSearch: () -> controller.search()

    it 'should invoke controller.paginate.onChange() on search() invocation', ->
      controller.search controller
      expect controller.paginate.loading
       .toBeTruthy()

      spyOn controller.paginate, 'onChange'
      promise = searchDeferred.resolve(result)
      $rootScope.$apply()

      expect promise
        .toBeResolvedWith response
      expect vm.paginate.totalElements
        .toBe 179
      expect controller.page
        .toBe result.response.page.number
      expect controller.size
        .toBe result.response.page.size
      expect controller.paginate.loading
        .toBeFalsy()
      expect controller.paginate.onChange
        .toHaveBeenCalled()

    it 'should page to vm.paginate.page = 1', ->
      controller.paginate.page = 1
      controller.paginate.cache[0] = _.range 0, 1000
      spyOn $scope.searchVm, 'doSearch'
      controller.paginate.onChange()

      expect vm.page
        .toBe 1
      expect $scope.searchVm.doSearch
        .not.toHaveBeenCalled()
      expect controller.vodAssets.length
        .toBe vm.paginate.size

When I execute the code I am getting the following errors

Blockquote
      Error: [ng:areq] Argument 'fn' is not a function, got Object
      http://errors.angularjs.org/1.4.8/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20Object in /Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js (line 1815)
      assertArg@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:1815:91
      assertArgFn@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:1825:12
      annotate@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:3810:16
      $$annotate@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular-mocks/angular-mocks.js:2222:41
      invoke@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:4501:46
      /Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:4344:85
      forEach@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:340:24
      createInjector@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular/angular.js:4344:10
      workFn@/Users/rbrooks3/sandbox/alphonso-web/bower_components/angular-mocks/angular-mocks.js:2428:60
      TypeError: null is not an object (evaluating '$q.defer') in /Users/rbrooks3/sandbox/alphonso-web/src/app/components/vod-assets-triage/vod-assets-triage.spec.js (line 34)
      /Users/rbrooks3/sandbox/alphonso-web/src/app/components/vod-assets-triage/vod-assets-triage.spec.js:34:15

Does anyone know why the beforeEach inject function is not being called?
Answer: Here,
  beforeEach(module('alphonso', function($provide) {
    $provide.factory('AdiSearchService', {
      $get: function() {
        return AdiSearchService;
      }
    });
    return $provide.factory('PidService', {
      $get: function() {
        return PidService;
      }
    });
  }));

module config function shouldn't return anything, and it returns an object.
Also, it obviously should be $provide.provider and not $provide.factory, short syntax for service mocking is
  beforeEach(module('alphonso', function($provide) {
    $provide.factory('AdiSearchService', {
      AdiSearchService: AdiSearchService,
      PidService: PidService
    });
  }));


Selecionar mais de uma opção com checkbox estilizado

Question: Estou usando alguns checks estilizados para marcar alguns tamanhos de alguns produtos em um filtro, vendo pelo inspeção do chrome os checks estão lá ao clicar o filtro é realizado, mas na visualização normal não consegui deixar os checks como marcados, não sei onde posso estar errando.
Nessa imagem os checks estão estilizados mas não consigo marcar nenhum e o filtro não é acionado.

Nessa outra imagem, pelo inspetor, consigo ver os checks e se marcar o filtro é realizado.

O site pode ser visto aqui:
Site em desenvolvimento
Comment: Tive que ir no histórico das edições pra ver rss...
Comment: Minha mulher veio aqui reclamar que agora tem mulher *pelada* no meu "joguinho" :/
Comment: hahaha, vc coloca uma mulher desse jeito e quer que alguém veja checkboxes?
Comment: essa imagem foi _troll_, hein.. meu chefe levantou pra ver que site eu estou acessando =D
Comment: Desculpa ai pessoal, nem me toquei da foto.
Comment: E estado "checado" seria o contorno Preto ao redor do elemento?
Comment: Olá @LeoCaracciolo, veja na segunda imagem, que desmarquei o display:none do input.
Comment: Pronto, "problema" da foto resolvido.
Comment: Seria isso mesmo @hugocsl, podendo selecionar mais de um check, mas não consegui.
Comment: Creio que terá que fazer isso via JS. Serve?
Comment: Com CSS só vejo uma forma, e vc tera que tirar o checkbox de dentro do A, e passar o efeito da LI para o A, assim vc faz no css input:checked+a  e coloca a classe
Comment: Olá @sam, nem assim eu consegui, será muito bem vinda.
Answer: Fiz uma simulação aqui tentando aproveitar o máximo do seu código. Porém vc precisa fazer algumas mudanças moderadas na sua estrutura do HTML e não sei se isso seria adequado nessa etapa do projeto...
Primeiro vc que para selecionar o checkbox clicando em algum elemento esse elemento deve ser uma  com o atributo for="idDoCheckbox" e vc tem que passes os estilos CSS da
 para esse label dentro do , além disso o checkbox deve vir antes do
Para entender melhor veja o exemplo abaixo.

.sidepanel {
    margin: 0 0 10px;
    padding: 14px 18px 7px;
    border: 2px solid #ccc;
}
.widget_sized ul {
    padding-bottom: 13px;
}
.widget_sized li {
    display: inline-block;
    vertical-align: top;
}
.widget_sized a label {
    box-sizing: border-box;
    width: 40px;
    height: 30px;
    display: block;
    text-transform: uppercase;
    text-align: center;
    line-height: 28px;
    font-size: 11px;
    font-weight: bold;
    color: #666;
    border: 1px solid #e9e9e9;
    transition: border 0.3s ease-in-out;
    -webkit-transition: border 0.3s ease-in-out;
    cursor: pointer;
}

.widget_sized a label:hover {
    color: #333;
    border: 1px solid black;
}
.widget_sized input[type="checkbox"]:checked + a > label {
    border: 1px solid black;
}
.widget_sized input[type="checkbox"] {
    display: none;
}
.widget_sized a {
    text-decoration: none;
}

   <input type="checkbox" id="id1" class="item_filter size" value="10">

    46

   <input type="checkbox" id="id2" class="item_filter size" value="10">

    48

Comment: Olá Hugo, esse  precisa ser dinâmico?
Comment: Não necessariamente... mas vc só pode ter um for="" para um id="" único, então se vc tem 10 inputs vc precisa de 10 ids diferentes e 10 labels diferentes com um for= para o ID correspondente. Aqui tem uma material sobre os IDs que pode te interessar https://pt.stackoverflow.com/questions/318255/por-que-é-considerado-errado-ruim-repetir-uma-id-em-html/ e se tiver mais alguma dúvida é só dar o toque
Comment: Olá Hugo, agora é coisa simples, como posso deixar as linhas, tanto quando passo o mouse e quando seleciono iguais, alterei e não deu certo, tipo, mais fininhas.
Comment: @adventistapr Vc queria deixar a linha so selecionado mais fina é isso? Aqui na resposta eu já editei e coloquei com 1px. Mas ai no seu projeto veja se vc não deixou algum CSS para traz sobrescrevendo esse estilo. Ou então coloca !importatnt no atributo border em último caso... Mas em 30 min vou estar em casa, eu vou dar uma refinada nesse CSS, pq eu peguei direto do link que vc postou na pergunta. Deve ter algum CSS redundante ai atrapalhando o que vc quer fazer.
Comment: @adventistapr cara dei uma formatado nos estilos do CSS da resposta e deixei só o essencial. Outra coisa! Dei uma olhada lá no seu site do link, e reparei que vc ainda está com parte do CSS antigo funcionando em paralelo com esse da resposta. Inclusive a LI ainda está com a borda, acho que é essa borda que vc quer remover `.widget_sized li:hover, .widget_sized li.active { border: 2px solid #333; }`
Comment: Será que posso trocar uma ideia no chat, coisa rápida, mas não sei como fazer
Comment: Chama ai, só que só devo ter un 15 min pra te ajudar pq minha noiva ta chegando na área... Mas pergunta lá que na medida do possível vou te respondendo
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/83044/discussion-between-adventistapr-and-hugocsl).


Comparing levels of factors after a GLM in R

Question: Here is a little background about my situation: my data refer to the number of prey successfully eaten by a predator. As the number of prey is limited (25 available) in each trial, I had a column "Sample" representing the number of available prey (so, 25 in each trial), and another called "Count" which was the number of success (how many prey were eaten). I based my analysis on the example from the R book on proportion data (page 578).  The explanatory variables are Temperature (4 levels, which I treated as factor), and Sex of the predator (obviously, male or female). So I end up with this model:
model <- glm(y ~ Temperature + Sex + Temperature*Sex,
          data=predator, family=quasibinomial)

After getting the Analysis of Deviance table, it turns out that Temperature and Sex (but not the interaction) have a significant effect on the consumption of prey. Now, my problem: I need to know which temperatures differ, i.e., I have to compare the 4 temperatures to each other. If I had a linear model, I would use the TukeyHSD function, but as I am using a GLM I can't. I have been looking through the package MASS and trying to set up a contrast matrix but for some reason it doesn't work. Any suggestions or references?
Here's the summary I get from  my model, if that helps making it clearer ...
y <- cbind(data$Count, data$Sample-data$Count)
model <- glm(y ~ Temperature + Sex + Temperature*Sex,
             data=predator, family=quasibinomial)
> summary(model)

# Call:
# glm(formula = y ~ Temperature + Sex + Temperature * Sex,
       family=quasibinomial, data=data)

# Deviance Residuals:
#     Min       1Q   Median       3Q      Max
# -3.7926  -1.4308  -0.3098   0.9438   3.6831

# Coefficients:
#                                        Estimate Std. Error t value Pr(>|t|)
# (Intercept)                             -1.6094     0.2672  -6.024 3.86e-08 ***
# Temperature8                             0.3438     0.3594   0.957   0.3414
# Temperature11                           -1.0296     0.4803  -2.144   0.0348 *
# Temperature15                           -1.2669     0.5174  -2.449   0.0163 *
# SexMale                                    0.3822     0.3577   1.069   0.2882
# Temperature8:SexMale                    -0.2152     0.4884  -0.441   0.6606
# Temperature11:SexMale                    0.4136     0.6093   0.679   0.4990
# Temperature15:SexMale                    0.4370     0.6503   0.672   0.5033
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

# (Dispersion parameter for quasibinomial family taken to be 2.97372)
#     Null deviance: 384.54  on 95  degrees of freedom
# Residual deviance: 289.45  on 88  degrees of freedom
# AIC: NA
# Number of Fisher Scoring iterations: 5

Comment: Why did you model `Temperature` as a factor? Don't you have the actual numerical values? I would use them as a continuous variable & then this entire issue is moot.
Comment: It's perfectly reasonable to want to know how to do this in general; your question stands. However, w/ regard to your specific situation, I would use temp as a continuous variable even if you had originally thought of it as a factor. Setting aside issues w/ multiple comparisons, modeling temp as a factor is an inefficient use of the info you have.
Comment: Hi @Anne and welcome. You can try to use the `glht` function in the [`multcomp` package](http://cran.r-project.org/web/packages/multcomp/multcomp.pdf). To perform TukeyHSD tests for temperature, use it like that `glht(my.glm, mcp(Temperature="Tukey"))`. And btw: Your model formula can be abbreviated to: `model<-glm(y ~ Temperature*Sex data=predator, family=quasibinomial)`. With the asterisk ($*$) the interactions *and* the main effects are fitted.
Comment: I am using Temperature as a factor because that is how I defined it in my experimental design. I guess it could be taken as a numerical value, but I would like to know how to solve my comparison problem on a factor all the same, as I might need it for further data (say, if I had "Substrate type" instead of Temperature).

* COOLSerdash, I don't know if my editing is what you were looking for as a "model output"... Tell me if I got it wrong and I'll make my best to fix it.
Comment: Hi, thanks for your quick reply ! However I must be doing something wrong because I only get an error message... I assume that my.glm is the glm I performed earlier (therefore, "model" in the case). What does mcp refer to ? I get an error message saying that the dimensions of coefficients and covariance matrix don't match... ?
Answer: Anne, I will shorty explain how to do such multiple comparisons in general. Why this doesn't work in your specific case, I don't know; I'm sorry.
Edit: Nowadays, I'd recommend using the emmeans package to do pairwise comparisons of the marginal means. Another possibility is the multcomp package and the function glht, which compares the coefficients of the main effects and not the marginal means. In the presence of an interaction, this makes less sens in my opinion. Here is an example:
mydata      <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
mydata$rank <- factor(mydata$rank)
my.mod      <- glm(admit~gre+gpa*rank, data=mydata, family=quasibinomial)

summary(my.mod)
#
# Coefficients:
#              Estimate Std. Error t value Pr(>|t|)
# (Intercept) -4.985768   2.498395  -1.996   0.0467 *
# gre          0.002287   0.001110   2.060   0.0400 *
# gpa          1.089088   0.731319   1.489   0.1372
# rank2        0.503294   2.982966   0.169   0.8661
# rank3        0.450796   3.266665   0.138   0.8903
# rank4       -1.508472   4.202000  -0.359   0.7198
# gpa:rank2   -0.342951   0.864575  -0.397   0.6918
# gpa:rank3   -0.515245   0.935922  -0.551   0.5823
# gpa:rank4   -0.009246   1.220757  -0.008   0.9940
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If you wanted to calculate the pairwise comparisons of the marginal means between the ranks using Tukey's HSD with emmeans, you could do that in this way:
library(emmeans)
em <- emmeans(my.mod, "rank")
contrast(em, "pairwise", adjust = "Tukey")

 contrast      estimate    SE  df z.ratio p.value
 rank1 - rank2    0.659 0.323 Inf   2.038  0.1739
 rank1 - rank3    1.296 0.358 Inf   3.620  0.0017
 rank1 - rank4    1.540 0.426 Inf   3.611  0.0017
 rank2 - rank3    0.637 0.291 Inf   2.190  0.1261
 rank2 - rank4    0.881 0.372 Inf   2.370  0.0830
 rank3 - rank4    0.244 0.401 Inf   0.608  0.9296

Results are given on the log odds ratio (not the response) scale.
P value adjustment: tukey method for comparing a family of 4 estimates

The function emmeans prints a warning that there are interactions present which may make the results misleading. For more information, the emmeans package offers a lot of tutorials (called vignettes).
Now let's compare the coefficients of the main effect for rank with multcomp:
library(multcomp)
summary(glht(my.mod, mcp(rank="Tukey")))

Fit: glm(formula = admit ~ gre + gpa * rank, family = quasibinomial,
    data = mydata)

Linear Hypotheses:
           Estimate Std. Error z value Pr(>|z|)
2 - 1 == 0   0.5033     2.9830   0.169    0.998
3 - 1 == 0   0.4508     3.2667   0.138    0.999
4 - 1 == 0  -1.5085     4.2020  -0.359    0.984
3 - 2 == 0  -0.0525     2.6880  -0.020    1.000
4 - 2 == 0  -2.0118     3.7540  -0.536    0.949
4 - 3 == 0  -1.9593     3.9972  -0.490    0.960
(Adjusted p values reported -- single-step method)

Warning message:
In mcp2matrix(model, linfct = linfct) :
  covariate interactions found -- default contrast might be inappropriate

All pairwise comparisons of the main effect for rank are given together with a $p$-value. Warning: These comparisons only concern the main effects. The interactions are ignored. If interactions are present, a warning will be given (as in the output above). For a more extensive tutorial on how to proceed when interactions are present, see these additional multcomp examples.
Note: As @gung noted in the comments, you should - whenever possible - include temperature as a continuous rather than a categorical variable. Concerning the interaction: you could perform a likelihood ratio test to check whether the interaction term significantly improves the model fit. In your case, the code would look something like that:
# Original model
model <- glm(y ~ Temperature+Sex+Temperature*Sex, data=predator, family=quasibinomial)

# Model without an interaction
model2 <- glm(y ~ Temperature+Sex data=predator, family=quasibinomial)

# Likelihood ratio test
anova(model, model2, test="LRT")

If this test is not significant, you may remove the interaction from your model. Maybe glht will work then?
Comment: Oh god, thank you SO much !! I have been able to write the command correctly this time and it worked ! Thanks again !
Comment: Additionnal question : is there a way to get multiple comparisons on the interaction ? I've got similar data, where the interaction (from the initial question, that would be Temperature*Sex) is significant, and I was wondering if it is possible to compare those together...
Comment: Do you mean multiple comparison for each level of the interaction? If yes, you might find [this site](http://www.ats.ucla.edu/stat/r/faq/testing_contrasts.htm) interesting (the last paragraph shows how to test all possible pairwise combinations).
Comment: @Nova which link do you mean? The one in the comments? [Here](https://stats.idre.ucla.edu/r/faq/how-can-i-test-contrasts-in-r/) is the new link to that site.
Comment: you can create a variable which corresponds to the interactions for a variable and use this variable to carry out the mcp. You do it like this. mydata\$gparank <- interaction(mydata\$gpa, mydata\$rank)
Comment: @COOLSerdash, that link no longer works - any idea where it is now?


Erro em JSON. O meu código não consegue ler o JSON

Question: Eu devo criar uma pagina que mostre um catálogo de álbuns fornecidos em xml. Daí tenho que transformar o catálogo.xml em JSON e mostrar ele em uma tabela com artista e com Título. O problema é que meu código não lê o documento pois fala que há tags inválidas.
Erro fornecido no Google Chrome: VM40:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
     at JSON.parse ()
     at myFunction (Teste.html:29)
     at XMLHttpRequest.xhttp.onreadystatechange (Teste.html:15)
myFunction @ Teste.html:29
xhttp.onreadystatechange @ Teste.html:15
XMLHttpRequest.send (async)
loadDoc @ Teste.html:19
onclick @ Teste.html:5
<!DOCTYPE html>

XMLHttpRequest

<button type="button" onclick="loadDoc()">Catálogo</button>

Answer: Não tem como usar JSON.parse para converter uma string XML em JSON.
Como você está recebendo um XML como resposta, troque o responseText por responseXML para que o retorno já venha parseado em formato XML, caso contrário virá como string.
Depois basta percorrer todas as tags ALBUM e pegar o texto da tag que você deseja e ir concatenando na variável table. Quando for fazer o innerHTML tem que fechar a tabela com
:
function loadDoc(){
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         myFunction(this);
      }
   };

   xhttp.open("GET",
   "http://clienteweb2017.000webhostapp.com/fundamentosWeb/paginaCatalogo.php",
   true);
   xhttp.send();
}

function myFunction(response) {
   var xmlDoc = response.responseXML;
   var table="

 Artist	Title
";

   var albuns = xmlDoc.getElementsByTagName("ALBUM");

   for (var i = 0; i <albuns.length;i++) {
      var art = albuns[i].querySelector("ARTIST").textContent;
      var tit = albuns[i].querySelector("TITLE").textContent;
      table += "
"+art+"	"
      +""+tit+"
";
   }

   document.getElementById("tabelaId").innerHTML = table+"
";
}

O resultado final será algo como:
Comment: Opa! É apenas um seletor. Vc pode selecionar a tag que quiser.
Comment: Orbigado pela resposta. Fiquei com uma dúvida quanto a um trecho do código. Gostaria de saber o que exatamente esse query selector faz. Ele interpreta as tags<> ? Por exemplo:  Bob   Aí ele vai exatamente no texto da tag que eu escolho  ou isso é por causa do text content ?


Textfield and MasonryGrid give error (Vertical viewport was given unbounded height)

Question: Masonry layout working properly without any other widgets, but not working when i add textfield and MasonryLayout together.
So i just want to these 2 widgets in column with scroll.....
TextField(
          decoration: InputDecoration(
            isDense: true,
            filled: true,
            fillColor: Colors.grey.withOpacity(0.1),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide.none,
            ),

            hintText: 'Search',
            hintStyle: TextStyle(
              fontSize: 15,
              color: Colors.grey,
            ),

            prefixIcon: Icon(Icons.search, color: Colors.black,size: 20,),

          ),
        ),

MasonryGridView.builder(
    crossAxisSpacing: 8,
    mainAxisSpacing: 8,
    gridDelegate: SliverSimpleGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    itemCount: 1,
    itemBuilder: (context, index) {
      return ClipRRect(
        child: Image.network("http://source.unsplash.com/random?sig=$index", ),

      );
    },
  ),

Answer: In your MasonryGridView set shrinkWrap true like this:
MasonryGridView.builder(
                physics: NeverScrollableScrollPhysics(), // <--- add this
                shrinkWrap: true, // <--- add this
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
                gridDelegate: SliverSimpleGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2),
                itemCount: 1,
                itemBuilder: (context, index) {
                  return ClipRRect(
                    child: Image.network(
                      "http://source.unsplash.com/random?sig=$index",
                    ),
                  );
                },
              ),

Comment: Done  it's working, but i can't scroll....
Comment: because you have only one item in your grid view. add more items, something like 20
Comment: no, i've changed that
Comment: sorry I forgot to add something, I updated my answer again.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/247944/discussion-between-smit-and-eamirho3ein).


Como iniciar um ConsoleApplication que gere todos os objetos do banco igual ao CodeFirst

Question: Ola! a Todos
Estou iniciando um projeto em Console Application em C#, tenho lido muito sobre Entity Framework, Code First, Migrations.
A finalidade deste projeto é gerar todas as tabelas de um schema de banco de dados em Data Models, peço a ajuda de vocês para isso. Minha duvida é a seguinte! abaixo:
Eu quero fazer o mesmo que o Add-in do Visual Studio chamado 'Code First' faz porem eu quero gerar os modelos (Model Domain, Model Dto, Model Service) em caminhos diferentes, a ideia deste gerador é automatizar a geração destes Modelos.
Alguém perguntaria por que não usar o Code First tals, pois então, o Code First gera tudo que eu preciso mas eu quero com nomenclaturas que eu possa colocar ao gerar o objeto entendem ex:
Base de Dados

ad_escola
ad_pessoa
ad_aluno
ad_professor

Baseado nas tabelas quero gerar organizadamente
Camada de Dados (sera um Projeto Windows Library).

Escola.cs
EscolaMapper.cs
Pessoa.cs
PessoaMapper.cs
Aluno.cs
AlunoMapper.cs
Professor.cs
ProfessorMapper.cs

Camada de Domain (sera um Projeto Windows Library) já com métodos Add, Get, Edit, etc.

Escola.cs
Pessoa.cs
Aluno.cs
Professor.cs

Camada de Dto (sera um Projeto Windows Library).

EscolaDto.cs
PessoaDto.cs
AlunoDto.cs
ProfessorDto.cs

Camada de Service (sera um Projeto Windows Library) que retorna os objetos já montados pelo Domain, ela irá comunicar-se com Front End ou Camada de Apresentação.

EscolaSevice.cs
PessoaSevice.cs
AlunoSevice.cs
ProfessorSevice.cs

Detalhes, esse gerador poderei usar em qualquer fase do projeto, se eu criar uma tabela nova no projeto, usarei ele para gerar os Modelos dessa nova tabela do banco.
Minha duvida é como posso pegar todas as tabelas do banco e gerar isso de de uma forma inicial bem simples.
Para mais informações criei um projeto no GitHub quem quiser ajudar a desenvolver é só
falar comigo, e trabalhamos juntos e o Gerador de Código, ficará para todos aqueles que ajudarem, é uma ótima ideia no meu ponto de vista.
A principio queria fazer ele enxergar 3 principais bancos de dados hoje comuns:

SQLServer
Oracle
MySql

Dados do GitHub

Link: https://github.com/rodrigoarf/Gerador
Software do GitHub: https://windows.github.com/

Aqueles que quiserem ajudar a desenvolver este pequeno projeto, falem comigo e me passem o usuário do GitHub pois adicionarei como "Contributor from Project", ai vocês podem desenvolver e dar Commit e no Repositorio do GitHup sempre terá a ultima versão atualizada para todos aqueles que contribuírem.
Aguardo dicas, sugestões de toda a comunidade.
Abraços.
Answer: Isto já existe. Chama ASP.NET MvcScaffolding, mas o projeto foi abandonado porque a Microsoft abandonou o suporte ao DTE no Visual Studio 2013, privilegiando a geração pelos menus de contexto do Visual Studio.
Outra coisa que pode ser interessante para o seu projeto é o SideWaffle, gerador de templates para extensões para o Visual Studio. Pode até ser mais interessante do que chamar os comandos por console.

UPDATE
Apenas ventilando o que eu já disse aqui e aqui, o MvcScaffolding foi atualizado para o VS2015. A versão mais recente é para VS2015 e VS2013. Apenas use a versão mais recente se tiver os dois Visual Studio, senão use a versão 1.0.10 travada no arquivo packages.config da seguinte forma:
<packages>
    <package id="MvcScaffolding.VS2015" version="1.0.10" targetFramework="net452" allowedVersions="[1.0.10]" />
    <package id="T4Scaffolding.Core.VS2015" version="1.0.1" targetFramework="net452" allowedVersions="[1.0.1]" />
    <package id="T4Scaffolding.VS2015" version="1.0.8" targetFramework="net452" allowedVersions="[1.0.8]" />
</packages>


Why are these definitions of groups of central type equivalent?

Question: Let $G$ be a finite group.

In the celebrated paper of Howlett and Isaacs, On Groups of Central Type, Math. Z. (1983)., the group $G$ is called to be of central type if $G$ has an irreducible complex character $\chi$ such that $\chi(1)^2=[G : Z(G)]$. (In other sources, the quotient $G/Z(G)$ is called to be of central type, where $G$ satisfies above property).
For each 2-cocycle $f \in Z^2(G, \mathbb{C}^*)$, a complex twisted group algebra, denoted by $\mathbb{C}^fG$, is defined by extending the multiplication $g_1.g_2:=f(g_1, g_2)g_1g_2$, $\forall g_1, g_2 \in G$, to all linear combinations of elements of $G$ with coeffecients in $\mathbb{C}$. It is known that complex twisted group algebra $\mathbb{C}^fG$ may be a simple ring. A group $G$ is called to be of central type, if the twisted complex group algebra $\mathbb{C}^f \overline{G}$ is simple for some $2$-cocyle $f$ on $\overline{G}$, where $\overline{G}=G/Z(G)$ . (For example see the preprints of Ofir Schnabel on this topic).    I know that $\mathbb{C}^fG$ is simple if and only if $G$ possesses only one class of irreducible $f$-projective character. But I can't see the relation of these two definitions. So my questions are as following:  QUESTION 1: How simplicity of $\mathbb{C}^f \overline{G}$ implies that $G$ is of central type according to the definition given in  $1$? (Update: this question is settled by the Theorem $1$ of this paper. The statement and proof of the theorem are given in answers).
Further Discussions:
In the paper mentioned in $1$, the authors proved the following brilliant theorem:
Theorem (Howlett-Isaacs): If $N \lhd G$ and $\lambda \in Irr(N)$ is a $G$-invariant irreducible character of $N$ such that ${\lambda}^G$ is a multiple of some $\chi \in Irr(G)$, then $G/N$ is solvable.

It is mentioned in this paper that if $\mathbb{C}^fG$ is simple, then Howlett-Isaacs theorem implies that $G$ is solvable.

QUESTION 2: Why the above claim is true?
  Thanks for any help.
Comment: I see a third definition in the literature.  Indeed, does the intro [to this paper](http://arxiv.org/pdf/0704.2516v1.pdf), including the references therein, cover your question, or not?
Comment: In $Z^2(G,\mathbb{C}^*)$, do you assume that $G$ acts trivially on $\mathbb{C}^*$ ?
Comment: @CaptainLama According to http://arxiv.org/abs/1412.2490 I would say yes. But generally, the action need not to be trivial (Ex. see the definition of Crossed Products in D. Passman books).
Comment: The thing is, the second definition seems to depend heavily on the choice of $f$. Is $G$ called of central type if $\mathbb{C}^f G$ is simple for all $f\in Z^2(G,\mathbb{C}^*)$ ?
Comment: No, it's obviously not true if $f$ is the trivial cocycle since then $\mathbb{C}^f G = \mathbb{C}[G]$ which is obviously not simple unless $G$ is trivial. So should it be "$\mathbb{C}^f G$ is simple for *some* $f\in Z^2(G,\mathbb{C}^*)$" ?
Comment: Off course not! If we choose $f=1$, then $\mathbb{C}^fG=\mathbb{C}G$ and the latter one is never simple since the augmentation ideal $\Delta(G) \neq 1$.
Comment: @zibadawatimmy  Thank you. According to the reference you provided, the irreducible $[\Gamma: Z(\Gamma)]$-dimensinal representation $V$ of $\Gamma$, determines a projective representation $\overline{V}$ of $G:={\Gamma}/Z(\Gamma)$ with some 2-cocycle $c$. We still need $\overline{V}$ to be the only equivalence class of irreducible $c$-projective representation of $G$ for $\mathbb{C}^cG$ to be simple. Unfortunately this is not covered in the text.
Answer: The Theorem $1$ of the following paper answers our question $1$. DeMeyer, F. R., Janusz, G.J. Finite groups with an irreducible representation of large degree. Math. Z. 108 (1969).

Answer to 2nd Question:   Assume that $\mathbb{C}^fG$ is simple. Therefore, $G$ has an irreducible complex $f$-projective character $\chi$ such that ${\chi(1)}^2=|G|$. It is well known that $\chi$ determines an irreducible ordinary character $\chi^*$ of the same degree on $G^*$, where $G^*$ is a central extension of $G$ (namely a Schur cover of $G$).  Now we have $G^*/C \cong G$ and ${\chi^*(1)}^2 = |G| = [G^* : C]$. Hence, $G^*$ is of central type (see definition 1). Restricting the character $\chi^*$ to $C$, we have ${\chi^*}_C = \chi^*(1) \lambda$, where $\lambda$ is a linear character of $C$. Now ${\lambda}^{G^*}(1) = [G^* : C]$. On the other hand, $\chi^*(1) \chi^*$ is a constituent of ${\lambda}^{G^*}$. Comparing the degrees we obtain that ${\lambda}^{G^*} =\chi^*(1) \chi^* $. Now the Howlett-Isaacs theorem yields.
Comment: OK. The editions are done. Also an answer to the second question is found.
Comment: I'm not sure I see how this is equivalent to your initial question : you get a 2-cocycle in $Z^2(G/Z(G),\mathbb{C}^*)$, which is is pretty easy ; what you asked was a cocycle in $Z^2(G,\mathbb{C}^*)$, and inflation will not give what you ask.
Comment: The probability that I didn't present my question in the most efficient way is not zero. However, This is actually what I wanted to know about the relation of simple twisted group algebras and their base groups.
Comment: Ok, then. You should probably edit your post for future readers to make it clear that in the definition "2" of groups of central type, you do not mean $G$ but $G/Z(G)$. And then make sure that Question 2 does not make the same confusion.


Dart function in a function

Question: My Code:
void main() {
  String name() {
    return "Uday Kiran";
  }

  void printF(var value) {
    print(value);
  }

  printF(name);
}

Hey, I'm sorry if my question is silly. But I'm probably new to the programming and I stuck by doing something like this. I actually wanted to pass the string returned by the name function, as a argument to my printF function, so that the string "Uday Kiran" would be printed on my console. But the output I get is something like this:

Any help would be appreciable:)
Comment: You are not calling the method but are referring to it as a `Function`. You call a method with `()` so you need to do e.g.: `printF(name());`. Also `printF(var value)` is not really a great method signature since you are then allowing every type as argument instead of restricting to e.g. `String`.
Comment: Hey, buddy thanks that worked. And thanks for your suggestion in declaring the function's parameter.
Comment: Ok, I will write an answer then.
Answer: The problem is that you are refer to name as a variable which points to a Function instead of calling the function it points to. In Dart, you call a function with () (in case of no arguments) so your example should instead be:
void main() {
  String name() {
    return "Uday Kiran";
  }

  void printF(String value) {
    print(value);
  }

  printF(name());
}

I also changed the type of argument to specify you want to get a String as argument as stated in your question. By doing so, you would also got an error explaining the problem with name in your example.

Dart function in a function


How to write a bass line in classical style?

Question: Folks:
I am trying to add bass to this melody. A good style of doing bass is the following link - Ennio Morricone's Once Upon A Time In The West. The first 60 seconds should give a clear demonstration of how that bass line was written. This bass line is simple, effective, very beautiful. One can't write a simpler bass line than this. I think he basically just plays double octave bass line here. It sounds just fit the melody. Please see the attached score (my composition). I try to do the same, which is a double octave bass line. I used the chord root notes in the score. The result just doesn't sound like a part of the melody. I think I got the chords right. I also tried to put each other note of the chords at the bass. It just doesn't sound fit to the melody. I am puzzled. Where do you think I got it wrong? Does this particular style of bass line have a name? (so I can do a research on it)
Thanks a lot.
Once Upon A Time In The West
Answer: Both of these are simply the root of the chord being played under a melody. The right hand melody implies the harmony by the melodic line and/or the harmonization. This has no specific name that I am aware of.
You have done pretty much the same thing as Morricone except without harmonizing the melody. Your implied harmony is Am G G Em Am Am Am Dm G Em G Am. However it can easily imply something else if you change either the melody or the bass notes in spots. There is really nothing wrong here. You just don't really like what you came up with.
There are many other ways this melody can be harmonized but that is a subjective compositional choice. Experiment with the harmonic rhythm and different chords in spots. You might try using an E or E7 chord on the next to last bar of each line to give more of a feeling of cadence and resolution. Maybe use a G in bars 5 and 11 instead of going to E. These are subjective suggestions but they are meant to show you that you have options.
Use the melody as a constant and see if you can come up with a few different bass options, or change or embellish the melody if you wish. Composing is a process. Experiment and revise and see what works. Ultimately it is your choice.


Playing audio files in javascript

Question: I have many small audio files, and I want to play these files one after another, not all of them at the same time. I have used the object Audio in javascript like this
var audio_1 = new Audio();
var audio_2 = new Audio();
var audio_3 = new Audio();

audio_1.src = "/path1";
audio_2.src = "/path2";
audio_3.src = "/path3";

Now I just need to call the function play for every object, but I need to play the audio_1 alone, and play audio_2 when the first one ended.
The solution I found is to test on the property ended of every object
 audio_1.ended; // returns true when it ends playing

I found an object onended inside the audio object, I thought it's a function but it's not, can someone help me and give me the best way to solve this problem.
Answer: use addEventListener instead of assigning a function to the onended property:
audio.addEventListener('ended', function() {}); // Do
audio.onended = function() {}; // Don't

So, a IMHO dirty way is this:
audio_1.play();
audio_1.addEventListener('ended', function() {
    audio_2.play();
    audio_2.addEventListener('ended', function() {
        audio_3.play();
    };
};

Comment: thanks a lot, I can put path to files in an array, and use only audio_1, when it ends I change the src to the next one and play again , until all the elements on the array are played.
Comment: @Khalid That's the proper solution ;-)

Playing audio files in javascript