Size and Power of Test: Poisson Distribution

Question: In a homework problem, I am given a Poisson distribution with $\lambda = 1$ as null hypothesis, $\lambda$ greater than or equal to 2 as an alternate hypothesis, and 3 as a test statistic. I am instructed to reject the null hypothesis if I observe that test statistic. We are describing traffic accidents in the problem, so the question is "What is the probability that you are committing a Type I Error if you reject the null hypothesis ($\lambda=1$) when you see 3 accidents?" I'm then asked for the power of the test.
My first thought was to use $(e^{-\lambda})*((\lambda^3)/(3!))$ to get the probability of 3 given a $\lambda$ of 1. But it seems like it has to be more complicated than that. Would someone mind putting me on the right track?
(By the way, I know it's extremely annoying to have the formula written in words rather than symbols---I'm brand new to the site and under sort of a time crunch, but I'll get it right in future posts. I apologize for the irritation!).
Answer: It is unclear from your question whether you are just observing one Poisson random variable, or a sample of them.  I will assume the latter, but the former follows as a special case.  Anyway, under this view of the problem you have $X_1,...,X_n \sim \text{IID Pois}(\lambda)$ and your hypotheses are:
$$H_0: \lambda = 1 \quad \quad \quad H_A: \lambda \geqslant 2.$$
Your rejection region is $\bar{X} \geqslant 3$, so you have power function given by:
$$\begin{equation} \begin{aligned}
B(\lambda)
&= \mathbb{P}(\text{Reject } H_0 | \lambda) \\[6pt]
&= \mathbb{P}(\bar{X} \geqslant 3 | \lambda) \\[6pt]
&= \mathbb{P}(n\bar{X} \geqslant 3n | \lambda) \\[6pt]
&= 1-\mathbb{P}(T < 3n | \lambda) \\[6pt]
&= 1- \exp(-\lambda) \sum_{k=0}^{3n-1} \frac{\lambda^k}{k!}. \\[6pt]
\end{aligned} \end{equation}$$
In the special case where $n=1$ (i.e., you have only one obesrvation) you have power:
$$\begin{equation} \begin{aligned}
B(\lambda)
&= 1- \exp(-\lambda) \Big[ 1 + \lambda + \frac{\lambda^2}{2} \Big]. \\[6pt]
\end{aligned} \end{equation}$$


How to assess overfitting?

Question: This is a follow-up of the question I posted earlier.
I am assessing the two RF models which are generated using two different set of features

NF - Test_Accuracy > Training accuracy (500 features)
HF - Test_Accuracy < Training accuracy (125 features)

Testing and Training is done using independent data sets and the accuracy is derived from the average of a 5-cross validation. The difference between the models are in the number of features. I am afraid there could be a possible overfitting in one of the model (It is not clear to me which model could be overfitting, because I have used independent dataset and k-cross validation on the datasets). I would like to know what are the standard methods (tools/libraries) which can be used to assess overfitting.
Answer: This result does not mean that you have overfitting.
First of all, CV is more reliable than test set -- you can have (bad) luck in selecting test, what results in (pessimistic) optimistic bias with respect to true accuracy. CV effectively smooths this problem by repeating the procedure of selecting test. What's worse for using the test, RF is a stochastic algorithm and so two runs with different seed will give you different test accuracies, and the difference may be even bigger than that between CV and test.
Second, you may use standard deviation of accuracy from all CV runs to test whether:

Your CV accuracy is really different from this on test.
One of the feature sets you used is really better than the other.
Comment: Thanks for the insightful answer. I will try with SD of accuracy for further analysis.
Answer: A common and well-established approach, complementing @mbq's answer, is using nested cross validation [1]. Basically, it's able to infer generalized performance of your method as there's two splits in the data: training (where you train), test (where you test and gather relevant performance metrics to perform tuning) and validation (where you test your tuning on yet unseen labelled data).
Set the number of folds and repeats of the inner and outer cross validation loops accordingly to the number of samples available.
To access overfit you can compare the performance in the inner loop to the outer loop. An overfitted model will perform much worse in the unseen data (i.e. validation data in our case).
Krstajic et al (2014) explain the method in details, and it's implemented in many statistical softwares and environments.
A similar approach is the so called double bootstrapping, where you perform bootstrapping in both loops instead of CV. Basically you can use any resampling strategy in either loop, given enough reasoning.
[1] Krstajic, D., Buturovic, L. J., Leahy, D. E., & Thomas, S. (2014). Cross-validation pitfalls when selecting and assessing regression and classification models. Journal of cheminformatics, 6(1), 1-15.

How to assess overfitting?


Backbone, correct way of saving data into a model?

Question: I have two ways of saving data (into a rest API), it works Ok in both ways but I was wondering which one is the way to go.
1st way:
// here serializeObject just converts form inputs into a serialized object
var inputs_data = this.ui.form.serializeObject();
// here in 3rd param from extend is the same as this.model.unset('logged');
var data = _.extend(this.model.toJSON(), inputs_data ,{logged: undefined});
// here I save and the data goes Ok!
this.model.save(data);

2nd way:
// here i serialize the object the same as above
var inputs_data = this.ui.form.serializeObject();
// here i exclude 3rd parameter
var data = _.extend(this.model.toJSON(), inputs_data);
// set data with model.set instead of model.save
this.model.set(data);
// remove unwanted attributes
this.model.unset('logged',{silent:true});
// finnaly just save
this.model.save(data);

So far I am using the 1st way, so I do not know if the app goes bigger it will bring any problems because of this.
Answer: If I were you I would use either Backbone.StickIt to synchronise an existing model with the form or use Backbone.Syphon to do something similar to what you are doing above.
Answer: I would go this way. You don't have to pass all attributes to model's save method, only the attributes that need to be changed (http://backbonejs.org/#Model-save)
var inputs_data = this.ui.form.serializeObject();
// remove unwanted attributes
delete inputs_data.logged;
// finally just save
this.model.save(inputs_data);

Comment: By watching the two ways I also got the conlusion that in the 2nd one  it would seem to work fine when updating model data and at the same time saving it, let's say like a live edit mode(sync).
Comment: Use `set` if you need to change model's attributes without syncing it. Then later you can call `save` without parameters to sync it to the server.


Printing a block in node.tpl.php

Question: Would appreciate it if someone could let me know how to print a block in node.tpl.php. I basically have a block created through a view and I haven't set a region for that block as I would like to do is display this block in a specific position in all my node pages.
This is what I did in my theme's template file:
function mytheme_preprocess_node(&$vars) {
  $vars['my_block'] = mytheme_block_render('views', 'myblock-block_1');
}

function mytheme_block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}

And in my node.tpl.php file, I just do:
<?php print $my_block; ?>

However, this is giving me a memory limit exhausted error.  I can get it to work perfectly if I render the block in mytheme_preprocess_page function and print it in page.tpl.php, but I need to print this in node.tpl.php.  I tried the following as well:
function mytheme_block_render($module, $block_id) {
  $block = module_invoke('views', 'block_view', 'myblock-block_1');
  return render($block);
}

That is giving me the same memory exhausted error.  Is it too later to render a block in the node preprocess function?  Why can I render it in the page preprocess function but not in node?  Is there some other preprocess function that we can render it in and then have access to it in node.tpl.php?
Comment: Possible duplicate of [White screen of death: Fatal error: Allowed memory size of X bytes exhausted](http://drupal.stackexchange.com/questions/54239/white-screen-of-death-fatal-error-allowed-memory-size-of-x-bytes-exhausted)
Answer: I think module_invoke() is correct and you can simply call that in your tpl file. However,
use
print $block['subject'];

print $block['content'];

instead of
print render($block);

Also
D6 and earlier:
$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];

D7:
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

Refer

http://drupal.org/node/359021
http://drupal.org/node/26502

for more some more help.
Comment: I added that directly in my node.tpl.php but the block is not showing up.
Comment: Please mention your Drupal version. Refer - http://drupal.org/node/26502
Comment: Edited my answer, added view more info, hope that helps.
Comment: I am using Drupal 7.
Comment: Looks like you have to do a print render($block['content']); Please try that and get back whether that solved it or not.
Comment: Yes!  That did fix it!  Doing print render($block['content']) is now displaying the block.  Thanks so much. You just saved me hours of work.
Answer: I used to encounter memory limit problem whenever I installed the Views module on a fresh installation. I usually added ini_set('memory_limit', '512M') in settings.php. It resolved my problem.
In your case, I'm not sure why are you facing this problem when you render your block to the template.
You could also give a try hook_node_view from the module level.
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        $block = module_invoke('views', 'block_view', 'myblock-block_1');
        $node->content['my_block'] = array(
            '#markup' => render($block['content']),
        );
    }
}

Comment: I hate to think about increasing the memory limit.  At this point, I can't afford to increase the memory anymore than 256M, which is what I have now.  I will give the module level a go and see what happens.  Thank you.  Still, wished there was a way to do it in the template file.
Comment: The following also works if you add it directly to node.tpl.php:

Printing a block in node.tpl.php


Horizontal movement of player causes egregious numbers when checking vertical velocity

Question: Player movement is working (at least somewhat) now, however one issue remains, and that's the insane numbers the y velocity of the Rigidbody2D on the player. Since the isGrounded check I plan to add will use velocity for the sake of stability, this needs to be fixed.
It confuses me, considering the velocity is 0 normally, but whenever moving left or right it changes to said high numbers.
Movement code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerM : MonoBehaviour
{
    private PControls control;
    Rigidbody2D rb;
    SpriteRenderer sp;
    Transform tr;
    public float speed = 0f;
    public float speedC;
    public float heightSpeed = 5f;
    public float heightC;
    public bool grounded;

    void Start()
    {
        control = new PControls();
        control.Enable();
        rb = GetComponent<Rigidbody2D>();
        sp = GetComponent<SpriteRenderer>();
        tr = GetComponent<Transform>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        RaycastHit2D hit = Physics2D.Raycast(rb.position, -Vector2.up);
        Color color = new Color(0, 0, 1.0f);
        Debug.DrawRay(transform.position, Vector2.down);
        speedC = rb.velocity.magnitude;
        var pos = control.Movement.Move.ReadValue<float>();
        float GetVerticalSpeed() => rb.velocity.y;

        if(pos == -1)
        {
            sp.flipX = true;
        }
        else if(pos == 1)
        {
            sp.flipX = false;
        }

        if((pos == 0) && (speed > 0.1f))
        {
            speed -= 3f * Time.deltaTime;
        }
        else if(speed < 1.4f)
        {
            speed += Mathf.Abs(pos) * 8 * Time.deltaTime;
        }

        if(speedC < 7f)
        {
            rb.AddForce(new Vector3((pos * 5), 0f) * speed * Time.deltaTime, ForceMode2D.Impulse);
        }

        var jump = control.Movement.Jump.ReadValue<float>();
        Debug.Log(GetVerticalSpeed());
        Vector3 v = rb.velocity;
        v.y = 10;

        if(jump == 1)
        {
            rb.velocity = v;
        }

    }
}

