Weighted average, then adding an intercept term

Question: I am working with a problem where we are calculating the weighted average of DNA modifications. Modified sites are placed into four different groups and the average weight is calculated from there. However, I am then supposed to add an intercept term. I am confused by "intercept term". How would I go about adding an intercept term in this case?
The step is written below:
"Next one forms a weighted average of the levels using the reported coefficient values and adds an intercept term."
Answer: If understand this correctly, you have 4 groups, which can be viewed as categorical variables. You can select one group and denote it as the 'refence'. A reasonable choice would be the group with the most observations. The estimated average for this group, $b_0$, would be your intercept. For the others group estimate their respective averages and the difference between these averages and the intercept. Finally you'll have a model of the form:
$Y = b_0 + b_1D_1X_1 + b_2D_2X_2 + b_3D_3X_3$, where $D_1, D_2, D_3$ are indicator variables equal to $1$ if $X$ belongs to the respective group (otherwise $0$)
Comment: Thank you for the comment! When you say estimated average, you mean just the mean correct?

The intercepts themselves do not reply on the other categories, in this case, does that mean I only need to make an estimated average for each category instead using the indicator variables?
Comment: Also, In regards to the intercept, the intercept will always be dependent on the DNA modification levels and not a constant number regardless of what the levels are?
Comment: The mean value conditionally that $X$ belongs in the given group.


Profiler builder with custom modules

Question: First things first: happy 2015 to everybody. :-)
Now, I am quite new with Drupal distributions and profiles and here is my situation: I have a running site where I have contributed modules and custom modules. I've installed profiler builder module. When I use drush distro to create a distribution, it generates 2 make files: drupal-org.make and local.make.example. The last one "contains" the first one and it contains the custom modules as well.
When I run drush make local.make.example ./destfolder, it throws some errors. It says "non-existent project type on custom-module". So after a bit of research I've been able to make it work adding some information to the local.make.example, and adding the custom modules in a zip format.
My question is, why does drush distro generates a useless folder structure (i.e. modules, themes, libraries)? Am I able to put something there to make drush-make work on local.make.example without needing to add extra information? Am I missing something?
The extra lines of code I added in each custom module to the local.make.example was:

projects[custom_module_name][type] = "module"
projects[custom_module_name][download][type] = "file"
projects[custom_module_name][download][url] = localurl

Thanks very much for your time and let me know if you need further information.
EDIT
I'm going a bit crazy about this… I've just found out that drush make creates the custom modules' folders but they are empty. Nothing inside… So basically, I just don't know how to tell drush-make to build the initial drupal folder's architecture when custom modules are stored on the same computer I'm executing drupal-make…
I've seen most of the examples that evolves custom modules use git, but I'd just like to know how to make it work with custom modules stored on my machine, if possible.
Answer: In my experience, Profiler Builder has problem with modules, that are not full projects on drupal.org. I tried to use a module, that is hosted in GIT repository and the output was similar to yours. But it worked fine with drush generate-makefile, where generated output was like:

projects[svg][type] = "module"
projects[svg][download][type] = "git"
projects[svg][download][url] = "http://git.drupal.org/sandbox/josegaert/1511596.git"
projects[svg][download][branch] = "7.x-1.x-dev"
projects[svg][download][revision] = "04db94c4dc2bf5c8c9a2a0da5452c4a79d26d863"

I created an issue for Profiler Builder describing this at https://www.drupal.org/node/2479185. You may also want to look at https://www.drupal.org/project/make_local
Answer: According to http://www.drush.org/en/stable/make/#project-download-options you should be able to specify url for file download method. Quoting Drush help:

The URL can also be a path to a local file either using the bare path or the file:// protocol. The path may be absolute or relative to the makefile.

There's other question similar to yours, where you can find further examples and discussion: How do I use "drush make" modules with a local module code?

Profiler builder with custom modules


Case When com LeftJoin

Question: Alguém pode me dar uma ajuda, já passei horas tentando fazer funcionar essa query:
SELECT p.id as idPedido, p.*, i.*, e.*, f.*, m.id AS idEmpresa, m.razao_social, l.id AS idFilial, l.razao_social AS rsf, c.id, c.nome
            FROM wu_pedido AS p
            LEFT JOIN wu_pedido_itens AS i ON (p.id = i.pedido_id)

            (CASE WHEN i.tipo_empresa = 'M' THEN
                LEFT JOIN wu_produto_empresa AS e ON (i.empresa_id = e.id)
                LEFT JOIN wu_empresa AS m ON (e.empresa_id = m.id)
            ELSE i.tipo_empresa = 'F' THEN
                LEFT JOIN wu_produto_filial AS f ON (i.empresa_id = f.id)
                LEFT JOIN wu_filial AS l ON (f.filial_id = l.id)
            END)

            LEFT JOIN wu_categoria_combobox AS c ON (p.status_pedido_id = c.id)

            GROUP BY p.id ORDER BY p.id ASC LIMIT :start, :limit

Comment: Que eu saiba você não pode utilizar CASE para decidir se vai fazer uma junção com a tabela A ou B.
Comment: se for o caso, pode transformar tudo em uma _string_, colocando o _union_ correto de acordo com a condição, depois chamar um `exec`.
Comment: Entendi, obrigado pessoal pela ajuda.
Answer: Você não pode utilizar o CASE para decidir qual JOIN irá fazer. Ao invés disso faça as duas queries separadas e utilize um UNION:
SELECT x.*
  FROM (
  SELECT p.id AS idpedido,
         p.*,
         i.*,
         e.*,
         f.*,
         m.id AS idempresa,
         m.razao_social,
         l.id AS idfilial,
         l.razao_social AS rsf,
         c.id,
         c.nome
    FROM wu_pedido AS p
    LEFT JOIN wu_pedido_itens AS i
      ON p.id = i.pedido_id
    LEFT JOIN wu_produto_empresa AS e
      ON i.empresa_id = e.id
    LEFT JOIN wu_empresa AS m
      ON e.empresa_id = m.id
    LEFT JOIN wu_categoria_combobox AS c
      ON p.status_pedido_id = c.id
   WHERE i.tipo_empresa = 'M'
   UNION
  SELECT p.id AS idpedido,
         p.*,
         i.*,
         e.*,
         f.*,
         m.id AS idempresa,
         m.razao_social,
         l.id AS idfilial,
         l.razao_social AS rsf,
         c.id,
         c.nome
    FROM wu_pedido AS p
    LEFT JOIN wu_pedido_itens AS i
      ON p.id = i.pedido_id
    LEFT JOIN wu_produto_filial AS f
      ON i.empresa_id = f.id
    LEFT JOIN wu_filial AS l
      ON f.filial_id = l.id
    LEFT JOIN wu_categoria_combobox AS c
      ON p.status_pedido_id = c.id
   WHERE i.tipo_empresa = 'F'
  ) x
GROUP BY  x.id
ORDER BY  x.id ASC limit :start,
          :limit

Comment: Obrigado pela resposta Sorack usei seu código com algumas modificações acho que estou no caminho certo, porem ele esta me retornando um erro #1060 - Nome da coluna 'id' duplicado vc saberia me dizer o que pode ser?
Comment: @lgustavo206 você colocou `*` para todas as tabelas. Se mais de uma tiver o campo com o mesmo nome vai dar isso.
Comment: Era isso mesmo! agora deu certo, muito obrigado pela ajuda @Sorack

Case When com LeftJoin


Submitting a form with AJAX causes page reload but only on mobile

Question: I am submitting the user profile edit form by hooking the user profile edit form like this:
$form['actions']['submit']['#ajax'] = array(
'callback' => 'user_profile_submit',
'wrapper' => $form['#attributes']['id'],
'method' => 'invoke',
'effect' => 'fade',
);

The callback function user_profile_submit invokes a simple jQuery alert notification specifying if the form was saved successfully. The setup works perfectly on the desktop i.e. the form is submitted with AJAX with no page reload whatsoever. However, saving the same form using mobile devices causes always a page reload. Any idea what might be causing this behavior? Thanks.
Update:
Problem can be observed in Chrome/Dolphin but not in Firefox.
Answer: Solved:
I have just downloaded the latest development version of jQuery Update module and the problem was solved. It has to do with this module nothing else.
Comment: When you say "latest development version", do you mean the version committed on 2015-Oct-21, or did you use a specific dev release that's later than that? Because the 2015-Oct-21 version is very likely the same as the prod version of the same date.
Comment: Nope, it is not the same. I mean `7.x-3.x-dev`. If you look closer you see that there is ~ 300kb of extra compressed code in the dev version but not in the release. They can have the same date stamp but the content is different.


build pandas documentation from source using installed pandas rather than an inplace build

