30 dias in Beta - We Need More Questions

Question: UPDATE 40 Days in Beta related to visits: Now the visits per day has returned to 170.
UPDATE 3 DAYS LATER related to visits.
The "Visits / day" metric for "33 days in Beta" has fallen to $222$. If this was an average ("total visits over total days") it would tell us that the last three-days average was only 62 visits/day. Thankfully, as @EnergyNumbers comments, this is not an average but a median metric. In that case, it simply tells us that the last three days were below 238/day, nothing more (they could be between 222 and 238, or below 222). So it is not very helpful for short-term tracking.  Nevertheless it is an indication that our core "visits" trend is currently downward sloping. Let's hope this has something also to do with the onset of the holiday season.
--
The numbers from Area51 for 30 days in Beta, which, for the first time, have also some comments from SE:

I have occasionally monitored these numbers for the last two weeks, and I have some comments:
Q/day
We are continuously dropping on this one, and have reached the alert point of 5. So no, it is not "okay" - we need more questions.
% Answered
That's more than "okay", IMO. I fear not this metric, every site has some dedicated people that see to it that many questions get at least one answer.
Users & Reputation
It does need work, but my feeling during the last days is that it is getting better, even though the 90-day projection looks bad. Vote people, vote.
Answers per Question
Needs some monitoring, but I think it won't be difficult to maintain 2 Q/A.
Visits
It was ~170 at ~the 15th day I think, rose to ~260, then it fell. I don't think it is bad for 30 days in beta, but we sure need to get it up. Remember that the metric may be biased upwards due to the 2.8k views question about minimum wage , and we may see it continuously dropping in the next days.
Overall: We need more questions, this is more important than, say, Avid Users, or Visits. More questions mean more content, which will increase visits and users in the mid-term. We need more questions (and alas, I know I have contributed just one question). And more votes.
Response to @Energynumebrs answer
Sure we need and we want the experts, but how do you propose that we will get them? How do we build a community of skillful people? In my experience, meeting places that succeed are meeting places that buzz -with all kinds of noise. A hundred bad questions, are a hundred questions that can be edited to become readable and interesting, and then be excellently answered. Ten excellent questions are just ten -too few. So I prefer to have something to work on and try to improve it so that it becomes attractive, rather than hope that somehow, in what way?, the experts we all want will embrace a nascent Q&A site with no a priori credentials in sufficient numbers, and start steadily asking questions and posting answers.
If there are questions, of any quality, then we can really do something about it. If there are too few questions then we can mostly hope that these experts will appear, on their own or because they have responded to our direct invitations.
Now, "just wait and hope" is not my kind of thing. "Sending invitations", I did, and will continue to do. "Working the questions" in any way, from commenting and editing to closing to deleting to answering is how I try to help things I am interested in succeed, i.e. by creating the credentials needed to attract the experts. And the credentials need the buzz: most people, experts included, don't like to stay around in silent places, empty places. But if they see and hear buzz, a lot of it annoying some of it attracting, there are more chances that they will side with the "attracting" trying to push off the annoying.
This is a massive site, not an exclusive club where prospective high-standing members demand, and rightfully so, to be spared the lowlifes. In another thread we both agreed that we "trust the SE experience": and all I "hear" from this experience all over the SE world is volume, volume, volume . And it makes sense, because if you have volume, you have a chance to create quality in sufficient volume. Otherwise, your carefully crafted quality over precious few gems, will probably prove to be too weak a signal for people to notice (and for SE to spare the site).
Comment: Great points here. I've been trying to ask a lot for the exact purpose of generating content. As long as you don't mind a large portion of questions from individual users like me, I'll keep doing it. (Also, props to @Alecos for answering so many of them!)
Comment: @jmbejara Absolutely, keep on, if you ask me. I should also wear my "student hat" and unearth all that lie unanswered behind the "hey, I am research-level now!" persona.
Comment: Note that the visits per day is a median, not a mean, so your calculation of 62 visits per day doesn't apply. Questions per day is a mean, visits per day is a median.
Comment: Its hard to make sense of the statistics for visits. But if you want to bump up visits, just ask another highly controversial question as the case with minimum wages. It'd be interesting to see how many of the first-time answerers in that question actually stayed here and posted more.
Comment: @FooBar I don't want to bump up visits artificially, on the contrary, we need to know what is the "core" visits number daily.
Comment: @AlecosPapadopoulos thats kind of my point: The decline in visits mostly comes from that. A more reliable core number we should aim at is #users and #questions.
Comment: @FooBar If the metric was an average, as I thought originally, it would be useful as a daily tracking device. Now that we know it is a median, it is indeed, not very useful, short-term.
Comment: Not only because of that... you get a lot of *views* with controversial topics. I suspect these to have a low translation rate into users that stay. Then, views are a bad proxy for "users who stay", which I strongly to believe is the most important goal at the start, together with #questions.
Comment: @Ubiquitous Thanks for looking after, but I used the Spanish word for "days" consciously.
Answer: What we really need is new active experts, graduate and postgraduate economists and econometricians. Everything else will follow from that.
Any fool could ask a hundred bad questions. The stats would get a temporary boost, and the site would be a worse place because of it.
In a year's time, the new questions asked in the coming month will be be useful content for search engines, but have little life beyond that. And yet over that same period, the new experts who arrive in the coming month and decide to stay, will still be here in a year's time generating new awesome content.
It's all about building a community of skillful, knowledgeable people. Do that, and everything else will come good. Fail to do it, and no other stats will save us.
How?
And it's perfectly reasonable to ask how we do this. I don't know. I try things, but there are plenty of other people who are far better at it than I am, so all I know is that I'm not in any place to offer advice. What people say is: share good questions on Twitter and other social media; use your other online networks to link back to great content here; pass on links to interesting content, to colleagues via university intranet discussion forums and the like.
Now, I've tried that with precious little success. But other people seem to get it to work. I don't yet know what makes the difference between success and failure. But I have found a few things that don't work for me, the way I do them, so I guess that's a start. Telling postgrad PhD students that it's a Stack Overflow for their own subject and providing a link didn't work for me. Simply tweeting question titles, or my rephrasing of them, with a link to the question, didn't work for me. Posting a list of Stack Exchange sites that I find interesting, with a one-sentence description and a link for each, didn't work for me. A lot of these things do apparently work for other people, when they do them in their way. So try them in your own way. They may well work for you.
Answer: I agree. All we need are more expert users. Everything else will come for that.
I have been advertising to the extent that it's almost bothering my colleagues. Follow up!
Comment: It would be _really good_  if direct advertising succeeds, despite the negative experience on the matter shared by @EnergyNumbers. It will save us from a lot of work to keep this site afloat.
Answer: One thing I'll try over the next days is to take discussions/questions I had with others and just put them as questions here. Then, hopefully, good answers that I can link around will prove that the platform has its right of existence.
If the mountain won't come to Mohammed, Mohammed must go to the mountain.


PHP - Converter XML para Objeto

Question: Existe uma forma com PHP de transfomar um XML em um objeto e objeto em xml?
Exemplo:
** Classe (objeto) **

<?php
class Telefone {
  private $codigoArea;
  private $numero;

  public function setCodigoArea($codigoArea) {
      $this->codigoArea = $codigoArea;
  }

  public function getCodigoArea(){
      return $this->codigoArea;
  }

  public function setNumero($numero) {
      $this->numero = $numero;
  }

  public function getNumero(){
      return $this->numero;
  }
}
?>

** XML **

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<telefone>
   <codigoArea></codigoArea>
   <numero></numero>
</telefone>

** Exemplo do que preciso: **

$fone = new Telefone();
$xml = algumMetodoFuncao($fone); --> Algum metodo/função que transforme meu objeto em XML (O $fone não é uma string)

Comment: Certinho... É  isso mesmo... Obrigado
Comment: Deu certo minha resposta?
Answer: $xml = simplexml_load_string($string);

Comment: Não tenho um XML/String... neste caso como ficaria  $xml = simplexml_load_string( ??? ); ? OBrigado
Comment: no manual do PHP tem um exemplo. http://php.net/manual/pt_BR/function.simplexml-load-string.php
Comment: Sim o simplexml-load-string eu tinha visto, mas pelo que entendi nao atende o que preciso... Fiz uma correção na minha pergunta. Agora tenho um exemplo do que preciso. Obrigado
Answer: Criei uma classe estática chamada XMLobject para fazer isso. Nela tem 2 funções:

gerarXML() : Recebe um objeto e cria um arquivo no diretório selecionado
gerarObjeto() : Recebe um arquivo xml e gera o objeto com os parâmetros dentro do arquivo

Para essas funções funcionarem, algumas regras tem que ser seguidas.
gerarXML()
Todo o elemento xml só pode ser gerado se houver um getter publico do atributo. Isso significa que se você quiser gerar um elemento <nome> no xml, a classe do seu objeto deverá conter um getNome().
gerarObjeto()
A classe do objeto que será criado deverá ser incluída antes de chamar este método. Caso contrário irá gerar um erro. Além disso, todo o elemento do xml precisa de um setter na classe. Isso significa que se você tem um elemento <sobrenome> no xml é necessário um setSobrenome() na classe.
Classe XMLobject
class XMLobject {

    static function gerarXML($objeto, $dir =""){

        $class = get_class ($objeto);
        $methods = get_class_methods ($class);
        $atributos = [];
        $functions = [];

        // recupera os atributos através dos metodos
        foreach($methods as $key => $method){
            if(strpos($method, "get") !== false && strpos($method, "get") === 0){
                $atributos[] = lcfirst(substr($method,3,strlen($method) -1));
                $functions[] = $method;
            }
        }

        // cria o xml com os valores dos geters
        $stringXML  = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
        $stringXML .= '<'.$class.'>';
        for($i = 0; $i < count($atributos); $i++){
            $function = $functions[$i];
            $stringXML .= '<'.$atributos[$i].'>'.$objeto->$function().'</'.$atributos[$i].'>';
        }
        $stringXML .= '</'.$class.'>';

        // gera o arquivo no diretorio informado
        file_put_contents($dir.$class.".xml",$stringXML);
    }

    static function gerarObjeto($xml_uri){
        // pega todos os elementos do arquivo xml
        $content = file_get_contents($xml_uri);
        preg_match_all('/<[\w\s\d\\"\'\.]+[^\/]>[\w\d]*/', $content, $elementos);
        $obj = null;
        foreach($elementos[0] as $key => $elemento){
            $valores = explode(">", $elemento);
            $atributo = substr($valores[0],1, strlen($valores[0]));
            if($key == 0) {
                // gera a classe
                $obj = new $atributo();
                continue;
            }
            if(is_object($obj)){
                // insere os valores nos atributos do objeto
                $method = "set".ucfirst($atributo);
                $obj-> $method($valores[1]);
            }
        }
        return $obj;
    }

}