Comment: I would guess it has something to do with the rb.AddForce. Comment it out and share your results. Another thing. You should not instantiate inner methods. Its jot clean code over all but esspecially not in a fixed update. Wasted resources.
Comment: Yeah, I wasn't planning on keeping that anyways, it was more of an attempt to fix this. It does help make the x and y velocity number not jitter around, but the `rb.velocity.y` still puts out high numbers moving left and right.

Do note that the high numbers only occur when touching the tilemap collider (what I'm using for ground).
Answer: Seems the main issue was fixed by converting the height velocity to an integer using System.Math.Round():
float vel = rb.velocity.y;
heightC = (int)System.Math.Round(vel);

Not sure it's the best solution, but it's something..


Exibir imagem em Javascript

Question: Sou novo em Javascript. Preciso verificar se o usuário está navegando em um apple ou android e dependendo da condição, mostrar o botão da store correspondente.

    <button id="apple-store">Apple Store</button>
    <button id="google-play">Google Play</button>

Comment: Na verdade esse código que passei na pergunta já está trazendo o device correto, agora preciso mostrar a imagem na tela, não sei como fazer pra ele mostrar a imagem na página, dependendo do device.
Comment: Você pode fazer isso de várias formas vou colocar um jeito simples na resposta.
Answer: Pode fazer assim.

Comment: pra mostrar a imagem no HTML?
Comment: Qual a sua dúvida? Onde quer exibir a imagem ?
Comment: Cara, não trabalho com Javascript, então não manjo nada. Sei que o retorno está vindo correto, o caminho da imagem, porém quero exibir a imagem na página.
Comment: Fiz uma alteração, vê se deu certo, se não comenta o erro que está dando.
Comment: Uncaught TypeError: Cannot read property 'appendChild' of null. Linha 15: document.body.appendChild(x);
Comment: Como está o Html ?
Comment: Olá, bom dia. Desculpe a demora, mas na sexta tive q ir embora do trabalho e estou sem net em casa, fds de semana desconectado. A ultima coisa que fiz foi o código que vc passou acima, não coloquei nada no HTML e aparece o seguinte erro no console: index.html:15 Uncaught TypeError: Cannot read property 'appendChild' of null
Answer: Obrigado a disposição de todos em responder minha pergunta. Com a ajuda de vocês consegui chegar num resultado satisfatório. Sei que ainda dá pra melhorar, mas do ponto onde estava acho que foi um grande progresso. Segue abaixo o código inteiro.
<!DOCTYPE html>

    Web Detect

Exibir imagem em Javascript


Appoggiaturas not playing in Noteflight audio

Question: I have arranged Für Elise in Noteflight with two 16th note appoggiaturas circled in red. I expect them to play in the audio but they don't (unlike acciaccaturas which do play).

The bar with the appoggiaturas sounded like this (without the appoggiaturas):

I would expect them to sound like this:

Is there a way to make the appoggiaturas play in the audio? Any help would be appreciated.
Answer: So by default, both appoggiaturas and acciaccaturas play with audio in Noteflight, so something seems to be going wrong. Here is an example of me constructing an appoggiatura and the resulting audio:

So in resolving this, the first thing I would recommend is to try deleting the current appoggiatura you have in your score, and then re-entering the appoggiatura the way I did, and see if it solves the issue. (Make sure to input the appoggiatura using only the mouse, as there may be a bug with another input method causing this issue)
If not, I would next recommend creating an appoggiatura in a new, blank score. If it works in this new score, but not in the original score, that would show that there may be an issue with the settings in the original score, or that some other form of input was used in the original score that is causing an issue, and then we could move on from there!
(It is interesting to note, that Noteflight has no built-in feature for muting individual notes or setting either of the grace note styles to not play audio.)
(I would also ask, if neither of these options work, are you using Noteflight premium, or the standard version of Noteflight?)
Comment: Okay, first question, do you have Noteflight premium or are you using the free version?
Comment: Good to know, that at least rules out modifying settings in the premium version to see if that results in a bug fix. The next question would be, what web browser are you using for Noteflight?
Comment: I had figured out that the appoggiaturas did align with the left-hand 16th note arpeggio.
Comment: It still didn't work.
Comment: I am using the free version.
Comment: Google Chrome is what I am using
Comment: In my new score, the appoggiaturas did play.
Comment: Fantastic, that means there isn't an issue with the account or the web browser, but just something in that particular score. So we at least have the option to move over to a new score. But let's try and see if we can get it to work in the current score. Could you try adding a new measure at the end of the score, and then add an appoggiatura there, to see if it plays any sound?
Comment: The appoggiaturas are played as acciaccaturas in recordings, I think. Why did Beethoven use appoggiaturas to represent acciaccaturas?
Comment: @Vighnesh Single unslashed grace notes are usually appoggiatura.  When they have a slash through them they are acciaccatura. But multiple note acciaccatura usually don't have the slash for some reason.


Cannot add date parameter in Rest request (Rest Sharp)

Question: I´m trying to send some JSON information to a server. I add a preserialzed string to the body and place some attributes to the header.
            RestClient client = new RestClient(requURI);
            RestRequest request = new RestRequest(reqPath, method);
            request.RequestFormat = DataFormat.Json;
            request.JsonSerializer.ContentType = "application/json; charset=utf-8";

            request.AddHeader("Date", getIsoStringFromDate(DateTime.Now));
            request.AddParameter("application/json; charset=utf-8", JSonString, ParameterType.RequestBody);

Everything works perfecty except for the date Header that won`t show up. When I change the line to
           request.AddHeader("Datexxx", getIsoStringFromDate(DateTime.Now));

It will be shown in the header (see network trace)
          System.Net Information: 0 : [5620] ConnectStream#61150033 -   Header
          {
           Datexxx: 2015-03-16 16:19:39
           Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
           User-Agent: RestSharp 126.96.36.199
           Content-Type: application/json; charset=utf-8
           Host: localhost:8080
           Content-Length: 620
           Accept-Encoding: gzip, deflate
           Connection: Keep-Alive
          }

I assume "date" is a predefined or prefilled value by Rest Sharp.
I added a dateFormat definition with
          request.DateFormat = "MMMM dd, yyyy";

But there s still no date header attribute showing up. Also tried the clear all parameters before adding but doesn`t help either.
There has been a github bug concerning this but it is more than 2 years old.. maybe I´m just missing something like a "includeDateInHeader" switch.
I use .Net 3.5 and Rest Sharp 220.127.116.11. or 126.96.36.199. Thx in advance!
Answer: seems some attributes such as content-type or date cannot be added as parameter but are added internally. To alter the value of "content-type" I had to change the serialzer setting (altough I didn`t use it because I added a json in the body that was serialized before!)
RestClient client = new RestClient(requURI);
RestRequest request = new RestRequest(reqPath, method);
request.RequestFormat = DataFormat.Json;
request.Parameters.Clear();
request.AddHeader("Date", getIsoStringFromDate(DateTime.Now));
            request.JsonSerializer.ContentType = "application/json; charset=utf-8";

as soon as I did this the header showed up as intended:
System.Net Information: 0 : [5620] ConnectStream#61150033 -   Header
{
 Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
 User-Agent: RestSharp 184.108.40.206
 Content-Type: application/json; charset=utf-8
 ...
}

Comment: it still doesn't adds Date parameter, did you find out the reason or solution ?


Panels on frontpage

Question: I'm trying to use Panels module on my drupal's frontpage.
I've created view called front_page with path set to front, proper node panel, set selection rules to URL (i've tried both front and <front>) but no matter what i'll set in Panel variant settings, i'm allways getting the default front page provided by drupal (or the one set in Site Information). When i'll change my variant's URL to i.e. node/*, it works fine. I simply can't just set a selection rule for front page.
Do you have any idea what am i possibly doing wrong ?
thanks in advance.
Answer: in panels there is a option for set the panel as homepage.
that checkbox the only thing to do is set here: http://yoursite/admin/settings/site-information
the path of your panel as homepage.
So, if the url of your panel is "home-page"  then just in the site-information section put that path as a homepage.
Comment: hmm where is that 'make this panel homepage' checkbox exactly ? I was reading something about it earlier but wasn't able to find it
Comment: oh it's ok, i've found it, i forgot that there is an option to create `Page Panel` in `Panels` module. Thanks!

Panels on frontpage


Is there one splitting strategy for both K-NN and Matrix Factorization recommender systems?

Question: I am researching several different recommender systems, some of which are based on a user K-Nearest Neighbour algorithm and some of which are based on a matrix factorization algorithm. My dataset is sparse and consists of interactions between users and items. Now, I am trying to split the data into a train and test set. My initial idea would be naively splitting the known interactions randomly (80-20). However, this is impossible, as KNN and MF algorithms have different requirements:

KNN: The test set should ideally contain the full profile of the user, i.e. it should contain all the known interactions of a set of test users.
MF: The test set should only contain users who are also in the training set, i.e. at least one interaction of every user should be present in the training set.

The two requirements clearly conflict. However, for standardization purposes, there should be one dataset to cover both types of algorithms. I cannot find much information about this in the literature. Is there a standard way of splitting that can be used for both scenarios?
Answer: I'm not sure where did you found the requirements and it lacks context, but I don't fully agree with them. First, notice that "all the interactions" and "at least one interaction" are not in conflict, but the second one is just more liberal.
Second, recall how the algorithms work. In $k$-NN, you make the recommendation based on the smallest distance among neighbors. In matrix factorization, you predict the missing ratings of the matrix. In both cases, you need some historical data where you observe the interactions of the users with items so that you can make recommendations for the items that were not rated by the users yet. To test it, you need relevant data with users who rated some historical items (but there are ways to deal with cold start) and the new items to be scored. In $k$-NN it will be a bigger technical problem to have enough historical ratings so you can calculate meaningful distance, but in both cases, your test set should be rather about what is the actual data that you would see in a production environment. If in a production environment you have many cases where users rated only a single item and you need to make a recommendation based on this data, this is a hard constraint on how would you approach the problem, not only validate the model. You also want the test set to resemble reality so that you know that the results are meaningful. If you would need to subset the data only to validate the model, then it is a likely hypothesis that you could use the model only for this subset of users as well, so how would you make the recommendations for the rest of the users?


Count of the number of nodes tagged with a particular status

Question: I have a content type called promise whose node can be tagged with a status: not started, in progress, achieved, broken.
I wish to show a count for each of the above statuses in a view block. So say there are 100 promises, I want it to show the following.

90 of 100 promises are not started
2 of 100 promises are in progress
3 of 100 promises are achieved
5 of 100 promises are broken

How can I go about this? I know how to count a taxonomy term and show it has 2, 3 or 18 nodes tagged against it, but how to show out of 100?
Comment: What do you think is the difference between 2, 3 or 18 nodes against 100?
Comment: The other nodes that are not part of that equation, so 2 nodes, it would be the other 3 statuses added together. I understand that, but not how to do it in views.
Answer: To do this without code, I think you'd need a view for each category and then in the footer or header, choose "Global: Results summary" and build your message there using the tokens. I saw you post about colours elsewhere so if you have a separate block for each, you can then theme each one as you wish.
If you set the view to "Display All Items" and then add css <code>.viewname .view-content {display:none;}</code> or a custom module to hide the results, it should work nicely.
You could then use some caching to minimize the performance hit.


Integration with steps $\int_{-\infty}^\infty f(t-u) \, du $

Question:
How do I solve this with steps?
  $$\int_{-\infty}^\infty f(t-u) \, du $$

where
$$f(t)=
\begin{cases}
 0& \text{if}\quad t<0\\
 1 & \text{if}\quad 0\leq t\leq1\\
 0 & \text{if}\quad t>1.
\end{cases}
$$
Comment: Welcome to MSE. It will be more likely that you will get an answer if you show us that you made an effort.
Comment: I have fixed your format; please review my edit.
Comment: Yes, thanks, that's what I wanted.
Comment: $f(t)$ is a "square function."  Sometimes it is called the $\Pi$ function.  The area under the square is $1.$  $f(t-u)$ is still a square function.  Adding a term will translate it horizontally, a negative sign will flip it along some vertical axis, but neither of those will change areas.  And the area under the square is still $1.$
Answer: enforcing the change of variables $x=t-u\implies du=-dx$ then
$$\int_{-\infty}^\infty f(t-u) \, du =\int_{-\infty}^\infty f(x)dx=  \int_{0}^1 \, dx=1$$

Alternatively
  $$0\le t-u\le1 \Longleftrightarrow  t-1\le u \le t$$

Hence $$\int_{-\infty}^\infty f(t-u) \, du =\int_{-\infty}^\infty 1_{[0,1]}(t-u) \, du=  \int_{t-1}^t \, du =1$$


Properties of non-negative integrable functions with 1st, 2nd and 3rd powers having same $L^1$-norm

Question: Let $f\in L^1([0.1])$, non-negative such that $f, f^2$ and $f^3$ have same $L^1([0,1])$ norm. Then, I want to show for a.e. $x$, either $f=0$ or $f=1$.
If $f\in[0,1]$, then just by comparing directly 1st and 2nd powers, we have $f=0$ or $1$ a.e. But if $f>1$, I have no idea on continuing and how to use 3rd power.
Answer: You have $$ \int f^3 - 2f^2 + f = 0$$
which can be arranged to find $$\int f (f-1)^2 = 0.$$
Since $f(f-1)^2 \ge 0$ it follows that $f(f-1)^2 = 0$ almost everywhere and thus $f=0$ or $1$ almost everywhere.
Answer: The existing answer, pointing out that $\int  f(f-1)^2=0$, is very cool  and very clever. But it depends strongly on the fact that the exponents are $1$, $2$, and $3$; in particular it doesn't say anything about the obvious generalization of the result in question. Here's a different argument that's maybe less of a "trick", and which in any case does generalize:
If we say $g=f^{1/2}$ and $h=f^{3/2}$ then we have $$\int gh=||g||_2||h||_2.$$
Hence $h$ must be a scalar multiple of $g$, which implies that $f=c\chi_A$, and now of course it follows that $c=1$.
There's a generalization that "must" be true if the original result is true; this argument does suffice for the generalization:

If $f\ge0$, $1<\alpha<\beta$ and $\int f=\int f^\alpha=\int f^\beta$ then $f=\chi_A$.

Sketch: Solving a few equations shows that there exist $a,b>0$ and $p\in(1,\infty)$ such that $a+b=\alpha$, $ap=1$ and $bp'=\beta$. Now if $g=f^a$ and $h=f^b$ we have $$\int gh=||g||_p||h||_{p'}.$$The condition for equality in Holder's inequality shows that...
Comment: Thank you for giving further insight for generalisation!


Exibindo Alert() de sucesso na mesma pagina. PHP, Html

Question: Queria emitir a mensagem de sucesso ou erro após o cadastro de produtos do meu site na mesma pagina, sem carregar uma nova em branco com a mensagem, eu vi perguntas similares, algumas utilizando ajax que não aprendi nada ainda e não consegui solucionar meu problema com os tópicos que encontrei aqui.
Cadastro de Categoria:

<form method="post" action="gravacategoria.php">

    Nova Categoria:

    <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">

    <button id="btnsalvarcat" name="btnsalvar" type="Submit" class="btn btn-primary">Salvar</button>
    <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>

</form>

GravaCategoria:

<?php
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];
    $nomecat=$_POST["txtcategoria"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        echo ("Produto inserido com sucesso");
    }
    else{
        echo("Erro");
    }

Obrigado!
Comment: Bom, a solução é, de fato, com AJAX. Comece estudando-o. Há funções como o `fetch` do JavaScript ou bibliotecas como JQuery, Axios, entre outros, que poderão facilitar sua vida. Boa sorte.
Answer: Uma solução simples é mandar os dados para um iframe na mesma página. Basta colocar na página:

E no form colocar um target apontando para o name do iframe:
<form target="gravar" method="post" action="gravacategoria.php">
         ↑

No PHP, no lugar do echo você chama um script com o alert da mensagem, mas antes é preciso fazer um if para verificar se o $_POST não está vazio:
<?php
$nomecat=$_POST["txtcategoria"];

if(!empty($nomecat)){
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        $mensagem = "Produto inserido com sucesso";
    }
    else{
        $mensagem = "Erro";
    }
?>

<?php
}
?>

Comment: Obrigado Sam, está bem melhor assim. Seria muito complicado para a mensagem ser exibida dentro form que estão os botoes cancelar e de salvar?
Comment: De nada. Cara, dá pra fazer a mensagem como vc quer. Basta usar `parent` no script do iframe, algo como `parent.document.getElementById("msg").innerHTML = "";`, onde `msg` seria o id de algum elemento que receberia a mensagem, por exemplo: ``
Comment: Estou usando   do jeito que estava, depois no script do gravacategoria, subistitui o alert por isso : if($result){
        $mensagem = "Produto inserido com sucesso";
    }
    else{
        $mensagem = "Erro";
    }
    ?>

E acrescentei  dentro do meu form de cadastro de categorias logo abaixo dos botoes. porem continua uma mensagem box na tela
Comment: Continua o alert? Não era pra aparecer mais já que vc retirou ele.
Comment: Deu certo amigo, muito obrigado
Comment: Sou novo no forum, voce parece entender de php tenho uma duvida sobre como aceitar a entrada de dados do usuario como moedas, porque quando vou testar se eu coloco o valor do produto com (virgula) nao cadastra no banco de dados e da erro preciso por com (ponto).
Preciso abrir uma nova pergunta para isso ou posso te perguntar aqui ?
Comment: Entra [neste chat](https://chat.stackexchange.com/rooms/101316/teste)
Comment: Dá pra você fazer uma mensagem personalizada com o modal do bootstrap, retornando json. E realmente, com o ajax será muito melhor
Comment: @adventistaam dá sim, mas nem se sabe se o cara tá usando bootstrap :D.
Comment: Estou usando bootstrap mais como disse não sei nada ainda de ajax, obrigado a todos as dicas, a solução do Sam era o que eu estava precisando, pelo menos até aprender JavaScript.
Obrigado
Answer: Realmente com o ajax e json seria bem legal, também.
Dá uma olhada
Nessa página estou usando o bootstrap, é só o html, mas usar os seguintes códigos separados:
HTML, JS e PHP
HTML

const msgArr = [
{title: 'Success', msg: 'Salvo com sucesso'},
{title: 'Error', msg: 'Falha ao tentar salvar'},
]

 $('#btnsalvarcat').on('click',function(e){
     e.preventDefault()
     salvarDados()
 })

salvarDados = () =>{
   const idx = getRandomIntInclusive( 0, 1 )
   alert( msgArr[ idx ].msg)
}

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <form method="post" action="gravacategoria.php">

    Nova Categoria:

    <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">

    <button id="btnsalvarcat" name="btnsalvar"  class="btn btn-primary">Salvar</button>
    <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>

</form>

No seu javascript voce poderia usar assim:
 salvarDados = () => {
    $.ajax({
      url: 'gravacategoria.php',
      type: 'post',
      dataType: 'json',
      data: {
         txtcategoria: $('#txtcategoria').val()
      }
   }).then( r =>{ // o r é o retorno do php
        if(r.status == true){
          alert('Salvo com sucesso!')
        }else{
          alert('Falha ao salvar!')

        }
    })
}

No php
<?php
$nomecat=$_POST["txtcategoria"];

if(!empty($nomecat)){
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        $t = array('status' = true);
        echo json_encode(  $t );
    }
    else{
        $t = array('status' = false);
        echo json_encode(  $t );
    }
?>

}
?>

Quem vai retornar para o ajax é o json encode, onde dentro dele você coloca o array
Essa é a sugestão e é assim que funciona o ajax
Comment: Obrigado pela dica, porem para poder usar eu preciso estuar ajax, muita coisa que não entendo
Comment: Ficou legal a solução.
Answer: formulario.php:
    <form method="post" action="gravacategoria.php">

             Nova Categoria:

                <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">

                <button id="btnsalvarcat" name="btnsalvar" type="Submit" class="btn btn-primary">Salvar</button>
                <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>

<?=$_GET['mensagem']?>

    </form>

gravacategoria.php:
<?php
$conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

#$idcategoria=$_POST["txtid"];
$nomecat=$_POST["txtcategoria"];

$stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

#$stmt->bindValue(1,$idcategoria);
$stmt->bindValue(2,$nomecat);

$dados=array(":par_categoria"=>$nomecat);

$result = $stmt->execute($dados);

if($result){
    $mensagem = "Produto inserido com sucesso";
    header("Location: formulario.php?mensagem=$mensagem");
}
else{
    $mensagem = "Erro";
    header("Location: formulario.php?mensagem=$mensagem");
}

Comment: Não é isso que ele quer. Ele não quer recarregar a página.


kryo.readObject cause NullPointerException with ArrayList

Question: I get a NullPointerException when I unserialize an ArrayList object using kryo.
Caused by: java.lang.NullPointerException
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:215)
at java.util.ArrayList.ensureCapacity(ArrayList.java:199)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:96)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:22)    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:679)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:106)

I can see that StdInstantiatorStrategy creates an ArrayList without calling its constructor leaving one of the fields uninitialized causing the exception.
The documentation says that the no argument constructor should be called first and if none is available, the StdInstantiatorStrategy should be used to do field by field initialization.
What am I doing wrong?
Answer: With kryo version 2.24, calling
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());

overrides the default instantiator strategy which uses the class no argument constructor if present. The correct way to do this is to call:
((Kryo.DefaultInstantiatorStrategy) kryo.getInstantiatorStrategy()).setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());

This is explained here https://github.com/EsotericSoftware/kryo
I think this has changed since version 2.21
Answer: I was getting a similar null pointer exception and I needed to add a custom serializer from: https://github.com/magro/kryo-serializers
Ex:
kryo.register( Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer() );

Answer: I meet the same problem and finally solve it. In my case, I use protobuf object in Spark job. Spark kryo serializer couldn't serialize/deserialize protobuf object very well. We can use two methods to solve this problem.

Use protobuf default serialize/deserialize method instead of kryo serialize method. For example, you can convert your Spark rdd[YourProtobufObject] to rdd[ByteString], use pb.toByteString() do the serialize and use .parseFrom(xxByteString) do the deserialize.  Actually, this method is not elegant, but it works.
Register your own protobuf class to kryo. The details as follows.

First, add config to SparkConf. For example

conf.set("spark.serializer","org.apache.spark.serializer.KryoSerializer")
.set("spark.kryo.registrator","your.own.registrator.implement.MyKryoRegistrator")

Second, create your own registrator implement. You can use Twitter  opensource Chill project ProtobufSerializer dependency or mvnrepository, and use ProtobufSerializer directly. The maven dependency looks like this.
 <dependency>
     <groupId>com.twitter</groupId>
     <artifactId>chill_2.11</artifactId>
     <version>0.9.3</version>
 </dependency>
 <dependency>
     <groupId>com.twitter</groupId>
     <artifactId>chill-protobuf</artifactId>
     <version>0.9.3</version>
     <exclusions>
         <exclusion>
             <groupId>com.twitter</groupId>
             <artifactId>chill-java</artifactId>
         </exclusion>
     </exclusions>
 </dependency>

create your own kryo registrator implement named MyKryoRegistrator
class MyKryoRegistrator extends KryoRegistrator {
  override def registerClasses(kryo: Kryo): Unit = {
    kryo.register(classOf[YourProtobufObject], new ProtobufSerializer())
  }
}

Third, run again your Spark job, it will be ok.
Answer: Also pay attention to how you create the list, there are ways to create non-modifiable list, which may cause this kind of serialization trouble.
For example popular shortcut in tests Arrays.asList("a", "b") can be problematic.
Workaround: new ArrayList<>(asList("a", "b")).


make content slide in and out when clicking link?

Question: I am green in this area and I am trying to learn while I build a virtual resume for a website I can use to advertise my programming services (my strength lies more with C#, Java and similar languages :')
Something I think would look pretty cool, is if when you click on a link in my side-bar, the content on the page slides out and is replaced with the content on the new page that slides in, in the previous page' place.
I am a bit lost on how to achieve this though and if I have to do a per-page thing, or if I can make one general method in Javascript to take care of it. I am using jQuery and bootstrap.
var main;
main = function () {
    $(".sidebar-nav a").click(function() {

    })
}

$("document").ready(main);

The HTML:

Brand

                    Index

                    About Me

                    Resume

                    Contact

h1

h2

h3

h4

h5

h6

Grumpy wizards make toxic brew for the evil Queen and Jack.

                    Toggle Menu

Let me know if you need the CSS.
Comment: @RokoC.Buljan Yes, that looks pretty much like what I'd like.
Comment: Something similar to [this ?](http://stackoverflow.com/a/21814409/383904)
Comment: comment in js: single line `//`, multiple line `/*some comment*/`
Comment: If you've got the CSS, please provide it.
Answer: You should use an AJAX technology to seamlessly load another page's HTML contents inline into the document.
The best choice (in my opinion) for this situation is the jQuery function load(), due to it's simplicity and pure convenience. You can also send a callback function, it's easy to implement.
You could then easily implement a CSS animation using the animation attribute.
Comment: Following the link from @RokoC.Buljan have given me the desired effect. Though I will like to accept your answer as it is an alternative solution to what he posted :)
Comment: Thank you! I tell you, AJAX is like magic if you ever try using it! @Vipar


Normal distribution in equality

Question: Let $p(x)=a_1x_1+a_2x_2+. . . .a_n x_n$ be a polynomial such that
$\sum_ia_i^2=1,$ each $x_i \sim N(0,1)$. then we know that $p(x) \sim N(0,1)$.
How can we bound $\Pr_{x\in N^n}\left(\left|p(x)-t\right|\leq \epsilon\right)$, for any $t \in \mathbb{R}$
Answer: Assuming the $x_i$ are independent.
$\Pr_{x\in N^n}(|p(x)-t| \le \epsilon)= \Pr_{x\in N^n}(t-\epsilon\le a_1x_1+\ldots+a_nx_n \le t+\epsilon)=$
$$\int_{\epsilon\le a_1x_1+\ldots+a_nx_n \le t+\epsilon}f(x_1,\ldots,x_n) dx_1\ldots dx_n$$
where $f$ is the probability distribution.
Pick some orthogonal basis $u_1\ldots u_n$ where $u_1 =(a_1,\ldots, a_n)$ and do change of variables.
$$\int_{\epsilon\le a_1x_1+\ldots+a_nx_n \le t+\epsilon}f(x_1,\ldots,x_n) dx_1\ldots dx_n=$$
$$ \int_{t-\epsilon\le u_1 \le t+\epsilon}\left(\int_{-\infty}^{\infty}\cdots\int_{-\infty}^{\infty}f(u_1,\ldots,u_n) du_2\ldots du_n\right)du_1= $$
$$ \int_{t-\epsilon\le u_1 \le t+\epsilon} g(u_1)du_1 $$
where $g(u_1)$ is the result of computing the inner integrals. Finally upper bound that using the maximum of $g(u_1)$ over $t-\epsilon\le u_1 \le t+\epsilon$
$$ \int_{t-\epsilon\le u_1 \le t+\epsilon} g(u_1)du_1 \le 2\epsilon\left( \max_{t-\epsilon\le u_1 \le t+\epsilon}g(u_1)\right)$$

Normal distribution in equality


Show that $x^2 - 79y^2 = \pm 3$ has no solutions in $\Bbb Z$

Question: I am trying to compute the ideal class group of $\Bbb Q(\sqrt{79})$ and this came up:
"Show that $x^2 - 79y^2 = \pm 3$ has no solutions in $\Bbb Z$ using congruences."
I've tried using quadratic reciprocity up to $p=11$ but I've not had any success. Hints are welcome.
Comment: $3$ is not a residue $\pmod {79}$.  That gets you half way there.
Comment: This is an annoying one because $$\left(\frac{79}{3}\right) = 1.$$
Comment: @lulu Thank you! Looking at congruences $\mod 4$ works as well for $+3$. I still have no idea about the other half though.
Comment: Your equation is an example of a [Generalized Pell Equation](https://scholarworks.boisestate.edu/cgi/viewcontent.cgi?referer=https://www.google.com/&httpsredir=1&article=1054&context=td).  In that link you'll find a general approach to addressing solvability. In particular, Theorem 1.24 of those notes tells you that a solution, if one exists, can be found in an explicit range.   (N.B.  I did a quick search for a simple congruence that would do the job and found nothing).
Comment: I know this is not using congruences but just as a question. Can we simply consider the cases where $(x^2,y^2)=3$ or $(x^2,y^2) = 1$ if we assumed it to be true?
Answer: Note: there is no proof using only congruences; $-3$ is represented by a form in the principal genus. The forms below are reduced in the Gauss-Lagrange sense, $ax^2 + bxy +cy^2$ coefficients $\langle a,b,c \rangle$ such that $ac<0$ and $b > |a+c|$
<code>316    factored   2^2 *  79

    1.             1          16         -15   cycle length             4
    2.            -1          16          15   cycle length             4
    3.             3          16          -5   cycle length             6
    4.            -3          16           5   cycle length             6
    5.             5          16          -3   cycle length             6
    6.            -5          16           3   cycle length             6

  form class number is   6
</code>
Any squarefree number $n$ with $|n| < \sqrt {79}$ is represented by $x^2 - 79 y^2$ if and only if it appears with $x/y$ as a convergent of the continued fraction for $\sqrt {79}.$ The numbers that qualify are $1,2.$ The slightly larger $-15$ also comes up
$$  \sqrt { 79} = 8 +     \frac{  \sqrt {79} - 8 }{ 1 }  $$
$$    \frac{ 1 }{   \sqrt {79} - 8 }  =  \frac{    \sqrt {79} + 8 }{15 } = 1 +  \frac{    \sqrt {79} - 7 }{15 } $$
$$    \frac{ 15 }{   \sqrt {79} - 7 }  =  \frac{    \sqrt {79} + 7 }{2 } = 7 +  \frac{    \sqrt {79} - 7 }{2 } $$
$$    \frac{ 2 }{   \sqrt {79} - 7 }  =  \frac{    \sqrt {79} + 7 }{15 } = 1 +  \frac{    \sqrt {79} - 8 }{15 } $$
$$    \frac{ 15 }{   \sqrt {79} - 8 }  =  \frac{    \sqrt {79} + 8 }{1 } = 16 +  \frac{    \sqrt {79} - 8 }{1 } $$
Simple continued fraction tableau:
$$
 \begin{array}{cccccccccccccc}
 & & 8 & & 1 & & 7 & & 1 & & 16 & \\
 \\
  \frac{ 0 }{ 1 }   &   \frac{ 1 }{ 0 }   & &   \frac{ 8 }{ 1 }   & &   \frac{ 9 }{ 1 }   & &   \frac{ 71 }{ 8 }   & &   \frac{ 80 }{ 9 }    \\
  \\
 & 1 & & -15 & & 2 & & -15 & & 1
 \end{array}
 $$
$$
 \begin{array}{cccc}
  \frac{ 1 }{ 0 }   & 1^2 - 79 \cdot 0^2 = 1 &     \mbox{digit}  &  8  \\
  \frac{ 8 }{ 1 }   & 8^2 - 79 \cdot 1^2 = -15 &     \mbox{digit}  &  1  \\
  \frac{ 9 }{ 1 }   & 9^2 - 79 \cdot 1^2 = 2 &     \mbox{digit}  &  7  \\
  \frac{ 71 }{ 8 }   & 71^2 - 79 \cdot 8^2 = -15 &     \mbox{digit}  &  1  \\
  \frac{ 80 }{ 9 }   & 80^2 - 79 \cdot 9^2 = 1 &     \mbox{digit}  &  16  \\
 \end{array}
 $$
Comment: Yes, it's important to realize that not every Diophantine equation can be understood by congruences alone. :)  Perhaps the most elementary example is that $x^4+1$ is irreducible over $\mathbb Z$, but is _reducible_ mod $p$ for every prime $p$.


What do exponential of coefficients (like odds ratio in logistic regression) from linear regression indicate?

Question: The long title says it all.
For example, I have performed linear regression (OLS) with commonly used iris dataset using following formula:
PL ~ SW + Species

Following is the output:
==================== Summary2() ====================
                  Results: Ordinary least squares
====================================================================
Model:               OLS               Adj. R-squared:      0.949
Dependent Variable:  PL                AIC:                 154.5772
Date:                2020-08-10 05:57  BIC:                 166.6197
No. Observations:    150               Log-Likelihood:      -73.289
Df Model:            3                 F-statistic:         919.7
Df Residuals:        146               Prob (F-statistic):  1.45e-94
R-squared:           0.950             Scale:               0.15983
--------------------------------------------------------------------
                       Coef.  Std.Err.    t    P>|t|   [0.025 0.975]
--------------------------------------------------------------------
Intercept             -0.1792   0.3375 -0.5309 0.5963 -0.8463 0.4879
Species[T.versicolor]  3.1130   0.1023 30.4196 0.0000  2.9108 3.3153
Species[T.virginica]   4.3074   0.0913 47.1795 0.0000  4.1269 4.4878
SW                     0.4788   0.0971  4.9321 0.0000  0.2869 0.6706
--------------------------------------------------------------------
Omnibus:               12.413        Durbin-Watson:           1.889
Prob(Omnibus):         0.002         Jarque-Bera (JB):        19.064
Skew:                  0.435         Prob(JB):                0.000
Kurtosis:              4.514         Condition No.:           36
====================================================================

I now convert the coefficients to exp(coefficients), as is done to get odds ratio in logistic regression. I get following values:
Species[T.versicolor] 22.8
Species[T.virginica]  74.2
SW                    1.61

What do these numbers indicate or how can these values be interpreted?
Edit: The answer to this question states that exponetiation is useful in the setting of Poisson regression. Does it apply to linear regression also?
Comment: It has some uses if you take the natural log of the outcome, which are related to the Poisson.
Comment: It will be great if you can explain this more in an answer here.
Answer: The interpretation of coefficents from logistic regression is due to the formulation, specifically:
$$ ln(\frac{P}{1-P}) = \beta_0 + \beta_1x $$
The log odds is on the left and the linear predictor with your coefficients is on the right.  If we exponentiate both sides, we now have exp(linear predictor) related to the odds ratio, or a unit change in exp(linear predictor) gives a unit change in the odds ratio.
$$ \frac{P}{1-P} = e^{\beta_0 + \beta_1x} $$
In linear regression, the relationship is simply:
$$ y = \beta_0 + \beta_1x $$
Exponentiation of the coefficents here does not give you a directly interpretable relationship to the response variable, Y.
Edit to address comment
The Poisson Regression formulation is
$$ln(y) = \beta_0 + \beta_1x $$
Exponentiation of each side gives that the exponentiated coefficients are related to the change in y.  Also remember that here, y is assumed to be count data following a Poisson distribution.
The various formulations provide the interpretations.  For OLS, there is no exponential in the formulation, so the coefficients don't need to be modified for interpretation.  Also, if you exponentiate the coefficients from an OLS model, there is not direct relationship to the endpoint any longer.
Comment: The answer here states it is useful for Poisson regression: https://stats.stackexchange.com/questions/319015/odds-ratio-for-poisson-regression
Comment: Not quite.  I edited my answer to addresses Poisson Regression.
Answer: Exponentiation of coefficients will generally be useful when the expected value involves an exponential function in some way. This non-exhaustive list includes

Poisson
negative binomial
other related GLMs
OLS regression with a logged outcome
logit
ordered logit
some parametric regression survival-time/duration models

Sometimes you will need to go beyond mere exponentiation to get something interpretable.


How to delete "any" element of a list in elixir

Question: I have a list of lists
>> list = [[1,""],[2,"b"],[3,""],[4,"c"]]

I want to delete the lists that contains "" element
>>list = [[2,"b"],[4,"c"]]

I'm trying to find something like
list = List.delete(list,[any,""])

Answer: You could combine Enum.reject/2 with Enum.member?/2 and reject any list that contains empty string
iex> Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], &Enum.member?(&1, ""))
[[2, "b"], [4, "c"]]

