jQuery each element in given div with class

Question: I have a little question. I try to build this simple quiz. Right now it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>

        <meta charset="utf-8" />
        <link rel="stylesheet" href="style/style.css" />

        <title></title>

1. Ile księżyców ma ziemia?

A) 1

A) 2

        Sprawdź

1. Ile księżyców ma ziemia?

A) 1

A) 2

        Sprawdź

My problem is obvious - when I click any question it changes the background-color of all p elements in all div.pytanie's. I know that I can use the id selector, but is it necessary? Maybe there is another option to trim each loop only to one div?
Comment: This is not what i exacly need - this solution clear all p elements in all questions - maybe you made some minor mistake? Thanks for help anyway :)
Comment: like this? http://jsfiddle.net/cHktk/2/
Comment: You have multiple elements with id `btn-sprawdz-1`.
Comment: @NOX yes it is only for testing purpose (more than 1 question)
Answer: Try
$(document).ready(function() {
    var score;
    score=0;
    // Mechanizm zaznaczania odpowiedzi
    $('.odpowiedz').click(function() {
        // Najpierw odznacz zaznaczone odpowiedzi
        $(this).closest('.pytanie').find('p.odpowiedz').css('background-color','white');
        // Zaznacz tę odpowiedź
        $(this).css('background-color','blue');
    });
    //Mechanizm sprawdzania
    $('#btn-sprawdz-1').click(function() {

    });

});

Demo: Fiddle
Comment: `+1` It's better to make `white` only `.odpowiedz` elements ;)
Answer: Working FIDDLE Demo
You must get all .odpowiedz in the current question, for this go up to your .pytanie
and then select all .odpowiedz:
$(this)
    // go up the dom to the current question
    .closest('.pytanie')

    // and now find all possible answers
    .find('.odpowiedz')

        // and make them white
        .css('background-color', 'white');

Answer: Yes it's possible with parent() selector.
$('.odpowiedz').click(function() {
   $(this).parent(); //

   $(this).parent().css('background-color','yellow');
});

Comment: My JS part looks like: http://jsfiddle.net/aL9Hb/ it is not work and i dont have any idea why? It shuld first set all bg-color to whit and then just set that one p bg-color to blue? Where Im wrong?
Comment: It's working, but it was setting white background while it had white bg already :) http://jsfiddle.net/aL9Hb/1/
Answer: This fiddle will set the clicked .odpowiedz in the current div to a blue background.
$('.odpowiedz').click(function () {
    // Najpierw odznacz zaznaczone odpowiedzi
    $(this).parent().find(".odpowiedz").css('background-color', 'white');
    // Zaznacz tę odpowiedź
    $(this).css('background-color', 'blue');
});

Comment: this also is working like a charm. Thanks for time and advice.


Specific exchange user under one database not able to login to the OWA

Question: Specific exchange users under one database are not able to login to the OWA. But when a user moves to another database its working. Please help to solve this issue.
Answer:
What is the error information when you cannot access OWA? Or are there any errors in the event log?
What is your version of Exchange?
Comment: Showing this...

Sorry, we can't get that information right now. Please try again later. If the problem continues, contact your helpdesk.
X-ClientId: JNOP - UHJA - JGJF - LUA
X-FEServer: A0410PEXMBX01
Date: 12/25/2022 6:25:37 AM
Comment: Exchange version 2013
Comment: Thanks for your reply.

Can the user login to the EAC?
Have you performed a migration? Check that the mailbox still has a move request, and if so, remove it.
Reference Articles: https://superuser.com/questions/915659/exchange-2013-eac-owa-error-we-cant-get-that-information-right-now

If the user is still unable to login to OWA, then it is possible that under that database, the user's mailbox is corrupted for various reasons, in which case moving it to another database can solve this problem.


Selecting the best indicator of disease progression

Question: Quite a while ago, I asked a question for which Peter Ellis provided a very interesting answer. Now I'd like to follow on that and have your comments and ideas on how to actually put it to use.
I try to restate the problem, hopefully this time in a more clear way using a synthetic  example.
Problem: Two groups of subjects participate in a longitudinal study. One is a control group and the another is a group of subjects with a degenerative disease. That is to say, from all other sources we know and expect to see a decline in the conditions of the subjects as time goes by. Over the course of the study, we measure all subject using a series of performance measures $M_{1}...M_{n}$. Our research question is: which of these measures can pickup the decline in patient's conditions the best.
Suggested solution: Peter's insight was to build a theoretical response variable and use model selection methods to see which of $M_{1}...M_{n}$ could predict it the best.
Here is a simple simulation with 2 measures to demonstrate the problem the best:
library(ggplot2)
library(nlme)

set.seed(1234)

# Followups in the longitudinal study
t <- 1:5

# Number of subjects in each group and number of followups
N <- 20
M <- length(t)

# Subject IDs
id <- c(paste('C', 1:N, sep=''), paste('P', 1:N, sep=''))

# The first measure. Each subject has a unique value at the baseline.
# There is also a difference between the groups at the baseline.
m1.c.start <- 150 + rnorm(N, 0, 5)
m1.p.start <- 140 + rnorm(N, 0, 5)

# The control group does not change over the time.
# The patient group, however, decline over the time.
m1.c <- rep(m1.c.start, each=M) + rep(0 * (t-1)/M, N) + rnorm(N*M)
m1.p <- rep(m1.p.start, each=M) + rep(-5 * (t-1)/M, N) + rnorm(N*M)

# Generate the data for the second measure.
# The separation of the two groups and rate of progress are weaker.
m2.c.start <- 70 + rnorm(N, 0, 3)
m2.p.start <- 71 + rnorm(N, 0, 3)
m2.c <- rep(m2.c.start, each=M) + rep(0 * (t-1)/M, N) + rnorm(N*M)
m2.p <- rep(m2.p.start, each=M) + rep(1 * (t-1)/M, N) + rnorm(N*M)

# Now put everything in a dataframe
data <- data.frame(
  m1 = c(m1.c, m1.p),
  m2 = c(m2.c, m2.p),
  group=c(rep('C', M*N), rep('P', M*N)),
  id = rep(id, each=M),
  t=rep(t, N*2))

Here are the plots of measures over the time:

Now to build a theoretical response: In the case, we'd like to see a constant response over the time for the control group and a change of performance for the patients. Also, at the baseline groups are typically already a bit different.
# The desired, theoretical response
data$theory <- 2 + (data$t-1)/M
data$theory[which(data$group=='C')] <- 1

Here is the plot of the theoretical response:

Notice that the exact value of the slope and the differences between the two groups in this theoretical curve should not be important as long as model we fit could consider them.
Finally, we fit a linear mixed model for each measure as well as a null model:
fit.0 <- lme(theory ~ 1, random=~1|id, data=data, method='ML')
fit.1 <- lme(theory ~ m1, random=~1|id, data=data, method='ML')
fit.2 <- lme(theory ~ m2, random=~1|id, data=data, method='ML')

I fit the models with ML option as I'm interested in comparing the fixed effects.
The final step is to compare the models to pickup the best measure of the disease progress. I use $AIC_{c}$ for this purpose. The AICcmodavg has a convenient function to build an $AIC$ table for us:
library(AICcmodavg)

f <- list(fit.0, fit.1, fit.2)
aictab(f, modnames=c('Null', 'm1', 'm2'))

Model selection based on AICc :

     K   AICc Delta_AICc AICcWt Cum.Wt     LL
m1   4 -45.15       0.00      1      1  26.68
m2   4 119.51     164.66      0      1 -55.65
Null 3 130.22     175.37      0      1 -62.05

The results suggest that $M_{1}$ is the best predictor of the theoretical response here.
Now what I'd like to know is:

Do you think the whole idea of this approach to pickup the best measure related to disease progression make sense? Have you seen something similar? Is this the right way to do it?
Do you think the theoretical model I built is sound? Are there cases that this model would mislead us?
Can we expand the same kind of approach for picking up the best measures in other types of designs (like e.g. before/after interventions, comparing two different interventions)?
Any other comments or suggestions?

EDIT: I changed bio-marker to measure in the text as I suspected that saying what we deal with are bio-markers draws attention to issues that are not pertinent to this narrow definition of the problem.
EDIT: With this approach looking at combination of measures is easy. For example:
fit.3 <- lme(theory ~ m1 + m2, random=~1|id, data=data, method='ML')