Exemplo de Uso:
Gerando um xml
$telefone = new Telefone();
$telefone -> setNumero("9999999999");
$telefone -> setCodigoArea("11");
XMLobject::gerarXML($telefone);

Resultado: (arquivo: Telefone.xml)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Telefone>
        <codigoArea>11</codigoArea>
        <numero>9999999999</numero>
    </Telefone>

Gerando um Objeto
$obj = XMLobject::gerarObjeto("Telefone.xml");
print_r($obj);

Resultado:
Telefone Object ( [codigoArea:Telefone:private] => 11
[numero:Telefone:private] => 9999999999 )

Comment: Perfeito... é isso mesmo que preciso... Muito obrigado
Comment: @Mamga que bom que deu certo. =) qualquer dúvida pode me chamar!

PHP - Converter XML para Objeto


Gradient of a multivariate function numpy

Question: I'm trying to calculate the gradient of multivariate function g using NumPy.
g = lambda w: -np.sin(np.pi*np.sum(w**2)) + np.log(np.sum(w**2))
gradient = lambda w: ...
the parameter w is a vector, for example, w = np.array([0.5,0.5]). I calculated the gradient like this;
gradient = lambda w: np.pi*np.sum(2*w)*-np.cos(np.pi*np.sum(w**2)) + np.sum(2*w)*(1/np.sum(w**2))
It does not give meaningful results. Is this formula correct or not?
Comment: Apply the Chain Rule.
Answer: If we write it more explicitly,
$$f(w)=-\sin\left(\pi\sum w_i^2\right)+\ln \left(\sum w_i^2\right)$$
$${\partial f \over \partial w_i}=-\cos\left(\pi\sum w_i^2\right)\pi2w_i+\frac{2w_i}{\sum w_i^2}$$
So, the derivative is a vector; which means your expression will look like
gradient = lambda w: -np.pi*2*w*np.cos(np.pi*np.sum(w**2)) + 2*w*(1/np.sum(w**2))

when used denominator layout.
Comment: Thanks. w is an array which consists of w0 and w1, for example w = np.array([0.5,0.5]). In this case np.sum(w^2) is equivalent to w0^2 + w1^2, so I considered the derivation (2 * w0 + 2 * w1) which is equivalent to np.sum(w*2).
Comment: Why do you sum the derivatives?
Comment: Because in the function there is np.sum(w^2) part which is equivalent to w0^2 + w1^2. The parameter w is a 2-element array, the square roots of w0 and w1 added in the function, so I think the derivative of (w0^2 + w1^2) part should be np.sum(2*w).
Comment: No, derivative of w0^2 + w1^2 wrt w0 is 2w0, and wrt w1 is 2w1. You do not sum the derivatives.
Comment: That is correct, in none of them it's summed.


Prove that $f(m+n) \leq \max(f(m),f(n))$

Question: Let $f$ be a function defined on the set of positive integers such that for each $m,n \in \mathbb{Z}_{+}$,
(i) $f(mn)=f(m)f(n)$,
(ii) $f(m+n) \leq f(m)+f(n)$,
(iii) $0 \leq f(m) \leq 1$.
How can I prove that $f(m+n) \leq \max(f(m),f(n))$?
The hint says to consider $\{f(m+n)\}^k$ for each positive number $k$, but cannot find the way...
Answer: You have for any $k \ge 1$,
$$\begin{eqnarray*}
f(m+n)^k &=& f\left((m+n)^k\right) \\
&=& f\left(\sum_{i = 0}^k \binom{k}{i} \, m^i n^{k-i} \right)\\
&\le& \sum_{i = 0}^k \underbrace{f\binom{k}{i}}_{\le 1} \ f(m)^i f(n)^{k-i} \\
&\le& \sum_{i = 0}^k \ f(m)^i f(n)^{k-i} \\
&\le& (k+1) . \max\{f(m), f(n)\}^k
\end{eqnarray*}$$
So for all $k \ge 1$, we have $f(n+m) \le (k+1)^{\frac{1}{k}} . \max\{f(m), f(n)\}$. Since $(k+1)^{\frac{1}{k}} \underset{k \to \infty}{\longrightarrow} 1$, we get
$$f(n+m) \le \max\{f(m), f(n)\}$$
To provide some context, (ii) is called the triangle inequality, and $f(n+m) \le \max\{f(m), f(n)\}$ is the ultrametric inequality.


HighCharts angular not working with dynamic data from Angular service

Question: Trying to assign dynamic values coming from angular service in angular component does not update HighChart. If I call drawChart from outside of service response subscribe method, it works but with hardcoded data because response data is not available outside subscribe method.

Following are HighChart options.
    chart:{ type: "bar"},
    title: {text:null},
    xAxis:{categories:null},
    yAxis: {
      title:{
        text:"time (seconds)"
      }
    },
    tooltip: {
      valueSuffix:"seconds"
    },
    series: []
     };```

</code>

HighChart on my HTML.
<code>    [Highcharts] = "SomeChart"
    [options] = "ChartOptions"
    style = "width: 100%; height: 100%; display: block;">
   </highcharts-chart>```

This high chart is being populated by following code in angular component.
    let resp = this.RptService.getWorkflowAvgTime();
    resp.subscribe(reportData=> {this.DataSource.data = reportData as sommeObject[];
    this.drawChart(reportData);})
  }```

</code>

following is drawChart function
<code>    {
        let s: Array<any> = []
        data.forEach(function (obj)
    {
         s.push({name: obj.yIdentifier, data:[obj.value]})
    })

       this.ChartOptions.series= s;
       console.log(this.ChartOptions.series); // Console prints proper values assigned to chartOptions
    }```

Answer: It is not working because to perform an update using the highcharts-angular you need to mark it by toggling the updateFlag. Without that, you will mutate the chartOptions but your chart will not update itself.
Docs references:
https://github.com/highcharts/highcharts-angular#options-details
Live demo:
https://stackblitz.com/edit/highcharts-angular-optimal-way-to-update-c9zk9y?file=src/app/app.component.ts
<highcharts-chart
   [Highcharts]="Highcharts"
   [options]="chartOptions"
   [(update)]="updateFlag"
>
</highcharts-chart>

<button (click)="handleUpdate()">Update chart</button>

export class AppComponent  {
   Highcharts: typeof Highcharts = Highcharts;
  updateFlag = false;

  data = [1, 2, 3, 4];

  chartOptions: Options = {
    series: [
      {
        type: 'line',
        data: this.data
      }
    ]
  }

  handleUpdate() {
    this.chartOptions.title =  {
      text: 'updated'
    };

    this.chartOptions.series[0] = {
      type: 'line',
      data: [5, 4, 3, 2, 1]
    }

    this.updateFlag = true;
  }
}


Discord.js v.12 Invalid destructuring assignment target

Question: I'm trying to learn discord.js and I just follow an example code that I found but it errors. This is my code:
const Discord = require('discord.js')
const client = new Discord.Client()

client.on('ready', () => {
    var generalChannel = client.channels.cache.get("I already put the valid ID")
    generalChannel.send("C'mon dude")

    console.log("Connected as " + client.user.tag)

    client.user.setActivity("Youtube", {Type: "WATCHING"})

    client.guilds.cache.forEach(("guild") => {
        console.log(guild.name)
        guild.channels.cache.forEach((channel) => {
            console.log('  ${channel.name} ${channel.type} ${channel.id}')
        })
    })
})

client.login("I already put valid token")

This is the error message:
SyntaxError: Invalid destructuring assignment target

Please tell me how to fix it
Answer: The problem is you try to use a string in ("guild"). See the double quotes around guild? You don't need them as you want to use the guild variable. You can try this instead:
client.guilds.cache.forEach((guild) => {
    console.log(guild.name)
    guild.channels.cache.forEach((channel) => {
        console.log('  ${channel.name} ${channel.type} ${channel.id}')

    })
})

Comment: Also, remember you can add async, and remove the ()s around "guild" since it's the only parameter


Applying machine learning techniques to panel data

Question: I have a panel data in which I observe 1500 companies and many individuals work  for those companies for multiple periods. I have explanatory variables at both individual (e.g. race, age, education) and company level (e.g. company age, R&D investment, spending on advertising, industry). So there are different types of explanatory variables i.e. continuous, categorical, binary. In this dataset, same individual might work for more than one company at the same time (given that some of them are consultants). My dependent variable is sales per year.
By using this data, I want to make a prediction of the dependent variable  and want to test the importance of each explanatory variable. Does anyone know which models would be more suitable and where I could find a reliable material on this topic? I was thinking about applying RNN to panel data (how to do it ?) but also open to other suggestions.
I know still ML and econometrics are not talking to each other with regard to causality but do you know any recent paper/ development related to this issue?
Comment: Here is a first discussion for this : https://d-nb.info/1173616306/34
Answer: I don't believe I can offer what you're looking for, but the first step is to use the repeated individual_id as a variable to ensure that each individual is in 1 partition. For example if you're using cross-fold validation, then an individual should only show up in 1 fold and not be spread out amongst the others.
As far as what machine learning algorithms to try - that is ultimately up to the data. In my experience though, I think your best results will come from some sort of boosted tree such as LightGBM or xGBoost. This will lead to you deciding how to encode the categorical variables, for which I recommend category_encoders library in python, if you're using python.
I'm sure there's interesting and novel ideas around RNN's but to be honest I don't think this problem is suited for that type of algorithm. This sounds like a classic regression problem to me.
Answer: Adding to Josh that using some tree based algorithm is lacking some clear transparency on how the features are impacting your sales (like you have in a classic linear regression framework, which is called a white-box model, because the coefficients are very easy to intertrep).
What you can get as relative importance from these tree based algorithms, which basically tell you how important the individual features are for constructing your tree and the output is a ranking. But with this ranking you can not get an understanding of how much an increase of x impacts your y.
There are two algorithms out there, which I know exist but I have never use so far:

Causal Forest is like a tree based algorithm, but incorporates the idea of causal inference and can be found here: https://lost-stats.github.io/Machine_Learning/causal_forest.html

Google's What-If Tool (WIT) is designed to follow the idea of counterfactuals, which can answer the question what would have happened if...

You can build your own counterfactuals using predictions. Train a model and get your predictions for varying values of the individual features (c.p.) and see how the output changes. Like this you can have an understanding which features impact the y how much even using some black-box models like neural nets or boosted trees.

Lastly I also want to mention that using scikit-learn you can return PDP (partial dependency plot) and ICE (individual conditional expectation) plots, which can give you an understanding of the relationship between your feature(s) and your target.


Translate interface (export/import)

Question: I have two languages:

french
arabic

I want to completely translate the arabic interface. If there a way to export the englisch translations, add the arabic one and reimport the file?
Answer: It can be done using Translation template extractor module