If your inner lists are always the same two-item style and you're only wanting to check the second item, you could also use an anonymous function
iex> Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], fn [_, b] -> b == "" end)
[[2, "b"], [4, "c"]]

or a comprehension that does pretty much the same thing
iex> for [a, b] when b != "" <- [[1,""],[2,"b"],[3,""],[4,"c"]], do: [a, b]
[[2, "b"], [4, "c"]]

Comment: Also: `Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], & match?([_, ""], &1))` and `Enum.reject([[1,""],[2,"b"],[3,""],[4,"c"]], fn [_, ""] -> true; _ -> false end)`.
Comment: `===` and `!==` are counter-idiomatic here. Use `==` and `!=` instead.
Comment: I'd never thought to use `match?/2` that way. I love it!
Comment: Well, two examples I posted, result in the absolutely same code. `Kernel.match?/2` gets expanded into [two clauses as above](https://github.com/elixir-lang/elixir/blob/v1.9.1/lib/elixir/lib/kernel.ex#L2820).


How to simplify $\dfrac{x+2}{x^2-2x-3}+\dfrac{x}{x^2-2x}$

Question: So I was once again bored when I decided to to try and see if I could do maybe some simple Algebra and came up with this problem:$$\text{Simplify: }\dfrac{x+2}{x^2-2x-3}+\dfrac{x}{x^2-2x}$$Which I thought that I would be able to do. Here is my attempt at simplifying the aforementioned equation:$$\dfrac{x+2}{x^2-2x-3}+\dfrac{x}{x^2-2x}$$$$=\dfrac{x+2}{x^2-2x-3}+\dfrac{1}{x-2}$$$$=\dfrac{x+2}{(x+1)(x-3)}+\dfrac{1}{x-2}$$$$=\dfrac{x^2-4}{(x+1)(x-3)(x-2)}+\dfrac{(x+1)(x-3)}{(x+1)(x-3)(x-2)}$$$$=\dfrac{2x^2-2x-7}{x^3-4x^2+4x+6}$$$$\text{Or }\dfrac{(x-2)(x+2)+(x+1)(x-3)}{(x+1)(x-2)(x-3)}$$

$$\mathbf{\text{My question}}$$

Is the solution that I have achieved correct, or what could I do to attain the correct simplification/attain it more easily?
Comment: It's not clear what "simplify" means. You've done a lot of algebra with rational expressions. Presumably it's correct. (I haven't checked.) See https://math.stackexchange.com/questions/3900917/is-there-any-official-specific-convention-that-defines-whether-an-expression-is/3901091#3901091
Comment: Result looks correct, but as Ethan said, it depends on what you mean by simplify... You could use partial fractions decomposition to write this as $\frac{5}{4(x-3)}+\frac{1}{x-2}-\frac{1}{4(x+1)}$, that can be considered simpler in some contexts
Comment: Think in terms of reducing a fraction to lower terms. In this case you have a rational expression; the numerator remains in expanded form while the denominator can be-and you did factored it. My answer would be $\frac{2x^2-2x-7}{(x+1)(x-2)(x-3)}$. There are no miraculous ways to simplify as @Sil suggested. That is not simplifying but rewriting in an equivalent way, possibly convenient for the next operation.
Comment: you can use Wolfram to simplify and compare with your result. https://www.wolframalpha.com/input?i=simplify%5B%289x%2B2%29%5E2-2x%5E2%2B3%5D
Answer: Your derivation is fine, but there is an important issue to note: while the original expression is not defined for $x=0$ the second one is a valid expression also when $x=0$, in this sense they are not completely equivalent.