In this example, the $AIC_{C}$ of fit.3 will be slightly worse than the model with only $M_{1}$ (i.e. fit.1).
Comment: I work in a research lab with scientists that are expert in cancer.  Their knowledge is needed to identify the biomarkers. Get this down to a small number.  It really then comes down to being a classification problem.  To actually solve a real problem like this can take years. Combination of markers may work better and success may depend on the actual genetics for the individual.
Comment: I think you and probably Peter Ellis are trying to find a neat statistical solution to a problem that in reality would be more complex and require a series of studies on cell, animals and humans with statistical analysis at each stage.
Comment: @MichaelChernick Thanks for your input. I mostly deal with biomechanics where problems like above are encountered all the time. Typically, a new device is built that can extract a large number of features related to subject's performance. The question is which of these measures, putting other validity considerations aside, can separate the groups or show progress of diseases the best. The methods I see in the literature are not satisfactory as they usually use a series of ANOVAs with the measures as DV and then compare effect sizes, etc.
Comment: @MichaelChernick Often the "expert" knowledge is biased towards what has already been studied (think how many article have been written about the [p53 gene](http://www.ncbi.nlm.nih.gov/gene?db=gene&report=generif&term=7157)). Even experimental studies would suffer from this bias (it's easier to find antibodies to well characterized proteins, etc.) Taking a more data-driven approach might be the ticket in this particular instance!
Comment: Nothing works perfectly.
Answer: To answer some of your questions:
Do you think the whole idea of this approach to pickup the best measure related to disease progression make sense?
Yes. Consider also that it might be a combination of measurements rather than a single one.
Have you seen something similar?
Yes. In almost all chronical diseases.
Do you think the theoretical model I built is sound?
I think your model is a very ideal one. How good it is depends upon many factors you are not mentioning, like the type of disease, the type of measurements, etc.
Can we expand the same kind of approach for picking up the best measures in other types of designs (like e.g. before/after interventions, comparing two different interventions)?
This is a very ambiguous question. In some cases you can while in others cannot.
I believe a good and simple example of a disease progression indicator can be found in HIV/AIDS.
Here some papers:
Circulating HIV-1-infected cell burden from seroconversion to AIDS: importance of postseroconversion viral load on disease course.
Natural history of HIV-1 cell-free viremia.
Comment: thanks for your answer. I'm traveling now and have very poor internet access. I'll check the papers you linked later as I can only see the abstracts from here. Anyway, after thinking some more, I believe my suggested theoretical model sucks and is probably wrong as it is not flexible enough to show an arbitrary difference $d > 0$ between the groups and an independent rate of decline $\alpha > 0$ at the same time. I wonder if there any systematic method to build such theoretical models?
Answer: Creating a theoretical response doesn't seem very promising as it doesn't exist in practice, on the other hand I would suggest to use a standard statistical model (logistic regression with a random effect on the subject level for example) to see which biomarker predicts the group (treatment versus control) more accurately, this would be the biomarker which is most adapted to your study I suppose.
Comment: But at which time point? Please notice that the objective of the study is to find the best indicators of the disease progression. Finding those that separate the two groups at say, the baseline, do not necessarily help with that.
Comment: Your gold standard is actually the "group" variable and I think the biomarker which distinguishes the best between patients and controls (simultaneously in all time points) should perhaps be the best among others.


MySQLi $userid returning 0

Question:     $username = $_POST['username'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirmpassword = $_POST['confirmpassword'];
    $time = time();

if($password != $confirmpassword) {
    echo '<meta http-equiv="refresh" content="0; url=?error=1" />';
    die();
} else {
        if($username != '') {
            echo '<meta http-equiv="refresh" content="0; url=?error=2" />';
            die();
        } else {

    $checkemail = $db->prepare("SELECT * FROM `member` WHERE `email` = ?");
    $checkemail->bind_param('s', $email);
    $checkemail->execute();
    $checkemail->store_result();
    $emailrows = $checkemail->num_rows;
    $checkemail->free_result();

    if($emailrows > '0') {
    echo '<meta http-equiv="refresh" content="0; url=?error=3" />';
    die();

    } else {

    $checkdisplay = $db->prepare("SELECT * FROM `member` WHERE `display` = ?");
    $checkdisplay->bind_param('s', $name);
    $checkdisplay->execute();
    $checkdisplay->store_result();
    $displayrows = $checkdisplay->num_rows;
    $checkdisplay->free_result();

    if($displayrows > '0') {
    echo '<meta http-equiv="refresh" content="0; url=?error=4" />';
    die();

    } else {

    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
        echo '<meta http-equiv="refresh" content="0; url=?error=5" />';
        die();
    } else {

    $createaccount = $db->prepare("INSERT INTO `member` (`display`, `email`, `salt`, `password`, `rank`, `joined`, `ip`) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $ip = $_SERVER['REMOTE_ADDR'];
    $salt = sha1(rand(10000000, 99999999));
    $encrypt = sha1($password . $salt);
    $rank = '1';
    $createaccount->bind_param('ssssiis', $name, $email, $salt, $encrypt, $rank, $time, $ip);
    $createaccount->execute();

    $getid = $db->prepare("SELECT `id` FROM `member` WHERE `display` = ?");
    $getid->bind_param('s', $name);
    $getid->execute();
    $getid->bind_result($userid);
    $getid->free_result();

    if(!$userid) {
        echo '<meta http-equiv="refresh" content="0; url=?error=6" />';
        die();
    } else {
            $encryptip = sha1($ip);

                session_regenerate_id();

                $_SESSION['sesid'] = $userid;
                $_SESSION['sesip'] = $encryptip;

                session_write_close();
ob_get_clean();
echo 'success';
echo $userid;
echo $encryptip;
    }

    }
    }

    }

}
}

I'm just learning the ropes of MySQLi, so got this mostly from a tutorial (though had to throw in parts from different sites - hence the errors).
Is anyone able to explain why $userid returns 0 instead of 1 that it should be? I'm hoping it's a simple mistake.
The query is correct, I've looked over it multiple times, and yes, $name is set.
Comment: Can you add a `var_dump($userid);` on the line after your `bind_result()` call?
Comment: asking someone to find an error in the code for you is offtopic. I told you what have to be done already: you leave only code that fetches userid and then verify all the input and output and premises. For some reason you stuck to your long and windy code and verified NOTHING.
Comment: @YourCommonSense I'm asking because I'm totally lost, I have no idea how MySQLi works and I'm hoping someone can help me.
Comment: @Alex.Ritna It outputs int(0). It's not setting for some reason.
Comment: @TedMosby Have you executed the MySQL query using the same data as is contained in $name, at the mysql prompt or another mysql client to verify the result of the query?
Comment: it is not about mysqli. it is about what you have to do. You have been told what to do, but refused to do so.
Comment: @Alex.Ritna Yes, when executed directly in PhpMyAdmin it gets the correct results.
Comment: @TedMosby I now see what YourCommonSense was talking about. You should heed the advice you've received as answers in your other mysqli related questions.
Answer: Strictly speaking, you don't need to select user id this way. As you just inserted data in the table, then you have call insert_id() function to get autogenerated id. That's all.
As of such "problems" in general - again: you have to isolate that code snippet, add code to verify every single one premise (var_dumping input, selecting raw DB content without conditions, comparing data from db with input (I mean code that compares and outputs the result)) and - if still unable to solve - be able to post both code along with output in your question, to make it sane and answerable.
You have to understand that code doesn't exist in vacuum. It runs on the server with it's distinct environment, it uses a database, it processes some input - ALL THESE THINGS TOTALLY UNKNOWN FOR THE READER - and thus it makes a question that consists of only code totally useless.
Comment: Thank you for the answer, I will look into insert_id(). Thanks for the additional information too.
Comment: I'll edit the question as well to make it a bit more broad so that it can be kept with your answer.

MySQLi $userid returning 0


Button scrolling down screen after click stops, after another click starts again

Question: I've got a little problem.
Here's my fiddle:
<code>[https://jsfiddle.net/ekpgbxrk/][1]
</code>
My question is: what's wrong with my code? Point is that I want to scroll site down after clicking button and after another click I want to stop, then to proceed.
I used:
http://www.mediacollege.com/internet/javascript/page/scroll.html
Please help!
Comment: The request to include code when posting a link to fiddle is there for a reason. Comply with it!
Comment: Please add your code.
Answer: The button onclick function is wrong. Change it to whatever function you'd want to call in your JS code.
Also change your JSFiddle's JS setting "Load Type" to "No wrap in - <head>"
Here is updated logic for your code.
<code>var scrolling = false;
var scrollDelay;

function scrollClick() {
    if (!scrolling) {
    scrolling = true;
    startScroll();
  } else {
    scrolling = false;
    stopScroll();
  }
}

function startScroll() {
    window.scrollBy(0, 50); // horizontal and vertical scroll increments
  scrolldelay = setTimeout('startScroll()', 125); // scrolls every 100 milliseconds
}

function stopScroll() {
  clearTimeout(scrolldelay);
}
</code>
Here is the updated fiddle https://jsfiddle.net/ekpgbxrk/5/
Comment: Thanks! :) I really appreciate that! :)
Answer: Your code logic is completely wrong.
I have rewrote the logic.
For your reference:
<code>[1]: https://jsfiddle.net/ekpgbxrk/1/
</code>


how to specify the main class when packaging with maven?

Question: I am wondering if there is any way to specify which main class I want my maven to use as reference, something like
mvn package -DmainClass=com.myMainClass

Dont want to modify the pom or the plugin itself, just send it as parameter, any idea?
Answer: The maven-jar-plugin jar goal defines a archive parameter with the
org.apache.maven.archiver.MavenArchiveConfiguration type that defines the
mainClass parameter.
But the archive parameter doesn't have a User property associated to that allows to provide the value as argument in the command line execution.
Note that the maven-assembly-plugin that allows also  to package the artifact as a JAR will not be more helpful : the archive parameter is not defined as a User property either.
So you don't have the choice (at least with the maven-jar-plugin): you have to use the mainClass property in the pom.xml.
Now if it makes sense, you can make this value dynamic : value mainClass in the pom.xml with a custom user property that you pass from the command line.
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.0.2</version>
        <configuration>
           <archive>
              <manifest>
                <mainClass>${my.mainClass}</mainClass>
            </manifest>
           </archive>
        </configuration>
        ...
      </plugin>
    </plugins>
  </build>
  ...
</project>

And execute :
mvn package -Dmy.mainClass=com.myMainClass


Data está vindo em formato errado

Question: Numa função jquery, eu recebo uma data na minha View. Acontece que a data está vindo assim:
/Date(1402369200000)/

Sei que preciso fazer um cast ou algo parecido, mas não sei como fazer. Alguém pode me dar um help?
Minha controller:
[HttpPost]
        public JsonResult MontaAgendamento(Agendamentos _agendamento)
        {
            V99_WEBEntities db = new V99_WEBEntities();

            var agendamento = (
                             from pdv in db.T_PDV
                             from tarefa in db.T_TarefaParceiro.Where(trf => trf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
                             from parceiro in db.T_OsParceiro.Where(prf => prf.IDTarefaParceiro == tarefa.IDTarefaParceiro)
                             from acao in db.T_Acao.Where(ac => ac.IDAcao == tarefa.IDAcao).DefaultIfEmpty()
                             from proxima in db.T_ProximaAcao.Where(pxm => pxm.IDAcao == acao.IDAcao).DefaultIfEmpty()
                             from info in db.T_InfoClientePdv.Where(inf => inf.CNPJ == pdv.CNPJ).DefaultIfEmpty()
                             from cliente in db.T_Cliente.Where(clie => clie.IDCliente == info.IDCliente).DefaultIfEmpty()

                             where pdv.CNPJ == _agendamento.Cnpj

                             orderby parceiro.DataVisita descending

                             select new
                             {
                                 pdv.CNPJ,
                                 pdv.DataCadastro,
                                 cliente.RazaoSocial,
                                 acao.Acao,
                                 proxima.ProximaAcao,
                                 parceiro.IDOsParceiro,
                                 parceiro.NumOs,
                                 parceiro.DataVisita,
                                 parceiro.DataAgendamento,
                                 parceiro.Tecnico
                             }).ToList().FirstOrDefault();

            return Json(new { agendamento }, JsonRequestBehavior.AllowGet);
        }

Minha jquery:
function MontaAgendamento() {

    var str = "";
    var resultado = jQuery.parseJSON('{ "Cnpj": "' + $("#txtCNPJ").val() + '" , "Os": "' + $("#txtOS").val() + '" , "Acao": "' + $("#txtAcao").val()
                                        + '" , "ProximaAcao": "' + $("#txtProxAcao").val() + '" , "DataCadastro": "' + $("#txtDataCadastro").val() + '" }');

    var _agenda = $('#txtCNPJ').val() + $("#txtOS").val();

    $.ajax({

        url: '/GerenciarPDV/MontaAgendamento',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ _agendamento: resultado}),
        success: function (data) {

            alert(data.agendamento.Acao);

            str += '
';

            str += '
';
            str += '
';
            str += '
';
            str += '	';
            str += '
';
            str += '
';
            str += '
';
            str += '
';
            str += '';
            str += 'Ação	';
            str += '';
            str += '<input id="txtAcao" type="text" readonly="true" value="' + data.agendamento.Acao + '" />	';
            str += 'Próxima Ação	';
            str += '';
            str += '<input id="txtProxAcao" type="text" readonly="true" value="' + data.agendamento.ProximaAcao + '" />	';
            str += '
';
            str += '
';
            str += '';
            str += 'Data Cadastro	';
            str += '';
            str += '<input id="txtDataCadastro" type="text" readonly="true" value="' + data.agendamento.DataCadastro + '" />	';
            str += '';

            str += 'ID V99:	';
            str += '';
            str += '<input id="txtIDV99" type="text" readonly="true" value="' + data.agendamento.IDOsParceiro + '"/>	';
            str += '
';
            str += '
';
            str += '';
            str += 'Data Agendamento	';
            str += '';
            str += '<input id="txtDataAgenda" type="text" readonly="true" value="' + data.agendamento.DataAgendamento + '"/>	';
            str += '';
            str += 'Tipo de Visita	';
            str += '';
            str += '<input id="txtTipoVisita" type="text" readonly="true" value="' +  + '"/>	';
            str += '
';
            str += '
';
            str += 'Data Visita	';
            str += '';
            str += '<input id="txtDataVisita" type="text" readonly="true" value="' + data.agendamento.DataVisita + '"/>	';
            str += '';
            str += '	';
            str += '';
            str += ' 	';
            str += '
';
            str += '
';
            str += '
';
.................................
$('#filtro').html(str);
            str = "";
        },
        error: function (error) {

        }
    })
}

Answer: O valor /Date(1402369200000)/ está no formato (unix) epoch (veja no wikipedia).
Para converter para Date em javascript use:
var x = new Date(1402369200000);
console.log(x);

// output: Tue Jun 10 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)

Você também pode utilizar uma lib que é muito útil para javascript:
http://momentjs.com/
Mais informações:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Comment: Não consegui converter, devido ao /Date e / no final. Como eu faço para um new Date(meu_campo) sem que venha esses caracteres que invalidam a construção da data
Comment: Nesse caso, é comum o replace das informações indesejadas. Veja mais detalhes aqui: http://stackoverflow.com/questions/1016847/converting-net-datetime-to-json
Comment: Aconselho fortemente vc a utilizar o moment.js. Se vc está trabalhando com datas em JavaScript e precisa formatá-las, essa é a melhor lib que utilizei.

Data está vindo em formato errado


How do we know some sample is from some distribution?

Question: I think my question might not make sense to some people, but I cannot figure out how to explain it to myself. Consider the following Theorem.

$\textbf{Theorem}$ Let the interarrival time $X_n$ be the time between the $(n-1)$th event and the $n$th event in the Poisson Process. Then, random variables $X_i$'s are independent, identically distributed exponential random variables with the parameter $\lambda$ same as the rate of the Poisson Process.

My question is this.

What does it mean that the $X_i$'s are exponentially distributed?

To elaborate, suppose a computer randomly generated a Poisson process, and calculated the interarrival times. How would we know that these $X_i$'s come from an exponential distribution? How would we even know that they are independent? The above theorem is merely an example, a lot of theorems or examples that claim that some random variables follows some distribution can serve the purpose.
Up to this point, my current 'best' explanation is that if the computer generates millions and millions of interarrival times, and plot the $\text{Pr}(X_i\leq t)$ graph, then it would look like the PDF of the exponential distribution. Is this a good explanation? Thanks in advance.
Comment: Yes, the CDF of a random variable determines its distribution. (Alternatively, the PDF of continuous random variables or the PMF of discrete random variables would also suffice.) Note that this is different from the statistical question of whether samples of a random variable come from a distribution, which is what dmh's answer is addressing.
Comment: It's unclear where your confusion lies. Do you recognize that (after having defined the Poisson process) that each interarrival time $X_i$ is a random variable? Then, your question just boils down to "what does it mean for a random variable to have a certain distribution?" which basically is just saying that the random variable's CDF matches the certain distribution's CDF.
Comment: @angryavian Yes that is exactly my confusion. I guess the certain example might have been confusing. So you mean that the CDF is enough?
Answer: It sounds like you want a statistical test that tells you whether your data comes from a distribution satisfying some properties of interest. Typically, youll need to define the family of alternate hypotheses in order to design your test. For example, you could test your samples for serial correlation , which is weaker than testing for independence. (I dont think there is a general method to check that a collection of samples are independent without knowing something about the data collection process)
For checking that the distribution of the $X_i$ is exponential, you could use a kolmogorov smirnov test. But that would require you to choose a value of the rate to test against. You could estimate the rate from the data and use this plugin estimate to compute a p value for the KS test. Asymptotically I think this procedure should be valid, but I'm not sure if it has any known finite sample guarantees.
Comment: Hmm.. I think statistical test is to answer for such reasons, but the theorem above is proved only by simple conditional expectations conditioned on the past interarrival tests. So, I don't get what the book means when they say that the interarrival times are actually "exponentially distributed".


Does the basis have to be orthogonal for a vector to be projected onto it?

Question: A vector $\mathbf{v}$ in $\mathbb{R}^n$ can be projected onto a subspace of $\mathbb{R}^n$ with an orthogonal basis {$\mathbf{u}_1, \mathbf{u}_2,...,\mathbf{u}_k$} with the formula:
$\overline{\mathbf{v}} = \text{proj}_{\mathcal{U}}(\mathbf{v}) = p_1\mathbf{u}_1 + p_2\mathbf{u}_2 + ... + p_k\mathbf{u}_k$
where
$p_i = \frac{\mathbf{v} \cdot \mathbf{u}_i}{\|\mathbf{u}_i\|^2}$, $1 \leq i \leq k$.
But is it generally required that the subspace for which $\mathbf{v}$ is going to be projected onto has an orthogonal basis? Can't $\mathbf{v}$ be projected onto any subspace of $\mathbb{R}^n$, not necerally one with an orthogonal basis?
Comment: Indeed, all you need to describe a projection (i.e., a linear map $P$ with $P^2=P$) is the target subspace and any complement of it ...  It appears however that the goal is to describe the *orthogonal* projection to the subspace.
Comment: are you familiar with the notion of direct sums of subspaces? i.e if $V$ and $W$ are subspaces of $\mathbb{R^n}$, do you know what a statement like: $\mathbb{R^n} = V \oplus W$ means?
Answer: All subspaces of $\mathbb R^n$ have an orthogonal basis, which can be derived from an arbitrary basis by the Gram–Schmidt process. Therefore, vectors can be projected onto any subspace of $\mathbb R^n$, and the orthogonal basis requirement is just to make the calculations simpler.
Comment: Ahh okay, but so the formula can be modified to be applicable for *any* basis?
Comment: @FacPam Rather, you first derive an orthogonal basis, then apply the formula.
Comment: But you say "... and the orthogonal basis requirement is just to make the calculations simpler" - so I would just like to know, does this mean that, in theory,  the formula can be modified to be applicable for any basis?
Comment: @FacPam No. You must have an orthogonal basis, but it always exists.
Comment: Then it cannot be true that "and the orthogonal basis requirement is just to make the calculations simpler" - if you now the that the orthogonality requirement is not just to make the calculations simple but a general requirement for projecting $\mathbf{v}$?
Comment: @FacPam The modification of the projection formula _is_ the prior derivation of an orthogonal basis.
Comment: There's no need to compute an orthonormal basis first, the inverse of the Gram-Matrix of the basis will do.
Comment: @MichaelHoppe Fine then.
Comment: @FacPam There's a _different_ formula when the basis isn't orthogonal, although it could be loosely considered to be a modification of the one you've got.


How to identify the ideal dose, when the doses were given to different numbers of patients?

Question: I have six groups of patients.  The groups contain different numbers of patients (i.e., 30 in group1, 70 in group2, etc).  Each group gets a different dose of a new drug (i.e., group 1 - 20 mg, group 2 - 30 mg, etc.). Each patient is asked to rate the severity of their symptoms (from 1 - very mild, to 6 very bad) before and again one week after the new medicine is administered.
I plan to subtract the post treatment score from the pre-treatment score (i.e., negative numbers mean the patient improved):
<code>Group 1
------------
                pre   post    Change
patient 1         5      3        -2
patient 2         6      2        -4
...
</code>
Then I would have a table as follows:
<code>                  Group 1     group 2      group 3  group 4  etc.....
Change Patient 1       -2          -5           -4       +1
Change Patient 2       -4          -4           -1       +2
</code>
I then need a statistical test to work out which dose of medicine is better at reducing the symptoms.
I have been doing some reading and wondered whether the ANOVA test would do it?  But apparently it would just tell me if there is a difference and not specifically which dose is best. How can I deal with that?
Comment: Your table layout strongly suggests that each patient participated in multiple groups, with each row describing one individual. If so, you will need to track the temporal sequence of their participation and accommodate that in the modeling. If not (which I suspect), then this is an inappropriate way to tabulate (or even maintain) the data, because it risks confusing distinct individuals and makes it difficult or impossible to associate patient-specific attributes with these results.
Comment: Were the patients randomly assigned to the different dosages?
Comment: thanks for you prompt reply, they were randomly allocated
Comment: BTW, did you use any control groups, such as groups receiving a (blinded) placebo?  If not, you can still identify the best dose--but you will be unable to use these data (by themselves) to support any claims concerning whether it is any better than a zero dose.
Answer: The standard ANOVA assumes your data are normally distributed within each group.  That won't be the case here, because your response variable is an ordinal rating.  In addition, difference scores can be a viable option in some cases (where the groups are not necessarily comparable at the start, and where differences are meaningful), but that isn't a good choice in your case: because you randomized your patients, you can consider the distributions to be similar beforehand, and the ordinal nature of the ratings makes the differences nonsensical.
Your best option will be to use ordinal logistic regression.  I would include the previous rating as a covariate.  Lastly, since your groups are associated with a meaningful number (e.g., 20 mg), I would not think of them as nominal groupings as in an ANOVA, but represent them as numbers on a continuum (20, 30, etc.) using a single continuous variable.
To identify the ideal dose, you could also include the squared dose as an additional variable.  That allows the model to fit a curved relationship.  The minimum of the curve can be identified by taking the derivative with respect to the dose, setting it equal to 0, and solving for the dose.  To do this, you can ignore the other variables that don't include the dose (e.g., the pre- rating, demographic covariates, etc.).  You can also work on the scale of the linear predictor—you needn't be concerned about the ordinal nature of the response or trying to figure out how to work with the link function to get actual response categories.  If this simplified version of your model is:
$$
\hat \beta_1 {\rm dose} + \hat \beta_2 {\rm dose}^2
$$
Then the derivative would be:
$$
\frac{d\ {\rm rating}}{d\ {\rm dose}} = \hat \beta_1 + 2 \hat \beta_2 {\rm dose}
$$
And the minimum would be:
$$
{\rm dose} = \frac{-\hat \beta_1}{2 \hat \beta_2}
$$
To answer your explicit question, the fact that the doses were given to different numbers of patients does not matter.  (It is true that, from the standpoint of experimental design, it is a strange choice; for example, it may leave you with suboptimal power.  But that is water over the dam now, and it doesn't affect any of the points discussed above.)


How to understand derivative of reciprocal function with taylor series

Question: With taylor series, $f(x + h) = f(x) + \frac{df}{dx}h + O(h^2)$,
we know the derivative of $f(x)$ is the coefficient of the first order term $\frac{df}{dx}h$.
Using this definition of derivative, we can easily understand the linearity of derivative:
$\frac{d(u+v)}{dx} = \frac{du}{dx} + \frac{dv}{dx}$ as
$u(x + h) = u(x) + \frac{du}{dx}h + O(h^2)$
$v(x + h) = v(x) + \frac{dv}{dx}h + O(h^2)$
Thus: $(u+v)(x+h) = u(x+h) + v(x+h)$
$= u(x) + \frac{du}{dx}h + O(h^2) + v(x) + \frac{dv}{dx}h + O(h^2)$
$= u(x) + v(x) + (\frac{du}{dx} + \frac{dv}{dx})h + O(h^2)$
from the coefficient of the first order term, we know the derivative of $u+v$ is $\frac{du}{dx} + \frac{dv}{dx}$
The question is how to use the same reasoning process to verify reciprocal rule, i.e.
$\frac{d(1/v)}{dx} = -\frac{1}{v^2}\frac{dv}{dx}$
I was starting with:
$\frac{1}{v}(x + h) = \frac{1}{v(x + h)} = \frac{1}{v(x) + \frac{dv}{dx}h + O(h^2)}$
And I stuck here, could you please give some directions on how to continue?
Answer: Assuming things are well defined etc...
$$\frac{1}{v+\frac{dv}{dx}h + O(h^2)} = \frac{1}{v}\cdot\frac{1}{1+\frac{1}{v}\frac{dv}{dx}h + O(h^2)}$$
$$ = \frac{1}{v}\left(1 - \frac{1}{v}\frac{dv}{dx}h + O(h^2)\right) = \frac{1}{v} - \frac{1}{v^2}\frac{dv}{dx}h + O(h^2)$$
by geometric series.


NullPointerException on EditText located in Dialog

Question: Here is my email_dialog.xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TableRow
    android:id="@+id/tableRow0"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</TableRow>

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <EditText
        android:id="@+id/txtEmailAddress5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:text="firstname.lastname@example.com"/>

</TableRow>

   <TableRow
    android:id="@+id/tableRow2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

       <Button
           android:id="@+id/btnCancelEmail"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:width="200px"
           android:text="Cancel" />

       <Button
           android:id="@+id/btnOkEmail"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:width="200px"
           android:text="Email" />

</TableRow>

Here is my method that calls and uses it:
void showEmailDialog() {
    // Final prevents the error in the newest onClick callback.
    final Dialog dialog = new Dialog(this);

    dialog.setContentView(R.layout.email_dialog);
    dialog.setTitle("Enter Email Address");
    dialog.setCancelable(true);

    final EditText txtEA = (EditText) findViewById(R.id.txtEmailAddress5);
    final Button cancelButton = (Button) dialog.findViewById(R.id.btnCancelEmail);
    final Button sendButton = (Button) dialog.findViewById(R.id.btnOkEmail);

    // set up cancel button
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }

    });

    // set up send button
    sendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "sendButton onClick()");
            String emailAddress;

            Log.d(TAG, "sendButton onClick() - String emailAddress");

            Log.d(TAG,
                    "sendButton onClick() - txtEmailAddress = (EditText)");

            emailAddress = txtEA.getText().toString();
            Log.d(TAG,
                    "sendButton onClick() - emailAddress = getText().toString();");

            sendEmail(emailAddress);

            dialog.dismiss();

        }
    });

    dialog.show();
    //
}