If you are a translator, install the module on a Drupal site as you would with any other module. Once potx module is turned on, you can go to the "Extract strings" tab on the Locale administration interface, select the module or theme you want to have a translation template for, and submit the form. You will get one single template file generated.
Answer: I didn't get you! You need to completely translate the Arabic interface? Add the Arabic language to your website then simply, download it's translation  file and import it into admin/config/regional/translate/import . What is the problem?
Answer: Completely translating the Drupal "interface" in another language is a bit bizarre/strange (as confirmed also by some of the other answers already). Therefor it may help to correctly understand the various Drupal components related to 'translation', as further explained below.
Drupal's translation system consists of 2 basic components: the translation of the interface and the translation of the content of a site.
The translation of the interface is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site).
The translation of the content is about the translation of nodes and entities. It requires a place to actually store the translated versions of the content (in multiple languages) and a system to choose which content is to be displayed where. The systems available for translation of content are:

Content translation (used in earlier versions of Drupal, and still available in D7), which translates entire nodes in multiple languages.
Entity translation (its API was first introduced in Drupal version 7, though there is no UI for it yet), which translates fields attached to the same entity.

Typical (often used) modules related to translations:

i18n.
Variable.
Localization update.
Entity Translation.

Modules to actually manage translations of nodes and/or entities:

Translation Management, for D6 only, not suited for D7.
Translation Overview, for D7, mentioned as a recommended add-on by i18n also.
Translation Management Tool, for D7 and/or D8, considered as the successor of Translation Overview, and "the" module to move forward with in D8 also.

Translate interface (export/import)


Poisson Process Conditional Probability computation

Question: Given $N(t)$ a Poisson Process with generation rate $\lambda$ with $t_1<t_2$ and $N_2>N_1$ I'm looking for a way to express the following probability:
$$ P[N(t_2)>N_2|N(t_1)<N_1]$$
In other words, what is the probability of counting more than $N_2$ events in time $t_2$ given that at time $t_1$ I had counted less than $N_1$ events?
So far I only got to express it in terms of sum of explicit probabilities.
$$ =\sum_{k=0}^{N_1-1} P[N(t_1)=k]P[N(t_2-t_1)\geq N_2-k]$$
$$ =\sum_{k=0}^{N_1-1} \frac{(\lambda t_1)^ke^{\lambda t_1}}{k!}\left[ \sum_{j=N_2-k}^{+\infty} \frac{(\lambda (t_2-t_1))^je^{\lambda (t_2-t_1)}}{j!}\right]$$
Is there a way to further simplify this expression? Or another clever way to look at the problem?
Answer: $$P(N(t_2)>N_2|N(t_1)<N_1)=P(N(t_1)<N_1 \land N(t_2)>N_2)/P(N(t_1)<N_1)=\sum_{k=0}^{N_1-1} [P(N(t_1)=k)P(N(t_2) >N_2)]/P(N(t_1)<N_1)=
\frac{\sum_{k=0}^{N_1-1} [P(N(t_1)=k)(1-P(N(t_2) \le N_2))]}{P(N(t_1)<N_1)}$$
if it's not for exam then this is (I hope) best form to implement in algorithm, after all not all problems have nice formula as solution


How to fix drush issue "Could not bootstrap at phase 5"?