On content edit, how can I check/select a bool field based on which tab is active?

Question: I have a content type with a paragraph that has two fields, each field inside its own tab controlled by the form display like so:

Here is what the set of tabbed fields looks like when editing a piece of content of the content type:

The paragraph also has a bool field called field_active_callout_tab with two values: 'Single' and 'Multi', same as the tabs.
If the 'Single' tab is clicked, I want the bool to be checked. If the 'Multi' tab is selected, I want the bool to be unchecked.
I tried to use the Conditional Fields module, but it will not allow control by tab label. How can I establish this dependency between the tab and the bool?
Answer: You can do it with jQuery, something like this should do it:
<code>$('.single-class').click(function () {
    $('.bool-class').prop('checked', true);
});
$('.multi-class').click(function () {
  $('.bool-class').prop('checked', false);
});
</code>
Comment: thanks for that! Can you please explain where this jquery should go? Do I need to put it in a js file and then reference it from the paragraph template, or can I add it directly into the paragraph twig template? Further, are these classes assumed to be added on the fields / tab labels directly in manage form display?
Comment: You must define a library in your module, it is explained how to do it here https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module. The class names you find by inspecting the element in the browser, for further information on how to do that look here https://www.lifewire.com/get-inspect-element-tool-for-browser-756549
Comment: I'm not using a module to control the banner, just a twig template. Do you think I should add a custom JavaScript file to the theme and reference it from within the twig file?
Comment: Yes you shall add it to the theme, it is actually the same procedure look here, https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