TAG is properly defined no worries there.
I keep getting:
txtEA.getText().toString()

to throw the null point exception.  I have the right R.id value which I verified like 50 times, I verify that the setContentView() is before i try to access the EditText and the two Buttons with setOnClickListener works perfect.
I could definitely use another set of eyes on this! I've dug around the similar questions and tried their solutions but none of them solved mine!
Answer: You should do this:
 final EditText txtEA = (EditText) dialog.findViewById(R.id.txtEmailAddress5);

You forgot to search for the txtEA in dialog.
Comment: Wow, I am blind.  I would have stared at that all day.  Thank you for fixing my obliviousness!
Answer: final EditText txtEA = (EditText) dialog.findViewById(R.id.txtEmailAddress5);

You must call findViewById on dialog.


Calcular média aritmética de um vetor

Question: import numpy as np

matriz = []
medias = []
alunos=1

while True:
    print("Informe o número do aluno ou um valor negativo para terminar:")
    valor=int(input('Digite o número do aluno: '))
    if valor<0:
        break
    else:
        alunos=1
        linha=[valor]
        media1=[]
        media2=[]
        media3=[]
        media4=[]
        media5=[]
        media6=[]

        for i in range(0,3,1): #Notas disciplina 1
            n1=float(input("Informe as notas da disciplina 1: "))
            linha.append(n1)
            media1.append(n1)
        media1.mean()
        print(media1)