Question: I installed drush via Composer. I am using drush 9.5.2 with Drupal 8.6.4.
I mention that everything is fine on local. However, in a docker instance in GitLab CI, when I execute vendor/bin/drush updatedb -y -vvv, I get:
 [preflight] Config paths: /builds/v2/my-project/vendor/drush/drush/drush.yml,/builds/v2/my-project/drush/drush.yml
 [preflight] Alias paths: /builds/v2/my-project/web/drush/sites,/builds/v2/my-project/drush/sites
 [preflight] Commandfile search paths: /builds/v2/my-project/vendor/drush/drush/src,/builds/v2/my-project/drush
 [bootstrap] Starting bootstrap to full [0.09 sec, 8.27 MB]
 [bootstrap] Drush bootstrap phase 5 [0.09 sec, 8.27 MB]
 [bootstrap] Try to validate bootstrap phase 5 [0.09 sec, 8.27 MB]
 [bootstrap] Try to validate bootstrap phase 5 [0.09 sec, 8.27 MB]
 [bootstrap] Try to bootstrap at phase 5 [0.09 sec, 8.4 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalRoot() [0.09 sec, 8.4 MB]
 [bootstrap] Change working directory to /builds/v2/my-project/web [0.09 sec, 8.4 MB]
 [bootstrap] Initialized Drupal 8.6.4 root directory at /builds/v2/my-project/web [0.1 sec, 8.4 MB]
 [bootstrap] Try to validate bootstrap phase 5 [0.1 sec, 8.4 MB]
 [bootstrap] Try to bootstrap at phase 5 [0.1 sec, 8.92 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalSite() [0.1 sec, 8.92 MB]
 [bootstrap] Initialized Drupal site default at sites/default [0.1 sec, 8.92 MB]
 [bootstrap] Try to validate bootstrap phase 5 [0.1 sec, 8.92 MB]
 [bootstrap] Try to bootstrap at phase 5 [0.1 sec, 8.92 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalConfiguration() [0.1 sec, 8.92 MB]
 [debug] Add service modifier [0.11 sec, 9.14 MB]
 [bootstrap] Try to validate bootstrap phase 5 [0.11 sec, 9.14 MB]
 [info] sql-query: SELECT 1; [0.11 sec, 9.28 MB]
 [info] Executing: mysql --defaults-file=/tmp/drush_FfJCYU --database=my_project --host=xxx.rds.amazonaws.com --port=3306 --silent -A < /tmp/drush_BsP1AL > /dev/null [0.11 sec, 9.28 MB]
 [info] sql-query: SELECT 1 FROM key_value LIMIT 1; [0.23 sec, 9.28 MB]
 [info] Executing: mysql --defaults-file=/tmp/drush_TOHYme --database=my_project --host=xxx.rds.amazonaws.com --port=3306 --silent -A < /tmp/drush_4SNKF4 > /dev/null [0.23 sec, 9.28 MB]
 [notice] Missing database table: key_value [0.35 sec, 9.28 MB]
 [bootstrap] Could not bootstrap at phase 5 [0.35 sec, 9.28 MB]

In BootstrapHook.php line 32:

  [Exception]
  Bootstrap failed. Run your command with -vvv for more information.

Exception trace:
 () at /builds/v2/my-project/vendor/drush/drush/src/Boot/BootstrapHook.php:32
 Drush\Boot\BootstrapHook->initialize() at /builds/v2/my-project/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:34
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->callInitializeHook() at /builds/v2/my-project/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:27
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->initialize() at /builds/v2/my-project/vendor/consolidation/annotated-command/src/CommandProcessor.php:117
 Consolidation\AnnotatedCommand\CommandProcessor->initializeHook() at /builds/v2/my-project/vendor/consolidation/annotated-command/src/AnnotatedCommand.php:391
 Consolidation\AnnotatedCommand\AnnotatedCommand->initialize() at /builds/v2/my-project/vendor/symfony/console/Command/Command.php:221
 Symfony\Component\Console\Command\Command->run() at /builds/v2/my-project/vendor/symfony/console/Application.php:971
 Symfony\Component\Console\Application->doRunCommand() at /builds/v2/my-project/vendor/symfony/console/Application.php:248
 Symfony\Component\Console\Application->doRun() at /builds/v2/my-project/vendor/symfony/console/Application.php:148
 Symfony\Component\Console\Application->run() at /builds/v2/my-project/vendor/drush/drush/src/Runtime/Runtime.php:112
 Drush\Runtime\Runtime->doRun() at /builds/v2/my-project/vendor/drush/drush/src/Runtime/Runtime.php:41
 Drush\Runtime\Runtime->run() at /builds/v2/my-project/vendor/drush/drush/drush.php:66
 require() at /builds/v2/my-project/vendor/drush/drush/drush:4

updatedb [--cache-clear [CACHE-CLEAR]] [--entity-updates] [--post-updates [POST-UPDATES]] [--no-cache-clear] [--no-post-updates] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--xh-link XH-LINK] [--notify [NOTIFY]] [--druplicon] [--] <command>

I mention that the command mysql -V is working.
And when I execute vendor/bin/drush sql:connect -vvv, I get:
 [preflight] Config paths: /builds/v2/my-project/vendor/drush/drush/drush.yml,/builds/v2/my-project/drush/drush.yml
 [preflight] Alias paths: /builds/v2/my-project/web/drush/sites,/builds/v2/my-project/drush/sites
 [preflight] Commandfile search paths: /builds/v2/my-project/vendor/drush/drush/src,/builds/v2/my-project/drush
 [bootstrap] Starting bootstrap to max [0.1 sec, 8.27 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalRoot() [0.1 sec, 8.4 MB]
 [bootstrap] Change working directory to /builds/v2/my-project/web [0.1 sec, 8.4 MB]
 [bootstrap] Initialized Drupal 8.6.4 root directory at /builds/v2/my-project/web [0.1 sec, 8.4 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalSite() [0.11 sec, 8.92 MB]
 [bootstrap] Initialized Drupal site default at sites/default [0.11 sec, 8.92 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalConfiguration() [0.11 sec, 8.92 MB]
 [debug] Add service modifier [0.11 sec, 9.11 MB]
mysql --user=my_project --password=xxx --database=my_project --host=xxx.rds.amazonaws.com --port=3306 -A

So, no problem with drush sql:connect.
Does the notice "Missing database table: key_value" could cause the issue?
How could we troubleshoot the issue?
Just in case, here is the build part of my gitlab-ci.yml:
build:
  stage: build

  before_script:
    - apt-get update

    #install additional gd extension, that is required by Drupal
    - apt-get install libpng-dev -y
    - docker-php-ext-install gd

    #install mysql-cli
    - apt-get install -y mysql-client

    #install composer
    - apt-get install zip unzip
    - php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    - php composer-setup.php
    - php -r "unlink('composer-setup.php');"

    #install composer package to run parallel tasks
    - composer -n global require -n "hirak/prestissimo"

  script:
    - mysql -V
    - php composer.phar install
    - vendor/bin/drush
    - vendor/bin/drush sql:connect -vvv
    - vendor/bin/drush updatedb -y -vvv
    - vendor/bin/drush config-import -y
    - vendor/bin/drush cache-rebuild -y

Answer: To fix the issue I had to export my local database and import it in the production server database (same for the sync configuration files).


Determining if a function is additive

Question: I have data collected on a grid of values $f(x,y)$. I have a hypothesis that the data is "additively separable", i.e.
$$
f(x,y) = h_1(x) + h_2(y) + g(x,y)
$$
where $g(x,y)$ is small and only represent the noise in my measurements. Is there a way to test for this? If I had infinite sampling resolution I could measure
$$
\frac{\partial^2 f(x,y) }{\partial{x}\partial{y}} =
\frac{\partial^2 h_1(x) }{\partial{x}\partial{y}} +
\frac{\partial^2 h_2(y) }{\partial{x}\partial{y}} +
\frac{\partial^2 g(x,y) }{\partial{x}\partial{y}} = g_{xy}(x,y)
$$
Then I could test if for some threshold value $\epsilon$, $|g_{xy}(x,y)| > \epsilon$. However, my data is real, with noise and limited samples. What statistical test could I use to check for additive separability?
Comment: I doubt these are the right tags, but I wasn't sure what to use. Please feel free to correct them.
Comment: You currently have no noise/variation about your model, which makes me suspect this isn't a statistical problem. With noise, and if you were trying to test if $g=0$ was zero a statistical test might be relatively easy (with some assumptions about the $h$'s). To do much more you're going to need to be precise about what "small" means and likely put some limits on $g$ (such as some kind of assumption about smoothness at least). If you can form estimates with $g$ both restricted to be small and not restricted, you might be able to do some kind of resampling-based test -- perhaps.
Comment: @Glen_b it may be that I'm not using the proper phrasings here, I'll take any help I can get. My data is assumed to have noise, and imprecision in measurement which I have some knowledge about via repeated measurements of the same point. Is it enough of a condition that $h,g$ are smooth and continuous (which I suspect is the case for me)? Shouldn't the test tell me what "small" is given a particular confidence rating?
Comment: If there's noise, why does your model have an equality there without a noise term? Are the $f$ values not observed? The part about small is not something the test tells us. Estimation might tell us something about the size of $g$, but only you can declare it to be sufficiently small by your own criteria. How are we (or some test) to know what you mean when you say 'small'?
Comment: @Glen_b One solution is to compute all possible values of $f(x_1,y_1)+f(x_2,y_2)-f(x_1,y_2)-f(x_2,y_1).$ Under the null they should be random with zero mean (although correlated in a predictable way), so we can apply a t-test of the null hypothesis provided we compute the standard error appropriately for the correlation. Notice that estimation of $h_1$ and $h_2$ is unnecessary!
Comment: @whuber Yes, if we're testing for $g=0$ (rather than just 'small'), this would work.
Comment: @Glen_b But that's not what we're testing! It's *assumed* $\mathbb{E}(g)=0.$ (Actually it's fine if $\mathbb{E}(g)=\mu$ is constant.) We don't care at all about the size of $g$; it's merely supplying additive error to the set of second differences of $f$ that I described. Those second differences equal $g(x_1,y_1)+g(x_2,y_2)-g(x_1,y_2)-g(x_2,y_1)$ under the null, enabling us to turn the data into a (very large) set of values viewed as the realization of a (very large) multivariate distribution with zero means and *known* covariance matrix, up to a constant: that's the setting for a t-test.
Comment: @whuber That's a good idea, and much more robust than estimating the second derivatives. Are you saying that I should apply that "box" test to all rectangular points in my sample? If so, and if you could explain how to apply the t-test to these box values I can accept this as an answer.
Comment: I haven't figured out the right way to do it yet.  Looking at all possible second differences is computationally impracticable except for small grids. Looking only at the second differences among neighboring points is quite a bit less computation and appears to be almost as powerful. But in principle you might do a lot better by examining the spatial distribution of these differences, enabling you to find local departures from additivity.  Regardless, I think the key to any solution is going to be some kind of analysis of these second differences.
Comment: @whuber How would I know what the covariance matrix is? My dataset _is_ small, so it would be feasible for me to calculate every possible second difference (for every sized rectangle).
Answer: Although the second order mixed differences
$$D_{12}f(x_1, x_2, y_1, y_2) = f(x_1,y_1)+f(x_2,y_2)-f(x_1,y_2)-f(x_2,y_1)$$
provide useful information, by themselves they do not have enough power to discriminate between slightly noisy additive functions and non-additive functions.
The trick is to compare $D_{12},$ suitably transformed to have good statistical properties, to some measure of the spread of $f,$ without assuming anything at all about $f$.  This answer gives the details and provides evidence that this procedure can work well even for small grids and relatively large amounts of noise.

A function $f$ of two variables $x$ and $y$ is "additively separable" ("additive" for short) when there exist functions $g$ and $h$ such that $f(x,y) = g(x)+h(y).$  A "noisy" additive function includes independent additive random errors $\varepsilon(x,y)$, so that the full model is
$$f(x,y) = g(x) + h(y) + \varepsilon(x,y).$$
Suppose we have observed $f(x_i, y_j)$ for all $mn$ combinations of $m$ distinct values $x_1, x_2, \ldots, x_m$ and $n$ distinct values $y_1, y_2, \ldots, y_n.$  (In full generality--assuming absolutely nothing about $f$, not even whether it is continuous--it matters not what the values $x_i$ or $y_j$ are, because they can be subsumed in the definitions of $g$ and $h$, respectively.  Furthermore, the ordering of the $x_i$ and $y_j$ are immaterial: the definition of additivity makes no use of that.)
The first idea is that additive functions $f$ can be detected by comparing $D_{12}$ to zero, because
$$\eqalign{
D_{12}f(x_1, x_2, y_1, y_2) &= g(x_1)+h(y_1)+\varepsilon(x_1,y_1) + g(x_2)+h(y_2)+\varepsilon(x_2,y_2) \\
&- g(x_1) - h(y_2) - \varepsilon(x_1,y_2) - g(x_2) - h(y_1) - \varepsilon(x_2, y_1) \\
&=\varepsilon(x_1,y_1) +\varepsilon(x_2,y_2)- \varepsilon(x_1,y_2)- \varepsilon(x_2, y_1)\\
&= D_{12}\varepsilon(x_1, x_2, y_1, y_2),
}$$
which is the sum of four independent errors.  Provided these "noise terms" tend to be small, all mixed differences ought to be small when applied to additive functions.  When applied to non-additive functions, the mixed differences ought to be greater.
Difficulties arise for several reasons:

Because the orders of the $x_i$ and $y_j$ do not matter, one can compute mixed differences for all $m(m-1)/2$ distinct pairs of $x$'s and all $n(n-1)/2$ distinct pairs of $y$'s, even though only $(m-1)(n-1)$ of them are (linearly) independent.  Which differences should be used?  (I propose using them all.)
Because adding and subtracting values of a function throughout its domain can cause relatively large values to be combined, the variation of a function's values can swamp any signal in the mixed differences.
It is tempting instead to fit a model of the form
$$\mathbb{E}(f(x_i, y_j)) = \alpha_i + \beta_j$$
and then study its residuals--but is there any way that can help and, if so, how should the model be fit?  Can we do this in a robust fashion that is resistant not only to outlying values of the $\varepsilon(x_i,y_j)$ but also to possibly extreme variation in $g$ and $h$ themselves?

A solution I have hit upon after much experimentation addresses these issues by constructing a set of paired values $(a_k, b_k)$ derived from the observations of $f$.   The indexes $k$ designate $2\times 2$ blocks in the data and therefore correspond to all tuples $(i_1, i_2, j_1, j_2)$ for which $1 \le i_1 \lt i_2 \le m$ and $1 \le j_1 \lt j_2 \le n$.  For such a tuple

let $a_k$ be the range of the four values of $f$ found in its block and
let $b_k$ be the square root of the absolute value of $D_{12}f$ for this block.

My proposal is to normalize all the values of $a_k$ and $b_k$ (computed for all possible blocks) relative to the maximum value of $a_k$ and look at their scatterplot.  For an additive function with no error, the $b_k$ are always zero and the scatterplot will be perfectly horizontal with no correlation.  When there is error, suppose the typical variance of the $\varepsilon(x,y)$ is $\sigma^2$.  Then the variance of the mixed differences will be $4\sigma^2$ while the $a_k$ will extend from near $0$ to the full range of $f$.  The square root of the absolute values of those first differences therefore will typically be around $2\sigma$ or so; provided this is small compared to the range of $f$, the scatterplot ought to be perfectly level--at least for the larger values of $a_k$.  (For the smaller values, $b_k$ will be constrained to be small no matter what.)  This is the second key idea and it seems to work.
This reasoning yields an additivity diagnostic plot: the normalized scatterplot of $(a_k, b_k)$ for noisy additive functions will

Tend to be near the horizontal axis and
Rise from the origin to a horizontal value well below $1$.

By contrast, the scatterplot for non-additive functions will tend to produce larger values of $b_k$ when the $a_k$ are large, because large ranges of functional values ought to exhibit relatively large deviations from additivity.  Consequently for many non-additive functions we expect the diagnostic plot to be nearly diagonal and linear, rising from the origin $(0,0)$ nearly to the opposite corner at $(1,1).$

Pictures are worth more than these words, so let's look at some examples.  In the figure I have constructed three functions whose values range approximately from $-1$ to $1$, sampled them on a $7$ by $7$ grid covering the square $[-1,1]\times [-1,1]$, generated a fixed normally-distributed noise vector of $\varepsilon(x_i, y_j)$ (with unit variance), and added various multiples $\sigma = 0, 0.1, 0.3$ of this noise vector to the three samples.  Each line of the figure corresponds to one function.  It displays the additivity diagnostic plots for the three versions--one with no noise and two with increasing noise--then shows the functional values on a grid, and finally shows the noisiest values on a grid.  The noise in that latter version has a standard deviation equal to $1/6$ the original range of the function, which is pretty big.  Notice, too, that a $7$ by $7$ grid has only $(7-1)(7-1) = 36$ degrees of freedom (independent mixed differences), which is a pretty small amount of data concerning these functions: all in all, this is a fairly difficult test of the procedure.

The red lines are lowess smooths of the scatterplots.
It should be evident which of these functions is additive: only the first one, $f(x,y) = (x^2+y^2)/2.$  The other two, $xy^3$ and $\cos(\pi x) \sin(2\pi y),$ are decidedly non-additive.  They are distinguished from the first in all three additivity diagnostic plots, which closely follow the preceding descriptions.  In short, because the plots on the first row (a) are low in height, (b) exhibit low correlation, and (c) have smooths that level off for larger values of $a_k$ (although the one for $\sigma=0.3$ is marginal), they signal that the first function may be additive.  Because the smoothed plots on the second and third rows all closely approximate the major diagonal of the square, they signal non-additivity of the data.
The visual similarities among the noisy versions of these functions (in the rightmost column) attest to the utility of this diagnostic plot.

Here is the R code used to construct the figure.  Do not try to apply it to large grids of data!  Because all $2 \times 2$ blocks of the grid are evaluated, the computational effort and storage requirements are both $O(m^2 n^2),$ which is pretty bad.  For instance, a medium-sized grid of (say) $m=50$ and $n=100$ has $6063750$ blocks to evaluate!  (For anyone lucky enough to have such a rich dataset, consider subsampling the blocks rather than exhaustively evaluating all of them.)
#
# Compute all rectangular differences.
# More generally, `fun` will be applied to all 2 x 2 sub-blocks of a.
#
diff.rect <- function(z, a=matrix(c(1,-1,-1,1), 2), fun) {
  if (missing(fun)) fun <- function(x) sum(x*a)
  m <- dim(z)[1]; n <- dim(z)[2]
  ii <- combn(1:m, 2); jj <- combn(1:n, 2)
  sapply(1:dim(jj)[2], function(j) {
    sapply(1:dim(ii)[2], function(i) fun(z[ii[,i], jj[,j]]))
  })
}
#
# Compare ranges to differences.
#
additive.test <- function(z, ...) {
  z.diff <- diff.rect(z)
  z.range <- diff.rect(z, fun=function(x) diff(range(x)))
  scale <- max(z.range)
  z.range <- z.range / scale
  z.diff <- sqrt(abs(z.diff) / scale)
  plot(z.range, z.diff, cex=0.7, col="#40404080", ylim=c(0,1), ...)
  abline(h = median(z.diff), col="#4040ff80", lty=2)
  lines(lowess(z.range, z.diff), lwd=2, col="Red")
}
m <- 7; n <- 7
x <- seq(-1, 1, length.out=m)
y <- seq(-1, 1, length.out=n)
#
# Plot differences against ranges.
#
require(raster)
image <- function(x, ...) plot(raster(x), asp=dim(x)[1]/dim(x)[2],
                               axes=FALSE, frame.plot=FALSE, ...)
par(mfrow=c(3, 5))
set.seed(17); error <- rnorm(m*n)
for (f in c(function(x,y) (x^2 + y^2)/2,
            function(x,y) x * y^3,
            function(x,y) cos(pi*x) * sin(2*pi*y))) {
  f.body <- deparse(f)[2]
  f.xy <- outer(x, y, f)
  for (sigma in c(0, 1/10, 3/10)) {
    g.xy <- f.xy + error * sigma
    additive.test(g.xy, main=paste("sd =", round(sigma, 2)),
                  xlab="", ylab="", cex.main=9/10)
  }
  image(f.xy, main=f.body, cex.main=9/10)
  image(f.xy + error * 3/10, main="SD = 0.3", cex.main=9/10)
}

Determining if a function is additive


Bing AdCenter API java keyword report Campaignid

Question: I am working with the KeywordPerformance java report example. Is there a parameter for campaignid that will allow the request to pull all of the campaigns back for an account?
Comment: I would remove the Google AdWords tag. Your question is about the Bing's API.
Comment: Thanks!  Working on both at once :)
Answer: Set one or several client account ID/IDs. Set also the right scope.
<code>    KeywordPerformanceReportRequest reportRequest =
        new KeywordPerformanceReportRequest();

    // Specify the language of the report.
    reportRequest.setLanguage(ReportLanguage.English);

    // Specify the format of the report.
    reportRequest.setFormat(ReportFormat.Xml);
    reportRequest.setReturnOnlyCompleteData(false);
    reportRequest.setReportName("Keyword Report");
    reportRequest.setAggregation(ReportAggregation.Daily);

    reportRequest.setTime(.....);

    // Specify the scope of the report.
    AccountThroughAdGroupReportScope scope =
        new AccountThroughAdGroupReportScope();
    scope.setAccountIds(ids);
    reportRequest.setScope(scope);
</code>
See also:
http://msdn.microsoft.com/en-US/library/bing-ads-reporting-keywordperformancereportrequest.aspx
http://msdn.microsoft.com/en-US/library/bing-ads-reporting-accountthroughadgroupreportscope.aspx
Then also call these if you like:
reportRequest.setFilter
reportRequest.setColumns
So I think the answer is:
Just don't set any CampaignIDs.
Provide only the client account(s) ID(s).


Composition of a convex function and a convex decreasing function is quasi-concave

Question: Let $h$ be a convex decreasing function and $g$ a convex function. Is it true that $h(g(x))$ is a quasi-concave function?
Answer: Yes.
Since $g$ is convex, for $\lambda \in [0,1],$
$$g(\lambda x +(1-\lambda )y) \leq \lambda g(x) + (1-\lambda)g(y).$$
and
$$\lambda g(x) + (1-\lambda)g(y)\leq\max[g(x),g(y)]$$
Since h is decreasing,
$$h[g(\lambda x +(1-\lambda )y)] \geq h[\lambda g(x) + (1-\lambda)g(y)]\geq h(\max[g(x),g(y)])\geq \min[h(g(x)),h(g(y))].$$
Answer: You don't need $h$ to be convex. Also, you only need $g$ to be quasiconvex. The following two facts should be observed:

Composition with any increasing function preserves quasi-convexity and quasi-concavity
A function $f$ is quasiconvex if and only if $-f$ is quasiconcave.
Therefore, composition with any  decreasing function turns  quasi-convexity into  quasi-concavity, and the other way around.


FileSystemWatcher - Como pegar o usuário que modificou arquivo C#

Question: Desenvolvi uma aplicação que monitora os eventos no filesystem usando a classe FileSystemWatcher e gostaria de deixar instalado no servidor de arquivos acontece que preciso registrar o usuário que acessou o arquivo pela rede.
Observação: localmente sei que posso usar:
System.Security.Principal.WindowsIdentity.GetCurrent().Name

ou
ManagementObjectSearcher searcher =
                 new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();

e pela rede?
Comment: que tal fazer um registro dos usuarios num BD. Quando for alterar o arquivo pedir confirmação de usuário, senha e confirmado passar info da hora e nome do usuário pra uma outra tabela. Fica inviável?
Comment: Fala aí. Putz cara inviabiliza muito. Deve existir uma forma, o próprio SO registra estes eventos quando a auditoria de arquivos é habilitada. :(
Answer: No título você diz usuário que alterou, mas na pergunta você diz o usuário que acessou.
Caso queira o usuário que acessou, você não conseguirá pelas propriedades do arquivo. Provavelmente terá que implementar um controle de acessos aos arquivos.
Caso queira o último usuário que alterou, você terá dificuldades quando o usuário for de outro domínio.
Caso esteja no mesmo domínio, tente o seguinte código:

var usr = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.SecurityIdentifier));

ou

var usr = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount));