How to setup an FTP server on Linux that will use an API for authentication rather that a static list of users?

Question: I'd like to have an FTP server on a Unix machine that will be able to query a certain API (probably via HTTP or local shell script) in order to authenticate the client.
It would be enough if there is a server that can handle the scenario below:

Client connects via FTP to my server
Client sends the username and password
Server executes a local script with the given parameter
(my custom logic inside the script)
Return a success/failure code/message back to the FTP server

Is there such a server on the market? Or is it possible to customize some of the existing servers to cover the scenario above?

Note 1: I see that vsftpd offers a module for virtual users, but it's not quite clear (to me) how to setup such a module with a custom (eg: HTTP) API
Note 2: There seem to be some ways to build (in C) PAM modules, but I'm hoping for an easier way (that will allow me to configure the authentication mechanism rather than building a C library).
Note 3: In regards to the question being put on hold: please note that this question focuses mainly on a means through which FTP authentication can be achieved using a custom protocol/API. I'm not looking for a specific product, but I'm trying to solve a specific problem. Obviously, a product is needed to implement such a solution since we're dealing with a FTP server.
Answer: It seems Pure-FTPD is what you need. Here are two points from their 'About' section seems exactly matching to your needs:

Multiple authentication methods can be chained in any order. For instance, SQL accounts, LDAP directories and system accounts can be used at the same time.
Custom authentication methods can easily be added. Pure-FTPd supports external authentication modules, and writing a new backend can be as simple as a few lines of shell script.

Further info: https://www.pureftpd.org/project/pure-ftpd
Comment: Thank you, I'll take a look into Pure-FTPD and I'll come back with a reply if it fits my needs.


How does the standard error work?