Comment: Seu objeto `media1` é uma lista do Python, que não possui um método chamado `mean`. O que você precisa não é de `media = np.mean(media1)`?
Comment: Exatamente! Muito obrigado!
Answer: Solução #1: Usando sum() e len()
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( sum(vetor) / float(len(vetor)) )

Solução #2: Usando lambda
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( reduce(lambda x, y: x + y, vetor) / float(len(vetor)) )

Solução #3: Módulo statistics
from statistics import mean
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( mean(vetor) )

Solução #4: Módulo numpy:
import numpy as np
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( np.mean(vetor) )

Saída:
4.5

Calcular média aritmética de um vetor


Network communication in 2Hosts

Question: We have 2 Linux Hosts each has 2 Nic Cards with below IP addresses,ech0 and eth1 are in different network , Host1:eth1 and Host2:eth1 are connected by direct cable, due to some Hardware issue N/W cable got bad, Is there any way to communicate between Host1:eth1 and Host2:eth1 ?
In Normal conditions: Communication from Host1:eth0 to Host2:eth1 and Host2:eth0 to Host1:eth1 is not working , i checked by this by TRACEROUTE -I command (Host1# traceroute -i eth0 10.1.1.201 or Host2# traceroute -i eth0   10.1.1.200)
===========================
Host1:
eth0  : 10.162.100.200/24
eth1  : 10.1.1.200/24

Host2:
eth0  : 10.162.100.201/24
eth1  : 10.1.1.201/24

==========================
Comment: I don't really understand your config.  Are host1 and host2 physically attached to each other with a working network cable?  Are they attached to the same switch/router?  Are they in the same building?
Comment: Thanks for your response.. Single static routes on HOST1(route add -host 10.1.1.200 gw 10.162.100.200 eth0) is not work ,since HOST1:eth0(10.162.100.200) don't know about HOST2:eth1(10.1.1.201). Traceroute shows this (HOST1# traceroute -i eth0 10.1.1.201 or HOST2# traceroute -i eth0 10.1.1.200). I need multiple static routes ,i am not sure how to write ROUTE/IPTABLES commands for below static routes. 1)Need static route on HOST1, If any packets with source address HOST1:eth1(10.1.1.200) and destination address HOST2:eth1(10.1.1.201) ,Then Forward packets to HOST1:eth0(10.162.100.200). 2)One mo
Comment: Above one can simplified as for packets with "source address HOST1:eth1(10.1.1.200) and destination address HOST2:eth1(10.1.1.201)" HOST1:eth1(10.1.1.200) => HOST1:eth0 (10.162.100.200)=> HOST2:eth0(10.162.100.201) =>HOST2:eth1(10.1.1.201) Need static routes for above path
Comment: As per SpacemanSpiff suggestion ,i will try with below commands Please let me know if anything wrong with below commands on HOST1
======== route add -host 10.1.1.201 gw 10.162.100.201 eth0 (HOST1:eth1(10.1.1.200) => HOST1:eth0 (10.162.100.200)=> HOST2:eth0(10.162.100.201) =>HOST2:eth1(10.1.1.201)) on HOST2
======== route add -host 10.1.1.200 gw 10.162.100.200 eth0 (HOST2:eth1(10.1.1.201) => HOST2:eth0 (10.162.100.201)=> HOST1:eth0(10.162.100.200) =>HOST1:eth1(10.1.1.200))
Comment: Tony, HOST1 and HOST2 are in same building ,HOST1:eth1 and HOST2:eth1 are directly connected by crossover cable, but cable is not working ,HOST1:eth0 and HOST2:eth0 are connected to Office Network VIA switch ,from Workstations we can access HOST1:eth0 and HOST2:eth0 only, we can't access HOST1:eth1 and HOST2:eth1 since they are in different N/W with crossover cable. I would like to send packets from HOST1:eth1 to HOST2:eth1 using HOST1:eth0 and HOST2:eth0 interfaces. ==========Config=================
Host1:
eth0 : 10.162.100.200/24
eth1 : 10.1.1.200/24 Host2:
eth0 : 10.162.100.201/24
eth1 : 10
Comment: @Vijay - STOP adding comments as answers, this is a question and answer site, nothing else, if you carry on we'll just destroy your account.
Answer: This should be a pretty simple case of routes and metrics. When eth1's link is up, it is a "connected" network which should have a priority and take precedence, so communication between the hosts is direct.
However, if you set a static route on Host1 pointing to host2's eth0 address as a gateway for the host2's eth1 interface, it should work when the link is down hard.
You would do the opposite on the other host.
Comment: A single static route will be sufficient on each host. As for iptables configuration I'm not familiar.

Network communication in 2Hosts


Consultar um retorno JSON de uma API via POST em ANGULAR

Question: Olá, tenho uma aplicação que preciso receber um JSON e popular meus campos de input, após realizar um Post de cpf/cnpj. No caso em questão é a API da SEPRO, onde faço a consulta de cpf/cnpj e ele me trás os dados do cliente, estou utilizando o POSTMAN para consumir esses dados.
Porem estou tendo dificuldade para passar o método Post na minha Service.ts, fiz de diversas formas mas não funciona, consigo realizar apenas o método Get com sucesso, se alguém puder me ajudar ficaria agradecido!!!  :)
dashboard-home.servce.ts
import { HttpClient } form '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DeshboardHomeService {

  constructor(private httpClient: HttpClient) {}

  sepro(cpf:any){
    return this.httpClient.post(`http://{{gatway_dns}}/pessoas/v1/pessoas_fisicas/10101010010/sepro`)
  }
}