Comment: Fala ai @Felipe Grossi... Usando o método `SecurityIdentifier` retorna o id e usando  'NTAccount' retorna algo assim "BUILTIN\Administradores".
Comment: Encontrei esta outra forma no stackoverflow gringo: string Owner = File.GetAccessControl("path").GetOwner(typeof(SecurityIdentifier)).Translate(typeof(NTAccount)).ToString();
Comment: @ThiagoCeconelo lendo este artigo: https://stackoverflow.com/questions/6016279/objectsecurity-getowner-returns-group-rather-than-user tive o seguinte questionamento: Como você tem acesso de administrador de domínio, o resultado pode ser inesperado. Peça para um usuário "comum" alterar o documento e rode o programa novamente para ver se o resultado sai conforme você deseja.
Comment: Cara funcionou... pelo menos em partes ... Quando o arquivo é deletado já não consigo usar esta função. :( . Cara como será que o SO registra isso no event viewer? Tem idéia?
Comment: Pelo que estou entendendo, você precisaria seguir por um caminho de controlador de acessos... mas como esta desenvolvendo na mão, vamos ver os recursos disponíveis. Para verificar o histórico de exclusão, tem como utilizar o event viewer sim, porém você terá que habilitar o audit dos arquivos. De uma olhada nesse artigo: https://support.microsoft.com/pt-br/help/301640/how-to-set--view--change--or-remove-auditing-for-a-file-or-folder-in-w
Comment: Pois é .. Agora como ou melhor que classe ou dll que o SO usa para registrar estes eventos associando os mesmos ao usuário? Cara complicado ...rsrs
Comment: Vejo que você vai ter que dividir seu problema em 2 partes:
1) Alteração / Criação do arquivo (que entendo você já ter o domínio do assunto)
2) Log de exclusão do arquivo (que você ainda não conseguiu dominar o assunto)
Vou dar mais uma pesquisada para ver se consigo te ajudar com o log da exclusão dos arquivos...
Comment: Pelo que pesquisei, para resolver o problema do arquivo deletado o caminho mais fácil e que provavelmente será lento... é habilitando o audit do windows: http://support.microsoft.com/kb/310399 e buscando pela classe System.Diagnostics.EventLog os eventos logados no event viewer.


Are a zero-truncated Poisson and basic Poisson nested or non-nested?

Question: I've seen plenty that discusses whether a basic Poisson regression is a nested version of a zero-inflated Poisson regression. For instance this site argues that it is, since the latter includes extra parameters to model additional zeroes, but otherwise includes the same Poisson regression parameters as the former, though the page does include a reference that disagrees.
What I can't find information about is whether a zero-truncated Poisson and a basic Poisson are nested. If the zero-truncated Poisson is just a Poisson with the extra stipulation that the probability of a zero count is zero, then I guess it sounds like they could be, but I was hoping for a more definitive answer.
The reason I'm wondering is that it will affect whether I should use Vuong's test (for non-nested models), or a more basic chi-square test based on the difference in loglikelihoods (for nested models).
Wilson (2015) talks about whether a Vuong test is appropriate for comparing the zero-inflated regression with the basic one, but I can't find a source that discusses zero-truncated data.
Answer: Just come across this now.   To avoid confusion, I am the Wilson of Wilson(2015) referenced in the original question, which asks whether the Poisson and truncated Poisson models are nested, non nested etc. Slightly simplifying, a smaller model is nested in a larger model if the larger  model reduces to the smaller one if a subset of its parameters are fixed at stated values; two models are overlapping if they both reduce to the same model when subsets of their respective parameters are fixed to certain values, they are non-nested if no matter how parameters are fixed one cannot reduce to the  other.  According to this definition the truncated Poisson and standard Poisson are non-nested. HOWEVER, and this is a point that seems to have been overlooked by many, Vuong's distributional theory refers to STRICTLY nested, STRICTLY non-nested, and STRICTLY overlapping. "STRICTLY" referring to the addition of six restrictions to the basic definition of nested etc. These restrictions are not exactly simple, but they do, among other things, mean that Vuong's results about the distribution of log likelihood ratios are not applicable in cases where models/distributions are nested at a boundary of a parameter space (as is the case with Poisson/zero inflated Poisson with an identity link for the zero-inflation parameter)  or when one model tends to the other when a parameter tends to infinity, as is the case with the Poisson/zero-inflated Poisson when a logit link is used to model the zero-inflation parameter. Vuong advances no theory about the distribution of log likelihood ratios in these circumstances.  Unfortunately here, this is the case with Poisson and truncated Poisson distributions, one tends to the other as the parameter tends to infinty, to see this, note that the ratio of the pmfs of Poisson and truncated Poisson distributions is 1-exp(-lambda) which tends to 1 as lambda tends to infinity, thus the two distributions are not stricty non-nested, or strictly anything  for that matter, and Voung's theory is not applicable.
The following R code will simulate the distribution of poisson and truncated Poisson loglikelihood ratios. It requires the VGAM package.
n<-30
lambda1<-1
H<-rep(999,10000)
for(i in 1:10000){
  print(i)
  y<-rpospois(n, lambda1)
  fit1 <- vglm(y ~ 1, pospoisson)
  fit2<-glm(y~1, family=poisson(link="log"))
  H[i]<-logLik(fit1)-logLik(fit2)
}