Question: My question is: How can I use my up to date pandas installation to build the pandas documentation?
I read the pandas/doc/README.rst, which says to navigate to the pandas/doc directory and run python make.py html. Unfortunately, this does not work for me as it seems to require having first done an inplace build of pandas. My (windows) computer does not have the necessary prerequisites for doing a development build, and it seems to be an unnecessary burden when I just want to add some notes that improve the documentation.
The background for why I am asking this question is that earlier this week I posted a SO question about pandas hdf5 output. In discussing the answer with Jeff, he encouraged me to add some commentary to the documentation. So I forked the pandas repository and began to think about how I would add to the documentation. I am not interested in setting up a development build of the complete pandas installation. I would like to be able to modify the documentation, build it, and see my changes before submitting a pull request. Is there a reasonable way to do this?
Thanks!
Comment: Shouldn't this be something you post on [`github`](https://github.com/pydata/pandas/issues) rather than SO?
Comment: I am sometimes unsure what to post where. I thought this was a general pandas question about how to contribute to pandas documentation so it should go on SO. Now that I have seen this is a bug (or undocumented feature--see my comment below), I made an [issue on github](https://github.com/pydata/pandas/issues/10340).
Answer: Here are the pandas contributing guidelines & howto's.
Comment: I had seen that. I discovered the problem I have is that the ``make.py`` script has the statement ``os.environ['PYTHONPATH'] = '..'``, which seems to force python to get pandas from the source tree. I commented out that line and now the error I was getting with ``python make.py html`` seems to have gone away and the html documentation is generated. I will forge ahead with adding my 2 cents to the documentation.


Output of a function in R with a list (lda model, ggplot, dataframe)

Question: I am struggling on how to get an output of a function in R I am creating with a list of elements. Apparently it is simple, however, I cannot get into that. I checked different questions in SO but no result. This might be an easy question and probably I am misprinting some line.
The output of the function I am creating has three elements that I think they should be included in a list:

Linear discriminant analysis model (lda).
A dataframe
A ggplot image

This is the version of the function I am working with:
fun <- function(data, tooth_type = c("m1", "m2", "m3"), position = c("U", "L")) {
  model <- lda(Species ~ MD + BL, data = data)
  # extract the information of the tooth we are working from the Omo database
  tooth <- omo_numeric_mdbl[omo_numeric_mdbl$Tooth == tooth_type & omo_numeric_mdbl$Position == position, ]
  tooth <- tooth[complete.cases(tooth[, 31:32]), ]
  predictions <- model %>%
    predict(tooth)
  pred <- as.data.frame(predictions$posterior)*100
  # plot
  lda.data <- cbind(data, predict(model)$x)
  ggplot_fun <- ggplot(lda.data, aes(LD1, LD2)) +
    geom_point(aes(color = Species))
  list(model, pred, ggplot_fun)
}

As you can see, inside the function there are three objects I would like to store:

pred: this is the dataframe
model: this is the lda information
ggplot_fun: this is the ggplot image

I tried:

as.list(model, pred, ggplot_fun) -> unsuccessful
list(model, pred, ggplot_fun) -> unsuccessful
x <- as.list(model, pred, ggplot_fun); return(x) -> unsuccessful
x <- list(model, pred, ggplot_fun); return(x) -> unsuccessful

Ultimately, what I would like is:
x <- fun(data, "m3", "L") # for example

x$pred       # show the dataframe (and display as kable, if required)
x$model      # show the lda model, and to get all the details inside as x$model$posterior
x$ggplot_fun # display the ggplot function

Comment: And what output are you getting at the moment? We don't have any data that would work on your function to test it, and you didn't tell us what your function is currently outputing. Are you getting an error? A warning? No output?
Comment: I was having an output, but everything was messy. I found out the solution and answered my question.
Answer: I finally solved the issue. In order to give the answer to others with the same questions I changed the last line of the example:
list(model, pred, ggplot_fun)

By this one
list(LDA = model, Prediction = pred, Ggplot = ggplot_fun)

Basically I named each of the elements.


Organizando um array com base em um campo

Question: Bom estou montando um array com uma consulta que vem do PDO ela está me dando o resultado que eu quero, porém não sei se essa é a melhor forma de fazer isso.
Segue o meu código php:
<code>             // Array com os dados
        $consulta[] = array('Cod' => 10, 'DataOp' => '2020-06-08', 'ValorOp' => 10);
        $consulta[] = array('Cod' => 11, 'DataOp' => '2020-06-09', 'ValorOp' => 15);
        $consulta[] = array('Cod' => 12, 'DataOp' => '2020-06-08', 'ValorOp' => 90);
        $consulta[] = array('Cod' => 13, 'DataOp' => '2020-06-11', 'ValorOp' => 78);

        // Inicia variáveis
        $listaBruta = array();
        $listaData = array();
        $lista = array();

        // Monta a lista
        foreach ($consulta as $linha) {

            $listaBruta[] = $linha;

            // Verifica se já existe a data no array
           if (!in_array($linha['DataOp'], $listaData)) {
             $listaData[] = $linha['DataOp'];
           }

        }

        // Monta lista agrupada
        foreach ($listaData as $linha) {

            // Inicia variáveis
            $listaFiltrada = array();

            // Filtra o array
            foreach ($listaBruta as $operacao) {

                // Verifica se a data é igual
                if ($linha === $operacao['DataOp']) {

                    $listaFiltrada[] = array(
                        "cod" => (int) $operacao['Cod'],
                        "valorOp" => (float) $operacao['ValorOp']
                    );

                }

            }

            $lista[] = array(
                "dataOp" => $linha,
                "operacoes" => $listaFiltrada
            );

        }

        echo json_encode($lista, 256);

</code>
A resposta que tenho é esse, ela esta do jeito que eu quero.
<code>    [
    {
    "dataOp": "2020-06-08",
    "operacoes": [
        {
            "cod": 10,
            "valorOp": 10
        },
        {
            "cod": 12,
            "valorOp": 90
        }
    ]
    },
    {
    "dataOp": "2020-06-09",
    "operacoes": [
        {
            "cod": 11,
            "valorOp": 15
        }
    ]
    },
    {
    "dataOp": "2020-06-11",
    "operacoes": [
        {
            "cod": 13,
            "valorOp": 78
        }
    ]
    }
]
</code>
Answer: Não tinha como eu perguntar porque n tenho ponto suficiente , tive que dar uma pequena mudado porque não tinha o objeto com os dados porem e so passar as array para objeto ve se isso lhe atende caso n atenta me avisa
<code> <?php
function arrumar($dados)
    {
        //pegar a lista e remontar ela usando a segunda coluna da array como chave principa
        foreach ($dados as $key => $value) {
            foreach ($value as $k => $v) {

                $resultado[$k][] = $v;
            }
        }
        //verificando quais array tem a data igual
        foreach ($resultado['dataOp'] as $k => $v) {
            if (isset($a[$v])) {
                $a[$v] = $a[$v] . ',' . $k;
            } else {
                $a[$v] = $k;
            }
        }
        //montar a lista
        foreach ($resultado['dataOp'] as $key => $linha) {

            $lista[] = array(
                "data" => $linha,
                "operacoes" => array(
                    "cod" => (int)$resultado['cod'][$key],
                    "valorOp" => (float)$resultado['valorOp'][$key]
                )
            );
        }
        //colocar a data do pedido como chave mestre assim apagando todas as dubicadas e colocando o conteudo da operacoes na array ja existente
        foreach ($a as $k => $v) {
            $explode = explode(',', $v);
            $i = 0;
            if (isset($explode[0])) {
                foreach ($explode as $rk => $vk) {
                    if ($i <> 0) {
                        $listar[$lista[$vk]['data']]['operacoes'] = array_merge([$lista[$keyatual]['operacoes']], [$lista[$vk]['operacoes']]);

                    } else {
                        $keyatual = $vk;
                        $listar[$lista[$vk]['data']] = $lista[$vk];
                    }
                    $i = 1;
                }

            }
        }

        //substituindo o nome da array mastre e colocando numero apara facilitar o usso ficando $operacoes[0] e asiim por diante
        foreach ($listar as $v) {
            $operacoes[] = $v;
        }

        return $operacoes;
    }
echo json_encode(arrumar($consulta), 256);
?>
</code>
Comment: Então acho vc me respondeu enquanto eu editava minha pergunta. O seu exemplo acabou ficando mais complexo do que, o que eu usei. E você não documentou, acabou ficando difícil de entender.
Comment: @HugoBorges desculpa por não ter documentado, ficarei mas atendo da proxima , vc poderia postar sua resposta fiquei curioso de como vc fez
Comment: Eu editei minha pergunta para ficar mais completa, e lá eu coloquei como fiz. Confere ai e me fala o que vc acha.
Comment: @HugoBorges a sim achei bacana , notei que elas se repetem dublicando as array iguais acho que seria pacana usar array_filter(), para apagar as iguais, segui seu conselho e coloquei oque os comentarios explicando oque cada coisa faz, te uma lida e ve se fica melhor para entender
Comment: Show, agora deu para entender melhor sua lógica. Aproveitando dei uma analisada no bug que você comentou. Optei por uma abordagem diferente, ao invés de remover as duplicidades eu usei a função `in_array` assim verifico se já existe o valor no array, e só depois adiciono ele. Assim evito as duplicidades. Editei minha pergunta com essa alteração.


my php mail function is not sending delevering mails in yahoo

Question: This is the way i used the mail function in php. Everything is fine for gmail; it is delivering in inbox, but in yahoo it is not delivering.
if (isset($_POST['send']))

    {

                   $uname=$_POST['username'];
        $mailid=$_POST['mail'];
        $subject="hai";
        $mail="firstname.lastname@example.com";
        $sendmessage=$_POST['sendmessage'];
        $headers= "From:".$mailid."\n";
        $headers .= 'MIME-Version: 1.0′ . PHP_EOL';
        $headers .= 'Content-type: text/html; charset=iso-8859-1'. PHP_EOL;
        $mail_sent=mail($mail, $subject, $sendmessage,$headers);
        if($mail_sent)
        echo "Thanks ";
        else
        echo "Request unsuccessful";

}

I don't know where the problem is. When I sent it to yahoo it is giving me the success message but not delivering.
Comment: check your yahoo message filtering settings
Comment: have you check the spam folder?
Comment: http://imgs.xkcd.com/comics/exploits_of_a_mom.png
Comment: i have checked in spam folder it is not there.how to see yahoo filtering settings
Answer: Apart from my comments for message filtering settings-
Change -
$headers .= 'MIME-Version: 1.0′ . PHP_EOL';

To
$headers .= 'MIME-Version: 1.0'.PHP_EOL;

Comment: ya i changed it but mail is not delevering it is showing sucess message.i even checked in spam also
Comment: how to check yahoo message filtering settings


how to get macro variable to evaluate math?

Question: I have the following sas marco snippet:
%macro processLink(uuid=, name=, cluster_external_ipaddress=);

 %let unix_starttime = 1000000*(&starttime - '01JAN1970:00:00'dt);
 %let unix_endtime = 1000000*(&endtime - '01JAN1970:00:00'dt);
...

when this runs it just creates the variable as a string ie
=1000000*(dhms(today()-1,0,0,0) - '01JAN1970:00:00'dt)
instead of the unix timestamp in usecs.
using unix_starttime = 1000000*(&starttime - '01JAN1970:00:00'dt); outside the macro in a data step works
do i need a null datastep in the macro for this to work as intended ?
Thanks
Comment: Don't get me started about SAS Marco
Comment: Where do the values for STARTTIME and ENDTIME macro variables come from? What do they look like?
Answer: In general if you want to work with DATA you are better off using SAS code and not MACRO code.  You can use CALL SYMPUTX() to generate a macro variable if you need it later.
data _null_;
  call symputx('unix_starttime',1000000*(&starttime - '01JAN1970:00:00'dt));
  ...
run;

You can use %eval() to do simple integer arithmetic and comparisons. If you need to use floating point numbers (or date/time/datetime literals) then you need to use %sysevalf().
 %let unix_starttime=%sysevalf(1000000*(&starttime - '01JAN1970:00:00'dt));

Comment: Thanks, all working now with the additional help from @J_Lard and using %sysfunc
Answer: In general, anything after a %let statement is treated as pure text.  However, there are functions available to wrap around the text which tell SAS to perform a mathematical operation.
These are %eval, used for integer calculations, or %sysevalf where calculations involving decimals are required.
So you could put %let unix_starttime = %eval(1000000*(&starttime - '01JAN1970:00:00'dt));
It's not applicable here, but if you ever need to include a function in a %let statement, then precede the function name with %sysfunc
Comment: @DwayneDibbley You need to put `%sysfunc` around your functions when you create the `&starttime` macro variable. `%sysfunc(dhms(%sysfunc(today())-1,0,0,0)`.
Comment: I still get an error with the %eval added ( is it the & of the datetime text causing the issue?  :  - %let unix_starttime = %eval(1000000*(&starttime - '01JAN1970:00:00'dt));
ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was:
       1000000*(dhms(today()-1,0,0,0) - '01JAN1970:00:00'dt)
Comment: You need to use %SYSEVALF() if you want it to recognize a date literal.


Recommendations for non-technical yet deep articles in statistics

Question: The inspiration for this question comes from the late Leo-Breiman's well-known article Statistical Modeling: The Two Cultures (available open access). The author compares what he sees as two disparate approaches to analyzing data, touching upon key ideas in classical statistics and machine learning. However, the article is intelligible to a wide audience--arguably to anyone who works with data, regardless of whether they've pursued statistics at the doctoral level or have only taken an introductory course. Moreover, the article is stimulating. That is, it readily generates discussion (as is evidenced by the series of lively commentaries published in the same issue).
I'm curious to discover more articles with these qualities. That is, articles that:

Touch on fundamental concepts in statistics/data analysis
Can be understood by a wide audience in terms of variation in research-focus and formal statistical training
Stimulate discussion, whether through insight or controversy
Comment: The answers so far have been very interesting! Keep them coming. Of course, I won't accept any of the answers as per http://meta.stats.stackexchange.com/questions/409/accepting-answers-on-community-wiki-potentially-big-list-questions
Comment: There's no [Royal Road](https://books.google.com/books?id=JZEHj2fEmqAC&lpg=PP1&pg=PA57#v=onepage&q&f=false) to statistics.
Answer: Shmueli, Galit. "To explain or to predict?." Statistical science (2010): 289-310.
I believe it matches your three bullet points.
It talks about explanatory versus predictive modelling (the terms should be self-explanatory) and notes that differences between them are often not recognized.
It raises the point that depending on the goal of modelling (explanatory vs. predictive), different model building strategies could be used and different models may be selected as "the best" model.
It is a rather comprehensive paper and an enjoyable read. A discussion of it is summarized in Rob J. Hyndman's blog post. A related discussion on Cross Validated is in this thread (with lots of upvotes). Another (unanswered) question on the same topic is this.
Answer:
Lehmann, Erich L. "The Fisher, Neyman-Pearson theories of testing hypotheses: One theory or two?." Journal of the American Statistical Association 88.424 (1993): 1242-1249.

It is not known to many but when the giants of the profession were still among us, they did not get on well with each other. The debate on the foundations of hypothesis testing specifically, whether it should be inductive or deductive,  saw some pretty serious insults flying around between Fisher on the one hand and Neyman-Pearson on the other. And the issue was never settled during their lifetimes.
Long after they have all passed, Lehmann tries to bridge the gap and in my opinion does a good job as he shows that the approaches are complementary rather than mutually exclusive. This is what students learn nowadays by the way. You need to know a few basic things about hypothesis testing but you can otherwise follow the paper without any problems.
Comment: Thanks for the citation. I have once asked a question about the alleged conflict between F and NP approaches: http://stats.stackexchange.com/questions/112769, and despite lots of attention and upvotes it received I am still not convinced by any of the existing answers (and did not accept any). I plan to go back to that thread and do some reading / put a bounty or something, but never find time; if you are familiar with Lehmann's paper I would encourage you to contribute an answer there.
Comment: @amoeba I have read Lehmann's paper again and again, it's very readable but I do not think I have researched the matter as thoroughly as you. So whenever you have the time it would be a good idea for you to go over it and see his point of view. You will find the discussion of the Behrens-Fisher problem particularly revealing.
Comment: Thanks for sharing. Maybe all I've heard has been rather one-sided, but everything I've heard about Sir Ron Fisher is that he was a rather unpleasant man to deal with, to say the least. He also had some questionable opinions on [the link between tobacco use and lung cancer](http://www.uic.edu.hk/~kentsang/powerst/Stolley1991whengeniuserrsRAFisherlungcancer.pdf).
Comment: A "lighter" alternative to the article is Christensen, Ronald. ["Testing Fisher, Neyman, Pearson, and Bayes."](http://www.tandfonline.com/doi/abs/10.1198/000313005X20871) The American Statistician 59.2 (2005): 121-126. I found it enjoyable.
Answer: Wilk, M.B. and Gnanadesikan, R. 1968.
Probability plotting methods for the analysis of data.
Biometrika 55: 1-17. Jstor link if you have access
This paper is, at the time of my writing, almost 50 years old but still feels fresh and innovative. Using a rich variety of interesting and substantial examples, the authors unify and extend a variety of ideas for plotting and comparing distributions using the framework of Q-Q (quantile-quantile) and P-P (probability-probability) plots. Distributions here mean broadly any sets of data or of numbers (residuals, contrasts, etc., etc.)  arising in their analyses.
Particular versions of these plots go back several decades, most obviously normal probability or normal scores plots. which are in these terms quantile-quantile plots, namely plots of observed quantiles versus expected or theoretical quantiles from a sample of the same size from a normal (Gaussian) distribution. But the authors show, modestly yet confidently, that the same ideas can be extended easily -- and practically with modern computing -- for examining other kinds of quantiles and plotting the results automatically.
The authors, then both at Bell Telephone Laboratories, enjoyed state-of-the-art computing facilities, and even many universities and research institutions took  a decade or so to catch up. Even now, the ideas in this paper deserve wider application than they get. It's a rare introductory text or course that includes any of these ideas other than the normal Q-Q plot. Histograms and box plots (each often highly useful, but nevertheless each awkward and limited in several ways) continue to be the main staples when plots of distributions are introduced.
On a personal level, even though the main ideas of this paper have been familiar for most of my career, I enjoy re-reading it every couple of years or so. One good reason is pleasure at the way the authors yield simple but powerful ideas to good effect with serious examples. Another good reason is the way that the paper, which is concisely written, without the slightest trace of bombast, hints at extensions of the main ideas. More than once, I've rediscovered twists on the main ideas covered explicitly in side hints and further comments.
This isn't just a paper for those especially interested in statistical graphics, although to my mind that should include everyone interested in statistics of any kind. It promotes ways of thinking about distributions that are practically helpful in developing anyone's statistical skills and insights.
Comment: This is a great choice. I've read this several times -- as soon as I saw the authors names in your answer I knew which paper this was, and straight away I wanted to read it  again. I think I have a copy of it here somewhere...
Answer: Ioannidis, John P. A. "Why Most Published Research Findings Are False." PLoS Medicine (2005)
Ioannidis, John P. A. "How to Make More Published Research True." PLoS Medicine (2014)
Must reads for every researcher/statistician/analyst who wants to avoid the dangers of using and interpreting statistics incorrectly in research. The 2005 article has been the most-accessed in the history of Public Library of Science, and it stimulated lots of controversy and discussion.
Comment: These are great articles. They are also technical for non-statisticians.
Answer: Tukey, J. W. (1960) Conclusions vs Decisions Technometrics 2(4): 423-433
This paper is based on an after-dinner talk by Tukey and there is a comment that 'considerable discussion ensued' so it matches at least the third of your dot points.
I first read this paper when I was completing a PhD in engineering and appreciated its exploration of the practicalities of data analysis.
Answer: Efron and Morris, 1977, Stein's Paradox in Statistics.
Efron and Morris wrote a series of technical papers on James-Stein estimator in the 1970s, framing Stein's "paradox" in the Empirical Bayes context. The 1977 paper is a popular one published in Scientific American.
It is a great read.
Comment: Fascinating! Is there are relationship between Stein's paradox and seemingly unrelated regression?
Answer: Well, despite the greater interest in Roy Model is among economists (but I may be wrong), its original paper "Some Thoughts on the Distribution of Earnings" from 1951, is a insightful and nontechnical discussion about self selection problem. This paper served as inspiration for the selection models developed by the nobel prize James Heckman. Although old, I think it matches your three bullet points.
Answer: Although it's a full-length book and not just an article, Judea Pearl's The Book of Why admirably meets all three of your criteria.
It addresses a foundational question of statistics—under what conditions can statistical analyses yield causal conclusions—in a way that successfully targets a general audience.  Philosophers, AI researchers, trial lawyers, climate activists, and of course statisticians will all find much of interest in this remarkable, cross-disciplinary book.
Among statisticians with a serious interest in causality, Andrew Gelman's review is less enthusiastic than most because Gelman finds Pearl's causal graphs and do-calculus less useful than do most textbooks on causal inference. Gelman likewise takes issue with many of Pearl's grander generalizations about the history of statistics.  But stirring up controversy and directly influencing the discipline both count as stimulation:
https://statmodeling.stat.columbia.edu/2019/01/08/book-pearl-mackenzie/
Answer: No Interpretation of Probability (Schwarz, 2018) is a favorite of mine.  It touches on a lot of deep and persisting interpretational issues in statistics, and offers a refreshingly deflationary resolution to many (but not all) of them.
The Reference-Class Problem is Your Problem Too (Hájek, 2007) is a pretty good summary of the fundamental impossibility of assigning statements of probability to uniquely interpretable empirical quantities, much in the vein of the first article.  I think it is a little unduly harsh on frequentism, but not so much that it hurts the article.
Prior Probabilities and Transformation Groups (Jaynes) is a nice overview of how symmetries in our problem-framing can be used to inform our choice of priors.  Jaynes is always a pleasure to read, if a bit dogmatic.
All of these require very little in the way of formal mathematical background, but touch on extremely important concepts that are relevant more or less everywhere in application.
Comment: Could you please add the authors?
Comment: I am fascinated by Schwarz 2018. Perhaps it even provides beneficial background context to [a question I asked recently](https://stats.stackexchange.com/questions/549914/are-randomness-and-probability-really-logically-dependent-notions).
Answer: A recent surge in Causality and machine learning give rise to Pearl's framework moving into mainstream data science and statistics practice. In this direction, an article from Judea Pearl is a great starting point on the intricacies of Causal Inference in Machine Learning:

The Seven Tools of Causal Inference, with Reflections on Machine Learning .
Judea Pearl.
Communications of the ACM, March 2019, Vol. 62 No. 3, Pages 54-60.


Various ways to remove local Git changes

Question: I just cloned a git repository and checked out a branch. I worked on it, and then decided to remove all my local changes, as I wanted the original copy.
In short, I had to do the following two commands to remove my local changes
git checkout .

git clean -f

My question is,
(1) Is this the correct approach in getting rid of local changes, or else please let me know the correct approach.
(2) when do we use git reset --hard as i am able to reset even without this command
Thanks
*Solution : Major Edit(s): 03/26 : *
Replaced many of vague terms with git specific terminology
 [tracked/untracked/staged/unstaged]
There could be only three categories of files when we make local changes:

Type 1. Staged Tracked files
Type 2. Unstaged Tracked files
Type 3. Unstaged UnTracked files a.k.a UnTracked files

Staged - Those that are moved to staging area/ Added to index
Tracked - modified files
UnTracked - new files. Always unstaged. If staged, that means they are tracked.

What each commands do:

git checkout . - Removes Unstaged Tracked files ONLY [Type 2]
git clean -f - Removes Unstaged UnTracked files ONLY [Type 3]
git reset --hard - Removes Staged Tracked and UnStaged Tracked files ONLY[Type 1, Type 2]
git stash -u - Removes all changes [Type 1, Type 2, Type 3]

Conclusion:
It's clear that we can use either
(1) combination of `git clean -f` and `git reset --hard`

OR
(2) `git stash -u`

to achieve the desired result.
Note: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retrieved using git stash pop.
So choosing between the above two options is developer's call.
Thank you Christoph and Frederik Schøning.
Edit: 03/27
I thought it's worth putting the 'beware' note to git clean -f
git clean -f
There is no going back. Use -n or --dry-run to preview the damage you'll do.
If you want to also remove directories, run git clean -f -d
If you just want to remove ignored files, run git clean -f -X
If you want to remove ignored as well as non-ignored files, run git clean -f -x
reference : more on git clean : How to remove local (untracked) files from the current Git working tree?
Edit: 05/20/15
Discarding all local commits on this branch [Removing local commits]
In order to discard all local commits on this branch, to make the local branch identical
to the "upstream" of this branch, simply run git reset --hard @{u}
Reference: http://sethrobertson.github.io/GitFixUm/fixup.html
or do git reset --hard origin/master [if local branch is master]
Note: 06/12/2015
This is not a duplicate of the other SO question that's marked as duplicate. This question address how to remove local GIT changes [remove a file added, remove changes added to existing file etc and the various approaches; Where in the other SO thread only address how to remove local commit. If you added a file, and you want to remove that alone, then the other SO thread doesn't discuss about it. Hence this is not a duplicate of the other one]
Edit: 06/23/15
How to revert a commit already pushed to a remote repository?
$ git revert ab12cd15

Edit: 09/01/2015
Delete a previous commit from local branch and remote branch
Case: You just commited a change to your local branch and immediately pushed to the remote branch,
Suddenly realized , Oh no! I dont need this change. Now do what?
git reset --hard HEAD~1     [for deleting that commit from local branch]
git push origin HEAD --force [both the commands must be executed. For deleting from remote branch]
Whats the branch ? Its the currently checked out branch.
Edit 09/08/2015 - Remove local git merge:
I am on master branch and merged master branch with a newly working branch phase2
$ git status
# On branch master

$ git merge phase2

$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 8 commits.

Q: How to get rid of this merge?
Tried git reset --hard   and git clean -d -f
Both didn't work.
The only thing that worked are any of the below ones:
$ git reset --hard origin/master

or
$ git reset --hard HEAD~8

or
$ git reset --hard 9a88396f51e2a068bb7  [sha commit code - this is the one that was present before all your merge commits happened]
Comment: "git stash" will remove any changes you have made.
Comment: @JavaDev
Your question was more like an answer.. appreciate that you kept on editing and compiled all the answers.
Comment: I guess this thread might answer your questions: https://stackoverflow.com/questions/1146973/how-do-i-revert-all-local-changes-in-a-git-managed-project-to-previous-state
Comment: Nice summary! I'd add another file category: "Type 4. Ignored files." `git stash -a` [or --all] will stash the ignored and untracked files as well. `git clean -x` will clean ignored files as well. `git clean -X` will clean only the ignored files.
Comment: thanks i ran all 4 of your commands to reverse local changes
Comment: possible duplicate of [Throw away local commits in git](http://stackoverflow.com/questions/5097456/throw-away-local-commits-in-git)
Comment: `git checkout -f` removes [tracked and untracked files](https://git-scm.com/docs/git-checkout#git-checkout--f).
Comment: But these solutions don't seem to remove my git ignored files, i.e. files and folders inside .gitignore (which may make sense ;-).  Do I have to remove these manually (or at least remove them from .gitignore)?
Comment: git reset origin/ --hard
Comment: This is pretty much "just how Git works" but saying that
git clean -f
is a way to restore a repo is incomplete to the point of misleading.  (Obviously these details are there buried in the discussion.)  But git clean -f will only clean a certain class of changes.  Notable, it WILL NOT fix creation of directories, and there are complications relating to ignored files.  (I don't know about you, but I'm pretty likely to have a directory created by running a build, or just because I stash some stuff.)  So, in summary, in general, git clean -f IS NOT the answer to the question.
Answer: It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:
Hard reset
git reset --hard [HEAD]

completely remove all staged and unstaged changes to tracked files.
I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.
Clean
git clean [-f]

Remove files that are not tracked.
For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.
The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.
Git clean will not touch files, that are already being tracked.
Checkout "dot"
git checkout .

I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:
"undo all changes in my working tree".
I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.
Stashing
Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.
To sum up
Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD followed by git clean -f will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).
All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)
I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard was that you had never staged anything. Had you staged a change, neither git checkout . nor git clean -f would have reverted that.
Hope this covers.
Comment: `.` is a pathspec referring to the current working directory, which might be the root of the repo. From git-scm.com: `git checkout [] [--] …` updates the named paths in the working tree from the index file or from a named .
Comment: It's never enough stressed that both `git reset --hard` and `git clean -dfx` and the like are *destructive*. Anyway, please fix the lowercase `head` in the answer, it should be either uppercase `HEAD` or not present at all.
Comment: Thank you both of you. I have summarized the answer and embedded into my question. Christoph let me know what `git stash -u` does and how to pop it, but Frederik let me know reset hard and using the combination of `git reset --hard` and `git clean -f` , and why not `stash` is preferred in some scenarios. Now Please help me in choosing which one should i mark as Answer :) , both are my answers.
Comment: I improved my answer why I think `git stash -u` makes most sense here.
Comment: Thank you for the reason behind using `git reset --hard`. I tried it out, and yes.. those files added to index(staging) were removed only after `git reset --hard`, and i assume by default `git reset --hard` is `git reset --hard head`. This link was also helpful http://gitready.com/beginner/2009/01/18/the-staging-area.html
Comment: Yes, `git reset --hard` is shorthand for `git reset --hard HEAD` (see https://www.kernel.org/pub/software/scm/git/docs/git-reset.html, examples section).

Christoph: you have a valid point - `git stash -u` is indeed the only single command to clean stuff up. And, obviously, you can pop the stash back up. But it is saved somewhere in storage/index (say for example you stashed sensitive information, now ready for others to peek), and semantically it's maybe not exactly the equivalent of cleaning your repo. But: it works - in 1 command ;)
Comment: Alternatively, for a single-liner, you could make a bat/shell file to execute the chained command `git reset --hard && git clean [-f]`. This would remove all changes (tracked, untracked, staged, unstaged), never to be found again.
Comment: http://git-scm.com/docs/git-clean explains the git clean args differently. -f (force) is normally needed to get it to delete anything. -x also removes ignored files. -X only removes ignored files. -d also removes untracked directories.
Comment: If you do this and still find that you have some local changes in your directory, its because those are untracked files. Do `git add .` and then `git reset --hard`
Comment: These commands don't work for me at all, just generates errors.
Comment: `git checkout .` seems like a nice solution.
Answer: Reason for adding an answer at this moment:
So far I was adding the conclusion and 'answers' to my initial question itself, making the question very lengthy, hence moving to separate answer.
I have also added more frequently used git commands that helps me on git, to help someone else too.
Basically to clean all local commits
$ git reset --hard and
$ git clean -d -f

First step before you do any commits is to configure your username and email that appears along with your commit.
#Sets the name you want attached to your commit transactions
$ git config --global user.name "[name]"

#Sets the email you want atached to your commit transactions
$ git config --global user.email "[email address]"

#List the global config
$ git config --list

#List the remote URL
$ git remote show origin

#check status
git status

#List all local and remote branches
git branch -a

#create a new local branch and start working on this branch
git checkout -b "branchname"

or, it can be done as a two step process
create branch: git branch branchname
work on this branch: git checkout branchname
#commit local changes [two step process:- Add the file to the index, that means adding to the staging area. Then commit the files that are present in this staging area]
git add <path to file>

git commit -m "commit message"

#checkout some other local branch
git checkout "local branch name"

#remove all changes in local branch [Suppose you made some changes in local branch like adding new file or modifying existing file, or making a local commit, but no longer need that]
git clean -d -f and git reset --hard  [clean all local changes made to the local branch except if local commit]
git stash -u  also removes all changes
Note:
It's clear that we can use either
(1) combination of git clean –d –f and git reset --hard
OR
(2) git stash -u
to achieve the desired result.
Note 1: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retreived using git stash pop. So choosing between the above two options is developer's call.
Note 2: git reset --hard will delete working directory changes. Be sure to stash any local changes you want to keep before running this command.
# Switch to the master branch and make sure you are up to date.
git checkout master

git fetch    [this may be necessary (depending on your git config) to receive updates on origin/master ]
git pull

# Merge the feature branch into the master branch.
git merge feature_branch

# Reset the master branch to origin's state.
git reset origin/master

#Accidentally deleted a file from local , how to retrieve it back?
Do a git status to get the complete filepath of the deleted resource
git checkout branchname <file path name>

that's it!
#Merge master branch with someotherbranch
git checkout master
git merge someotherbranchname

#rename local branch
git branch -m old-branch-name new-branch-name

#delete local branch
git branch -D branch-name

#delete remote branch
git push origin --delete branchname

or
git push origin :branch-name

#revert a commit already pushed to a remote repository
git revert hgytyz4567

#branch from a previous commit using GIT
git branch branchname <sha1-of-commit>

#Change commit message of the most recent commit that's already been pushed to remote
git commit --amend -m "new commit message"
git push --force origin <branch-name>

# Discarding all local commits on this branch [Removing local commits]
In order to discard all local commits on this branch, to make the local branch identical to the "upstream" of this branch, simply run
git reset --hard @{u}

Reference: http://sethrobertson.github.io/GitFixUm/fixup.html
or do git reset --hard origin/master [if local branch is master]
# Revert  a commit already pushed to a remote repository?
$ git revert ab12cd15

#Delete a previous commit from local branch and remote branch
Use-Case: You just commited a change to your local branch and immediately pushed to the remote branch, Suddenly realized , Oh no! I dont need this change. Now do what?
git reset --hard HEAD~1 [for deleting that commit from local branch. 1 denotes the ONE commit you made]
git push origin HEAD --force [both the commands must be executed. For deleting from remote branch]. Currently checked out branch will be referred as the branch where you are making this operation.
#Delete some of recent commits from local and remote repo and preserve to the commit that you want. ( a kind of reverting commits from local and remote)
Let's assume you have 3 commits that you've pushed to remote branch named 'develop'
commitid-1 done at 9am
commitid-2 done at 10am
commitid-3 done at 11am. // latest commit. HEAD is current here.

To revert to old commit ( to change the state of branch)
git log --oneline --decorate --graph // to see all your commitids
git clean -d -f // clean any local changes
git reset --hard commitid-1  // locally reverting to this commitid
git push -u origin +develop // push this state to remote. + to do force push
# Remove local git merge:
Case:
I am on master branch and merged master branch with a newly working branch phase2
$ git status

On branch master
$ git merge phase2
$ git status
On branch master
Your branch is ahead of 'origin/master' by 8 commits.
Q: How to get rid of this local git merge? Tried git reset --hard and git clean -d -f Both didn't work.
The only thing that worked are any of the below ones:
$ git reset --hard origin/master
or
$ git reset --hard HEAD~8
or
$ git reset --hard 9a88396f51e2a068bb7 [sha commit code - this is the one that was present before all your merge commits happened]
#create gitignore file
touch .gitignore // create the file in mac or unix users
sample .gitignore contents:
.project
*.py
.settings

Reference link to GIT cheat sheet: https://services.github.com/on-demand/downloads/github-git-cheat-sheet.pdf
Comment: Your command for Deleting Remote Branch might be **not best**. You are using `git push origin :branch-name` however I recommend using `git push origin --delete branchname`
Comment: Agree, i updated with your suggestion, thank you @vibs2006
Comment: This answer is closer than above, because it includes -d in
git clean -d -f
I didn't run into the problem of ignored files (yet) but it is extremely likely users will have created directories that need to be deleted.
For the ignored file issue, you probably want -x.  In summary, the answer is
git clean -fdx
(Like with most things git, the default is not what you want.)
As for "stash" doing what is requested.  Maybe so.  But it has the side effect of creating a stash.  (If that is some 200GB file you accidentally created, you would probably care.  A lot.)  So that should be noted.
Answer: As with everything in git there are multiple ways of doing it. The two commands you used are one way of doing it. Another thing you could have done is simply stash them with git stash -u. The -u makes sure that newly added files (untracked) are also included.
The handy thing about git stash -u is that

it is probably the simplest (only?) single command to accomplish your goal
if you change your mind afterwards you get all your work back with git stash pop (it's like deleting an email in gmail where you can just undo if you change your mind afterwards)

As of your other question git reset --hard won't remove the untracked files so you would still need the git clean -f. But a git stash -u might be the most convenient.
Comment: `git reset --hard`will not remove untracked *files* indeed, but it *will* remove untracked changes, i.e. changes to files, that are already in the index. I'm sure that's what you meant :)
Comment: When i used `git stash -u`, i saw this response from git bash. "Saved working directory and index state WIP on {branchname} . May be this saved one is what we could retrieve using `git stash pop`.
Comment: Thank you both of you. I have summarized the answer and embedded into my question. Christoph let me know what `git stash -u` does and how to pop it, but Frederik let me know reset hard and using the combination of `git reset --hard` and `git clean -f` , and why not `stash` is preferred in some scenarios. Now Please help me in choosing which one should i mark as Answer :) , both are my answers.
Comment: but what if there is a file I added to my repository that I don't want to track? only in my repo. If I add it to the ignore list then I have a .ignore file to commit which will effect everyone else as well.
Answer: 1. When you don't want to keep your local changes at all.
git reset --hard

This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
2. When you want to keep your local changes
If you want to pull the new changes from remote and want to ignore the
local changes during this pull then,
git stash

It will stash all the local changes, now you can pull the remote changes,
git pull

Now, you can bring back your local changes by,
git stash pop

Comment: `git reset --hard` does not remove all local changes.  It only removes the modifications.  If you want to remove adds, then you must also `git clean -fd`
Answer: I think git has one thing that isn't clearly documented. I think it was actually neglected.
git checkout .
Man, you saved my day. I always have things I want to try using the modified code. But the things sometimes end up messing the modified code, add new untracked files etc. So what I want to do is, stage what I want, do the messy stuff, then cleanup quickly and commit if I'm happy.
There's git clean -fd works well for untracked files.
Then git reset simply removes staged, but git checkout is kinda too cumbersome. Specifying file one by one or using directories isn't always ideal. Sometimes the changed files I want to get rid of are within directories I want to keep. I wished for this one command that just removes unstaged changes and here you're. Thanks.
But I think they should just have git checkout without any options, remove all unstaged changes and not touch the the staged. It's kinda modular and intuitive. More like what git reset does. git clean should also do the same.
Answer: Use:
git checkout -- <file>

To discard the changes in the working directory.
Answer: The best way is checking out the changes.
Changing the file pom.xml in a project named project-name you can do it:
git status

# modified:   project-name/pom.xml

git checkout project-name/pom.xml
git checkout master

# Checking out files: 100% (491/491), done.
# Branch master set up to track remote branch master from origin.
# Switched to a new branch 'master'

Answer: For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.
This will stash all changes in {0} key and instantly drop it from {0}
git stash && git stash drop
Answer: First of all check is your important change saved or not by:

$ git status

than
try

$ git reset --hard
it will reset your branch to default

but if you need just undo:

$ edit                                     (1)
  $ git add frotz.c
  filfre.c $ mailx                                    (2)
  $ git reset
  (3) $ git pull git://info.example.com/ nitfol

Read more >> https://git-scm.com/docs/git-reset
Comment: Side note: reset --hard is dangerous command this will remove all the changes and it cant be undone. The user should be aware when using reset hard.
Answer: Option 1: Discard tracked and untracked file changes
Discard changes made to both staged and unstaged files.
$ git reset --hard [HEAD]

Then discard (or remove) untracked files altogether.
$ git clean [-f]

Option 2: Stash
You can first stash your changes
$ git stash

And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.
Option 3: Manually restore files to original state
First we switch to the target branch
$ git checkout <branch-name>

List all files that have changes
$ git status

Restore each file to its original state manually
$ git restore <file-path>

Comment: for the first option do `git clean -fdx` if you want to remove also directories. `-x` is a bit dangerous, see [here](https://stackoverflow.com/questions/8200622/how-to-remove-untracked-files-in-git), since it removes ignored files too


PHP null returned with json_decode

Question: for some reason I am having issues with json fields having HTML generated by a WYSIWYG editor.
I am using wordpress and angularJS and I am trying to make a form that updates a certain post.
Getting the data works fine e.g. I am doing something like on the server
$data = [
'title'=>$post->post_title,
'description'=>$post->post_content // contains html via a WYSIWYG editor
.... more stuff
]
header('Content-Type: application/json');
echo json_encode($data);
exit;

The form auto populates with the above data OK.
The issue is happening when I am trying to update the post via returning a JSON.stringify(data) back to server. When I attempt to json_decode($_POST['data']) on the server I get the following PHP errors which happens because of the HTML contents of data.description.  Without data.description my code works fine to update the post
json_last_error: 4
json_last_error_msg: "Syntax error"
json_decode($_POST['data']) == null

But In Javascript when I do console.log(JSON.stringify(data)) and validate the JSON data is fine.
I don't have magic quotas enabled get_magic_quotes_gpc() => 0.
I also tried stripslashes($_POST['data']);
This issue seems strange because the data was successfully converted to json by php and then decode via javascript but the reverse operation is not working.
$_POST['data'] value .. JSON string is incomplete when received at server
{\"deadline\":\"31 Août 2015\",\"country\":\"Canada\",\"city\":\"Montréal-Est\",\"province\":\"Québec\",\"jobillicoCategory\":\"180\",\"recruiterName\":\"HR Team\",\"recruiterEmail\":\"email@example.com\",\"titleEn\":\"\",\"descriptionEn\":\"\",\"requestId\":\"d4618389-6bb5-5e51-8489-d39a4fc09016\",\"ID\":1996,\"title\":\"Buyer - Planner\",\"description\":\"
We are currently looking for an experienced, motivated and ready buyer-planner, to take on new challenges. The candidate\'s responsibility is to fulfill and coordinate production planning activities within customer constraints and requirements in order to ensure customer satisfaction and the achievement of business objectives. In addition, they will carry out the purchasing of components necessary for production, while respecting GMP regulations and purchasing policies.
\\r\\n

value of console.log(JSON.stringify(data)) which is complete
{"deadline":"31 Août 2015","country":"Canada","city":"Montréal-Est","province":"Québec","jobillicoCategory":"180","recruiterName":"HR Team","recruiterEmail":"firstname.lastname@example.com","titleEn":"","descriptionEn":"","requestId":"d4618389-6bb5-5e51-8489-d39a4fc09016","ID":1996,"title":"Buyer - Planner","description":"
We are currently looking for an experienced, motivated and ready buyer-planner, to take on new challenges. The candidate's responsibility is to fulfill and coordinate production planning activities within customer constraints and requirements in order to ensure customer satisfaction and the achievement of business objectives. In addition, they will carry out the purchasing of components necessary for production, while respecting GMP regulations and purchasing policies.
\r\n

\r\n
Main Responsibilities
\r\n
\r\n
\r\n
Carry out product orders from suppliers;;
\r\n
\r\n
\r\n
Participate in the research, selection, evaluation and validation of suppliers;
\r\n
\r\n
\r\n
Schedule orders according to clients' needs and business objectives;
\r\n
\r\n
\r\n
Research quotes and collect samples for submissions;
\r\n
\r\n
\r\n
Perform other duties as required by the company.
\r\n
\r\n
\r\n

Requirements
\r\n
\r\n
\r\n
BAC in Operations Management (GOP), Business Administration in Logistics or other;
\r\n
\r\n
\r\n
 Between one and three years of experience in a manufacturing company;
\r\n
\r\n
\r\n
Advanced skills in Microsoft Office (Word, Excel);
\r\n
\r\n
\r\n
Good knowledge of ERP systems.
\r\n
\r\n
\r\n

Skills
\r\n
\r\n
\r\n
 Knowledge in the order of production and management of raw materials / components;
\r\n
\r\n
\r\n
 Professionalism, interpersonal skills and strong ability in work organization;
\r\n
\r\n
\r\n
 Resourcefulness and initiative, active listening and understanding customer needs;
\r\n
\r\n
\r\n
 Good analytical skills, concern for improvement, team spirit, good communication skills and leadership;
\r\n
\r\n
\r\n
Good negotiation skills.
\r\n
\r\n
\r\n

Join a growing dynamic company located in eastern Montreal. The company offers benefits, continuing education, a dynamic working environment and opportunities for advancement.
"}

Update
OK I think it is '&'nbsp; on the HTML that is breaking the json when it is being sent to the server. How to sanitize from nbsp;? encodeURIComponent() ? or replace()?
 function ($http, globals) {
     var request = {
         method: 'POST',
         url: globals.ajax_url,
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
         }
     };
     return function (action, data) {
         var queryStr = "action=" + action;
         if (data) {
             queryStr += "&data=" + JSON.stringify(data);
         }
         request.data = queryStr;
         return $http(request);
     };
 }

Comment: What is the actual value of `$_POST['data']`?
Comment: check [json_last_error](http://php.net/manual/en/function.json-last-error.php) for any json decoding errors (very possible for malformed json etc..)
Comment: post your javascript code that is sending the data back to PHP.
Answer: it should be
echo json_encode($postdata);

$postdata is the name of the variable, not $data
Comment: no that was just a typo that part of the code is fine
Answer: Finally found solution.
I had to add encodeURIComponent because & nbsp; which is -added via tinymce WYSIWYG - in query string will cause issues if not escaped.
function ($http, globals) {
            var request = {
                method: 'POST',
                url: globals.ajax_url,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            };
            return function (action, data) {
                var queryStr = "action=" + action;
                if (data) {
                    queryStr += "&data=" + encodeURIComponent(JSON.stringify(data));
                }
                request.data = queryStr;
                return $http(request);
            };

PHP null returned with json_decode


"OpenSSL::Cipher:CipherError" received when setting up sekrets gem. why?

Question: I get past step 2 when setting up the sekrets gem for use with a Sinatra app. Both files ".sekrets.key" and "config/settings.yml.enc" are created, which respectively contain the key and the encrypted value. But when I run:
<code>$ sekrets read config/settings.yml.enc
</code>
or
<code>$ sekrets edit config/settings.yml.enc
</code>
I receive the following error:
<code>F, [2014-05-06T16:48:05.850486 #31312] FATAL -- : bad decrypt (OpenSSL::Cipher::CipherError)
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:297:in `final'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:297:in `cipher'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:305:in `decrypt'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/bin/sekrets:224:in `block (2 levels) in run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:185:in `call'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:185:in `openw'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/bin/sekrets:222:in `block in run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:217:in `call'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/lib/sekrets.rb:217:in `openr'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/bin/sekrets:219:in `run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/main-6.0.0/lib/main/program/class_methods.rb:155:in `block in run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/main-6.0.0/lib/main/program/class_methods.rb:144:in `catch'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/main-6.0.0/lib/main/program/class_methods.rb:144:in `run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/main-6.0.0/lib/main/factories.rb:18:in `run'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/main-6.0.0/lib/main/factories.rb:25:in `Main'
/usr/local/rvm/gems/ruby-2.0.0-p353/gems/sekrets-1.7.0/bin/sekrets:3:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.0.0-p353/bin/sekrets:23:in `load'
/usr/local/rvm/gems/ruby-2.0.0-p353/bin/sekrets:23:in `<main>'
/usr/local/rvm/gems/ruby-2.0.0-p353/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.0.0-p353/bin/ruby_executable_hooks:15:in `<main>'
</code>
I've checked the lines responsible for the errors in sekrets.rb, but can't figure out why or how this is happening.
Answer: When I created the key and encrypted file, I named the keypair "abcd". When I put the decryption key in a file, I accidentally echoed "abc" instead of "abcd".
The problem was a typo. T_T


Mostra como ficou a $query

Question: Pessoal ja vi isso funcionando em algum lugar mas nao me lembro onde. e o seguinte quero dar um echo em meu codigo e exibir como ficou o insert no Mysql tipo
$query1 = $conn->query("INSERT INTO dados1 VALUES (NULL, '".$nome."')");
        $id_dados1 = $id_doutor;
        echo "$query1";

e quando eu dar o echo preciso que me retorne algo do tipo
INSERT INTO dados1 VALUES (01, Joao)

para que eu saiba como ficou o insert
Comment: Com o pdo? ou MySQLi? `$query1` tem o retorno da consulta ou um false mas não a string da consulta ...
Comment: Talvez [essa resposta](http://pt.stackoverflow.com/q/34797/91) responda.
Answer: Bem já pensou em "gerar" a query antes de executar? Algo como:
<?php
$sql1 = "INSERT INTO dados1 VALUES ('" . $nome . "');";
$query1 = $conn->query($sql1);
var_dump($query1);

echo $sql1; // Imprime SQL 1
?>

Até porque para imprimir usando o próprio retorno concerteza você terá que alterar sua classe "$conn" para gerar esse retorno.
Quanto ao último ID inserido ele só sabe qual é após fazer o INSERT, e para isso você pode usar uma função ou um novo SELECT para puxar esse último ID como:
SELECT MAX(ID) FROM dados1

Ou usar uma funão como disse o PHP possui a função mysql_insert_id, ela vai ser descontinuada nas futuras versões do PHP, porém não sei o que existe dentro da sua classe "$conn" então você pode tomar ela como ponto de partida para tentar implementar dentro.

Mostra como ficou a $query


How can I add Support module's tickets to the homepage?

Question: I am trying out the Support module to create a client support ticketing system. Out of the box it seems to be configured so that I need to navigate to mysite.com/support to view the table of support tickets. How can I change this so that the support tickets appear on the homepage? Drupal version is 7.9
Answer: You could change the default front page for your site in the admin section at example.com/admin/config/system/site-information.  Enter support and it will now be your front page.


How do I highlight search queries using Vue+html

Question: Here my search is working but I am a newbie and doesn't know how to use the npm...I am using HTML with VueJS to implement this and successsfully created the search filter but couldn't implement the highlight filter..Some leads are markjs.io that is used and some other custom vuejs filters but couldn't implement them.
class Post {
  constructor(title, link, author, img, course, coursel, cours, coursl, cour, courl, cou, coul, co, col) {
    this.title = title;
    this.link = link;
    this.author = author;
    this.img = img;
    this.course = course;
    this.coursel = coursel;
    this.cours = cours;
    this.coursl = coursl;
    this.cour = cour;
    this.courl = courl;
    this.cou = cou;
    this.coul = coul;
    this.co = co;
    this.col = col;
  }
}
const app = new Vue({
  el: "#app",
  data: {
    search: "",
    postList: [
      new Post("abc", null, "xyz", "wqw", "qwe", "", " ", null, " ", null, " ", null, " ", null, );
    ]
  },
  computed: {
    filteredList() {
      return this.postList.filter(post => {
        return post.title.toLowerCase().includes(this.search.toLowerCase()) ||
          post.author.toLowerCase().includes(this.search.toLowerCase()) ||
          post.course.toLowerCase().includes(this.search.toLowerCase()) ||
          post.cours.toLowerCase().includes(this.search.toLowerCase()) ||
          post.cour.toLowerCase().includes(this.search.toLowerCase()) ||
          post.cou.toLowerCase().includes(this.search.toLowerCase()) ||
          post.co.toLowerCase().includes(this.search.toLowerCase());
      });
    }
  }
});

Here is the HTML code I am using

    <input type="text" v-model="search" placeholder="Search"
      onfocus="if(this.value==this.defaultValue)this.value=''"
      onblur="if(this.value=='')this.value=this.defaultValue" />

        {{ post.author }}

        {{ post.title }}
      {{ post.course }}
      {{ post.cours }}
      {{ post.cour }}
      {{ post.cou }}
      {{ post.co }}

Comment: what does this have to do with npm? npm is a package manager.
Comment: I don't know yet how to use npm and add packages to code..my code has HTML,CSS and this JS files only..
Comment: your title says you don't want to use npm, your post talks about something that has nothing to do with npm, so: why mention npm?
Comment: generally devs don't use html with vuejs and use jsx (not sure abt that too) so I don't to attract answers on that front..
Comment: that still has nothing to do with npm, but is also not even true. plenty of folks use vue, plenty of other folks use react, but plenty more folks use "neither of those two". Just tag your question with the correct tags, and title and describe the problem to the degree necessary to let others help you.
Answer: <template>

    <input v-model="text" @input="input" />

      Lorem ipsum dolor sit āmet, consetetur sadipscing elitr, sed diam nonumy
      eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
      voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
      clita kasd gubergren, nò sea takimata sanctus est Lorem ipsum dolor sit
      amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
      nonumy eirmod tempor invidunt ut labore et

</template>

Simple highligh searching this might help you
Comment: Actually I have data to be displayed separately and not all at once in paragraph style so can I add parameters to search so that all of my data could be searched..like

lorem ipsum...  and then

replace each instance of "#x" with "#x,#y"  so that both of my text pieces when searched can be highlighted?
Comment: You can re-produced that code. So you need to add tag (more than #x) and manage them
Comment: yes so basically I have a course name and then some have sub courses as well and then author also..and this needs to be structured well for display..
Comment: Also please if you can convert the code into defined html,css and js files it would be more useful for me


OnRowUpdating Does not take value of edit template textbox

Question: I am trying to update a value in my gridview on row updating. However, it refuses to take in the value written in the textbox. I populate the gridview if the page is not post back. Help!
GRIDVIEW:
  <asp:UpdatePanel runat="server" UpdateMode=Conditional><ContentTemplate>
    <asp:GridView runat="server" ID="searchGV" AutoGenerateColumns="False" GridLines="None"
        CssClass="mGrid" EmptyDataText="The Search Did Not Return Any Results"
        PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Width="100%" OnRowCancelingEdit="searchGV_RowCancelingEdit"
        OnRowEditing="searchGV_RowEditing" DataKeyNames="media_id" OnRowUpdating="searchGV_RowUpdating">
        <Columns>
            <asp:BoundField DataField="media_id" Visible="false" HeaderText="" />
            <asp:BoundField DataField="dir_path" Visible="false" HeaderText="Dir" />
            <asp:TemplateField HeaderText="Date Taken" >
                <ItemTemplate>
                    <asp:LinkButton ID="dateLinkCsBtn" OnClientClick='<%#Eval("dir_path","Javascript:return test(\"{0}\",event);")%>'
                        runat="server" Text='<%# Bind("date") %>'></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Media Type">
                <ItemTemplate>
                    <asp:Label runat="server" ID="mediaTypeLbl" Text='<%#Eval("description") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Alias File Name">
                <ItemTemplate>
                    <asp:Label runat="server" ID="aliasFileName" Text='<%#Bind("alias_file_name") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" Text='<%#Bind("alias_file_name") %>' ID="updateAliasTxt"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
        </Columns>
    </asp:GridView>
    </ContentTemplate></asp:UpdatePanel>

CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        FillGrid();
    }

}

protected void searchGV_RowEditing(object sender, GridViewEditEventArgs e)
{
    searchGV.EditIndex = e.NewEditIndex;
    FillGrid();
}
protected void searchGV_RowCancelingEdit(object sender,
                          GridViewCancelEditEventArgs e)
{
    searchGV.EditIndex = -1;
    FillGrid();
}

public void FillGrid()
{
    Media_DAO media_query = new Media_DAO();
    searchGV.DataSource = media_query.get_search_media(alias_file_name_txt.Text.Trim(), Convert.ToInt16(mediaTypeDDL.SelectedValue),
            from_date_txt.Text.Trim(), to_date_txt.Text.Trim(), Convert.ToInt16(Session["user_id"]));
    searchGV.DataBind();
}

protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    GridViewRow row = searchGV.Rows[e.RowIndex];
    TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
    int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);

    Media_DAO media_query2 = new Media_DAO();
    media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
    searchGV.EditIndex = -1;
    FillGrid();
}

Answer: while declaring the grid you have specified only 1 *data key value*
asDataKeyNames="media_id"

DateKeys for grid view is stored in array format starting from 0.
The error may be in getting the media_id while updating. You need to change it as follows.
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    GridViewRow row = searchGV.Rows[e.RowIndex];
    TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
    int media_id = Convert.ToInt16(e.Keys[0]); //this will get the media_id

    Media_DAO media_query2 = new Media_DAO();
    media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
    searchGV.EditIndex = -1;
    FillGrid();
}

Since the earlier method was searchGV.DataKeys[e.RowIndex]["media_id"] , you might not get the media_id value if the row number which you are trying to edit is greater than 1.
Answer: The DataKeys property of GridView returns a collection of DataKey objects that represents the data key value of each row for a GridView. Thus, DataKeys[1] gives 2nd row, DataKeys[4] gives 5th row ...
Therefore, you need to use either the Value OR the Values property to access the value of a key field.
Rather than doing this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);

do this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Values["media_id"]);
// You can also use the Value property which gives the key value at index 0
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Value);


How to make taxonomy terms link to an external site?

Question: I am using the Lexicon module to automatically insert links to a vocabulary with information about words in the lexicon.
But the vocabularies I am using are owned and hosted by a completely different organisation, which means that hosting the information on my website would result in duplicated and outdated information. Therefore I need to link my terms in the taxonomy to an external site (instead of this website).
I tried using the Redirect module but it doesn't manage tokens to external websites.
My question: how to make my taxonomy terms link to an external site?
Comment: After 6 hours of fighting with tokens and redirect modules I have found a very efficient solution with Field redirection module. https://www.drupal.org/project/field_redirection

I feel silly finding it 10 minutes after posting the question but I will add a good guide for other users as I've noticed that other people got similar issues.
Answer: Solving this issue for me required three modules:
Link module: Creates a link field for external links. Module page
Lexicon: A module that look for keywords and allow you to set up a lexicon that automatically link keywords to a page explaining them. Module page.
Field Redirection: A module that allow you to create pages that automatically redirect the user to a different page. Module page.

Install the modules and activate them.
Go to Manage fields of the vocabulary you wish to use for external links (structure-->taxonomy-->[your vocabulary]--> Manage fields). Add a link field to the vocabulary and set it's format to "redirect" (this is described in the documentation of the Field Redirection module).
Go to Manage display and hide all other fields (also according to FR module instructions).
Now it is time to set up the Vocabulary. Go to configuration-->system-->lexicon settings. Under the General tab, check "Link terms to the taxonomy term page" and uncheck the options that will make several terms appear on the same page (field redirection will otherwise always redirect to the link associated with the first term on the page).
Link targets are edited for each term in the taxonomy and you add the URL in the "Link" field of each term.

Lexicon is the module you interact with to make the links appear as you want them and any issues will probably be caused by improper setup of the Lexicon. Links/Redirect Field are a small add on that transport users to external websites instead of the lexicon page created by the Lexicon module.


Combinatorics (Venn diagram problem)

Question: On the planet Xprom: 12.000 creatures have horn, 15.000 creatures have tail and 20.000 creatures have NO FUR, 8.000 creatures have horn and tail, 6.000 creatures have tail and fur, 5.000 creatures have fur and horn, and 1.000 creatures have horn, fur and tail. What's the population of Xprom?
Comment: Why should I tell you? Please give context.
Comment: @Bero, remove combinatonics tag and put elementary set theory tag
Comment: @Vikram, nope. This is a combinatorics problem (inclusion/exclusion, to be more precise).
Comment: Yes it's inclusion/exclusion formula (IEF), but it's tricky because you have complement of one set
Answer:
Denote H - onlu with horn; T - only with tail, F - onlu with Fur.
HT - with horn and tail only, and so far.
Z - without horn, tail, fur (pure animals).
All the sets H,F,T, FH, FT,HT,FHT, Z are separated (drawn by different colors).
Then:
H + HT + FH + FHT = 12.000;
T + HT + FT + FHT = 15.000;
Z + H + HT + T = 20.000;
HT + FHT = 8.000;
FT + FHT = 6.000;
FH + FHT = 5.000;
FHT = 1.000.
Hence, (without zeroes):
HT = 8 - 1 = 7;
FT = 6 - 1 = 5;
FH = 5 - 1 = 4;
H = 12 - 1 - 7 - 4 = 0; (if someone has horn, then must have tail or fur);
T = 15 - 1 - 7 - 5 = 2;
Z = 20 - 7 - 0- 2 = 11;

Hmm, population of Xprom is undefined...
It is unknown how many persons live with fur only.
All I can tell that population is $\ge 30.000$.
Comment: @Vikram, anyway, it is undefined amount of creatures with fur only. It can be arbitrary: as 0, as 10.000, as 100.000 .
Comment: something wrong with the problem, I am getting no fur creatures=10 and problem says it is 20
Comment: Of course, there are $8$ different parts, but $7$ linear equations are given only. So, $1$ variable remains to be undefined.
Answer: You can solve this using the inclusion/exclusion formula: given a population with (not necessarily disjoint) subsets $A_1, A_2,..,A_n$, the size of the union is given by (where $|A_i|$ is the size of the set $A_i$): $$| A_1 \cup A_2 \cup ...\cup A_n|=|A_1|\cup|A_2|\cup...\cup |A_n|- ( (A_1 \cap A_2)\cup (A_2 \cap A_3)\cup....) +..$$
(See , e.g.http://en.wikipedia.org/wiki/Inclusion-exclusion_principle). Can you see how to apply this to your situation?

Combinatorics (Venn diagram problem)


Is it more efficient to assign an evaluation to a variable?

Question: Does Ruby remember the results of what has already been evaluated? Say I have:
s = "a b c d e"

If I did:
s.split.join[2] + s.split.join[3] # => "cd"

Would it be more or less efficient to instead do:
x = s.split.join
x[2] + x[3] # => "cd"

My thinking is that if I didn't assign s.split.join to a variable, then every time I use that value, Ruby would have to evaluate s.split.join. If s.split.join was called many times, that seems more costly than just checking the value of a single variable.
Comment: Yes, that is basically what local variables are for. Ruby does not cache anything.
Comment: _Sidenote:_ your example is better written as `s = "a b c d e"; s.split[2..3].join` or `s.split.join[2..3]`.
Comment: haha... thanks for the sidenote. Yeah, I just arbitrarily picked two elements, which happened to be consecutive and expressible as a range xD
Comment: It's very easy to test whether Ruby caches the evaluation of expressions automatically: since `puts` *always* returns `nil`, Ruby would be allowed to cache any call to `puts`, and thus it would be impossible to print anything in Ruby, if that were true. `puts 'Hello'; puts 'World'` would print only `Hello`, because `puts 'World'` has the same value as `puts 'Hello'` and thus would be never evaluated.
Answer: Anything not set to a local variable will be reevaluated, so in your case it would be more efficient to set a local variable.


How to make a button to act as browser back button?

Question: I am working on Joomla. I want to create a button so that if I click on that button browser redirects to previously processed page.How to make a button to act like browser's back button? This question was asked earlier here.I tried all those solutions. but none is working for me. Plaese answer this question. Thanks in advance.
Answer: <button onclick="window.history.back()">Go back</button>

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Try the button here: http://jsfiddle.net/GTQ48/
Comment: Nice, the original answer got a downvote...
Answer: JavaScript button:
<button onclick="window.history.go(-1)">Back</button>

Source: Go back button in a page
Comment: -1 for copying my answer.
Comment: Actually, I got it from http://stackoverflow.com/questions/13511679/go-back-button-in-a-page. It's a duplicate post really.
Comment: Yeah, but still, should've left your original one. It's not cool.
Comment: My apologies, I'm still new here :)
Comment: @shomz...that solution is not working for me.that is why I posted the question again.So that I could find some new solutions.Butttt :(


Is it possible to expose custom table data to Views without custom code?

Question: I have a custom table that I'd like to expose to administrators so that they can perform simple searches on the table data. I know I can create a series of custom views handlers for each field, but is there is a way to expose and search through the custom table data without custom coding? I expect there is a contrib module out there that solves this problem, but my Googling has come up dry.
Comment: If you defined it with the Data module, I think you should be able to do just that. However, nothing will be as close as wiring it with the Views API I believe. https://www.drupal.org/project/data
Comment: I did not define this particular table with the Data module.
Comment: I'm voting to close this question because questions explicitly asking to recommend, find or compare a module, theme, distribution, or other off-site resource are off-topic for Drupal Answers.
Answer: Apparently Views Custom Table does that:

View custom table module provide you functionality to integrate your
custom table data to views, and access all it's column in views. This
module use hook_view_data to add custom tables in views. this module
provides you following functionalities.

Auto integrate custom table data to views
Auto map mysql data types with drual data types
Extend relationship of custom table data to drupal entities


Formatar String do formato moeda para Number com casas decimais

Question: Estou com o seguinte problema, tenho o valor de um Input que está recebendo o valor em real, por exemplo:
"2,55"

Preciso converter esse valor para um formato de number com as mesmas casas decimais e a virgula. Não pode ser: 2.55 por exemplo, pois a API está configurada para receber um number, no formato:
2,55

Já utilizei de algumas funções que vi por aqui, porém todas a saída é uma string, se alguém poder me ajudar, agradeço!
Comment: Os números em javascript não podem ter vírgulas. Tem que converter para string.
Answer: Para converter para um valor em string para número pode utilizar por exemplo parseInt() ou parseFloat().
No seu caso como é um valor com decimais pode usar o parseFloat(), mas tem um detalhe, o valor deve usar "." como separador decimal, se fizer diretamente o parse com a tua string não vai converter corretamente:

console.log(parseFloat("2,55"));

Para converter corretamente precisa então substituir a "," por ".", e pode fazer isso usando a função replace():

let varlorString = "2,55";
let valorComPonto = "2,55".replace(",",".");
console.log(parseFloat(valorComPonto));
Comment: Entendi, de fato quando eu utilizava o parseFloat() diretamente com a virgula, ele sempre quebrava as casas decimais. Fico agradecido pela resposta, pois não sabia que não era possível essa conversão com parseFloat com virgula.


Matrix equation optimization

Question: Let s be a positive real number, let M be a matrix, and let $v_1, v_2$ be vectors. $v_2$ will only have 1's or 0's as entries.
Given M, $v_1$ and $v_2$, find an s such that $(sMv_1) \cdot v_2$ = 0.5. I don't need an exact solution, just some way to get pretty close. If it makes any difference, I'm trying to do this through MATLAB.
For example, I have M = $\begin{bmatrix}1 & 1/3 & 0 & 1/5 & 0 & 1/4 & 0 \\ 0 & 0 & 1/2 & 1/5 & 0 & 0 & 0 \\ 0 & 1/3 & 0 & 1/5 & 0 & 0 & 0 \\ 0 & 1/3 & 1/2 & 0 & 1/2 & 1/4 & 0\\ 0 & 0 & 0 & 1/5 & 0 & 1/4 & 0\\ 0 & 0 & 0 & 1/5 & 1/2 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1/4 & 1\end{bmatrix}$, $v_1$ = $\begin{bmatrix} 0.15 \\ 0.15 \\ 0.10 \\ 0.25 \\ 0.10 \\ 0.20 \\ 0.50 \end{bmatrix}$ and $v_2$ = $\begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \end{bmatrix}$.
My code can already find the closest integers for s (in this case, s is between 2 and 3) but how can I find a better approximation of s?
Answer: Can you do something as follows?
$(sMv_1) \cdot v_2 = s (Mv_1) \cdot v_2 = s (Mv_1)^T v_2 = s v_1^T M^T v_2 = 0.5$
So $s = \frac{0.5}{v_1^T M^T v_2}$.
Comment: This is the only possible solution for $s$ (depending on $M,v_1,v_2$, the resultant $s$ may be negative from this equation, in which case there doesn't exist a solution).

Matrix equation optimization


How do I know which class my random forest model is predicting?

Question: I have a random forests model with which I am trying to predict species presence or absence.
This is my code:
#read in dataframe containing observations of species presence/absence & predictor variables
mydata <- read.csv('mydata.csv')

#fit random forests model
fitmodelA <- randomForest(SPECIESA ~ var1 + var2 + var3 + var4 + var5 +var6 + var7 + var8 +
 var9 + var10, data=mydata, mytry=3, ntrees=500, replace=T, importance=T, keep.forest=T)

#predict to new data
predictmodelA <- predict(fitmodelA, newdata, type="prob")

# save as raster image
writeRaster(predictmodelA,"predictSPECIESA.tif")

Apparently I should get back a matrix that has the probability for both classes, i.e., in  two columns. Do I understand correctly that it is also possible to add the "index" argument to predict only one class?
With my code the way it is, my output raster produced one layer with probabilities 0 to 1, but no other attributes – what class is this predicting? I am more interested that my map show predictions of presence rather than absence.
Probably a simple solution to this...? Thanks!
Answer: I don't understand your confusion at all. When you choose type="prob" the output is, naturally, the probability of each class. So you should be getting two columns. You can simply choose either one by doing predictmodelA[,1] or predictmodelA[,2] in your two case example. Since the R vanilla implementation of randomForest needs a factor variable for the case of classification, the order of these probability columns will just follow the order of the factor levels.
By the way I don't think your last bit of code will get you to the raster file you want. You would first need to determine it's coordinates, so you need to add them to your prediction vector, for example:
raster_species <- data.frame(species_prediction=predictmodelA,x=X_coordinate, y=Y_coordinate

then explicitly tell R which variables are the coordinates (I'm guessing you are using the raster package):
coordinates(raster_species)<-~x+y

Indicate that it is gridded
gridded(raster_species)=TRUE

and the simply label it a raster
raster_species <- raster(raster_species)

you can then plot it and save it
plot(raster_species)

writeRaster(raster_species, filename="raster_species.tif", format="GTiff", overwrite=TRUE)

Comment: Thank you for your response. The problem I am stuck on is that I don't know which factor is in which index. In other words, what is the order of factors? Is my class 0 index 1, and class 1 = index 2?
Comment: Note that I am using the predict function from the raster package (i.e., predicting directly from my raster layers) not from a dataframe, because my layers were too big to convert to dataframe. My rasters are floating point data and I think one problem is that there is no attribute table associated with them.
Comment: if you take your target object and do levels(as.factor(vector)) literally the first level is the first predicted class.
Answer: This is a partial answer:
What I ended up doing was simply adding the argument
index=1:2

to my predict function.
I haven't figured out how to get a valid dataframe out (because my rasters are floating pt, there is no associated attribute data, i.e., values in the dataframe are all NA when I print it in R) but I can create an output raster just fine.
Comment: could you please show this code in its entirety? is it predictmodelA <- predict(fitmodelA, newdata, type="prob", index=1:2) ?
Comment: also, in your example, what is newdata? the manual for this package passes in the training data frame back in.

pred <- predict(rfModel, trainData)

it's at this point, that i am also confused. pred is a list of probabilities (it seems), but against which field? is it the class field? i would expect something like this.

pred <- predict(rfModel, trainData$label)

but the package doesn't like that. basically what are those prediction values? which field(s) was the random forest trying to make a prediction on?
Comment: @JaneWayne - yes, the code would be:
predictmodelA <- predict(fitmodelA, newdata, type="prob", index=1:2)
My NewData was a new database with exactly the same predictors but for an expanded number of rows (i.e., for an expanded area of interest) and no training data was included.