Comment: O que seria isso **`{{gatway_dns}}`**?
Comment: Eles disponibilizam método post na api deles? na pesquisa que fiz só achei os métodos GET. segue os links que achei abaixo [Consulta CNPJ DF V2 (Trial)](https://apicenter.estaleiro.serpro.gov.br/documentacao/consulta-cnpj/pt/demonstracao-v2/), [Consulta CPF](https://apicenter.estaleiro.serpro.gov.br/documentacao/consulta-cpf/pt/demonstracao/)
Comment: Então no Postman, para consumir os dados do cliente tenho que fazer um Post com o CPF/CNPJ, ai ele me retorna o JSON com nome completo, empresa etc...
Comment: Se você puder compartilhar isso que você falou. se entendi direito no postman esta dando certo. Confira também de onde a variável `gatway_dns` vem.
Answer: Vou dar um exemplo básico que utilizei por bastante tempo para aprender Angular,
ApiService.ts - Service (Serviço)
Esse é o nosso serviço, ele irá ficar com as requisições http para a rota car da api que temos que consumir.
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Car } from './car';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({providedIn:'root'})
export class ApiService {

  baseURL: string = "http://localhost:8080/";

  constructor(private http: HttpClient) {
  }

  getCars(): Observable<Car[]> {
    console.log('getCar '+this.baseURL + 'car')
    return this.http.get<Car[]>(this.baseURL + 'car')
  }

  addCar(car:Car): Observable<any> {
    const headers = { 'content-type': 'application/json'}
    const body=JSON.stringify(car);
    console.log(body)
    return this.http.post(this.baseURL + 'car', body,{'headers':headers})
  }

}

AppComponent - Component (Componente)
Esse é o nosso componente, ele irá fazer uma injeção de dependência para o nosso ApiService e utiliza-lo para as chamar requisições http.
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { Car } from './car';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  title = 'AppComponent';
  cars:Car[];
  car = new Car();

  constructor(private apiService:ApiService) {}

  ngOnInit() {
    this.getAllCars()
  }

  // Get sendo utilizado
  getAllCars() {
    this.apiService.getCars()
      .subscribe(data => {
        console.log(data);
        this.cars=data;
      })

  }

  // Post sendo utilizado
  addCar() {
    this.apiService.addCar(this.car)
      .subscribe(data => {
        console.log(data);
        this.getAllCars(); // Atualiza todos os carros, pois adicionou novo
      })
  }

}

Agora é apenas você chamar essas funções conforme sua necessidade, nesse caso, sempre que esse componente for iniciado eu vou chamar a função getAllCars() para obter todos os carros, assim como você pode chamar a função addCar() quando o usuário clicar em um botão.
O Angular utiliza em suas requisições HTTP o Observable, essa é uma das formas que utilizamos para trabalhar com requisições e mais comum, os Observables no Angular, a ideia é que seja feito um .subscribe() para cada requisição http, como return this.http.post.


How can I get a list of all my site's module and themes?

Question: I want to get the list of current modules and themes and modify them on Drupal 9, previously in Drupal 8,7 I used the following functions to get and save them but it seems they are depricated on Drupal 9.
 system_get_info(), _system_rebuild_module_data()

what is equivalent to these functions in Drupal 9 and how can get/update data about the module/themes in Drupal 9?
Comment: I'm voting to close this question as off-topic because this information can easily be found in the documentation, for example [`system_get_info()`](https://api.drupal.org/api/drupal/core%21modules%21system%21system.module/function/system_get_info).
Comment: From the help center: How do I ask a good question?

We'd love to help you. To improve your chances of getting an answer, here are some tips:
Search, and research

Have you thoroughly searched for an answer before asking your question? Sharing your research helps everyone. Tell us what you found and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and above all, it helps you get a more specific and relevant answer!"
Comment: Wow Yusef, and now downvoting the answers. Really not nice.
Comment: @leymannx I could remember I down vote on answers. but the sound correct.
I apologize for that ( maybe someone seated behind my seat ). naughty colleagues
Answer: The change records tell you all you need to know ...
https://www.drupal.org/list-changes/drupal/published?keywords_description=system_get_info&to_branch=&version=&created_op=%3E%3D&created%5Bvalue%5D=&created%5Bmin%5D=&created%5Bmax%5D=
Comment: Oh wow I didn't know of drupal.org/list-changes/drupal, thanks for that gem! I was always just googling for the functions.
Comment: @leymannx, there is a link on the project page https://www.drupal.org/project/drupal
Comment: @4k4 – Ah I've probably never been on that page, too! Bookmarked!
Answer: Simply check the deprecation notice on system_get_info

Deprecated
in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  \Drupal::service('extension.list.$type')->getExtensionInfo() or
  \Drupal::service('extension.list.$type')->getAllInstalledInfo()
  instead.

and the change record on _system_rebuild_module_data() and co. are replaced by services to give you all available modules and themes

// If you want to just get all extensions without rebuilding.
$module_list = \Drupal::service('extension.list.module')->getList();


How could I make checking user input case-insensitive?

Question: I am adding a few ways of checking user input to my code. Instead of writing if Answer == ("Yes") or Answer == ("yes"), is there any way I could make the variable input case-insensitive, so that I don't have to type the word yes twice? Additionally, would there be any way I could make the every variable input option in the line case-insensitive? if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):.
def Repeat():
  Answer = input ("\nDo you want to play again? (Y/N): ")
  if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):
    print ("")
  if Answer == ("No") or Answer == ("no") or Answer == ("N") or Answer == ("n"):
    exit()
  if Answer == "Options" or Answer == "options" or Answer == "o" or Answer == "O":
    print ("")
  else:
    print ("Invalid Input")
    Repeat()
Repeat()

Comment: `Answer = input ("\nDo you want to play again? (Y/N): ").lower()`
Comment: I would use `.lower` and `in` like so… `if Answer.lower() in ["yes", "y"]:`
Answer: You can change the case of the user input and just check against that:
 answer = input("\nDo you want to play again? (Y/N): ").lower()
 if answer in ("yes", "y"):
     ...


Mail forwards from Office 365 rejected due to SPF failure

Question: I am an outsourced IT provider and traditionally I have setup firstname.lastname@example.com to forward to firstname.lastname@example.com
We've recently migrated some customers to Office 365 and when we setup email@example.com as a distribution list and our mailing account as a recipient messages sent are getting rejected as they aren't passing SPF.
It appears exchange online is not enveloping the messages so anybody who has a -all or ~all in their SPF record is unable to sent emails to us.
how is it possible to configure office 365 to forward emails in such a way that they will pass SPF?
An example of the problem is this:
firstname.lastname@example.com sends an email to firstname.lastname@example.com which forwards to email@example.com as email@example.com. vendor.com's spf record does not allow emails from spf.protection.outlook.com thus gets rejected by our spf check.
what I want is exchange online to envelope the message so that it appears to come from exchange online and thus pass spf check.
Answer: I don't think that Exchange is actually forwarding the emails. If that were the case then the email would be listed as coming from an @customerdomain address. The emails are just redistributed to another mail system. This being the case, and by design, SPF is broken because Office365 is not allowed to send mail on behalf of vendor.com.
One way to achieve this would be to set up firstname.lastname@example.com as a shared mailbox and configure auto-forwarding on the mailbox settings. This way the emails are being sent by an @customerdomain.com address and SPF won't fail.
I considered how you might set up some kind of exclusion in your mail system, but you would have to know the details of all senders to be able to configure any kind of bypass; even then you would be opening yourself up to security risks, which happens any time you decide to 'trust' a sender.
That said, I just did my own bit of research and it seems Microsoft are in the process of rolling out Sender Rewriting Scheme (SRS), which fixes this very problem:

To combat email abuse, new authentication mechanisms, such as SPF, DKIM, and DMARC, are being used to combat the spoofing of domains by spammers. These mechanisms, however, are not compatible with the way emails have been forwarded from Office 365 to forward addresses set up for hosted mailboxes. More and more, recipient email servers are rejecting forwarded emails coming from Office 365 as the sender address is not for a domain Office 365 is allowed to send as. To fix this issue, a sender rewriting scheme is being rolled out in Office 365 that will change the sender email address to use the domain of the tenant whose mailbox is forwarding the message. This will avoid the rejections taking place by some email servers with strict settings for their SPF checks. Specifically, the Mail From field that email servers use to determine the sender email address will be rewritten. The separate From header which contains the sender address that is shown to recipients in their email client will not be changed. If any forwarded emails fail to be delivered to the forwarded address, the non-delivery responses will be sent to the original sender of the email which has always been the case.
Estimated Release: Q2 CY2018
Feature ID: 24056
Added to Roadmap: 10/25/2017
Last modified : 07/25/2018

Maybe your problem will be resolved imminently...
https://products.office.com/en-us/business/office-365-roadmap
Comment: It's strange. It's 2024 and even with SRS theoretically working (checked on raw message) SPF alignment isn't. I've tried also the Shared Mailbox trick but the results were the same.


How to enter overlapping notes in Sibelius 7

Question: I can't manage to find a way to enter overlapping notes in Sibelius 7.
Any help?
By overlapping notes I mean notes from other voices that have a longer duration than others which are placed at the very same beat.
Comment: If you use separate voices(!) for the notes there should be no problem!
Answer: In Sibelius, you can use up to four separate voices on a single staff. The stems on notes for voices 1 and 3 point upward, while those for voices 2 and 4 point downward. The four voices are accessible via the numbered buttons labeled 1–4 and "All" at the bottom of the keypad menu. The "all" button selects all voices which are currently in use in the selected passage of music, and whatever change you make will affect all voices.
You should be able to enter music for the upper voice normally, then press the button labeled "2" to select the second voice and enter the music for the lower voice. The durations of the two voices will be completely separate, allowing for "overlapping" notes.
Just make sure to be aware of which voice you are editing at all times so that you don't accidentally change the wrong voice! Of course, even if this does happen, you can always select the music, right click, hover over "voice," and then select which voice you want to move the selected passage to.
Comment: I can't work out how to enter notes on the second voice, though. If I have a note selected, selecting the second voice switches the note to that voice. If I don't have a note selected, clicking where I want to enter music just flips me back to the first voice! So how do I set the insertion point for the new voice?
Answer: Enter the note to be performed by voice 1.
Then press the 1 key which will add a unison note, also in voice 1.
Then press Alt+2 which will change the selected note to be voice 2. So you'll have one notehead with one up stick and one down stick. You can use the up and down arrows to change the pitch.
It's not obvious, but once you've done it a few times it becomes second nature.