Question: I have been looking into the inner-workings of the standard error recently, and I found myself unable to understand how it works. My understanding of the standard error is that it is the standard deviation of the distribution of sample means. My questions are:
• how do we know the standard error is the standard deviation of the sample means when we usually take just a single sample?
• why doesnt the equation to calculate the standard error mirror the standard deviation equation for a single sample?
Comment: These are explained for a simple but interesting problem (a ternary response) in plain, non-statistical language at http://stats.stackexchange.com/a/18609.
Comment: When you say "single sample" do you mean one sample set or really a sample size of 1?
Answer: Suppose $X_1, X_2, \ldots, X_n$ are independent and identically distributed.  This is the situation I am pretty sure you are referring to. Let their common mean be $\mu$ and their common variance be $\sigma^2$.
Now the sample mean is $X_b=\sum_i X_i/n$.  Linearity of expectation shows that the mean of $X_b$ is also $\mu$.  The independence assumption implies the variance of $X_b$ is the sum of the variances of its terms.  Each such term $X_i/n$  has variance $\sigma^2/n^2$  (because the variance of a constant times a random variable is the constant squared times the variance of the random variable).  We have $n$ identically distributed such variables to sum, so each term has that same variance.  As a result, we get $n \sigma^2/n^2 = \sigma^2/n$ for the variance of the sample mean.
Usually we do not know $\sigma^2$ and so we must estimate it from the data. Depending on the setting, there are various ways to do this.  The two most common, general-purpose estimates of $\sigma^2$ are the sample variance $s^2 = \frac{1}{n}\sum_i(X_i-X_b)^2$ and a small multiple of it, $s_u^2 = \frac{n}{n-1}s^2$ (which is an unbiased estimator of $\sigma^2$).  Using either one of these in place of $\sigma^2$ in the preceding paragraph and taking the square root gives the standard error in the form of $s/\sqrt{n}$ or $s_u/\sqrt{n}$.
Comment: This is very good. Do you have suggestions for books or readings to develop similar line of thinking skills. Thanks.
Comment: Elegant answer!
Answer: Yes, the standard error of the mean (SEM) is the standard deviation (SD) of the means.  (Standard error is another way to say SD of a sampling distribution. In this case, the sampling distribution is means for samples of a fixed size, say N.)  There is a mathematical relationship between the SEM and the population SD: SEM = population SD / the square root of N.  This mathematical relationship is very helpful, since we almost never have a direct estimate of the SEM but we do have an estimate of the population SD (namely the SD of our sample).  As to your second question, if you were to collect multiple samples of size N and calculate the mean for each sample you could estimate the SEM simply by calculating the SD of the means.  So the formula for SEM does indeed mirror the formula for the SD of a single sample.
Answer: +1 to both @JoelW. & @MichaelChernick.  I want to add a detail to @JoelW.'s answer.  He notes that "we almost never have a direct estimate of the SEM", which is essentially true, but it's worth explicitly recognizing a caveat to that statement.  Specifically, when a study compares multiple groups / treatments (for example, placebo vs. standard drug vs. new drug), an ANOVA is typically used to see if they are all equal.  The null hypothesis is that each group has been drawn from the same population, and thus, all three means are estimates of the population mean.  That is, the null hypothesis in a standard ANOVA assumes that you do have a direct estimate of the SEM.  Consider the equation for the variance of the sampling distribution of means:
$$
\sigma^2_{\bar x}=\frac{\sigma^2_{pop}}{n_j},
$$
where $\sigma^2_{pop}$ is the population variance, and $n_j$ is the number of groups.  Although we don't usually perform the calculations in this way, we could simply use standard formulas to plug in estimated values, and with minimal algebraic reshuffling, form the $F$ statistic like so:
$$
F=\frac{n_j\times s^2_{\bar x}}{s^2_{\text{pooled within group}}}
$$
In this case, we really would be using the standard formula (only applied over the group means), that is:
$$
s^2_{\bar x}=\frac{\sum_{j=1}^{n_j}(\bar x_j-\bar x_.)^2}{n_j-1},
$$
with $x_.$ being the mean of the group means.
In that we typically believe the null hypothesis is not true, @JoelW.'s point is right, but I work through this point, because I think the clarity it affords is helpful for understanding these issues.
Comment: I think your comment is basically the same as this one, which was written with less mathematical notation: http://stats.stackexchange.com/questions/32206/why-compare-sum-of-squares-with-anova-and-not-mean/32231#32231

How does the standard error work?


Want to design scroll bar with values associated with value

Question: I want to design something like this but not clicking, what it is called. Can someone please suggest me some link where I can look for its implementation in Javascript. I am looking for Scroll Bar associated with values to it, but desired result is not coming on Google.
Comment: [``](https://www.w3.org/wiki/HTML/Elements/input/range)
Comment: Have looked for jQuery UI Slider ? https://jqueryui.com/slider/#slider-vertical
Comment: First result on google for javascript value slider, [rangeslider.js](http://rangeslider.js.org/)
Comment: @LouysPatriceBessette This is what I was looking for. Thanks :)
Comment: Thanks everyone for your suggestions
Answer: There's a D3.js plugin that also uses jQuery UI Slider.  This module lets you display an axis of values along the slider.
http://thematicmapping.org/playground/d3/d3.slider/


PHP Replace - Get elements from other php file?

Question: I have this code:
<?php
    $test = 'My name is Dan';
    echo str_replace("Dan","Peter", $test);
?>

I want the elements Dan and Peter to come from another php file. I want something like:
<?php
    $test = 'My name is Dan';
    echo str_replace($elements, $test);
?>

And $elements would contain "Dan", "Peter", so both elements in the same file.
Bonus question: Is it possible to add something like: if $elements in not available/not accessible then don't replace anything?
I am pretty new to php.
Comment: And where is the problem ?
Comment: you can declare in include file $search='Dan'; $replace='Peter';  so in original file  echo str_replace($search,$replace, $test);
Comment: @luca that's exactly what I just did :). Thanks anyway.
Comment: @Rizier123 How do I add the elements to the second file? I can't get it working whatever I do. I get: Warning: str_replace() expects at least 3 parameters, 2 given
Comment: Then show your current code of both files and where you include them
Comment: if $element var is in an other php file with the same name, you have to include this file before echo.
Comment: it's included but I forgot to put it in the example above. My quesiton: how will the included file look like? Simply "Dan", "Peter" or echo "Dan", "Peter" ??
Comment: include file :   .... $element="Dan", "Peter"; ...
Comment: @10now You can provide an array on both the search and replace side, but you can't combine the search and replace into one array... You'd have to create that yourself... Try reading some documentation... ;)
Answer: I did it myself.
I added two $strings. So now it's like this:
echo str_replace("$string1","$string2", $test);


Basic Page - Associated Image Field

Question: I created an Image Field for the Basic Page Content Type.
I want to control the output of this image to use as a banner with a caption on top. Is there a function to render out a field specific to the page,
such as <?php print render($page['my_image_field']); ?>.
I wan't to style this separately from the body content.
Answer: You can do this within a tpl file specific to your content type. In this case it sounds like it'd be node--page.tpl.php
All the drupal 7 template naming suggestions are available at - https://drupal.org/node/1089656
Just make sure you have a regular node.tpl.php file in your theme before creating the new one.
From there this thread tells you how to go about printing your field elsewhere (specific to drupal 7)- https://drupal.org/node/1059636
Specific to your question:
<?php
hide($content['field_my_image_field']);
print render($content);
?>

then wherever you want your image to appear at use
<?php
print render($content['field_my_image_field']);
?>

Basic Page - Associated Image Field


How can I have a nested loop with a fileglob pattern?

Question: I'm trying to create a set of authorized SSH keys for a set of users in Ansible. I have a users variable set up like so:
users:
  - { username: root, name: 'root' }
  - { username: user, name: 'User' }

In the same role, I also have a set of authorized key files in a files/public_keys directory, one file per authorized key:
roles/common/files/public_keys/home
roles/common/files/public_keys/work

I want to copy each public key to each user.
I have tried using the following task:
- name: copy authorized keys
  authorized_key: user={{ item.0.username }} key={{ item.1 }}
  with_nested:
    - users
    - lookup('fileglob', 'public_keys/*')

However, item.1 contains the literal string "lookup('fileglob', 'public_keys/*')", not each file path under files/public_keys.
Is there a way I can get a listing of the files/public_keys directory and copy each public key to each user?
Answer: The trick is to transform the fileglob return value into a list via the split function, so you can iterate over the values:
- name: copy authorized keys
  authorized_key:
    user: "{{ item.0.username }}"
    key: "{{ lookup('file', item.1) }}"
  with_nested:
    - "{{ users }}"
    - "{{ lookup('fileglob', 'public_keys/*').split(',') }}"