hist(H,col="lemonchiffon")

Answer: The basic Poisson can be thought of as nested inside a more general form:
$p(x) = (1-p)\frac{\text{e}^{-\lambda}\lambda^x}{x!} + p1(x=0)$
When $p = 0$, we have the basic Poisson.  When $p = -\exp\{-\lambda\}/(1 -\exp\{-\lambda\})$, we have the zero-truncated Poisson.  When $-\exp\{-\lambda\}/(1 -\exp\{-\lambda\}) < p < 0$, we have a zero-reduced Poisson.  When $0 < p < 1$, we have a zero-inflated Poisson, and we have a degenerate distribution at $p = 1$.
So it seems to me that the nested version of the Vuong test, or the chi-square as you suggest, would be appropriate in your case.  Note, though, that the chi-square can have problems due to the small probabilities of "large" (relative to $\lambda$) observations.  You'd probably want to use a bootstrap to get the p-value for the chi-square statistic instead of relying on the asymptotics unless you've got rather a lot of data.
Comment: @Scortchi I am curious about the definition of "nested" you are applying.  Although I don't disagree with your conclusion, I come to it from a slightly different point of view: yes, the Poisson is nested within this family (because it arises by restricting to $p=0$) but various conclusions about asymptotic distributions of MLE parameter estimates for $p$ do not apply because this value of $p$ *lies on the boundary* of the family.  Am I missing some important distinction?
Comment: @whuber, I was going to comment/provide an answer about the same point.  The [referenced link](http://statisticalhorizons.com/zero-inflated-models) does note: "... although the chi-square distribution may need some adjustment because the restriction is on the boundary of the parameter space"
Comment: NB *Both* the Poisson & the zero-truncated Poisson are special cases of the distribution you've defined. One isn't nested in the other. So you can't use Wilks' theorem to derive an asymptotic chi-squared distribution for twice the log likelihood ratio, whichever you consider to be the null hypothesis. (I think there are some regularity conditions for the Vuong test too.)
Comment: Thanks @jbowman - that's the sort of more rigorous answer I was hoping for. I'm unclear though: I thought the whole point of a Vuong test was for non-nested models, so even though it goes beyond my original post, could you provide a little more information about the "nested version of the Vuong test". To be clear about the source of my confusion: up until this moment I was only aware of the `vuong` function in package `pscl` in R which says it's for non-nested models. I just googled and found function `vuongtest` in package `nonnest2` which includes an argument 'nested'. Is that it?
Comment: Yes, that is.  Actually, the Wikipedia page https://en.wikipedia.org/wiki/Vuong%27s_closeness_test on the Vuong test is mildly helpful (often it's not so much) in describing the difference.
Comment: Great. Follow-up question: what would the difference in df between a plain Poisson and a zero-truncated Poisson be, for the chisq test? Apologies if that should be obvious from your description, but I'm afraid I'm not as mathy as I should be.
Comment: Just divide all the probabilities by $(1-\exp\{-\lambda\})$ (and set $p(0) = 0$, of course).  That makes all the probabilities sum to 1. I have to say, though, that I suspect a chi-square wouldn't be as powerful as just testing the probability of seeing 0 "0" values given that the estimated probability of seeing a 0 is $\exp\{-\lambda\}$.  Not sure about that, though.  The idea is that the relative probabilities of all integers > 0 are the same, and if you observe even one "0" you don't need a test to reject zero-truncation, so focusing on p(0 | non-zero-truncated) might give a better test.
Comment: @Scortchi - arrgghhhhh.... what was I thinking?  Well I'll probably delete the answer, or I'll have to rewrite it so that it is correct.
Comment: @jbowman: Please don't delete it: (1) it illustrates that the two models mentioned aren't nested, & (2) considering tests about or confidence intervals for $p$ in this broader model is a useful approach in itself (have you ever really had to decide between a Poisson & a zero-truncated Poisson based on the observations?).
Comment: @whuber. The two specific models the OP's interested in aren't nested one within the other, & each has only one parameter to estimate - $\lambda$. That's all I meant to point out, & I hadn't got as far as you in thinking about inference about $p$ in the broader model given in this answer.


Jquery child element links

Question: I am using the following function to create a simple accordion. The problem is that the final tier that opens contains links. These links inherit the click function from their parents and therefore don't function correctly as links. Any ideas on how to avoid this? Ta
jQuery('.loc_level_1').click(function(){
    jQuery(this).children('.level_2').slideToggle('200');
    return false; // this prevents event bubbling
});

Comment: You should include your HTML.
Answer: Adding a handler to the links and stopping propagation from there should work:
jQuery('.level_2 a').click(function(e){
    e.stopPropagation();
});

http://jsfiddle.net/infernalbadger/f8PRF/
Answer: I don't understand - it seems you wrote the solution to your problem already :)
However, it would be more elegant to just do:
jQuery('.loc_level_1').click(function(event){
    jQuery(this).children('.level_2').slideToggle('200');
    event.stopPropagation();
});

Comment: Thanks, this method works but now it adds the link url to the end of the existing URL?
Comment: That means that your links probably don't start with protocol (`http://` or some other)... **Also**, if `.loc_level_1` is actually `` I would suggest doing `event.preventDefault()` as well...
Answer: Use this:
jQuery('> .loc_level_1').click(function(){
    jQuery(this).children('.level_2').slideToggle('200');
    return false; // this prevents event bubbling
});

The ">" means "only select immediate children, not children-of-children".

Jquery child element links


Choosing samples of different sizes - considerations?

Question: Let's say I have four populations with the sizes 2451, 2117, 7577, and 1545. Each of these are sets of activity sequences on which I do sequence analysis. Based on this I want to do clustering based on pairwise dissimilarity scores. When I do such cluster analysis with the full datasets, it seems that the results of the clustering is degenerative - i.e. it cannot clearly separate out clusters with different characteristics. However, with smaller N it is able to more clearly separate out the different clusters.
For these computational reasons I need to sample so that each sample has an N of maximum 1000. Assume that I have perfect control over the sampling process, and that sampling more or less does not increase any costs.
What is the best strategy for sampling? Should I take say 10% of the observations from each population? Or would it be better to simply select 1000 observations from each population? What considerations would go into making such a decision?
Comment: Why are you trying to do sampling when you have all of the population data? Any analysis of samples is used to make inferences about the population. Once you know the population then the analysis of samples is unnecessary since you can just state the true values of variability and central tendency with no margin of error.
Comment: Please tell us the *purpose* of the sampling.  What will you do with the sample results?  What do you know in advance about the populations?  Would it be possible to sample the populations in stages, analyzing the results of each stage before attempting the next stage?
Comment: @John's comment is well to the point.  It is hopeless to expect better results by eliminating information!  It appears your problem is really about clustering and not about sampling at all.  But to make progress you would need to provide details of what you are attempting to do and what the results have been so far.
Answer: First it should not only be "for computational reason," but rather if an n of 1000 will let you derive the estimate with an acceptable margin or error (if it's a survey) or test the suggested associations or differences.
Second, to keep them proportional or not depends on if you'd like to draw conclusion only base on each population, or you'd also like to draw conclusion for all these four populations together.
Say, if they are four districts in a city, and the city planner would like to know more about all four district, then it's better to take 7.3% (see footnote 1) from each of the population. That is equivalent to simple random sampling and you can get a city-level estimate without the need to weight any subject.
If your interest is purely district by district, then randomly selecting 1000 withing district will probably be easier to administer and analyze. But do you really need a sample rate of nearly 60% for the population with N = 1545? That'd be potentially wasteful.
You can also consider assigning different sampling weight... but at the end the research questions should be decided first before sampling schemes are drafted. I'd guess more information about your work is needed.

1: Assuming the final sample is 1000, sampling 1000 out of (2451 + 2117 + 7577 + 1545) = 13690 people is approximately taking 7.3% in each population.
Comment: Where does the 7.3% figure come from?
Comment: I thought the total N was 2451 + 2117 + 7577 + 1545 = 13690. Then the sampling rate would be 1000/13690 = 0.073.
Comment: "Each sample has an N of maximum 1000" and "1000 samples from each population" both suggest many more than 1000 units can be sampled in total.  Regardless, when introducing the result of a calculation in an answer it will help your readers to explain how you arrived at it.
Answer: If you're trying to estimate the parameters of each population, I would think the best strategy from a strictly accuracy (not necessarily efficient use of time) standpoint is to randomly sample 1000 from each population.
Of course I think depending on tests being used, the actual sample needed to make reasonable estimates of each population is significantly smaller, if obtaining these samples takes significant time or energy.
Comment: I assume it is better because it maximizes the size of each sample?
Comment: Well, yes, each additional sample makes it more probable (marginally) that you'll accurately estimate the parameters of the population. Of course do you need 1000 samples to estimate a population of 1500? No - I don't have the formula/ confidence interval calculations here, but you reasonably only need a a couple hundred likely, if that.
Comment: This answer is incorrect for two principal reasons. First, finite-sample corrections will cause the sample sizes to be slightly unequal. More importantly, other considerations ought to dominate, especially any information about the variability within each population and information about the relative costs of sampling the population.


How to add filter on node list in a custom module?

Question: I am developing a module. In that module I have a page to list all the nodes of a specific type to user.
I need to:
1- show the nodes each on a row with ' Edit | Delete ' link in each row.
2- I also need to show a dropdown to give the user ability to filter the nodes by one of the node field.
I've created the first one but I don't know how to add a custom filter to the output.
Would you help me ?
I am working on Drupal 6.
Thank you.
Answer: If you are using Views 3 and within CCK you have listed allowed values for the field in question, you can set it up like this.

Select the field in question with the allowed values option, eg, in Filters, select 'Content: Field Name (field_name) - ALLOWED VALUES'
Click on EXPOSE.
Click in the values and select them all.
Click Limit list to selected items.
Save it.

You should now have an exposed filter with a drop down that limits the view to that field.
Answer: You can use views for listing nodes of specific types.
Also, in views, you can use Contextual filters for other options.
Please explore more options of views and you will find every option there.
Thanks.
Comment: Answers should go into much more detail. I do not believe that a drop down list on an exposed filter can be easily populated using a field from the nodes. Please expand to let the OP know how to accomplish what he is trying to do.
Comment: But if I build a page display view I guess setting permission is a little difficult, because I have some other views and give unregistered user view permission but for the issue I asked in question I want just authenticated ones see the view. As I remember I can't set permission for views separately.
Comment: @hd. That's where you remember wrong. Different views have different permissions, for sure.


How do I get per month average in an Excel Pivot Table

Question: This may sound simple but I can't seem to figure this out.  I have a data table that looks like something below.  I've created a couple of pivot tables with charts and dropped them on a dashboard with a timeline slicer.  Right now it just shows sums, but I want the user to be able to switch between sum and average hours/month.
If I change the total column on the pivot table to average, it shows average hours per employee across all months. How do I set this up so it totals each month and then shows the average of the months?
Employee    |Hours  |Task   |Department |Month
Joe         |20     |A      |East       |Jan, 2018
Joe         |20     |B      |East       |Jan, 2018
Bob         |40     |A      |West       |Jan, 2018
Joe         |20     |A      |East       |Feb, 2018
Joe         |20     |B      |East       |Feb, 2018
Bob         |40     |B      |West       |Feb, 2018
Joe         |20     |A      |East       |Mar, 2018
Joe         |20     |B      |East       |Mar, 2018
Bob         |40     |B      |West       |Mar, 2018

UPDATE
Here's what I want the pivot table to look like.  I'm showing two different views because as the user changes the month filter it will adjust.
Task    |Jan    |Feb    |Mar    |Sum    |Average
A       |60     |20     |20     |100    |33.33
B       |20     |60     |60     |140    |46.66

Task    |Feb    |Mar    |Sum    |Average
A       |20     |20     |40     |20
B       |60     |60     |120    |60

The issue here really stems from the way the data table is setup.  If I collapsed the employee entries down into Task sums (i.e. remove employees)  then I could easily get at the average per month.  However, I need to keep the data at the employee level.
Comment: show expected output please?
Answer: Without seeing your desired outcome, I will update answer if you provide, here is a way to see both views. You can add the same field twice to the values area and for the first summarize field value by sum and for the other by average

With months as columns (note average is calculated on field record count not distinct count)

To get your average by month count, add your pivottable to the data model, then add the count of month, summarized as distinct count, to the values area, and then add a measure to calculate the sum of hours/distinct count month.
Comment: This is showing the average of each row that goes into the total.  I want to show the monthly average of all months.  So in your example, if that was for Task A, the bar chart would show Task A: Total 240 and then Task A: Average 80
Comment: No, average here is calculating the average for each row that makes up each month.  So in your second image above it shows the average of Task B = 28.  I need the number to be 46.66 (140/3 months, not 140/5 employee hour entries across the 3 months)
Comment: Is not simply pivot the months into columns?


What to do when an omitted level-2 predictor is associated with a level-1 predictor?

Question: Raudenbusch and Byrk (2002) write on p. 261:

If an omitted level-2 predictor is associated with a level-I
predictor, the coefficient for that level-1 predictor will be
estimated with bias. In this case, we have $Cov(u_{qj}, X_{q'ij}) \neq 0$. This problem can be solved, however, without elaborating the
level-2 model. Any covariance between a level-1 predictor, $X_{qij}$
and a level-2 random effect must operate through the covariance
between the group mean $\bar{X}_{qj}$ and that random effect. Such a
covariance can be eliminated by group-mean centering the level-1
predictor.
Alternatively, inclusion of $\bar{X}_{qj}$ as a covariate in each
level-2 equation will eliminate any confounding between $X_{qij}$ and
omitted variables at level 2.
These two approaches suggest a specification test for the effect of
omitted level-2 predictors on a fixed level-1 coefficient. One runs
the model with and without group-mean centering of the level-1
coefficient. If the fixed level-1 coefficient associated with that
level-1 predictor remains essentially unchanged, the model is not
vulnerable to this type of bias.

They don't seem to pass any judgment on which of these two approaches should be preferred if the model is vulnerable to this type of bias. What should drive such a decision? Is one of the methods generally better?
Raudenbush, S. W., & Bryk, A. S. (2002). Hierarchical linear models: Applications and data analysis methods (Vol. 1). sage.
Answer: A little late to the party, but I thought I'd provide some perspective. In this section of the text they are talking about something economists call endogeneity or subject-level unmeasured confounding. These are fancy words/phrases for the situation where a correlation exists between predictors and the error term (of which there are at least two in a multilevel model).
The possibility of endogeneity is the reason that economists tend to prefer so-called fixed effects models, in which they treat the clusters they have in their data as the universe - they are only interested in making inferences about that group of clusters. Practically, fixed effects models include a set of 0/1 indicators for all clusters as predictors in an OLS model (although R, Stata, SAS, etc. have special packages or programs for these models). The challenge with these models is that group-level variables cannot be included so if one's theory is about a group-level variable, they will have trouble testing it in the fixed effects framework.
In terms of the two options proffered by Raudenbush & Bryk, I don't think either one is more highly valued than the other. Each strategy "protects" the level 1 variables from level 2 endogeneity, but any level 2 predictors are still subject to endogeneity concerns. It depends a bit on your modeling goals. It is suggested by Enders and Tofighi (among others; see this nice summation by Jason Newsom) that if you are going to specify random slopes for lower-level variables, then group-mean centering is helpful. So in that case, you might group-mean center all level 1 variables. If, on the other hand, you are not modeling random slopes, then perhaps just including the level 2 means of of all level 1 variables in the model is better. At least there, you can look at the tests of significance for the group mean coefficients to see which variables might be problematic.


Why doesn't the MLB implement a salary cap?

Question: I was reading an article in FiveThirtyEight a few months back which described the NBA as one of the most lopsided leagues in North America. By that it meant that the same teams tended to be successful, and you could come close to predicting which teams were likely to win a championship before the season even started.
Second on that list was the MLB. When you look across the MLB it's very easy to identify a handful of power-houses who usually do well, and then half the league who is written off from the very start.
Logically speaking, this seems to be a major problem because the entire league becomes more about which owner has the most money, and less about which team is actually managed and performs the best.
So why is it exactly that the MLB hasn't implemented a salary cap yet?
Answer: The owners would implement a salary cap in a New York Minute if they had the opportunity.  The players, however, would not agree, and because MLB is so successful monetarily even without one, and also has one of the most powerful players unions, the owners don't have the power to force it on them.  It's not hard to find articles about how the MLB owners would like a salary cap and the MLBPA refuses; see this one, this one,
Why is that?  Because a salary cap is not intended to create parity.  The primary function of a salary cap is to reduce player salaries, or at least keep them from escalating too quickly.  Salary caps reduce the maximum a player can earn - either directly (NBA-style) or indirectly (NFL style) by simply reducing the total amount a team may spend on salaries.
The problem with MLB being uncapped (particularly pre-recent luxury tax rules) was that player contracts simply escalated as new owners came in and decided to spend a lot.  That escalation was not necessarily related to total income of the league.  NFL and NHL, and to a lesser extent NBA (which is a softer cap closer to MLB's current system) have direct ties between revenue and player salaries - which mean you can't have player salaries escalate dramatically, unless the total revenue for the league is very high.
Look at the following chart of post-1994 strike revenue vs. player salaries:

While the two lines trend together over the long term, there are some regions that are very different - particularly in 2001-2004 and 2008-2012 where player salaries were well above the trend line compared to the MLB revenue.  Some of the major CBA changes were in direct result of these differences.  Note that the latest CBA seems to have finally had enough impact that the players' line is below the MLB line for the first time since 1998.
A full salary cap would guarantee it stayed below or on the trend line.  Hence why the owners - who are almost all businessmen who want to run a successful business, Jerry Reinsdorf aside - want a full salary cap.  And conversely, the MLBPA would prefer not to have one, so salaries can be higher thanks to free market bidding.

One note about the NBA: Because of the NBA's very ... odd ... salary cap, it actually has less fairness.  That's because Lebron-type players are badly underpaid due to the player-salary limit.  NFL and NHL style salary caps are much more fair in terms of evening out competition.  They also reward good front offices though - which is probably why they have fewer 'new winners' compared to the MLB. They also have less trading than the MLB of future talent for now talent, meaning that teams like the Rays, the Royals, the A's, etc. can grow on relatively small salaries by trading their good players away for future prospects who will be much cheaper.  MLB also has a far more limited salary structure for newer players - most players play three full seasons for almost nothing and three more at very low rates before becoming free agents, as opposed to the NFL (rookie salaries are limited, but far less so than MLB) or NBA.
Comment: But the league will pretend a salary cap is about parity.
Answer: Simple answer, the MLB and the MLBPA don't want a salary cap.  It isn't proven that a salary cap would make things any more competitive.  In terms of data, in the NBA for example, it has seemed to make things slightly less competitive.

In the past 30 years, 19 different teams have won the World Series. In comparison, only 14 different teams won the NFL Super Bowl, 13 won the NHL Stanley Cup and 8 won the NBA championship in that same time frame.

The only sport in that group to not have a salary cap is MLB.  So it shows, at least in terms of championships, that while the big money teams do have a better chance, it doesn't always matter, and there is certainly more parity in terms of who can win it all in MLB.
According to Wikipedia

Instead of a salary cap, Major League Baseball implements a luxury tax (also called a competitive balance tax), an arrangement in which teams whose total payroll exceeds a certain figure (determined annually) are taxed on the excess amount in order to discourage large market teams from having a substantially higher payroll than the rest of the league. The tax is paid to the league, which then puts the money into its industry-growth fund.[20][21]
A team that goes over the luxury tax cap for the first time in a five-year period pays a penalty of 22.5% of the amount they were over the cap, second-time violators pay a 30% penalty, and teams that exceed the limit three or more times pay a 50% penalty from 2013 onwards. There is also an incentive to lower payroll; if in any year a team goes under the threshold, the penalty rate decreases to 17.5%, 25% or 40% (depending on prior record over the previous five years) for the next time the tax is paid, which will apply from 2013.
The cap limit for 2011-2013 is $178 million, and for 2014-2016 $189 million.

According to this paper:

We find no evidence in our data to suggest that salary caps have helped competitive balance, measured as the variation in wins between the best and worst teams in a league in a given year, in professional sports. Further, there is some indication that the introduction of the salary cap in the NBA is associated with a significant decrease in competitive balance.
Answer: A cap obviously makes it more competitive. The NBA without a cap would be far more easy to predict a winner. That's why the NBA must have a cap -- it's a very predictable sport.
The players standing in the way of there being a salary cap is probably true. The owners of New York and LA teams would vote against a cap and everyone else would probably vote for a cap.
Due to a cap reducing what a player can earn, it is voted against. It ruins the sport and is very self-centered of the players. But a player isn't generally very bright, so it's no real surprise!
I would also disagree with the smarter post where it says the NBA has a bad salary cap and people like Lebron are underpaid. That's purely opinion and not factual. Salaries like Lebons stop teams like the Cavs from being able to bring in enough other talent to win a championship -- we see this all the time. Lebron takes 30 mil a year and then scratches his head why his team can't win. I would say Lebron takes too much of the allocated percentage and that we see this with just about all superstars in the salary cap era, apart from the Spurs and Warriors who were smart enough to avoid this (they avoided it by accepting less money.)
The reason the NBA still seems unbalanced is because you only have 5 players on the court and when 3 superstars decide to join forces, it makes them very hard to beat. That has happened lately. You can be rest assured it would be far worse without a cap. You would probably have all stars on two teams.
Comment: Welcome to SE.Sport. This opinions is very interesting, but it is better to confirm the written with any official source (if possible)
Comment: NBA's salary cap is "bad" because it doesn't do a very good job of being a salary cap: it's not a hard salary cap, and teams can go over it easily.  Lebron is underpaid by any reasonable metric you might choose; that's not controversial in the world of sports statistics.  It's in fact built into the salary cap - the limit on top player salaries.  If it weren't there, they'd be paid more (that's obvious - why have a limit otherwise?)
Comment: If you wanted to ask that as a question, though, I'd be happy to answer in much more detail.  It's quite an interesting topic (why the NBA salary cap does not encourage balanced competition, compared to the NFL or NHL), really.  You're not wrong that the NBA does have some aspects that will make it hard to ever have true balance - but an NHL style salary cap would go a long, long way to evening it.


Inject javascript body in blazor wasm dynamically

Question: All the methods I have seen in blazor wasm to inject Javascript involves calling a javascript function. what if I want to inject a dynamic javascript function block.
Example: await JS.InvokeVoidAsync("
Is this possible? "InvokeAsync" only seems to accept a function name.
Answer: Try it like this call the  function name and then pass the data as an argument, as you're directly invoking JS, the script tag is unnecessary
await JSRuntime.InvokeVoidAsync("alert", "Hello!");

Comment: Although, this works, I need to pass a dynamic custom function. see my answer below
Answer: Add the following function in index.html

call it from razor page: await JS.InvokeAsync<object>("addCode","alert('A')")
Comment: yup that works just be aware of dom xss https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html
Comment: I'm not sure why you would prefer this at all compared to the other one. You might as well just `eval` if you want to do that, and remember: there's always a way around eval. Why not just use the other solution?


Alternativa correta que implementa um validador para um campo data no Laravel

Question: a.
<code>$this->validate($request, [
    'data_nascimento' => 'regex:ddmmyyyy',
]);
</code>
b.
<code>$this->validate($request, [
    'data_nascimento' => 'required|date',
]);
</code>
c.
<code>$this->validate($request, [
    'data_nascimento' => 'digits:8|integer',
]);
</code>
d.
<code>$this->validate($request, [
    'data_nascimento' => 'datetime|null',
]);
</code>
Estou entre A e B, preciso de ajuda.
Comment: `regex:ddmmyyyy` está incorreto.
Answer: Acredito que essa seja a melhor, a sua data que vem da tela está no formato Brasileiro, ou seja, dia, mês e ano, utilize date_format com o formato d/m/Y:
<code>$this->validate($request, [
    'data_nascimento' => 'required|date_format:"d/m/Y"',
]);
</code>
Referencia: date_format:format
Comment: Obrigado pela informação.
Comment: @PedroSoares a sua data está no formato brasileiro? como está o formato?
Comment: Sim, formato brasileiro.
Comment: @PedroSoares se for a resposta da sua, pergunta assinale como resposta!


Wilcoxon Rank Test or T-Test?

Question: What data analysis is better? or fit for my data?
I've used Likert scale for my questionnaire (1-5) and I have 387 respondents.
Wilcoxon Rank Test or T-Test?
Comment: Better by what criterion? To consider what hypothesis? How many items in your scale? This question is much too vague and broad to really answer as it stands. In addition, more focused versions of this question are almost certainly already answered  -- e.g. see "Related" posts in the sidebar (-->) such as [this one](http://stats.stackexchange.com/questions/19681/when-to-use-the-wilcoxon-rank-sum-test-instead-of-the-unpaired-t-test), so even if you fixed your question enough to be answerable, it would probably be effectively a duplicate.
Answer: A discrete variable with so few possible values can not be assumed to be distributed Gaussian, so you can't use t-test.
Also be careful using Wilcoxon tests, which one of signed-rank and rank-sum tests you have to choose depends on your data and question. If you are interested in whether median score is greater than/less than a specified value, you can use 1-sample Wilcoxon test, a slightly different approach to Wilcoxon signed-rank test. If your respondents are divided into 2 groups and you want to know whether median score of one group is greater than other one, you have to use Wilcoxon rank-sum test. If you have again 2 groups, but the respondents are somehow dependent, like they are siblings or same persons answering before and after some event, you have to use Wilcoxon signed-rank test. And if the respondents form more than 2 groups, you should consider Kruskal-Wallis test.

Wilcoxon Rank Test or T-Test?


Pegar atributo dentro de um array no MongoDB

Question: Olá, amigos. Boa noite!
Estou tendo um problema no desenvolvimento de uma api, preciso fazer a consulta de alguns atributos dentro de um array de um Schema no MongoDB para adicioná-los à um e-mail de um pedido.
Alguém poderia me ajudar? segue abaixo o modelo do Schema:
Eu preciso pegar os valores do array 'items', porém só preciso de price, quantity e title.

const schema = new Schema({
    customer: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Customer'
    },
    email: {
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'Customer'
    },
    name: {
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'Customer'
    },
    number: {
        type: String,
        required: false
    },
    createDate: {
        type: Date,
        required: true,
        default: Date.now
    },
    status: {
        type: String,
        required: true,
        enum: ['created', 'done'],
        default: 'created'
    },
    items: [{
        quantity: {
            type: Number,
            required: true
        },
        price: {
            type: Number,
            required: true
        },
        product: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        },
        title: {
            type: mongoose.Schema.Types.String,
            ref: 'Product'
        }
    }],
});
Comment: Já deu uma olhada nesse [recurso](https://docs.mongodb.com/manual/tutorial/query-arrays/) para *Query* em *arrays*?
Comment: Qual é a dúvida mais especificamente? O que já tentou?
Answer: Você quer aplicar um filtro que pegue apenas esses três campos dentro de items certo. O findOne(conditions, [fields], [options], [callback]) ou sem callback com async/await. Ficaria assim.

Com async/await:

const { items } = await Products.findOne({_id: 'objectId' },'items.price items.quantity items.title')
consolelog(items[0])
res.status(200).send(items[0])

Resultado da busca com async:
{
    "quantity": "",
    "price": "",
    "title": ""
}

Sem async e com callback:

Products.findOne({_id: 'objectId'},'items.price items.quantity items.title', (err, result) => {
    if(err){
        console.log(err)
    }else{
        console.log(result.items[0])
        res.status(200).send(result.items[0])
    }
})

Resultado da variável result com uma lista dentro do objeto:
{
    "quantity": "",
    "price": "",
    "title": ""
}

No primeiro resultado eu usei desestruturação  para pegar apenas items, no segundo resultado com callback fica mais complicado mas nada que dificulte muito.


Ramsey Theory: Showing the existence of a special set of natural numbers.

Question: Show that there is an infinite set of natural numbers such that the sum of any two elements has an even number of prime factors.
My attempt:
Define a coloring on the doubletons of $\mathbb{N}$, that is a coloring $f:\mathbb{N}^{(2)}\to \{0,1\}$ by:
$$
f(\{x,y\}) = \left\{
        \begin{array}{ll}
            0 & \quad \text{if $x+y$ is has an even number of prime factors} \\
            1 & \quad \text{otherwise}
                    \end{array}
    \right.
$$
By the Infinite Ramsey Theorem, there exists an infinite subset $N\subseteq \mathbb{N}$ such that all of the doubletons of $N$ are colored $0$ or all of the doubletons of $N$ are colored $1$. If $N$ is monochromatic in $0$, then we are done, as $N$ witnesses the desired property. Otherwise, assume, $N$ is monochromatic in $1$. Then for every doubleton of $\{x,y\}\subseteq N$, $x+y$ has an odd number of prime factors. If there exists a prime $p$ such that for all $x\in N$, $p\nmid x$. Then define:
$$
pN=\{px \mid x\in N\}
$$
We have that for arbitrary $\{x,y\} \subseteq N$, $x+y$ has an odd number of prime factors. Therefore, we have that $px + py = p(x+y)$ will have an even number of prime factors and we are done as $pN$ witnesses the desired property. Otherwise, we have that $N$ satisfies: $$\forall p \exists x (p\mid x)$$
If there is a $p$ such that $p$ only divides finitely many $\{x_1,x_2,\ldots, x_n\} \subseteq N$  then $N\setminus \{x_1,x_2,\ldots, x_n\}$ is still an infinite set and we do the same trick as before:
$$
p(N\setminus \{x_1,x_2\ldots,x_n\})=\{px: x\in N\setminus \{x_1,x_2\ldots,x_n\}\}
$$
witnesses the desired property.
If not then for all $p$, $p$ divides infinitely many of the elements of $N$. In fact, for every prime $p$, $p$ divides all but finitely many elements of $N$. Because if there is an infinite subset $A\subseteq N$ and a prime $p$ such that $p$ divides each element of $A$ but $N\setminus A$ is infinite, then we can appeal to the same argument as above to obtain a set that has the desired properties. Now enumerate $N$ as $N=\{n_1,n_2,n_3,\ldots\}$, we know that for each prime $p$, there is an index $i$, such that $p\mid n_j $ for all $j\ge i$. We can deduce that there is a finite index $k$, such that every prime $p$ divides $n_i$ for  $i\ge k$. If not, then there is a prime $p$, such that for all $k\in \mathbb{N}$, $p\nmid n_i$ for $i\ge k$ which is not the case. So every prime number divides $\{n_k,n_{k+1},n_{k+2},\ldots \}$ a wild contradiction to the fact that $N$ is a subset of natural numbers.
My Question:
Am I coming to a false conclusion in the last paragraph? I feels ridiculous that I should end up deducing that the set: N has numbers that infinitely many primes divide.
Wrong conclusion. $``$We can deduce that there is a finite index $k$, such that every prime $p$ divides $n_i$ for  $i\ge k$." is not true, we cannot deduce that...
Comment: @AndresCaicedo I just realized I could have used the set: $\{pn+1: n \in \omega\}$ for fixed prime $p$, which makes the problem a triviality.... Also, I realized, the false logic there too
Comment: Everything goes well, until the last paragraph. You have that for each $p$ there is an $i$ such that $p\mid n_j$ for all $j\ge i$. This does not imply that there is a fixed $k$ such that $p\mid n_i$ for all $i\ge k$. For instance, let $n_i$ be the product of the first $i$ primes, for all $i$.
Comment: Yes. The problem was asked [here](http://math.stackexchange.com/q/7527/462) a few years ago (of course), and that was the approach, but I like the additional analysis that you provided.
Comment: I guess what I've proved is sort of interesting. Under this coloring, either there is a monochromatic set such that the sum of every two numbers of that set has an even number of prime factors or there is a monochromatic set such that each prime $p$ divides all but finitely many of its elements.
Answer: Ah we just use the set: $\{7n+1: n \in \omega\}$ to begin with.