Retirar uma parte do texto dentro de um arquivo txt

Question: Colegas.
Tenho o seguinte código onde pego um arquivo csv através de upload e armazeno em um arquivo txt, do qual tem que ter a formação das posições conforme a base de dados de um programa. Para isso estou usando o código abaixo:
         $diretorio = 'arquivos/';
            $arquivo = $diretorio . basename($_FILES['userfile']['name']);

            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $arquivo)){

               $abrirArquivo = fopen($arquivo, "r");

              while(!feof($abrirArquivo)) {
                    $ler = fgets($abrirArquivo,460);
                    $campo1 = substr($ler, 0, 8);
                    $campo2 = substr($ler, 9,10);
                    $campo3 = substr($ler, 20, 10);
                    $campo4 = substr($ler, 31, 22);
                    $campo5 = substr($ler, 40, 10);

$leituraFinal = "
$campo1          $campo2   $campo3                          $campo4                     $campo5
";

                //$trocar = str_replace("
","",$leituraFinal);
                $trocar = preg_replace("
",null,$leituraFinal);
                file_put_contents($diretorio . "JAN_2012.txt",$leituraFinal,FILE_APPEND);
                file_get_contents($diretorio . "JAN_2012.txt");

            }
     }
}

Legal. Funciona, ao menos em partes, pois no arquivo txt aparece no final da linha o
.
Answer: Se bem percebo pretendes substituir "null" por uma mudança de linha no ficheiro txt. Creio que para isso tens de fazeres o seguinte:
$trocar = preg_replace("\n", null, $leituraFinal);

Substituindo o código anterior:
$trocar = preg_replace("
",null,$leituraFinal);

Answer: Para que você possa remover a tag br do final do arquivo txt, você poderia fazer da seguinte forma alterando o seguinte precho do seu código:
$trocar = preg_replace("
",null,$leituraFinal);

Para:
$trocar = preg_replace('/
$/', '', $leituraFinal);

Onde a expressão regular só irá remover o br que estiver no final do txt, mas caso você queira remover todos os br que possam vir a existir nesse arquivo txt faça dessa forma a alteração:
$trocar = preg_replace('/
/', '', $leituraFinal);


Some confusion in creating pivot table

Question: I am trying to create a pivot table but i am not getting the result i want. Couldn't able to understand why is this happening.
I have a dataframe like this -
    data_channel_is_lifestyle   data_channel_is_bus     shares
0       0.0                               0.0            593
1       0.0                               1.0            711
2       0.0                               1.0            1500
3       0.0                               0.0            1200
4       0.0                               0.0            505

And the result i am looking for is name of the columns in the index and sum of shares in the column. So
i did this -
news_copy.pivot_table(index=['data_channel_is_lifestyle','data_channel_is_bus'], values='shares', aggfunc=sum)

but i am getting the result something like this -
                                                   shares
data_channel_is_lifestyle   data_channel_is_bus
            0.0                    0.0             107709305
            1.0                                    19168370
            1.0                    0.0              7728777

I don't want these 0's and 1's, i just want the result to be something like this -
                               shares
data_channel_is_lifestyle     107709305
data_channel_is_bus           19168370

How can i do this?
Comment: So you want to sum `shares` where `data_channel_is_lifestyle==1` and similar for `data_channel_is_bus`?
Comment: @QuangHoang yes, that is what i am looking for. Can you tell me how to do it?
Answer: As you put it, it's just matrix multipliation:
df.filter(like='data').T@(df[['shares']])

Output (for sample data):
                           shares
data_channel_is_lifestyle     0.0
data_channel_is_bus        2211.0

Comment: @bholaprasad `df.filter(like='data')` returns a dataframe with columns which contains `data` as a string in it , then using a transpose and a [dot](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dot.html) multiplication it returns the above result.
Comment: Sorry, couldn't able to understand your answer. what will go in the like='data' and what is @ after T. Is it from new version of pandas?
Comment: @bholaprasad since your `data_channel_is_lifestyle` looks binary (`0` or `1`), summing over `1` values just means that you sum the product of `data_channel_is_lifestyle` and `shares`. And that's exactly [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication#Definition).

Some confusion in creating pivot table


Django fixtures not accepting YAML?

Question: $ python manage.py loaddata fixtures/initial_data.yaml
Problem installing fixture 'fixtures/initial_data': yaml is not a known serialization format.
$
$ python manage.py loaddata fixtures/initial_data.yml
Problem installing fixture 'fixtures/initial_data': yml is not a known serialization format.

According to Django documentation this format should be supported, but I get the above  errors. JSON on the other hand works ok.
Django version:

django.VERSION
      (1, 3, 1, 'final', 0)
Comment: What version of django are you using?
Answer: .yaml is what you want. Make sure YAML is installed and available to Python by running:
> pip install pyyaml

Comment: In case of Mac OS, you should install libyaml 1st -> port install libyaml.
Comment: or `brew install libyaml` if you use homebrew
Comment: Please note that only files with an "yaml" extension will be accepted as fixtures by Django (tested on Django 2.2). So initial_data.yaml will be loaded but initial_data.yml wont be loaded and an error will be thrown:  `CommandError: Problem installing fixture 'initial_data': yml is not a known serialization format.`
Answer: debian based linux - ubuntu etc etc
sudo apt-get install python-yaml
or
apt-get install python-yaml

Django fixtures not accepting YAML?


Receiving discord.js slash command parameters

Question: I'm currently trying to make a calculation using parameters input via a slash command. Putting them in works fine, however I do not know how to actually retrieve them. the current code yields an error TypeError: Cannot read properties of undefined (reading 'get') which has me quite confused, as the discord.js documentation shows that said function should exist and be exactly what I'm looking for.
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('manacost')
        .setDescription('Calculates the ´soul spawn cost using your inputs')
        .addStringOption(option =>
            option.setName('health')
                .setDescription('The amount of health your soul has. Supports k=1000...')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('damage')
                .setDescription('The amount of damage your soul has. Supports k=1000...')
                .setRequired(true))
        .addIntegerOption(option =>
            option.setName('breeze')
                .setDescription('The amount of breeze you have.(0-80)')
                .setRequired(false)),
    async execute(interaction) {
        if (!interaction.isChatInputCommand()) return;
        let hp = interaction.options.get('health');
        let dmg = interaction.option.get('damage');
        let b =  interaction.option.get('breeze');
        console.log({hp, dmg, b});
        await interaction.reply({content: hp, dmg, b});
    },
}

Answer: The interaction options can be found using interaction.option.getString() or interaction.option.getInteger(). Also in your Code you have mixed up interaction.options and interaction.option. You should only use interaction.options.
That means your code has to change from

let hp = interaction.options.get('health');
let dmg = interaction.option.get('damage');
let b =  interaction.option.get('breeze');

to

let hp = interaction.options.getString('health');
let dmg = interaction.options.getString('damage');
let b =  interaction.options.getInteger('breeze');

You should take a look at this post from the discord.js guide for more information and a look at the other option types.


i need to insert an image in my listview

Question: I am new in android development and I need to modify my code to make it show the text with image function:
print_view xml  :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BFAF80">

<ListView
    style="14dp"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:id="@+id/operations"
    android:layout_below="@+id/search_view"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_below="@+id/operations"
    android:layout_centerHorizontal="true"
    android:src="@drawable/printer" />

list_row_item xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:padding="20dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:src="@drawable/wifi"
        android:layout_height="wrap_content"
        android:id="@+id/imageForList" />

    <TextView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:layout_height="wrap_content"
        android:text="Nearby Wifi"
        android:id="@+id/textForList" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:src="@drawable/bluetooth"
        android:layout_height="wrap_content"
        android:id="@+id/imageForList2" />

    <TextView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:layout_height="wrap_content"
        android:text="Nearby Blutooth"
        android:id="@+id/textForList2" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:src="@drawable/usb"
        android:layout_height="wrap_content"
        android:id="@+id/imageForList3" />

    <TextView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:layout_height="wrap_content"
        android:text="Direct USB Connected"
        android:id="@+id/textForList3" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:src="@drawable/cloud"
        android:layout_height="wrap_content"
        android:id="@+id/imageForList4" />

    <TextView
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginTop="35dp"
        android:layout_height="wrap_content"
        android:text="Google Cloud Print"
        android:id="@+id/textForList4" />
</LinearLayout>

SettingsList java class:
public class SettingsList {

private int[] images;
private String[] items;

public SettingsList(int[] images, String[] items) {

    this.images = images;
    this.items = items;
}

public int[] getImages() {
    return images;
}

public void setImages(int[] images) {
    this.images = images;
}

public String[] getItems() {
    return items;
}

public void setItems(String[] items) {
    this.items = items;
}
}

SettingsAdapter java class :
public class SettingsAdapter extends ArrayAdapter<SettingsList> {

public SettingsAdapter(Context context, int resource, List<SettingsList> objects) {
    super(context, resource, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolderItems holder;
    if(convertView == null){
        LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.list_row_item, parent, false);
        holder = new ViewHolderItems();
        holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList);
        holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList2);
        holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList3);
        holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList4);
        holder.holderText = (TextView)convertView.findViewById(R.id.textForList);
        holder.holderText = (TextView)convertView.findViewById(R.id.textForList2);
        holder.holderText = (TextView)convertView.findViewById(R.id.textForList3);
        holder.holderText = (TextView)convertView.findViewById(R.id.textForList4);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolderItems)convertView.getTag();
    }
    SettingsList current = getItem(position);
    holder.holderImage.setImageResource(current.getImages()[position]);
    holder.holderText.setText(current.getItems()[position]);

    return convertView;
}

static class ViewHolderItems{
    ImageView holderImage;
    TextView holderText;
}
}