Note that using bare variables, without {{ and }}, for with_items was deprecated in Ansible v2.
Comment: This should be accepted answer
Answer: You might have to significantly rewrite your command, but there's provision for looping over fileglobs
from the example:
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
  with_fileglob:
    - /playbooks/files/fooapp/*

Other promising options are Looping over Subelements which is actually illustrated by SSH keys
Comment: I know you can loop over file globs using `with_fileglob`; I'm just not sure how to use that in conjunction with a nested loop. Looping over subelements _could_ work, but I'm hoping I don't have to manually specify the entire list of keys I want to copy, since I _should_ just be able to get that as a list (using `with_fileglob`).
Comment: I'm not sure either.  The next best suggestion is to pop into `#ansible` on `irc.freenode.net` and see if the gurus there have any bright ideas.
Answer: for me this was working only in this form
    - name: Set up authorized keys for root
      authorized_key:
        user: root
        state: present
        key: "{{ lookup('file', item) }}"
      with_fileglob: 'public_keys/*.pub'


Samba User permissions

Question: I m trying to setup custom User permissions for a certain user on my samba server. What i try to achieve is to login with mentioned user, lets say its name is user1, and only access two folders folder1, and folder2(with rwx permissions). The share contains plenty of other folders,which he should NOT see them.
All my samba users are part of a group, lets say its called staff.
My global config is this :
<code>[global]
log file = /var/log/samba/log.%m
load printers = no
socket options = TCP_NODELAY
full_auditrefix = %u|%T|%m|%S
full_audit:facility = local5
interfaces = 192.168.0.20/255.255.255.0
passdb backend = tdbsam
allow hosts = 127. 192.168.0. 192.168.3.
unix extensions = no
cups options = raw
vfs objects = full_audit
full_audit:success = connect disconnect mkdir rmdir write sendfile rename unlink chmod fchmod chown fchown
full_auditriority = notice
workgroup = MYSERVER
full_audit:failure = connect
use sendfile = yes
security = user
max log size = 50
</code>
The shared directory config :
<code>[share]
writeable = yes
path = /home/share
vfs object = full_audit
comment = Linux
valid users = user1,user2,user3
create mode = 0660
directory mode = 0770
</code>
With this configuration user1 can login and see all the files and folders. (which is not my purpose)
If i erase user1 from the staff group, and set the mentioned folder1, folder2 with the permissions of 777, the user wont have permission to access the server. I just tested it.
So my question is how can i provide for the user accessibility to the share, but restriction to those folders only?
The mentioned shares permissions are:
<code>drwxrwxr-- 28 root staff 4.0K Jan 30 16:22 share
</code>
Answer: I found one helpful link hope this can help you with your issue.
https://www.samba.org/samba/docs/using_samba/ch09.html
Br.
Comment: Thanks for the link, but i sorted out the problem. The shared folder should have had execute permission added additionally for other to login.

Samba User permissions


Ext groups due to Yoneda: why is this class zero?

Question: Consider category of $\mathbb{K}[x]$-modules. Let $\mathbb{K}$ be a trivial $\mathbb{K}[x]$-module, i.e. $x$ acts by zero. Easy to see that $\mathrm{Ext}^2 (\mathbb{K}, \mathbb{K}) = 0$. But there is exact sequence
$$0 \rightarrow \mathbb{K} \rightarrow \mathbb{K}[x]/(x^2) \rightarrow \mathbb{K}[x]/(x^2) \rightarrow \mathbb{K} \rightarrow 0.$$
It has to be equivalent to trivial one. It is due to this description of $\mathrm{Ext}^2$.
Question: How to construct this equivalence explicitly?
Comment: Dear quinque, the sequence is the trivial sequence *by definition* (I guess the middle map is meant to be zero, while the outer ones are isomorphisms). Or what's your definition of Yoneda-$\text{Ext}^2$?
Comment: Thank you, Hanno. It was just misprint.
Comment: Are you sure those modules are projective $\Bbb K[x]$-modules?
Comment: I am sure, that they are not. But do they have to be projective?
http://en.wikipedia.org/wiki/Ext_functor#Construction_of_Ext_in_abelian_categories
Comment: @Jeremy, quinque, you're right, of course. Deleting.
Answer: Late to the party, but anyway...
A length 2 exact sequence
$$ 0 \to A \to B \to C \to D \to 0 $$
represents the zero class in $\mathrm{Ext}^2(D,A)$ if and only if we can fill in the hook diagram
$$\require{AMScd}\begin{CD}
@.@.@.0\\
@.@.@.@VVV\\
0 @>>> A @>>> B @>>> I @>>> 0\\
@.@.@.@VVV\\
@.@.@.C\\
@.@.@.@VVV\\
@.@.@.D\\
@.@.@.@VVV\\
@.@.@.0
\end{CD}$$
where $I$ is the image of the map $C\to D$, to a pull-back/push-out diagram
$$\require{AMScd}\begin{CD}
@.@.0@.0\\
@.@.@VVV@VVV\\
0 @>>> A @>>> B @>>> I @>>> 0\\
@.@|@VVV@VVV\\
0 @>>> A @>>> E @>>> C @>>> 0\\
@.@.@VVV@VVV\\
@.@.D@=D\\
@.@.@VVV@VVV\\
@.@.0@.0
\end{CD}$$
for some $E$. In fact this works for any abelian (even exact) category, whether or not it has enough projectives or injectives.
In the example from the question this is clear: the image $I$ is just $\mathbb K$, and we can take for $E$ the module $\mathbb K[x]/(x^3)$, together with the obvious maps.
Comment: This follows from the long exact sequence for hom. We have the sequence $\Ext^1(D,B)\to\Ext^1(D,I)\to\Ext^2(D,A)$, so the image in $\Ext^2(D,A)$ is zero if and only if it comes from an extension in $\Ext^1(D,B)$, which is what is expressed in the diagram.
Comment: where can we find a proof of this? Is there such a description for longer extensions?
Comment: I don't have the reputation to add a comment so I am responding to the question of Artur Araujo here. You can find this statement as Lemma 4.1 in the book "Theory of Categories" by Mitchell:
http://www.maths.ed.ac.uk/~v1ranick/papers/mitchell.pdf
Answer: Take the projective resolution
$$0\to0\to\mathbb{K}[x]\to\mathbb{K}[x]\to\mathbb{K}\to0$$
of $\mathbb{K}$, which you can regard as a length $2$ extension of $\mathbb{K}$ by $0$, and take the direct sum with
$$0\to\mathbb{K}\to\mathbb{K}\to0\to0\to0$$
to get
$$0\to\mathbb{K}\to\mathbb{K}\oplus\mathbb{K}[x]\to\mathbb{K}[x]\to\mathbb{K}\to0,$$
which is a length $2$ extension of $\mathbb{K}$ by $\mathbb{K}$.
But this extension has a map to both your extension
$$0\to\mathbb{K}\to\mathbb{K}[x]/(x^2)\to\mathbb{K}[x]/(x^2)\to\mathbb{K}\to0$$
and to the trivial extension
$$0\to\mathbb{K}\to\mathbb{K}\stackrel{0}{\to}\mathbb{K}\to\mathbb{K}\to0,$$
so all three extensions are equivalent. In fact, it has a map to every length $2$ extension of $\mathbb{K}$ by $\mathbb{K}$.


How to solve $f\frac{\partial^2f}{\partial x\partial y} = \frac{\partial f}{\partial x}\frac{\partial f}{\partial y}$

Question: I want to solve the following non-linear PDE:
$$f\frac{\partial^2f}{\partial x\partial y} = \frac{\partial f}{\partial x}\frac{\partial f}{\partial y}.$$
I don't know much about solving PDE's, especially non-linear ones, so I'm not sure how to find all the solutions. It is easily verified that a function of the form $f(x, y) = g(x)h(y)$, with $g$, $h$ differentiable, is a solution, but are all solutions of this form?
Comment: Perhaps if you change coordinates to $z=x+\mathrm{i}y$ and $\bar{z}=x-\mathrm{i}y$, you get something along the lines of Laplace's equation. That should be a good first step...
Answer: I think the answer is yes.  Note that
$$\frac{\partial}{\partial y} \left ( \frac{1}{f} \frac{\partial f}{\partial x}\right ) = \frac{\displaystyle \frac{\partial f}{\partial y} \frac{\partial f}{\partial x} - f \frac{\partial^2 f}{\partial y \partial x}}{f^2} = 0$$
so that
$$\frac{1}{f} \frac{\partial f}{\partial x} = \frac{\partial \log{f}}{\partial x}= g(x)$$
or
$$\log{f} = G(x) + r(y)$$
where $G(x) = \int^x dx' g(x')$.  This implies that $f(x,y) = a(x) b(y)$ by taking logs on both sides.  A similar analysis leads to the same conclusion with $x$ and $y$ reversed in the first equation above.


Definition of $\rho$-mixing and its relation to strong mixing?

Question: From Wikipedia:

Suppose $\{X_t\}$ is a stationary Markov process, with stationary distribution $Q$. Denote $L²(Q)$ the space of Borel-measurable functions that are square-integrable with respect to measure $Q$. Also let $ℰ_tϕ(x) = E[ϕ(X_t) | X_0 = x]$ denote the conditional expectation operator on $L²(Q)$. Finally, let $Z = \{ϕ∈L²(Q): ∫ ϕdQ = 0\}$ denote the space of square-integrable functions with mean zero.
The $ρ$-mixing coefficients of the process $\{x_t\}$ are
  $$
    \rho_t = \sup_{\phi\in Z:\,\|\phi\|_2=1} \| \mathcal{E}_t\phi \|_2.
$$
  The process is called $ρ$-mixing if these coefficients converge to zero as $t → ∞$.

I was wondering

How $ \rho_t$ can represent the "difference" between the stationary distribution $Q$ and the conditional distribution of $X_t$ given $X_0 = x$?
why  restricting focus on $Z = \{ϕ∈L²(Q): ∫ ϕdQ = 0\}$?
How is $\rho$-mixing related to strong mixing defined in an earlier part of the same Wikipedia article?   $\rho$-mixing seems to mean convergence of measure of $X_t$ to the limiting distribution, while strong mixing seems to mean $X_t$ become more and more independent from $X_0$, again from Wikipedia:

implies that for any two possible states of the system (realizations of the random variable), when given a sufficient amount of time between the two states, the occurrence of the states is independent.

What kind of mixing is for Markov chain mixing time?
Whenever talking about the stationary distribution, is the underlying Markov process  discrete-time? If not, how is the stationary distribution for a continuous time Markov process defined?

Thanks!
Answer: A great reference for many of these questions is:
In particular this reference defines rho mixing  outside the confines of Markov processes using a formal notion maximal correlation, and it has a nice discussion of the connections between various notions of mixing.  I am a co-author of the paper referenced the Wikipedia entry by Chen et al for rho mixing.   Our paper was focused on Markov processes, but the initial discussion drew heavily on more general results from Bradley.
Probability Surveys
Vol. 2 (2005) 107–144
ISSN: 1549-5787
DOI: 10.1214/154957805100000104
Basic Properties of Strong Mixing
Conditions.
A Survey and Some Open Questions†
Richard C. Bradley
e-mail: firstname.lastname@example.com
Abstract: This is an update of, and a supplement to, a 1986 survey pap
Comment: Thanks! Very surprised and pleased to receive a reply from you. My post was a while ago, and hope someday I could have a chance to pick up the topic again.


optimal algorithm to solve CLSP(Capacitated Lot Sizing) with the transportation constraints and storage levels

Question: A bank has an ATM machine. For a particular week, the usage of cash in millions as below.

5- Monday
4- Tuesday
1- Wednesday
15- Thursday
6- Friday
2- Saturday
4- Sunday

The bank hires a depositing company to deposit money in 5, 3, or 1 rounds per week.
The depositing company provides following packages to the bank when charging for depositing money,

Cost for depositing in 4 rounds per month- 21135
Cost for depositing in 12 rounds per month- 32000
Cost for depositing in 20 rounds per month- 41975

Ordering remains as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday. This order shouldn't be violated when categorizing values.
Example

5 rounds

[(5+4),1, 15, 6, (2+4)]
[(5+4), 1, (15+6)=20+1, 2, 4]
can have many other combinations which don't break order.

3 rounds

[(5+4+1), 15, (6+2+4)]
[(5+4), (1+15), (6+2+4)]
can have many other combinations which don't break order.

1 round

[(5+4+1+15+6+2+4)]
Also the bank has to bear a holding cost of 0.019% of the remaining amount at the end of the day.
Example
Consider 1st week usage of cash as follows.( in millions)
Mon-    13
Tue-    5
Wed-    4
Thu-    4
Fri-    2
Sat-    11
Sun-    1
5 - rounds
1st week Cash depositing order - 13, (5+4), 4, (2+11), 1
Assuming depositing is done in 5 rounds for all 4 weeks of the month,
(5*4 = 20)
Total depositing cost = 41975
1-  13 deposited,
    13 withdrawn,
        0 remaining,
            0 holding cost
2-  (5+4) deposited,
    5 withdrawn,
        4 remaining,
            4*0.00019  holding cost
3-  0 deposited,
    4 withdrawn,
        0 remaining,
            0 holding cost
4-  4 deposited,
    4 withdrawn,
        0 remaining,
            0 holding cost
5-  (2+11) deposited,
    2 withdrawn,
        11 remaining,
            11*0.00019 holding cost
6-  0 deposited,
    11 withdrawn,
        0 remaining,
            0 holding cost
7-  1 deposited,
    1 withdrawn,
        0 remaining,
            0 holding cost
Total holding cost for 1st week = 4*0.00019 + 11*0.00019  = 0.00285 millions= 2850
Likewise I need to find the total holding cost for the month considering each particular week.
3- rounds
Cash depositing order for 1st week - 13, (5+4+4), (2+11+1)=(1+1+12)
Edit- Assuming 12 rounds per month package is choosen, therefore 3 rounds per week( 3*4 =12)
Total depositing cost = 32000
1 - 13 deposited,
    13 withdrawn,
        0 remaining, 0 holding cost
2-  (5+4+4) deposited, 5 withdrawn, (4+4) remaining, (4+4)*0.00019 holding cost
3-  0 deposited, 4 withdrawn, 4 remaining, 4*0.00019 holding cost
4- 0 deposited, 4 withdrawn, 0 remaining, 0 holding cost
5- (2+11+1) deposited, 2 withdrawn, (11+1) remaining, (11+1)*0.00019 holding cost
6- 0 deposited, 11 withdrawn, 1 remaining, 1*0.00019 holding cost
7- 0 deposited, 1 withdrawn, 0 remaining, 0 holding cost
Total holding cost for 1st week = (4+4)*0.00019 + 4*0.00019 + (11+1)*0.00019 + 1*0.00019 = 0.00475 millions = 4750
Likewise I need to find the total holding cost for the month considering each week.
Edit - suppose the 41975 package is picked. Then it means cash deposited in 20 rounds per month. That means 5 rounds per week. If the 32000 package is picked, then 12 rounds per month. That means 3 rounds per week. If the 21135 package is picked, then it means for 4 rounds per month, that means 1 round per week. There are no mixed combinations of 5,3,1 for the four weeks of a particular month. Only all four weeks are done in 1, 3 or 5 rounds. We have to select the best package considering holding cost and package cost.
A good combination of 5 rounds which doesn't violate order, can be better than all the 3 rounds solutions and the 1 round solution. Same applies for 3 rounds solution aswell. Or else 1 round solution can be better than all 5 rounds and 3 rounds solutions.
When depositing rounds increase, holding cost reduces but depositing cost increases. When rounds decrease, depositing cost reduces but holding cost increases. So I need to find the order of depositing money for each week of the month and the monthly depositing package which can make a good tradeoff between total holding cost and total depositing cost, consuming the least time.
Any insight to the approach will be really helpful.
Answer: In your case you have a fixed monthly cost (FMC) and a variable monthly cost (VMC) for each choice of package. FMC is in {x, x+10000, x+20000}, while VMC is the sum of the variable weekly costs VWC for the 4 weeks. VWC is determined by the partition of the interval of the set of days D = (M,T,W,T,F,S,S) into k disjoint sub-intervals, with k in {1,3,5}.
Therefore you have to choose min{FMC1+VMC1*, FMC3+VMC3*, FMC5+VMC5*}, where VMCk* denotes the minimum variable monthly cost for partitioning D into k intervals (Note that for the case of k=1 the answer is trivial since there exists a single partition for each week). Since the variable weekly cost is  VWC= 0.7*(r1+r2+r3+r4+r5+r6+r7), ri being the remaining amount of day i, it all boils down to minimizing the remaining quantity of each week.  In calculating the VMCk* you can use DP-algorithm described in this paper, with the objective of minimizing the remaining amount of each week.
So in high level:

Obtain the minimum variable weekly cost -> minimum remaining amount of each week using DP, for each package of deposits {1,3,5}. And then the variable monthly cost as the sum of the 4 weeks.
Choose the minimum total cost from considering the fixed cost of each package and the variable one obtained at 1.
Comment: ichantz thank you very much. Can you please check the new edits that I have mentioned in the problem under "Edit". Also I added the actual values for packages. So {x, x+10000, x+20000} is changed to {21135, 32000, 41975}. And the holding cost percentage is changed to 0.00019. It was because 7% was for annual holding cost. I had to divide it by 365 to get the percentage per day. So VWC = 0.00019*(r1+r2+r3+r4+r5+r6+r7)
Comment: can I solve this using Mixed Integer Programming and is there a way to use some kind of heuristics, so that I don't need to try each combination which saves the computation time
Comment: The solution I propose is based on branch and bound, and at each branch you use DP to calculate the optimal. Greedy algs might give you a good approximation, but not the optimal. Notice that you do not try every possible combination, you have a total ordering imposed by the days of the week, so you restrict to interval combinations, i.e. you cannot have a single deposit for the days (M,W,F). Also in bottom up DP you store the optimal values (remainings) for the previous days in an array and you do not have to recalculate them.
Comment: In DP to find the optimal solution, you have to find optimal solutions for each part. In order to find the optimal for the whole week, you have to build on optimal solutions for the previous days. Think that when you have the optimal remainder up to day j, the optimal for day j+1 is the minimum of either a) not making a new deposit (while satisfying the demand constraint), or b) choosing the deposit which minimizes the remaining amount held. In case of b) you have to choose the length of the deposit (how many days to cover) while respecting the number of weekly deposits of each package.
Comment: Thank you very much. I'm trying to understand it. Is the method you suggested faster than implementing a genetic algorithm (crossover probability of chromosomes)
Comment: I think that the algorithm in the paper ultimately chooses to partition the 7 data points into 7 categories because it always returns the maximum fitness value solution. Fitness value is maximized when cash is deposited and withdrawn one by one.   `opt(0) =0`   `opt(1)=max{(0+end(1,1))}=end(1,1)`                  `opt(2)=max{(opt(0)+end(1,2)),(opt(1)+end(2,2))}= opt(1)+end(2,2)`    `opt(3)=max{(opt(0)+end(1,3)), (opt(1)+end(2,3)), (opt(2)+end(3,3))}= opt(2)+end(3,3)`                                                                                etc. How can I constrain to 5,3 or 1
Comment: Even when the order is preserved, for each grouping of 7 into 3 and 7 into 5, there are 15 combinations. So totally 30 combinations for each week. Will I have to try them all? Isn't there a way to avoid obvious costly combinations?


Reflection vector doesn't match book solution

Question:
Let L be the line in R3 that consists of all scalar multiples of [2 1 2].  Find the reflection of the vector [1 1 1] in line L.

I'm calculating this using 2(u dot v) u - v. My solution:
2 ([2 1 2] dot [1 1 1])([2 1 2]) - [1 1 1]
= 2 (5) ([2 1 2]) - [1 1 1]
= [20 10 20] - [1 1 1]
= [19 9 19]

The correct solution is apparently 1/9 [11 1 11].  What am I missing here?
Answer: It's because $\|u\|\neq1$. Therefore, the formula that you should have used is$$2\frac{\langle u,v\rangle}{\|u\|^2}u-v.$$Try it and you will see that you will get the correct answer.
Comment: Thank you José!
Comment: I'm glad I could help.
Answer: For further clarity, what I was missing here (and what the book failed to mention until three chapters later) was that a unit vector $u$ has a length of 1, that is, $u \cdot u = 1$.
$\begin{bmatrix}2\\1\\2\end{bmatrix}$ needed to be normalised to a unit vector.
After normalising, the unit vector is $\begin{bmatrix}\frac{4}{\sqrt{9}}\\\frac{1}{{\sqrt{9}}}\\\frac{4}{{\sqrt{9}}}\end{bmatrix}$, and the answer resolves.


how to get previously selected tab after dismissing modal IOS

Question: I have an application using UITabBarController. There are 5 tabs (tab1, tab2, cameraTab, tab3, tab4). When user taps on middle tab , the modal view will appear hiding the TabBar (in my case camera - UIImagePickerController). If user then taps on cancel button on that modal view, how do I make it to return to previously selected tab. For example: if i am on tab2 and I tap on the camera tab, modal view appears and then I tap on cancel, how do i return back to tab2 automatically. The same goes for all other tabs, if I'm on tab3 it should return to tab 3 and so on. Right now it remains on camera tab without modal view - just blank view with background image.
I'd really appreciate if you can help me with some examples. I've been searching in various ways - there must be a way that UITabBarController keeps a record of previously selected tab.
Thank you
Answer: Personally, I think you should create a custom view where the middle camera tab would not be a tab at all, it would actually just be a button that presents the modal view and then that view would have a button to dismiss it. I would do a little research in http://idevrecipes.com/ to see if there is anything there. If not, maybe github. The tab bar itself is looking for views to push, not present.
I am sorry I couldn't give you more of an answer, but I wanted to give you something for waiting so long.
Comment: thanks AlienDev at least for responding. I'll check on the link you sent me and if I don't find anything I'll start thinking how to implement your approach of a button. I wonder how Instagram does it.


Como aumentar o gráfico sem quebrar o layout em mobile

Question: Problema: Criei uma gráfico utilizando a API do google, porém tive que deixar o gráfico pequeno para quando tiver em mobile ele não quebrar. O problema é em tamanho para desktop fica inviável.
Como tem que ficar:
Gostaria que o gráfico ocupasse o tamanho de col 12 desktop e quando fosse para mobile ele respeitasse a largura do mesmo.
Código HTML:

Script:
 function carregarGraficoTeste() {
        // Some raw data (not necessarily accurate)
        var data = google.visualization.arrayToDataTable([
            ['Legenda 1', 'Legenda 2', 'Legenda 3', 'Legenda 4', 'Legenda 5', 'Legenda 6', 'Legenda 7'],
            ['Inserir texto', 165, 938, 522, 998, 450, 614.6],
            ['Inserir texto', 135, 1120, 599, 1268, 288, 682],
            ['Inserir texto', 157, 1167, 587, 807, 397, 623],
            ['Inserir texto', 139, 1110, 615, 968, 215, 609.4],
            ['Inserir texto', 136, 691, 629, 1026, 366, 569.6]
        ]);

        var options = {
            title: 'apenas um teste',
            legend: { position: 'bottom', maxLines: 2 },
            seriesType: 'bars',
            height: 300,
            width: 400

        };

        var chart = new google.visualization.ComboChart(document.getElementById('teste'));
        chart.draw(data, options);
    }

Answer: Fiz um exemplo com o gráfico responsivo. Ele não estipula tamanho, controla o mesmo por css, e no javascript ele reconhece quando o tamanho da tela muda.
Comment: Deu certo, obrigadão.


Dúvida com R: Pegar uma linha na coluna x que contenha um valor especifico e transformar em outra tabela

Question: boa noite.
Estou com a seguinte situação:
Tenho uma tabela com 3 informações: curso, id_cresc, qt_alunos
Eu preciso encontrar as linhas que tem id_cresc = 0 para somar a qt_alunos de essas linhas onde id_cresc = 0.
Exemplo de db:
curso        id_cresc    qt_alunos
Pegagogia    0.05%          100
Agronomia    0%             20
Design       0%             50

Assim queria que a saída no R fosse ou já o somatório de qt_alunos (quando id_cresc for = 0%) ou somente a coluna qt_alunos, onde também id_cresc = 0%).
Desculpa pela forma da pergunta primeira vez que estou realmente usando está ferramenta para tirar dúvidas.
Comment: Bem-vindo ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, dê uma olhada [neste link](https://pt.meta.stackoverflow.com/questions/6700/como-fazer-uma-pergunta-reproduz%C3%ADvel-em-r/6701#6701) (principalmente no uso da função `dput`) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Answer: library(readr)
library(dplyr)

Cria-se o dataframe:
df <- tibble(curso = c("Pegagogia", "Agronomia", "Design"),
           id_cresc = c("0.05%", "0%", "0%"),
           qt_alunos = c(100, 20, 50))

Se vc quer o resultado só com a soma:

use mutate() aliado à parse_number() para converter uma coluna para o formato numérico;
use filter() para filtrar apenas as observações que atendam às suas necessidades
use group_by() para agrupar (nesse caso só vai ter um grupo mesmo);
use summarise()  + sum() para obter uma coluna com a soma

df %>%
  mutate(id_cresc = parse_number(id_cresc)) %>%
  filter(id_cresc == 0) %>%
  group_by(id_cresc) %>%
  summarise(soma = sum(qt_alunos))

# A tibble: 1 × 2
  id_cresc  soma
     <dbl> <dbl>
1        0    70

Se vc quer a somente a coluna "qt_alunos", onde  "id_cresc = 0%"

use mutate() aliado à parse_number() para converter uma coluna para o formato numérico;
use filter() para filtrar apenas as observações que atendam às suas necessidades
use select() para selecionar sua variável de interesse

df %>%
  mutate(id_cresc = parse_number(id_cresc)) %>%
  filter(id_cresc == 0) %>%
  select(qt_alunos)

# A tibble: 2 × 1
  qt_alunos
      <dbl>
1        20
2        50