PrintView mainactivity :
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PrintView  extends ActionBarActivity {    private ListView lv;
private SettingsAdapter adapter;
private List<SettingsList> itemList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.print_view);
    int[] imgs = new int[]
            {
                    R.drawable.wifi,
                    R.drawable.bluetooth,
                    R.drawable.usb,
                    R.drawable.cloud,

            };
    String[] values = new String[]
            {"Nearby Wifi",
                    "Nearby Blutooth",
                    "Direct USB Connected",
                    "Google Cloud Print"

            };
    lv = (ListView)findViewById(R.id.operations);
    itemList = new ArrayList<>();
    itemList.add(new SettingsList(imgs, values));

    adapter = new SettingsAdapter(PrintView.this, R.layout.list_row_item, itemList);
    lv.setAdapter(adapter);

}

}

Comment: http://www.codeproject.com/Articles/507651/Customized-Android-ListView-with-Image-and-Text
Comment: you are not even following my steps... You leave the adapter, list_row_item.xml, and SettingsList as they are....Remove the imageview from the print_view.xml
Comment: @KostasMatrix:

please help me :( by editing your answer,,, now you know exactly what i need .. i will appreciate that from you
Comment: check my answer....i editted. Copy and paste it as it is. and you will have your list working fine.
Comment: i did everything copy paste but the image didn't appear just the text !!
Comment: do you have the images in the drawable folder???did you named them correctly?
Comment: finally, it's work, thnks
Answer: Try this:
1) Create a res/layout/list_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:padding="20dp"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher"
            android:layout_height="wrap_content"
            android:id="@+id/imageForList" />

        <TextView
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:layout_marginTop="35dp"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textForList" />
    </LinearLayout>
</LinearLayout>

2) Create your custom List item:
public class SettingsList {

    private int image;
    private String item;

    public SettingsList(int image, String item) {

        this.image = image;
        this.item = item;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }
}

3) Create your custom adapter
public class SettingsAdapter extends ArrayAdapter<SettingsList> {

    public SettingsAdapter(Context context, int resource, List<SettingsList> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolderItems holder;
        if(convertView == null){
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.list_row_item, parent, false);
            holder = new ViewHolderItems();
            holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList);
            holder.holderText = (TextView)convertView.findViewById(R.id.textForList);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolderItems)convertView.getTag();
        }
            SettingsList current = getItem(position);
            holder.holderImage.setImageResource(current.getImage());
            holder.holderText.setText(current.getItem());

        return convertView;
    }

    static class ViewHolderItems{
        ImageView holderImage;
        TextView holderText;
    }
}

4) In your Activity that you want the listview to be shown do this:
public class YourActivity extends ActionBarActivity {

    private ListView lv;
    private SettingsAdapter adapter;
    private List<SettingsList> itemList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView)findViewById(R.id.operations);
        itemList = new ArrayList<>();
        itemList.add(new SettingsList(R.drawable.wifi, Nearby Wifi));
        itemList.add(new SettingsList(R.drawable.bluetooth, Nearby Blutooth));
        itemList.add(new SettingsList(R.drawable.usb, Direct USB Connected));
        itemList.add(new SettingsList(R.drawable.cloud, Google Cloud Print));
        adapter = new SettingsAdapter(YourActivity.this, R.layout.list_row_item, itemList);
        lv.setAdapter(adapter);

    }

}

5) The print_view.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BFAF80">

    <ListView
        style="14dp"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:id="@+id/operations"
        android:layout_below="@+id/search_view"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Hope it helps!!!
Comment: i have a problem with (images_array, string_array), cannot resolve it
Comment: what do you mean you cannot resolve it?check my editted answer
Comment: android make it with red line and said (cannot resolve symbol images_array)
Comment: i editted my answer...check it again. And also where i say images_array i mean that there you should put your int[] imgs, where i say string_array you should put your String[] values
Comment: i will edit my question with your steps and i need from you to see if i missed any of them or made mistakes


In process builder how to create a new criteria that checks if the Case owner has changed and also that the owner is not a Queue

Question: Ok, so in a process builder i have to create a new criteria that checks if the Case owner has changed (which i have this part) but also that the owner is not a Queue that part i'm stuck on
Answer: You need to check that Owner Id is updated and Id in Owner Id (Queue) is not same as Owner ID:


If $X\sim \mathcal{N}(0, \frac{1}{\lambda}I_p)$ and $Y \sim \mathcal{N}( 0 ,I_n)$, are they independent?

Question: Suppose both $X$ and $Y$ are multivariate normal such that $X\sim \mathcal{N}(0, \frac{1}{\lambda}I_p)$ and $Y \sim \mathcal{N}( 0 ,I_n)$, are they independent? By multiplying their densities together, I got
\begin{align}
&\frac{1}{(2\pi)^{p/2}\lambda^{-p}} \frac{1}{(2\pi)^{n/2}} \exp\left(-\frac{1}{2}X^T \lambda X - \frac{1}{2} Y^T Y\right) \\[5pt]
= {} & -\frac{1}{(2\pi)^{(n+p)/2}\lambda^{-p}}\exp\left(-\frac{1}{2}\begin{bmatrix}X \\ Y\end{bmatrix}^T \begin{bmatrix} \lambda^{-1} I_p & 0 \\ 0 & I_p \end{bmatrix}^{-1} \begin{bmatrix}X \\ Y\end{bmatrix}\right)
\end{align}
Can I conclude that $X$ and $Y$ are independent? My concern is that the thing I got might not be their joint distribution at all. In fact, to argue that their joint distribution is indeed the product of marginal, I have to assume they are independent in the first place?
Comment: Your concern is correct: there is no reason why $X$ and $Y$ should be independent.
Comment: Giving the distributions of X and Y gives no indication about the dependence of X and Y. Sorry but what is your source on (stochastic) independence?
Answer: You can't generally tell from the distributions of two variables $X$ and $Y$ whether or not they're independent. Let $X$ and $Y$ be Bernouilli of parameter $\frac 1 2$. Are they independent? Well, they could be. But we could also have $X=Y$.
Answer: From the fact that $X$ and $Y$ have those distributions you cannot tell whether they are independent without further information.
But if the joint density of $X$ and $Y$ is the one you have given, then they are independent.


Difference between biconditional and logical equivalence

Question: A biconditional can also be stated as "P is equivalent to Q," whereas a logical equivalence can also be stated as "P is logically equivalent to Q." I never understood intuitively what the difference between them was. I get that biconditional is true when both P and Q are true or false, and logical equivalence means P and Q have all of the same possible truth values, but I cannot grasp intuitively what they really mean and what the difference between them is.
Comment: Basically, the [biconditional](https://en.wikipedia.org/wiki/Logical_biconditional) is a connective (a part of the language) while [logical equivalence](https://en.wikipedia.org/wiki/Logical_equivalence) is a semantical relation between formulas expressible in the meta-language. The two are strictly linked: $\vDash (\varphi \leftrightarrow \psi)$ iff ($\varphi \vDash \psi$ and $\psi \vDash \varphi$).
Comment: It may help to note that the language may have no biconditional connective but the relation of logical equivalence between formulas still exists.
Comment: Does this answer your question? [What is the difference inbetween $\leftrightarrow$, $\iff$, and $\equiv$?](https://math.stackexchange.com/questions/3926367/what-is-the-difference-inbetween-leftrightarrow-iff-and-equiv)
Comment: See also this answer on SE Philosophy: https://philosophy.stackexchange.com/questions/65024/what-is-the-difference-between-logical-equivalence-and-material-equivalence
Comment: Does this answer your question? [Distinction between equality, logical equivalence and biconditionality.](https://math.stackexchange.com/questions/500644/distinction-between-equality-logical-equivalence-and-biconditionality)
Answer: Basically, the distinction is between talking about a specific situation versus all possible situations.

Suppose I have two different propositional variables $p$ and $q$. Then:

$p$ and $p\wedge p$ are logically equivalent. (Remember that "$\wedge$" means "and.")
$p$ and $q$ are not logically equivalent.
However, $p\iff q$ might be true (e.g. if both $p$ and $q$ happen to be true).

This is ultimately a distinction between talking about general necessities versus specific situations. The keyword here is "model." In the setting of propositional logic (there are other logics), a model is just a specific assignment of truth values to the propositional variables in the language. E.g. suppose our language has propositional atoms $p, q, r$. Then "$p$ and $q$ are true, $r$ is false" (or rather, the function $\nu: \{p, q, r\}\rightarrow\{true, false\}$ sending $p$ and $q$ to $true$ and $r$ to $false$) is a model. Note that given a model, we can also talk about the truth values of more complicated sentences in that model: e.g. "$p\wedge r$" is false according to the model above.
(Indeed, we can prove by "structural induction" that an assignment of truth values to propositional variables uniquely extends to an assignment of truth values to all propositions, which respects the obvious rules - e.g. if $\varphi$ and $\psi$ are both assigned "true," then $\varphi\wedge\psi$ must be assigned "true," and so forth. Sometimes a model is defined as a truth assignment to all propositions, which satisfies these reasonable rules; the proof described in the previous sentence means that we can get away with the simpler definition above.)
When we say that two sentences are logically equivalent, we mean that there is no model in which they have different truth values. The expression "$p\iff q$," however, is a (compound) sentence which is (in general) true in some models and false in others. This is the distinction:

The notion of "logical equivalence" is talking about what things are possible in general.
When we say that a sentence is true/false, we are talking about its truth/falsity in a specific model.

For example, in the model $\nu$ defined above the sentence "$p\iff q$" is true, even though $p$ and $q$ are not logically equivalent (exercise).
At this point, it's useful to introduce a bit of terminology: a sentence which is true in every model is called a tautology. When we say "$\varphi$ and $\psi$ are logically equivalent," we're just saying "$\varphi\iff \psi$ is a tautology."

A bit of more advanced material
There is also a "relative" version of this. Suppose $\varphi$ is some proposition which is true in every model in which the proposition $\psi$ is also true. (Note that this just means that the proposition "$\psi\implies\varphi$" is a tautology.) Then we write "$\psi\models\varphi$."
The value of this new symbol is that it lets us generalize considerably: if $\Gamma$ is a set of propositions, we write "$\Gamma\models\varphi$" iff $\varphi$ is true in every model where every proposition in $\Gamma$ is true. If $\Gamma$ is infinite, this is meaningfully different from just talking about tautologies (since "$\Gamma\implies\varphi$" isn't actually a proposition).
However, one of the most important theorems in logic - the compactness theorem - states that if $\Gamma\models\varphi$ then there is some finite subset $\{\gamma_1, \gamma_2,...\gamma_n\}\subseteq\Gamma$ such that $\{\gamma_1, \gamma_2,...,\gamma_n\}\models\varphi$. And this just means that the proposition "$(\gamma_0\wedge\gamma_1\wedge...\wedge\gamma_n)\implies\varphi$" is a tautology. So via the compactness theorem we can reduce questions about the relation "$\models$" to questions about tautologies, but that's far from obvious.
(And there are important logics which don't have this property, so actually they are meaningfully different in general.)
Answer: Think of the material biconditional $\LARGE\leftrightarrow$ as a logical operation on two sentences rather than as equivalence. Unlike the latter, it is not making an assertion nor in a metalangauge.

The statement $\Large P\equiv Q$ asserts the logical equivalence of $P$ and $Q.$ It means that $\large P\leftrightarrow Q$ is a (logical) validity, i.e., is true regardless of interpretation.
What's the difference between $↔$ and $≡$ ?

The statement $\Large P {\iff} Q$ asserts the (not necessarily logical) equivalence of $P$ and $Q.$ This means that that $\large P \leftrightarrow Q$ is either analytically (in an axiom system) or synthetically true , i.e., that $P$ and $Q$ have the same truth value in the given interpretation.
$\Large P {\iff} Q$ can be read as '$P$ is true if and only if $Q$ is true' or '$P$ being true is a necessary and sufficient condition for $Q$ to be true'.

For example, the sentences $\:0=0\:$ and $\:3^2=9\:$ are mathematically but not logically equivalent.
P.S. Symbolic logic is an area rife with conflicting notation, terminology and even notions; my understanding is eclectically evolving.
Answer: Logical equivalence is typically defined using the biconditional, so that A <=> B if and only if A => B and B => A.
However, logical equivalence as so defined may differ from a mathematical equivalence. A mathematical equivalence relation defined on a certain domain is one that is 1) reflexive ( A <=> A), 2) symmetric, (if A <=> B, then B <=> A), and 3) transitive. (if A <=> B and B <=> C, then A <=> C). A mathematical equivalence relation then divides its domain into equivalence classes. As applied to propositions, these classes are typically "true", and "false".
In classical two-valued logic, these definitions coincide, so that logical equivalence is also a mathematical equivalence and does signify that two propositions have the same truth value.
In multivalued logics, with few exceptions, logical equivalence as defined by the biconditional is not a mathematical equivalence.


How to get the model name from /proc/cpuinfo in linux?

Question: I am working in C and trying to get specific information from /proc files.
I know in linux when I do the following I get the model name.
cd /proc
cat cpuinfo | grep 'model name'

but if I'm trying to do this in C it results in a core dumped
thisfile = fopen("/proc/cpuinfo | grep 'model name' ", "r");

How can I get the model name when opening a file?
Answer: fopen("/proc/cpuinfo | grep 'model name' ", "r"); will return a NULL pointer because the file /proc/cpuinfo | grep 'model name' certainly doesn't not exist
fopen allows to open a file, not to execute commands
Use popen :
FILE * fp = popen("grep 'model name'  /proc/cpuinfo", "r");

if (fp != NULL) {
  ...read in
  pclose(fp);
}

Comment: Thank you for your explanation and help!


How to get block id on block add & edit form?

Question: Blocks are plugin in Drupal-8, I need to add a form element in the block add form & all the block edit forms.
I am able to add the new form element in the form by form alter. But i need to get the block id on submit(custom submit handler). For block add forms block id has to be new block created & for block edit form, the existing block id.
How can i get the block id?
Answer: Have a lookt at Extend Block Class and my answer there about the block_class module.
It does exactly the same to add configurable CSS classes to blocks.
Comment: It supports those too. Creating custom blocks is a two-step process, you first create the block and then put it in a region, on that step you can also configure the same settings as with all other blocks.
Comment: Block class is allowing to add classes to all the existing block, but it is not adding class field to new custom block plugins. I also need to display my form element while adding as well as editing custom blocks.
Answer: Place this cistom block(php code) to seven theme under Breadcrumbs for page /admin/structure/block/manage/*
<?php
/**
* Cistom admin block for get number block numberID on edit entity.block.edit_form
*/
if( \Drupal::routeMatch()->getRouteName() == 'entity.block.edit_form' ) {
    $blockMachineName = \Drupal::token()->replace('[current-page:url:args:last]');
    $blockLoad = \Drupal\block\Entity\Block::load($blockMachineName); //dump($blockLoad);
    if($blockLoad) { //dump($blockLoad->get('id'));
        $blockIdStr = str_ireplace('block_content:', '', $blockLoad->get('settings')['id']); //print "blockIdStr: {$blockIdStr}";
        $query = \Drupal::database()->select('block_content', 'bc')->fields('bc', ['id'])->condition('bc.uuid', $blockIdStr);
        $blockIdNum = $result = $query->execute()->fetchField(); //print " blockIdNum: {$blockIdNum}"; //drupal_set_message("id: {$blockIdNum}");
        print "BlockIDs Str: {$blockIdStr} Num: {$blockIdNum}";
    }
}
?>


Cells counting problem

Question: There is a 3D grid with cells for which we define its value (0 or 1) as F(i,j,k)=F(i-1,j,k) XOR F(i,j-1,k) XOR F(i,j,k-1), base cases are F(0,0,0)=1 and F(x,y,z)=0 for x < 0 or y < 0 or z < 0 (if at least one parameter is negative).
We want to count amount of cells with F()=1 in the cube with corners (0,0,0) and (N, M, K). Dimensions are about 10^9.
I'm looking for the fast approach on this problem.
This function produces interesting picture, you may find it here.
Comment: Note that the `0`s in the ASCII representation represent `1`s and the dots represent `0`s.
Comment: The two-dimensional analogue of this problem, with squares -- how many 1-cells are there in the upper-left N-by-N square in the first slice? -- is apparently a known sequence (http://oeis.org/A064194)
Answer: First things first:
$F(i,j,k) = 1$ if and only if the pairwise bitwise-ands of $i$, $j$ and $k$ are all $0$.
Proof:
(by induction on $i + j + k$)
If $i + j + k = 0$, then $i=j=k=0$, and so the pairwise bitwise-ands of $i$, $j$ and $k$ are all $0$ and $F(i,j,k)=1$.
Suppose now that $i + j + k > 0$ and the pairwise bitwise-ands of $i$, $j$ and $k$ are all $0$. Note that not all of $i$, $j$ and $k$ are $0$. Thus at least one of $i$, $j$ and $k$ has a $1$ in its binary expansion. Since all of the $1$'s in the binary expansions of $i$, $j$ and $k$ occur in the lowest place, there is exactly one of $i$, $j$ and $k$ that has a least-significant $1$ in its binary expansion. Let us suppose that that is $i$ and that it contains a $1$ corresponding to $2^z$. Either $j = 0$, or $j-1$ will have a $1$ corresponding to $2^z$. Either way, $F(i,j-1,k) = 0$. Similarly, $F(i,j,k-1) = 0$. Finally, $i-1$ is similar to the bitwise-exclusive or of $1$ with $2^{z+1}-1$. Since this only changes bits that are not in $j$ or $k$, $F(i-1,j,k) = 1$, and so $F(i,j,k) = 1$.
Finally, suppose that $i + j + k > 0$ and that the bitwise-and of $i$ and $j$ is non-zero. Then in this case we know that $F(i,j,k-1) = 0$, and so we are just required to prove that $F(i-1,j,k) =$  $F(i,j-1,k)$. Since they are both in $\{0,1\}$, it follows that we need to show that if either of them is equal to $1$, then so is the other. To that end, let us suppose that $F(i-1,j,k) = 1$, and we will argue that $F(i,j-1,k)$ must also be equal to $1$.
Since $i$ and $j$ have at least one bit in common, but $i-1$ and $j$ do not, the least significant bit of $i$ must be equal to the least significant bit of $j$ and must be the only bit they have in common. Furthermore, $k$ must have no bits that low down. Thus it follows that $F(i,j-1,k)$ will equal $1$.
QED
Thus you are asking:
How many $0 \le i \le N, 0 \le j \le M$ and $0 \le k \le K$ have pairwise bitwise-ands equal to $0$.
Let this answer be $f(N, M, K)$.
Note that $i$, $j$, $k$ must be all even, or exactly one of them must be odd.
The number with $i, j, k$ all even is equal to $f(\lfloor N/2 \rfloor, \lfloor M/2 \rfloor, \lfloor K/2 \rfloor)$. The number with $i$ odd and $j, k$ both even is equal to $f(\lfloor (N - 1)/2 \rfloor, \lfloor M/2 \rfloor, \lfloor K/2 \rfloor)$, and so on.
Thus $$\begin{align*}f(N, M, K) &= f(\lfloor N/2 \rfloor, \lfloor M/2 \rfloor, \lfloor K/2 \rfloor)\\ &+ f(\lfloor (N - 1)/2 \rfloor, \lfloor M/2 \rfloor, \lfloor K/2 \rfloor)\\ &+ f(\lfloor N/2 \rfloor, \lfloor (M-1)/2 \rfloor, \lfloor K/2 \rfloor)\\ &+ f(\lfloor N/2 \rfloor, \lfloor M/2 \rfloor, \lfloor (K-1)/2 \rfloor).
\end{align*}$$ Using this inductive definition and caching (and stopping at $f(0,0,0) = 1$) you can calculate $f(N, M, K)$ in $O(\max(\log N, \log M, \log K))$.
Comment: The formula for $f(N,M,K)$ is off slightly: the number of even integers in $[0,n]$ is $\lceil (n+1)/2\rceil$, and the number of odd integers is $\lfloor (n+1)/2\rfloor$.

Cells counting problem


How to Convert the Cognos ReportPath () Component into Breadcrumbs?

Question: I'd like to know how to turn the Cognos ReportPath () component into breadcrumbs. For Example:
ReportPath ():
/content/folder[@name='My Department']/folder[@name='My Application']/report[@name='My Report']
Breadcrumbs:
My Department > My Application > My Report
My specific environment uses Microsoft SQL Server. Unfortunately, the Layout Calculation expression builder does not allow the replace() function. I've tried using multiple combinations of substring, position, and character_length functions to manipulate the Cognos ReportPath () component, but I cannot wrap my head around how to make this work.
Please share the method you use to turn the Cognos ReportPath () component into breadcrumbs.
Answer: There are no recursive calls in the layout expressions, which means there is no real dynamic way to do this within that realm.  The Cognos macro language on the other hand is quite good at doing this via the split and join functions, however these are only applicable to data items and prompts, not layout expressions.
If this only needed in HTML format, you could just use Javascript to grab the ReportPath via ID or divs, then manipulate it after.
If its required in excel or PDF, you would use that same Javascript to populate a value prompt, thus allowing for display and macro/data validation.
Its not pretty but it works