Left join without using left join with 3 tables

Question: I have to get all data from 3 tables with left join. I did that with and without using left join. But my teacher ask another solution that uses just inner join. I just couldn't find the solution please give some advice. Here are the tables:

And the results should look like this:

With left join solution:
SELECT O.*,C.CUST_CODE,C.CUST_NAME,P.PART_CODE,P.PART_NAME
FROM ORDERS O
LEFT OUTER JOIN PART P ON P.PART_ID = O.PART_ID
LEFT OUTER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID

Without left join solution:
SELECT O.*,
(SELECT C.CUST_CODE FROM CUSTOMER C WHERE C.CUST_ID=O.CUST_ID) AS CUST_CODE,
(SELECT C.CUST_NAME FROM CUSTOMER C WHERE C.CUST_ID=O.CUST_ID) AS CUST_NAME,
(SELECT P.PART_CODE FROM PART P WHERE P.PART_ID = O.PART_ID ) AS PART_CODE,
(SELECT P.PART_NAME FROM PART P WHERE P.PART_ID = O.PART_ID ) AS PART_NAME
FROM ORDERS O

Comment: @TimBiegeleisen Yes, but he is specifically asking for inner join.
Comment: That result cannot be done with `inner join`. That's because some of your order contain NULL values for customer or part. Are you 100% sure your teacher said **inner** join ?
Comment: This link should help you solve your problem http://stackoverflow.com/questions/7510481/how-can-i-substitute-a-left-join-in-sql
Comment: @SQLGeorge There are a handful of ways to do this without a `LEFT JOIN`.  This is what I believe the OP is asking.
Comment: @SQLGeorge Yes he wants us to use just inner join
Comment: @VladimirS. There are two tables in that question i have three tables
Comment: @OgünADSAY I gave you a possible solution below.  Essentially, you start off by taking the `INNER JOIN`, and then add back the pieces of the result set which were dropped by taking that inner product of all the tables.
Answer: Here is one approach which uses only INNER JOIN and does not use LEFT JOIN anywhere.  It begins with your original query using INNER JOIN instead of LEFT JOIN, and then adds to that result set the pieces which are missing from taking the inner product of all the tables.
SELECT t.* FROM
(
    SELECT O.ORDER_ID, O.ORDER_DATE, C.CUST_CODE, C.CUST_NAME, P.PART_CODE, P.PART_NAME
    FROM ORDERS O
    INNER JOIN PART P
        ON P.PART_ID = O.PART_ID
    INNER JOIN CUSTOMER C
        ON C.CUST_ID = O.CUST_ID
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, NULL AS CUST_CODE, NULL AS CUST_NAME, P.PART_CODE,
        P.PART_NAME
    FROM ORDERS O
    INNER JOIN PART P
        ON P.PART_ID = O.PART_ID
    WHERE O.CUST_ID NOT IN (SELECT C.CUST_ID FROM CUSTOMER C)
        OR O.CUST_ID IS NULL
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, C.CUST_CODE, C.CUST_NAME, NULL AS PART_CODE,
        NULL AS PART_NAME
    FROM ORDERS O
    INNER JOIN CUSTOMER C
        ON C.CUST_ID = O.CUST_ID
    WHERE O.PART_ID NOT IN (SELECT P.PART_ID FROM PART P)
        OR O.PART_ID IS NULL
    UNION
    SELECT O.ORDER_ID, O.ORDER_DATE, NULL AS CUST_CODE, NULL AS CUST_NAME,
        NULL AS PART_CODE, NULL AS PART_NAME
    FROM ORDERS O
    WHERE (O.CUST_ID NOT IN (SELECT C.CUST_ID FROM CUSTOMER C) AND
           O.PART_ID NOT IN (SELECT P.PART_ID FROM PART P)) OR
           (O.CUST_ID IS NULL AND O.PART_ID IS NULL)
) t
ORDER BY t.ORDER_ID ASC

Follow the link below for a working demo:
SQLFiddle
Comment: Sir before first UNION is the answer with Left Join itself. I didn't understand what did you did in here? Sorry for bad English.
Comment: @MartinSmith I began with his original query and then modified it to get the answer.  I forgot to remove the `LEFT JOIN`.
Comment: Oh dear...it's time for a Fiddle (growl)
Comment: It returns just 5 rows. It should be 9 rows
Comment: Thank you.
And I have to mention that he said it can be done with just one SELECT statement. I don't know how :)
Comment: Too bad you didn't mention this sooner, because I won't attempt another answer, as the one I gave you is working fine.
Comment: OMG. I don't know if i should give him this as a result :D
Anyway thank you so much.
Comment: @TimBiegeleisen thank you for the fiddle, I can now test and understand why my solution is not working :)
Comment: My answer is actually conceptually simple.  It basically does just an `INNER JOIN` instead of a `LEFT JOIN`, and then adds back the pieces which the `INNER JOIN` chopped off.  Try running each `SELECT` in isolation until it is clear what is being done.
Comment: @TimBiegeleisen I did not read the data correctly at first glance. I had not noticed that some customers_id and parts_id in the orders table did not exist in their respective tables... I realized it when I used your fiddle
Comment: No worries...the big challenge here was realizing that the `IS NULL` condition needed to be added to all the post `INNER JOIN` `WHERE` clauses.  Happy to be of help to you.
Answer: This makes no sense in "real life", but I understand it's meaningfulness in a SQL course. You have a good teacher.
Try like this
SELECT * FROM
(
    SELECT O.*,C.CUST_CODE,C.CUST_NAME,P.PART_CODE,P.PART_NAME
    FROM ORDERS O
    INNER JOIN PART P ON P.PART_ID = O.PART_ID
    INNER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID

    UNION

    SELECT O.*,NULL,NULL,P.PART_CODE,P.PART_NAME
    FROM ORDERS O
    INNER JOIN PART P ON P.PART_ID = O.PART_ID
    WHERE O.CUST_ID IS NULL

    UNION

    SELECT O.*,C.CUST_CODE,C.CUST_NAME,NULL, NULL
    FROM ORDERS O
    INNER JOIN CUSTOMER C ON C.CUST_ID = O.CUST_ID
    WHERE O.PART_ID IS NULL

    UNION

    SELECT O.*,NULL,NULL,NULL, NULL
    FROM ORDERS O
    WHERE O.PART_ID IS NULL AND O.CUST_ID IS NULL

)   T

ORDER BY ORDER_ID

Comment: Yeah he is the best :)
Comment: I omitted something when I posted it, I edited it 30 seconds  later. Have you tried the latest version? And what is not working ?
Comment: Nope, sorryMsg 156, Level 15, State 1, Line 23
Incorrect syntax near the keyword 'ORDER'.
Comment: its, not it's -- please ;)
Comment: Sorry still not working. I think we can't write SELECT in FROM,
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near ')'.
Comment: Godamn, it should work! Try to remove the main query `SELECT * FROM () ORDER BY` to keep only the 3 nested queries, that's the most important
Comment: I know it seems it should be working but not working I've tried all this.
I did that too removed SELECT * FROM () ORDER BY but it only gives 6 rows 7th,8th and 9th rows are missing
Comment: Thank you for the effort. And I have to mention that he said it can be done with just one SELECT statement. I dont know how :D
Comment: ah I missed that. I still have adapted my query. I'll think to another approach, it's fun. But it's not fun to be downvoted...
Comment: I didn't downvoted. I never downvote anybody :) Just upvoted for the effort  :)
Comment: ok with the fiddle posted by Tim it's easy to understand what's not working with my query: I had not seen that some customers and parts referenced in order table, don't exists in their respective tables.


Uncaught error while generating qrcode with "endroid/qr-code" library

Question: I am creating a qr-code generator program with PHP, and I am using a library called qr-code. I have gotten to the point where I have successfully gotten the string the user wishes to convert into a qrcode, at the point to generate the qrcode I get the following error :
Uncaught Error: Call to a member function getContentType() on null in index.php:13 Stack trace: #0 {main} thrown in index.php on line 13

I have been at this for a while now, and I am stuck. There is really now in-depth documentation for the library in question, Please help me out. Here is my code :
<?php
require __DIR__ . '/vendor/autoload.php';

use Endroid\QrCode\QrCode;

// Get url from form
if (isset($_GET['submit'])) {
  $url = strval($_GET['url']);
  echo gettype($url);
  $qrcode = new QrCode("$url");
  echo "
";
  header('Contert-Type: application/' . $qrCode->getContentType());
  $createCode = $qrCode->writeString();
}

?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="description" content="" />
    <title>QR Code Generator</title>

    <link rel="stylesheet" href="./bootstrap.min.css" />

      QR Code Generator

        <form method="GET" action="<? htmlspecialchars($_SERVER['PHP_SELF']);?>">

            URL
            <input type="text" class="form-control" id="url" name="url" />

          <button type="submit" name="submit" class="btn btn-danger">Generate</button>
        </form>

                <?php echo $createCode;?>

Here is a link to the library
Answer: You are trying to use $qrCode which does not exist, look at your code carefully:
  $qrcode = new QrCode("$url");
  echo "
";
  header('Contert-Type: application/' . $qrCode->getContentType());
  $createCode = $qrCode->writeString();

First you use $qrcode then you use $qrCode (which does not exist).
Change the first line to:
$qrCode = new QrCode("$url");


Entity Framework overwrites a foreign key from another record

Question: This is just an example so you can understand, this is a system with people and their favorite books.
This is what the models look like:
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Book> favBooks { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PageCount { get; set; }
}

My problem is if I add a book and 2 people and both have this as a FAV book, then one person is overwritten.
Book mathForDummies = new Book()
{
     Name = "Math for Dummies",
     PageCount = 457
};

_db.book.Add(mathForDummies);
_db.SaveChanges();

Person lena = new Person()
{
     Name = "Lena",
     favBooks = new List<Book>
     {
          mathForDummies
     }
};

Person max = new Person()
{
     Name = "Max",
     favBooks = new List<Book>
     {
          mathForDummies
     }
};

_db.person.Add(lena);
_db.person.Add(max);

_db.SaveChanges();

In this case, both have this book, but max overwrites lena.

Is there a better way, or am I overlooking something?
Answer: Your problem is not with Entity Framework itself, but with your database schema: your list is a n-to-one (or many-to-one) relationship and you need a n-to-n (or many-to-many).
Since book table has only one PersonId column (maybe it has a different name), each book can only be associated with one person at a time. To create a n-to-n relationship, you'll need a join table (that have BookId and PersonId columns).
Look this link to see how to configure it.
Comment: Yes, I realize that about the relationship. And the database (schema) was generated by EF. What also surprises me. But I'll have a look at your link, I'll get back to you later if necessary.
Comment: Yes, I have one more question. Do you know randomly. Which include or so I have to use so that my book is not a null?

https://prnt.sc/MYkFXBqHPV5Z
Comment: @Schecher_1, you can configure the schema generated by EF using the Fluent API. One way to set a column as not null is through the `OnModelCreating` method of your `DbContext`. See more on https://www.learnentityframeworkcore.com/configuration/fluent-api/isrequired-method.


Dados referente a imagens ficando repetidos ao ler XML

Question: Estou tentando buscar dados de imagens de um xml mas estou tendo dificuldade em faze-lo, o registro que estou lendo está sendo sobreposto.
Fiz um primeiro foreach e consigo buscar a data que preciso, mas preciso agora entrar um nível a mais para buscar dados de algumas imagens e não estou conseguindo, o código até busca o primeiro registro de forma correta mas na sequência ocorre essa sobreposição.
O código que tenho é esse:

require_once ('../Connections/conn.php');

mysql_select_db($database_conn, $conn);
$query_rcCidades = "SELECT * FROM PrevisaoCidade WHERE PrevisaoCidade.ativo = 1 ORDER BY PrevisaoCidade.IdCidade";
$rcCidades = mysql_query($query_rcCidades, $conn) or die(mysql_error());
$row_rcCidades = mysql_fetch_assoc($rcCidades);
$totalRows_rcCidades = mysql_num_rows($rcCidades);

do {

    // CIDADES CADASTRADAS
    $cCidades = 6683;

    $urlIcon = 'http://api.climatempo.com.br/api/v1/forecast/15days/icon?idlocale="'.$cCidades.'"';

    // PERMISSÃO
    $post = array(
        'key' => '', // chave de pedido
        'client' => '', // login do cliente
        'nocache' => true, // desabilitar cache
        'type' => 'xml', // tipo de retorno json ou xml
        'application' => 'Previsão 15 dias - Cidades'
    );

    // OBTENDO PERMISSÃO
    $http = array(
        'method' => 'POST',
        'header' => 'Content-type: application/x-www-form-urlencoded',
        'content' => http_build_query($post)
    );

    $context = stream_context_create(array('http' => $http));

    // ÍCONE
    $request = file_get_contents($urlIcon, true, $context);
    $itemIcone =  simplexml_load_string($request);

    // SELECIONANDO ÍCONE
    $IcoManha = null;
    $IcoTarde = null;
    $IcoNoite = null;
    $IcoDia = null;

    // A VARIÁVEL $ItemIcone CONTÉM O XML CARREGADO
    foreach($itemIcone->data->item->weather->item as $reg) {

        // ZERANDO O ARRAY
        $data = array();

            // ÍCONES
            $data['api']['data']['item']['weather']['item'][] = array
            (
                // LENDO OS NÓS
                'date' => (string)$reg['date'],

            );

            $Data = $data['api']['data']['item']['weather']['item'][0]['date'];

            // SEGUNDO FOREACH PARA BUSCAR AS IMAGENS
            // A VARIÁVEL $ItemIcone CONTÉM O XML CARREGADO
            foreach($itemIcone->data->item->weather->item->icon as $regs) {

                $dataIcon = array();

                $dataIcon['api']['data']['item']['weather']['item']['icon'][] = array
                (
                    // LENDO OS NÓS
                    'morning' => (string)$regs['morning'],
                    'afternoon' => (string)$regs['afternoon'],
                    'night' => (string)$regs['night'],
                    'day' => (string)$regs['day'],

                );

                // ATRIBUINDO AS VARIÁVEIS
                $IcoManha = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['morning'];
                $IcoTarde = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['afternoon'];
                $IcoNoite = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['night'];
                $IcoDia   = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['day'];

            }

            echo "DATA: " . $Data . " MANHA:" . $IcoManha . " TARDE: " . $IcoTarde . " NOITE: " . $IcoNoite . " DIA: " . $IcoDia . "";

            // echo "DATA: " . $Data . "MANHA:" . $IcoManha . " TARDE: " . $IcoTarde . " NOITE: " . $IcoNoite . " DIA: " . $IcoDia . "";
            }

} while ($row_rcCidades = mysql_fetch_assoc($rcCidades));

O xml é esse:
A visualização do tentativa resulta nisso:
Comment: estava errado a minha resposta, então alterei o código
Answer: Na verdade eles não estão se repetindo ou se sobrepondo, você que está alterando o valor para que ele seja SEMPRE o mesmo, graças ao segundo foreach. Para você entender melhor faça esse teste:

    echo "DATA: ". $Data; // coloquei o echo antes do segundo foreach.

    // SEGUNDO FOREACH PARA BUSCAR AS IMAGENS
    // A VARIÁVEL $ItemIcone CONTÉM O XML CARREGADO
    foreach($itemIcone->data->item->weather->item->icon as $regs) {

        $dataIcon = array();

        $dataIcon['api']['data']['item']['weather']['item']['icon'][] = array
        (
            // LENDO OS NÓS
            'morning' => (string)$regs['morning'],
            'afternoon' => (string)$regs['afternoon'],
            'night' => (string)$regs['night'],
            'day' => (string)$regs['day'],

        );

        // ATRIBUINDO AS VARIÁVEIS
        $IcoManha = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['morning'];
        $IcoTarde = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['afternoon'];
        $IcoNoite = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['night'];
        $IcoDia   = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['day'];

        echo " MANHA:" . $IcoManha . " TARDE: " . $IcoTarde . " NOITE: " . $IcoNoite . " DIA: " . $IcoDia . "";  // o echo fica dentro do foreach

    }

Não fiz o teste, mas agora, provavelmente, ele lançou vários registros com datas repetidas, certo? Isso você também não quer.
SOLUÇÃO (sugestão)
$dadosData = array(); // array que vamos usar para data
$dadosImg = array(); // array que vamos usar para iagens

// A VARIÁVEL $ItemIcone CONTÉM O XML CARREGADO
foreach($itemIcone->data->item->weather->item as $reg) {

    // ZERANDO O ARRAY
    $data = array();

    // ÍCONES
    $data['api']['data']['item']['weather']['item'][] = array
    (
        // LENDO OS NÓS
        'date' => (string)$reg['date'],

    );

    $Data = $data['api']['data']['item']['weather']['item'][0]['date'];

    $dadosData[] = "DATA: ". $Data; // aqui vão sendo inseridos os valores da data

    // SEGUNDO FOREACH PARA BUSCAR AS IMAGENS
    // A VARIÁVEL $ItemIcone CONTÉM O XML CARREGADO
    foreach($reg -> icon as $regs) {

        $dataIcon = array();

        $dataIcon['api']['data']['item']['weather']['item']['icon'][] = array
        (
            // LENDO OS NÓS
            'morning' => (string)$regs['morning'],
            'afternoon' => (string)$regs['afternoon'],
            'night' => (string)$regs['night'],
            'day' => (string)$regs['day'],

        );

        // ATRIBUINDO AS VARIÁVEIS
        $IcoManha = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['morning'];
        $IcoTarde = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['afternoon'];
        $IcoNoite = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['night'];
        $IcoDia   = $dataIcon['api']['data']['item']['weather']['item']['icon'][0]['day'];

        $dadosImg[] = "MANHA:" . $IcoManha . " TARDE: " . $IcoTarde . " NOITE: " . $IcoNoite . " DIA: " . $IcoDia . "";  // insere os valores das imagens

    }

}

// loop para resgatar os valores

for($x = 0; $x < count($arrayData); $x++){

    echo $dadosData[$x].$dadosImg[$x]; // mostra todos os valores

}

Comentários do Código:
Esse código está dentro do loop do, eu setei o valor do primeiro foreach para o segundo e lancei os valores resgatados nos arrays, depois fiz um loop for fora do foreache imprimi essas variáveis.
Comment: Olá @Andrei Coelho, muito obrigado pelas excelentes dicas, me ajudou demais, sou grato pela qualidade do código.
Comment: @adventistapr tranquilo, fico feliz em poder ajudar.


Debugging a Delphi project EXE locally

Question: I have an EXE produced by the D2006 compiler and associated RSM and MAP files in the same folder as the EXE.  The files are local to the machine Delphi is installed on.  I can start the IDE and "Load Process" the EXE and run it but I can't see any symbolic information if I pause execution.
What do I have to do to see procedure names, etc as labels in the disassembly, and be able to 'GoTo' an address by specifying the routine name?
If I have the source available in the same folder, can I do high-level stepping, etc?
Comment: AFAIK, this won't work. Delphi uses debug info located in the .dcu files to debug. You might be able to do it using "Remote Debugging" with the .rsm symbols, but not by loading the process directly through the IDE's debugger, and I think you still need the .dcu files locally to do it using the remote debugger. You have the application's source code (you said "source available in the same folder"). Why not load the project in the IDE and debug as normal?
Comment: Thanks @Ken.  When I deploy an executable and save the executable, MAP and RSM files, and source set at that time.  If I get an error in a previous build in the field, I figured I could restore that file set to a temporary folder, load the EXE and use the IDE to debug the code at the source level.  What you are saying is that I would need to save the DCU files also.  While I could load that file set in the IDE and debug it, I would have the problem that some of the library routines used will have "moved on". Maybe the answer is to use the remote debugger instead (which I have never used).
Comment: and yes, I know that a version control system would let me do this....
Answer: To debug my delphi apps I use madExcept, is a very nice tool, and easy to setup for your projects, here go some info about it.
"madExcept was built to help you locating crashes in your software. Whenever there's a crash/exception in your program, madExcept will automatically catch it, analyze it, collect lots of useful information, and give the end user the possibility to send you a full bug report."
http://madshi.net/madExceptDescription.htm
Comment: This doesn't answer the question asked, which is how to debug an *already built executable*. madExcept is an exception handling product, but has to be compiled into the application in the first place. It's not a *debugger*, and doesn't do remote symbol debugging. (It is a fantastic exception handling package, however.) Please read the question again. If you want to recommend madExcept, it should be as a comment to the original question instead; it's not an answer.

Debugging a Delphi project EXE locally


Feel lost in the scheme of the reducibility of polynomials over $\Bbb Z$ or $\Bbb Q$

Question: I'm studying abstract algebra. I have learned Eisenstein criterion, rational root test, Guass's lemma and so on. However, I can't see the scheme and the whole picture that these things plays the roles in. I think I should better directly ask here. I don't know where to start asking, so I list some questions below. Hope you can see what I'm stucking in. Need to be given the direction.

Is the ultimate target here is that we want to tell whether a polynomial can be factored over $\Bbb Z$, or over $\Bbb Q$, or over $\Bbb R$, or over $\Bbb C$?
Which do we really care about in the factorization? Integer coefficients polynomials, or rational coefficients? Or both?
Is it a standard produre that whenever dealing with the (ir)reducibility problem of a polynomial of rational coefficients, we turn it into integer coefficient first? Why? Or is it vice versa?
What is the importance or usage of Gauss's lemma?
How about reducibility over $\Bbb R$ or $\Bbb C$ when there're no many tools can be used as in the $\Bbb Q[x]$?
Comment: What we care about really depends on what problem we are trying to solve. I understand how you feel: it often happens that one is given a lot of mathematical instruments (theorems) without knowing why he should care or what he should do with them. But don't desist: these theorems do have applications (the best way to see it is to find some nice, interesting exercises, which is not always easy to do, above all at the beginning). Note that if a polynomial factors over $\mathbb{Z}$, it also factors over all the rings that contain $\mathbb{Z}$. So the other one is the direction you usually want.
Comment: A polynomial (with coefficients in $\Bbb C$) can **always** be decomposed into linear factors in $\Bbb C$, as $\Bbb C$ is an algebraically closed field.
Comment: Before I meant: "factors over $\mathbb{Z}$ with factors that are not just constants".
Answer: Warning: my bullet points are not isomorphic to yours!

If a polynomial factors over a smaller field, then it also factors in the bigger ones above (for general rings, this is more tricky: $ax^2+a$ factors over $\mathbb{Z}$ as $a(x^2+1)$ for all $a\neq 0,\pm1$ (since $a$ is not a unit), but in $\mathbb{R}$ it is irreducible, because $a$ is a unit). Also, if a polynomial has a zero in a smaller ring, then it also has (the same) zero in the bigger rings above.
Being irreducible doesn't coincide with having no zeros, in general. For example, $(x^2+1)(x^2+1)$ is reducible over anything, but it doesn't have a zero in $\mathbb{R}$. Conversely, $x$ is always irreducible but it always has a zero. Nevertheless, the two things are related: for instance, if $F$ is a field and $P(x) \in F[x]$ is a polynomial with degree greater than one that has a zero in $F$, then $P$ is reducible (this comes from division with remainder of polynomials).
Integers are also rational numbers. So integer coefficient polynomials are also rational coefficient polynomials. But it is also true that a polynomial with rational coefficients is just a rational multiple of a polynomial with integer coefficients (just clear the denominators), and their zeros coincide (and the zeros are usually the most interesting thing). Irreducibility over $\mathbb{Q}$ implies irreducibility over $\mathbb{Z}$, if the polynomial is primitive. One does not immediately see why the converse should be true, but it is, by Gauss lemma! So irreducibility over $\mathbb{Z}$ and $\mathbb{Q}$ is the same for primitive polynomials. Why do we consider only primitive polynomials? For the reason mentioned above: if you can divide the polynomial by some integer $a\neq 0,\pm 1$, then it is reducible over $\mathbb{Z}$, but not necessarily over $\mathbb{Q}$. But since roots don't depend on a division by a constant factor $a$, note that Gauss lemma implies that a polynomial with integer coefficients and degree greater than one has an integer root if and only if it has a rational root! That's amazing!
What I find very helpful is to always see any (complex) polynomial of degree $n$ as $u(x-\alpha_1)\dots(x-\alpha_n)$, where $u$ is some complex number and the $\alpha_i$ are the roots (not necessarily distinct). This is always possible, since $\mathbb{C}$ is algebraically close (maybe you have not learnt it yet, but it is true and there are many very beautiful proofs of this fact).
It is easier to check irreducibility in $\mathbb{Z}$ than in $\mathbb{Q}$, that's why you often do so.
As I already said, polynomials over $\mathbb{C}$ always have a very easy form. In $\mathbb{R}$ you have that irreducible polynomials always have degree at most $2$. This comes from the fact that if $\alpha$ is a complex root of some real polynomial, then also $\overline{\alpha}$ is (why?). So let $P$ be any real polynomial that has at least a non-real root. Then it is divisible by $(x-\alpha)(x-\overline{\alpha})=x^2 + |\alpha|^2-2xRe(\alpha)$, which is a real polynomial. In particular, if it has degree at least $3$, it is not irreducible.

Many things will become clearer when you will do some field theory: there irreducibility of polynomials becomes very important. Also at this stage, doing some exercises involving irreducibility criteria will certainly clarify things.
Comment: @Eric It is actually more interesting to see when a polynomial factors over $\mathbb{Z}$ or $\mathbb{Q}$, because it is harder than for $\mathbb{R}$ or $\mathbb{C}$ (there the theory of polynomials is easier). But of course, it depends on what you are doing. Number theory is often concerned with integers and rationals, analysis just does not care and only wants real or complex things (very badly said)
Comment: Every complex polynomial of degree at least $2$ factors over $\mathbb{C}$ and every real polynomial of degree at least $3$ factors over $\mathbb{R}$
Comment: Thanks. This is very helpful! Still digesting. Since I find that you're online now, I want to ask a little question. Can I say that, it may be not interesting to study whether a polynomial factors over "$\Bbb Z$" in the practical problem (since $\Bbb Z$ is too "small", and studying its reducibility over fields like $\Bbb Q,~\Bbb R,~\Bbb C$ is more useful, from our experience in high school algebra), however, studying whether it factors over $\Bbb Q$ turns out to be somewhat reduce to the problem that whether it factors over "$\Bbb Z$"?
Comment: I see. I'm not sure I understand the third bullet. First let me check a little point that in the sentence "*Irreducibility over $\Bbb Q$ implies irreducibility over $\Bbb Z$, if the polynomial is primitive.*"  I think you mean "for **an integer coefficient** polynomial $f(x)$, suppose $f(x)$ is primitive, then $f(x)$ is irreducible over $\Bbb Q$ iff $f(x)$ is irreducible over $\Bbb Z$" right? (By the standard definition,) we cannot talk about whether, say $\frac{1}{3}x^2+1$ is primitive, so when we say a polynomial is primitive, we implicity require that it is of integer coefficient?
Comment: Exactly. Let's suppose $f$ is primitive (with integers coefficients, but it is superfluous to say it, it is implicit). Then if it factors over $\mathbb{Z}$ it clearly also factors over $\mathbb{Q}$ (since the two factors must have degree at least 1 (otherwise $f$ would not be primitive), so they are not constants). The other direction is implied by the Gauss lemma (I am not sure which version you had).
Comment: Yes, I'm also thinking about your words about Gauss lemma. :P The Gauss lemma I have is "the product of two primitive polynomials is primitive." And I have its collary: "If a integer coefficients polynomial $f(x)$ is reducible over $\Bbb Q$, then it is reducible over $\Bbb Z$." Fortunately, I can understand the proofs of them. However, is this direction (being reducible over $\Bbb Q\Rightarrow$ being reducible over $\Bbb Z$) useful in practice? I can't imagine ...
Comment: ... the case that it is more easy for us to check whether a polynomial factors over $\Bbb Q$ than factors over $\Bbb Z$ (I *roughly* guess that this is one reason we need Eisenstein criterion for irreducibility over $\Bbb Q$?). Hmm... maybe you had already answered in the post, but I need to think more about it.
Comment: What we use in practice now is exactly the corollary you mentioned. It is useful because to check irreducibility over $\mathbb{Z}$ is easier than over $\mathbb{Q}$, in general, since there are only finitely many ways in which you can write an integer as a product of other integers. For instance, you see that $x^2+3x+1$ is irreducible over $\mathbb{Z}$ because otherwise it would be of the form $(x-a)(x-b)$ and the integers $a$ and $b$ would satisfy $ab=1, a+b=-3$, which is clearly not possible for integers. Also, you use Gauss lemma to prove the Eisenstein criterion, I think.
Comment: Note: "irreducible over $\mathbb{Z} \ \Rightarrow \ $ irreducible over $\mathbb{Q}$" is equivalent to "reducible over $\mathbb{Q} \ \Rightarrow \ $ reducible over $\mathbb{Z}$"
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/71642/discussion-between-57jimmy-and-eric).
Answer: What we really care about depends, as always, on our viewpoint, i.e., on the problems we want to solve. In number theory, polynomials with integer and rational coefficients are very interesting, and finding roots is a famous, old question going back to "Diophantos". To solve Diophantine equations, like $x^n+y^n=z^n$, we need at least some algebraic number theory, e.g., the ring of integers of the cyclotomic field $\mathbb{Q}(\zeta_n)$. For Dedekind rings, and commutative rings in general, we need the basics from commutative algebra, e.g., irreducible and prime elements, respectively ideals. So one reason to study this, comes from this motivation. Cyclotomic fields are very important examples of number fields, and cyclotomic polynomials very important examples of irreducible polynomials, you were asking about. The name of Gauss appearing in this context, is directing towards number theory, I would say:)
Answer: Here is one story: not the only one, but a very common one.
Often we are interested in the factorisation of a polynomial $f\in\mathbb{Q}[X]$.
Multiplying by any $c\in\mathbb{Q}$ doesn't change anything, so we can clear the fractions and suppose $f\in\mathbb{Z}[X]$, although we are still interested in factorisations in $\mathbb{Q}[X]$.
Gauss's Lemma tells us how factorisations in $\mathbb{Q}[X]$ relate to factorisations in $\mathbb{Z}[X]$, so our focus moves to such factorisations.
Now Eisenstein's Criterion (and the ideas behind it) relate the factorisations of $f\in\mathbb{Z}[X]$ in $\mathbb{Z}[X]$ with the factorisations of $\bar{f}\in\mathbb{Z}_p[X]$ in $\mathbb{Z}_p[X]$, a potentially "easier" problem.


Why is off-centered prior necessary for HMC sampler?

Question: In this PyMC3 tutorial on Bayesian Mixed Effects Models, there is some Re-parameterization "to avoid chain divergences."
with pm.Model(coords=coords) as hierarchical:
    # Hyperpriors
    intercept_mu = pm.Normal("intercept_mu", 0, sigma=1)
    intercept_sigma = pm.HalfCauchy("intercept_sigma", beta=2)
    slope_mu = pm.Normal("slope_mu", 0, sigma=1)
    slope_sigma = pm.HalfCauchy("slope_sigma", beta=2)

    # Define priors
    sigma = pm.HalfCauchy("sigma", beta=2, dims="group")

    # Reparameterise to avoid chain divergences
    # β0 = pm.Normal("β0", intercept_mu, sigma=intercept_sigma, dims="group")
    β0_offset = pm.Normal("β0_offset", 0, sigma=1, dims="group")
    β0 = pm.Deterministic("β0", intercept_mu + β0_offset * intercept_sigma, dims="group")

    # Reparameterise to avoid chain divergences
    # β1 = pm.Normal("β1", slope_mu, sigma=slope_sigma, dims="group")
    β1_offset = pm.Normal("β1_offset", 0, sigma=1, dims="group")
    β1 = pm.Deterministic("β1", slope_mu + β1_offset * slope_sigma, dims="group")

    # Data
    x = pm.Data("x", data.x, dims="observation")
    g = pm.Data("g", data.group_idx, dims="observation")
    # Linear model
    μ = pm.Deterministic("μ", β0[g] + β1[g] * x, dims="observation")
    # Define likelihood
    pm.Normal("y", mu=μ, sigma=sigma[g], observed=data.y, dims="observation")

Consider that β1 = pm.Normal("β1", slope_mu, sigma=slope_sigma, dims="group") was swapped out for the below:
β1_offset = pm.Normal("β1_offset", 0, sigma=1, dims="group")
    β1 = pm.Deterministic("β1", slope_mu + β1_offset * slope_sigma, dims="group")

Why is this necessary and what does it accomplish?
Edit: I see the comment link to Stan forum, is there a slightly more concise/higher level explanation available?
I understand that HMC doesn't do well with high curvature areas; but why is multiplying the slope by an additional Normally distributed random variable helpful?
Comment: The Stan team has produced quite a lot of good materials on the topic, e.g. https://mc-stan.org/users/documentation/case-studies/divergences_and_bias.html
Comment: See also [Neals Funnel](https://mc-stan.org/docs/2_29/stan-users-guide/reparameterization.html) from the Stan documentation.
Answer: The explanation below is based on Statistical Rethinking, 2nd edition, pages 420-423.

As you well say, samplers have issues exploring high curvature areas. A re-parametrization is a way to change the area that is being explored.
Consider a funnel made from the following parametrization:
$$
\begin{aligned}
v &\sim \operatorname{Normal}(0, 3) \\
x &\sim \operatorname{Normal}(0, \exp(v))
\end{aligned}
$$
Where does the funnel come from? Half the values of $v$ will be negative, and for negative numbers $\exp(v) < 1$. So we know that $x$ will be centered around 0, with a quite small variance. For half the other values of $v$, $\exp(v)$ will not only be larger than 1, it will grow—literally—exponentially. Hence, a funnel arises: increasingly more concentrated values of $x$ for more negative values of $y$, increasingly more spread values of $x$ for more positive values of $y$
Consider a reparametrization now, as follows:
$$
\begin{aligned}
v &\sim \operatorname{Normal}(0, 3) \\
z &\sim \operatorname{Normal}(0, 1) \\
x &= z \exp(v)
\end{aligned}
$$
Where did the funnel go? We are no longer sampling $x$, but a standard normal variable $z$. Gladly, multiplying a normally distributed variable by a constant, changes its scale (or variance). Hence we can get our desired $x$ by multiplying $z$ by the exponentiated $v$. This step is a deterministic one, there is no probability involved, so there is no need for the sampler to explore anything here. We see that the sampler now just has to explore normal distributions, which have straightforward curvatures. The joint distribution of both $v$ and $z$ will now just be a multivariate normal, which has nothing pointy or weird going on.


Finding formula from given table

Question: I'm sucks at finding formula, can you guys help me? As we can see below, there is a table with x, y, z, and i values. My question, what is formula to get the value of i, if the values of x, y, z are given?

x
y
z
i

1
275
50
137,50

2
275
50
206,25

5
275
50
247,50

I thought the formula as simple as

y-(y*(z/100))

but the formula only apply for first row data, looks like it should involve x value somewhere,  I don't know how
Comment: This is far too little data. For example, we cannot determine the role of $y,z$ in the formula since their values in the 3 data are the same.
Answer: I think your math teacher was trying to be too clever. The simplest formula is just:
$137.50 * (1+\frac{x-1}{x})$
No need to use $y$ or $z$.
Comment: thanks, I have enlightenment

i = (y-(y*(z/100)))*(1+((x-1)/x))

Finding formula from given table


Jquery delete row with ajax call

Question: I have the following function that deletes an entire row:
<code>$(".deleteTR").click(function(e){

    if (confirm("Are you sure you want to delete this entry?")) {
        $(this).closest('tr').remove();
    }

    return false;
})
</code>
I want to go to the controller where the delete function is placed, I tried to use this ajax call but it is not working and it doesn't go to the controller:
<code>$.ajax({
  type: "POST",
  url: '@Url.Action("Delete", "Application")',
  data: JSON.stringify(app),
  dataType: "json",
  contentType: "application/json",
  cache: false,
  success: function(data) {
    //show content
    alert('success')
  },
});
</code>
The controller method:
<code>//Post
    [HttpPost, ActionName("DeletePack")]
    [ValidateAntiForgeryToken]
    public ActionResult DeletePackageConfirmed (int id)
    {
        Package package = db.Packages.Find(id);

        db.Packages.Remove(package);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
</code>
Comment: Where this code is placed? in a separate `js` file? Check for any console errors..
Comment: I mean, is this in a `js` file or `.cshtml` file??
Comment: Can you show your Controller method? Are there any browser console errors?
Comment: yes,  http://localhost/DeploymentApp/Application/DeletePack 500 (Internal Server Error)
Comment: btw I edited the code and added the controller method
Comment: You have internal server error.. Did you place a debugger in VS and checked where it is erroring out in controller method?
Comment: Thanks for this info I tried another solution and it's working now
Comment: You can post it as answer so that it will help others..
Comment: I tried another way and changed the whole function
Answer: Please Try this code :
<code>      $(".deleteTR").click(function(e) {

        if (confirm("Are you sure you want to delete this entry?")) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Delete", "Application")',
            data:  JSON.stringify( app),
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (data) {
                $(this).closest('tr').remove();
                alert ('success')
            },

        });

        }

        return false;
    })
</code>
Comment: Same thing, it doesn't go to the controller

Jquery delete row with ajax call


Preprocessing twig templates

Question: I currently have two templates, one of which is page.html.twig, which is the main page and I can preprocess with MYTHEME_preprocess_page(). MYTHEME_preprocess_page() affects all the other pages in different modules.
The other template is _carousel.html.twig (theme/templates/includes/_carousel), which I include into page.html.twig, but I cannot hook into it with MYTHEME_preprocess__carousel().
Is this the default behavior, or am I missing something?
Comment: Yes, preprocess_page affects all pages, because that is the rendering stack. HTML, Page, Region, blocks, etc. Its hard to tell what you are trying to do here without more information.
Comment: @Kevin I guess the question is why `MYTHEME_preprocess__carousel()` cannot be used for a template file that is included into another template file.
Comment: Hey @Kevin, sorry for not answering earlier. What i'm trying to do is more of a reusable component approach. Since i need the same carousel on another page, I want to fetch the data only when it's included, not on every page.
Answer: hook_preprocess_page() is invoked for every page Drupal renders. That's why it needs to check for which page is invoked, if it really needs to preprocess specific pages.
A preprocess hook isn't invoked for template files that are included from other template files.
For both the cases, the answer is yes, that is default, expected behavior.

Preprocessing twig templates


Clique numbers and Theorem 4.5.1 in "The Probabilistic Method" by Alon and Spencer

Question:
My question is "What is the precise formulation of the following theorem from Alon and Spencer's book The Probabilistic Method?"

For context,

Let $G(n,1/2)$ be the probability space of random graphs where edges are chosen uniformly and independently with probability $1/2$.
The quantity $f(k)$ is the expected number of cliques of size $k$ amongst elements of $G(n,1/2)$, i.e. $f(k) = {n \choose k}2^{-{k\choose 2}}$.
The authors note that if $k \sim 2\log_2n$, then the function $f(k)$ "drops under one," whatever that means, and $f(k)$ is "very roughly like $n^k2^{-k^2/2}$," whatever that means.
If $G$ is a graph, let $\omega(G)$ be the size of the largest clique in $G$, (i.e. the size of the vertex set corresponding to the largest complete subgraph of $G$).

Here's the theorem:

Theorem 4.5.1 Let $k = k(n)$ satisfy $k \sim 2\log_2n$ and $f(k) \to \infty$. Then almost always $\omega(G) \ge k$.

What I (think I) understand already:

$k\sim 2\log_2n$ means $k(n)/2\log_2n\to 1$ as $n\to\infty$.
"almost always $\omega(G)\ge k$" means that for each $\epsilon > 0$ there is an $N = N(\epsilon)$ such that if $n\ge N$ then for any $G(n,1/2)$, the probability of the event $\{\text{$G\in G(n,1/2)$ satisfies $\omega(G)\ge k$}\}$ is greater than $1-\epsilon$.

What I do not understand:

How can we assume that $f(k)\to \infty$ as $n\to\infty$ if we assume that $k\sim 2\log_2n$? By point 3 above in the context I gave, assuming that $k\sim 2\log_2n$ means "$f(k)$ drops under one," so how can $f(k)$ also go to infinity? (Based on this point, an appropriate answer to my question will have to address what is being said precisely in point 3 from the context.)

Many thanks.
Answer: A more precise statement of the theorem would be

Let $k(n)$ be a function of $n$ such that $k(n) \sim 2 \log_2 n$ as $n \to \infty$ (that is, $\lim\limits_{n \to \infty} \frac{k(n)}{2 \log_2 n} = 1 )$ and $f(k(n)) \to \infty$ as $n \to \infty$. Then $$\lim_{n \to \infty} \left(\Pr[\omega(G) \ge k(n)]\right) = 1$$ where $G$ has the $G(n,\tfrac12)$ distribution.

So you seem to understand the theorem correctly.
To clarify the statement that seems to be confusing you: saying

The function $f(k)$ drops under one at $k \sim 2 \log_2 n$

means that if we let $k^*(n)$ be the least value $k$ (for a fixed value of $n$) such that $f(k) < 1$, then $k^*(n) \sim 2 \log_2 n$.
There are lots of functions $k(n)$ satisfying $k(n) \sim 2 \log_2 n$. Some of them will satisfy $f(k(n)) < 1$ for all $n$, and some others will have $f(k(n)) \to \infty$ as $n \to \infty$. In fact, for $k$ in this range, $f(k)$ changes so rapidly that we can define a function $k(n)$ with $f(k(n)+1) \to \infty$ as $n\to\infty$ and yet $f(k(n)-1) \to 0$ as $n\to\infty$. The theorem requires that we pick a "going-to-$\infty$" kind of $k$.
Also, the statement

$f(k)$ is very roughly like $n^k 2^{-k^2/2}$

is, just as it says, a very rough asymptotic estimate: it's not accurate to within a $1+o(1)$ factor or even to within a constant factor, but it's close to the truth. More precisely, going from $\binom nk$ to $n^k$ and from $2^{-\binom k2}$ to $2^{-k^2/2}$ both drop a factor which is an exponential function of $k$: much less significant than either of the factors we keep.
We could make the statement precise by saying something like $\log f(k) \sim \log (n^k 2^{-k^2})$ if $k \sim 2 \log_2 n$ (both as $n \to \infty$), but that's missing the point: the reason we make this estimate is to get a rough idea of how big $f(k)$ is before we analyze it more precisely.
Comment: Your "almost always" is equivalent to my "almost always" - I just wanted to be consistent and use the language of limits everywhere it applies. $G(n,1/2)$ is a probability distribution in my view since it assigns a probability to each value of $G$.
Comment: Thanks very much, I think this clears it up. Could you explain the notation $\text{Pr}_{G\sim G(n,1/2)}[...]$? Also, could you give an example of some function $k$ that has the property $f(k)\to \infty$?
Comment: I use $Pr_{X \sim D}[\dots]$ to denote a probability with respect to a random variable $X$ following distribution $D$. As for an example of a function $k$ with this property, Mathematica's `Limit` command tells me that $k = 2\log_2 n - \sqrt{\log_2 n}$ works.
Comment: I am not very familiar with distributions. Is my interpretation of the "almost always" bit equivalent to what you are saying about distributions? Thanks again. I'm not really sure what $G$ is when you say "where $G$ has the $G(n,1/2)$ distribution".


Any alternatives to the Gmail mobile CSS and JavaScript framework?

Question: Does anyone know what CSS and JavaScript API the Gmail mobile app uses?  It looks very neat and clean from my phone.  Are there any similar frameworks that gives you such a neat and clean look?  I had a look at the jQuery mobile API, also looks good.
Comment: Seems like a no brainer to me, companies like Google have their own internally developed CSS and Javascript api...
Comment: I'm looking for a similar framework for my mobile app.
Comment: This is as close as you're going to find: http://www.sencha.com/products/touch/
Comment: Is built over the Google Closure Library. Check this out https://developers.google.com/closure/library/
Answer: Google uses their own in-house built Javascript frameworks and CSS.
Comment: Yes, I wish they used it on there desktop sites.  Gmail looks like crap these days on the desktop.
Comment: It looks really neat and clean.


implementing a custom behavior on recyclerview inside coordinatorlayout

Question: I have 3 views in my layout file with CoordinatorLayout as the root view : AppbarLayout, RecyclerView and a Footer(not visible all the time). Recyclerview implements the default behavior appbar_scrolling_view_behavior, that ideally, brings recyclerview below the appbarlayout. But the recyclerview and footer overlap. To Prevent that, I had to write a custom behavior so that when footer is visible, Recyclerview should make space for the footer. But now, the default behavior of appbar_scrolling_view_behavior is gone and now appbarlayout and recyclerview overlap.Here is the Image of the layout
Link to the custom behavior i implemented:
https://github.com/Mandeep221/CustomBehaviorForRecyclerview/blob/master/CustomBehavior.java
My Question: How can i implement 2 things(simultaneously in one behavior):

get the recyclerview below the appbarlayout inside the co-ordinatorlayout
get the recycelerview to make space for the footer if the footer is visible.

If you can suggest some workaround, that would also be great! Thanks alot!

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways|snap" />

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="4dp"
        android:scrollbars="vertical"
      app:layout_behavior="prokure.it.prokure.Search.NewSearch.CustomBehavior" />

    <prokure.it.prokure.FooterBarLayout
        android:id="@+id/footerBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        //footer child views

            </LinearLayout>
    </prokure.it.prokure.FooterBarLayout>

</android.support.design.widget.CoordinatorLayout>

Answer: Don't keep the android.support.design.widget.CoordinatorLayout as root layout.
Add a RelativeLayout as a root layout. Then add android.support.design.widget.CoordinatorLayout with property layout_alignParentTop and layout_above="@+id/footerBar" and set prokure.it.prokure.FooterBarLayout as align parent bottom as second child of RelativeLayout.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/footerBar">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/app_bar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways|snap" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="4dp"
            android:scrollbars="vertical"
             />
    </android.support.design.widget.CoordinatorLayout>

    <prokure.it.prokure.FooterBarLayout
        android:id="@+id/footerBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            //footer child views

        </LinearLayout>
    </prokure.it.prokure.FooterBarLayout>
</RelativeLayout>

Answer: Another simpler way is to add following lines to your prokure.it.prokure.FooterBarLayout
    app:layout_anchor="@id/list_recycler_view"
    app:layout_anchorGravity="bottom"

and keep prokure.it.prokure.FooterBarLayout inside coordinator layout.
Make sure to add an empty cell at the end of the recycler view so that prokure.it.prokure.FooterBarLayout does not overlap with last cell of RecyclerView.


Domain Access + Domain i18n = Site names not translating in other languages?

Question: I have 4 languages and 2 domains: site.com site.eu
I set up languages in these domains like:

site.com - english (default)
br.site.com - brazilian
site.eu - german
fr.site.eu - french

When I try to type Site Name for french and brazilian it does not save the line. but it save Slogan.
So Drupal use default site name of default language for both Brazilian And French sites: br.site.com and fr.site.eu
this instruction did not help me http://reyero.net/drupal/internationalization_domain_access_multilingual_variables_for_each_domain
There are Realms information that I've found. But how to configure correct I do not know.
Answer: I'm assuming you're using the "Domain Access" module. And even though you didn't explicitely mention it, you also use the i18n module. If my assumptions are correct, then be aware of what's mentioned on the project page of the "Domain Access" module:

If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefor I think you should try the Domain Variable module, to check if it fixes you issue.
Answer: i fixed with this:

add all the domains you have to the domains: so not only site.com and site.eu but also br.site.com and fr.site.eu and all others subdomains
set up in the every domain settings need name.

and think i've found one more method:
in domain access settings admin/structure/domain/settings there is checkbox:
Override site name with name of domain.
when i uncheck this the site name translations started work!


Lebesgue measure of a compact set and a line

Question: I am trying to work out the problem below. My only idea at the moment is that the compactness of $K$ gives me convergent subsequences. Any help would be appreciated.
Suppose that $K$ is a compact subset of the unit square $[0, 1]^2$
in $R^2$ and the two-dimensional Lebesgue measure of $K$ is greater than 1/2. Show that there are infinitely
many lines $L$ in $R^2$
such that $m_L(K ∩ L) > 1/2$, where $m_L$ is the one-dimensional
Lebesgue measure on the line $L$.
Comment: do you know Fubini?
Answer: Denote by $\mu$ the Lebesgue measure over $[0,1]$. The 2-dimensional Lebesgue measure over $[0,1]^2$ is given by the product measure $\lambda=\mu\times \mu$ and using Fubini we have:
$$\lambda(K)=\int 1_K(x,y) \ d\lambda(x,y)=\int_{0}^1\left (\int_0^1 1_K(x,y)\ d\mu(x)\right ) d\mu(y)$$
Now if there are only finitely many lines $L$ such that $L\cap K$ has length bigger than $\frac{1}{2}$ we would have $$\int_0^1 1_K(x,y)\ d\mu(x)\leq \frac{1}{2}$$
from where $$\lambda(K)\leq\int_{0}^1\frac{1}{2} d\mu=\frac{1}{2}$$
and this contradicts the hypothesis.


Highlighting dates from database in a jQuery calendar

Question: I use Keith Wood's great jQuery Datepicker.
The calendar is linked to a database.
After selecting dates from that same database these are properly highlighted in the calendar when it is shown as pop-up (after clicking in the related input field)by using following code:
<input type="text" id="datepicker" name="datephp" value="<?php echo $allgluedatesok;?>">

For a better usability it is of course better that this calendar is always displayed.
In that case the dates are not highlighted when I use following code…

<input type="hidden" id="hiddenFieldIDphp" name="datephp" value="<?php echo $allgluedatesok;?>">

Does someone know what I am doing wrong here?
Answer: It seems like when you link  Keith Wood's datepick calendar to an altField like that, only the datepick object updates the altField and not the other way around...
So when you put the dates in the input's value attribute, nothing is triggered to happen with the datepick calendar, event though, when you select the dates in the inline calendar, the input is updated correctly.
So the solution is to set the dates of the datepick calendar manually in javascript with the results of your PHP:

Note though, that the PHP string $commaseparatedDateStrings now must be of type: '07/31/2014','08/01/2014','08/02/2014' (with the quotes!) and so on, so that it's correctly parsed as the javascript's 'setDate' function arguments...
PS: I left your calendarsPicker() in the code, though when I downloaded Keith Wood's datepicker, the extension was called: datepick()...

EDIT: It seems like to add multiple dates, you must use an array instead of passing indefinitely many arguments like I said above... so the line with 'setdate' should become:
$("#datepicker").calendarsPicker('setDate',[<?php echo $commaseparatedDateStrings;?>]);


What does "Med." as a style mean in jazz fake books?

Question: I imagine it stands for "medium", but is it a tempo indication or does it mean something else/more? For example, how does (Med. Bossa Nova) differ from (Bossa Nova)? Some pieces also only have (Med.).
Answer: It's a tempo marking. There's no strict definition, but a medium tempo is often in the range of ~100-150 bpm.
The marking Med. Bossa Nova means to play a bossa nova groove/style at a medium tempo. The Bossa Nova groove doesn't always have to be played at medium tempo. For example, check out this fast version of Girl From Ipanema, which is usually played at a medium tempo. A song in a jazz Real Book with just Med (and no accompanying groove like Bossa Nova) will usually be played as a swing.
Comment: Just to follow up on some valuable discussion in other comments, a lack of tempo marking doesn't always imply `Med.` tempo. If a song is commonly played at two different tempos, it might not have a tempo marking when written up in the real book.
Comment: @Tim, I agree completely! In the last paragraph, I'm basically saying that if the feel isn't marked, swing is a good bet :)
Comment: I've not come across 'med' as meaning swing. Surely 'med' refers to tempo - as in your answer - but swing is feel, not tempo.
Comment: possibly: medio tiempo
Answer: Just 'medium'.   Meaning just as much (or just as little) as 'medium' ever does.  A bit like putting 'mf' as a dynamic.   (Except that some dynamic IS required at the start of a piece, a qualifier such as 'medium' isn't.)
Comment: The tempo suggestion.
Comment: That it isn't specially fast or slow.  Or very little. I thought I made that clear in my answer?
Comment: If there was no `Med`, I'd also assume that it's not specially fast or slow. That's why I found it weird that sometimes it's specified and sometimes it isn't.
Comment: Yeah.  Not the weirdest thing jazz guys do, but weird.
Comment: So in the case of `(Med. Bossa Nova)`, what does it tell me about the piece that `(Bossa Nova)` doesn't?
Comment: So, basically, a piece with 'med' will be played pretty well like a piece with no marking..?
Comment: @Tim well, talking strictly about real/fake books, the original real books put a tempo marking when there really was a classic tempo for the tune, and it might sound bit odd to deviate too far from it (though we still do of course!). Many do not have tempo markings and this isn't to say they are all Med, but they tend to have a wider range of what would be considered 'normal performance tempos'. Eg Stella by Starlight is commonly nearing a ballad, a burner or comfortably in between, and is given no marking. The newer real books tried to give a tempo marking to every song.


All Virtual Hosts redirect to one Host - nginx Reverse Proxy

Question: I have two Virtual Hosts for apache & nginx. The domains are (kevin-fechner.xyz & ketogenix.de)
My own site (kevin-fechner.xyz) was working fine while I only had one domain. But after adding another one, all (only two) redirect to the new one (ketogenix.de) or reports a 502 Bad Gateway.
Both sites are running Wordpress.
Environment:

Ubuntu 16.04
Apache/2.4.29
nginx/1.10.3
ssl
http2

Curl -I:
ketogenix.de
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 15 Jun 2018 08:39:48 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://ketogenix.de/

kevin-fechner.xyz
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 15 Jun 2018 08:39:58 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://kevin-fechner.xyz/

https://downforeveryoneorjustme.com/
- result: it's up
Virtual Hosts
ketogenix.de
nginx
    server {
    root /var/www/ketogenix.de;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name ketogenix.de www.ketogenix.de;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    location / {
            try_files $uri $uri/ /index.php;
    }

    location /wp-admin/ {
        index index.php;
        try_files $uri $uri/ /index.php$args;
    }

    location ~ \.php$ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        # proxy_pass http://127.0.0.1:8080;
        proxy_pass http://127.0.0.1:8080$request_uri;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/ketogenix.de/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ketogenix.de/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.ketogenix.de) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = ketogenix.de) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;

    server_name ketogenix.de www.ketogenix.de;
    return 301 https://ketogenix.de$request_uri;
}

apache
<VirtualHost 127.0.0.1:8080>
        ServerAdmin developer.kevinfechner@gmail
        ServerName ketogenix.de
        ServerAlias www.ketogenix.de
        DocumentRoot /var/www/ketogenix.de

        <Directory /var/www/ketogenix.de/>
                Options Indexes FollowSymLinks
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

kevin-fechner.xyz
nginx
    server {

    root /var/www/kevin-fechner.xyz;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name kevin-fechner.xyz www.kevin-fechner.xyz;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    location / {
            try_files $uri $uri/ /index.php;
    }

    location /wp-admin/ {
            index index.php;
            try_files $uri $uri/ /index.php$args;
    }

    location ~ \.php$ {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $host;
            # proxy_pass http://127.0.0.1:8080;
            # proxy_pass http://127.0.0.1:8080$request_uri;
            proxy_pass http://127.0.0.2:8081$request_uri;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }

    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/kevin-fechner.xyz/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/kevin-fechner.xyz/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = kevin-fechner.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    listen [::]:80;

    server_name kevin-fechner.xyz www.kevin-fechner.xyz;
    return 301 https://kevin-fechner.xyz$request_uri;
}

apache
<VirtualHost 127.0.0.2:8081>
        ServerAdmin developer.kevinfechner@gmail
        ServerName kevin-fechner.xyz
        ServerAlias www.kevin-fechner.xyz
        DocumentRoot /var/www/kevin-fechner.xyz

        <Directory /var/www/kevin-fechner.xyz/>
                Options Indexes FollowSymLinks
                AllowOverride all
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Error Logs
tells nothing
Things I've tried

adding ServerName
changing IP adress
changing port
restarting nginx & apache

I hope you can help me.
Note: I've removed all my comments from the virtual host files.
Comment: Have you added `Listen 127.0.0.2:8081` to Apache config?
Comment: Thank you! I totally forgot I have to edit that file as well. It's working now!
Comment: If you write that as an answer I'll gladly mark it as accepted.
Answer: Looks like you don't add Listen 127.0.0.2:8081 directive to Apache configuration. That lead to 502 error, because there is no process listening on port 8081.


Unclear definition of "N-way ANOVA" and "N-way mixed ANOVA"

Question: I am confused about the definition of "N-way ANOVA" and "N-way mixed ANOVA". Are they two totally disjoint classes? Or does "N-way ANOVA" includes "N-way mixed ANOVA"?
For example, when I am referring to a "three-way ANOVA", does it mean I am having three between-subject factors and no within-subject factor? (Sometimes I see this is further specified as "between-subjects three way ANOVA" rather than just "three-way ANOVA")
Or is saying a "three-way ANOVA" not enough for clarifying whether if there is any with-subject factor?
Answer: Mixed ANOVA means that there are both within- and between- subject variables.
Just saying n-way ANOVA is a confusing description of your analysis...as you said, sometimes people specify "between-subjects three way ANOVA".


Export SqlDatabase to Bacpac using SqlPackage.exe fails on fillfactor

Question: I am using the following command to execute sqlpackage to export a bacpac for a local db.
"C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin\sqlpackage.exe" /action:Export /tf:".\dbname_Baseline.bacpac" /SourceConnectionString:"XXXXXXXXXXXX"
It fails saying "Element Primary Key: [dbo].[PK_Name] has an unsupported property FillFactor set and is not supported when used as part of a data package."
I understand fillfactor is not supported but is there anything to make it ignore unsupported properties?
Thanks
Mark
Comment: Try updating the DacFx and SMO packages from [nuget](https://www.nuget.org/packages) or install the newest [SSMS](https://msdn.microsoft.com/en-us/library/mt238290.aspx). That should update the necessary dll's for I/E in your GAC.
Answer: Pass the switch
<code>/p:IgnoreFillFactor ={ True | False }
</code>
Comment: Hi, I get 'IgnoreFillFactor' is not a valid argument for the 'Export' action. when I try to put this argument to my command line.
Comment: This looks like a parameter for /action:Publish instead of /action:Export.  (getting a db ready for sql azure is fun isn't it?)
Answer: I have been experimenting with exporting to bacpac for a small database of around 1GB and you can reconfigure the fillfactor in the database. In SQL Server Manager Studio, just script a 'drop and re-create' for the index, edit the generated script to remove the fillfactor specification, run the script and this re-creates the index with a default fill factor acceptable to sqlpackage.exe. This should work for PKs as well as indexes, it should be quick for small databases and should have no adverse effect on the database.
I realize this doesn't answer the question about making sqlpackage.exe ignore some errors, but it is probably a better way of fixing the problem as it does so directly in the database.
Comment: This is a valid solution for small databases. However, we've got a large database with 270+ problem indexes! There has to be a better solution to this!
Comment: To expand my answer you can also change the fillfactor using the ALTER INDEX REBUILD command, you don't have to use the SQL Server Manager Studio GUI. You could write a script to rebuild the indexes one by one with the required fill factor, and you could run the changes over a period of time. Once an index is rebuilt with the required fillfactor it should not need to be rebuilt again. Also I believe SQL Server Enterprise edition allows ALTER INDEX REBUILD to occur online, which should reduce the downtime.


absolute URL with TinyMCE

Question: Everytime i add an image to tinyMCE it converts the image URL to something stupid (removes the hostname and adds ../ or whatever it needs) , so i won't be able to use the image created by tinymce in any other level of the site !
can this be fixed somehow ? relative_urls: "false", not working
Thanks
Answer: Use this in your javascript initialization:
relative_urls : false,
remove_script_host : false,
convert_urls : true,

Get TinyMCE to use full image url instead of relative one
Answer: Before initializing tinymce i set the following variable
var system_url = "http://myserver.com/workspace/codebase/html/";

so that i am able to use system_url later for adressing images and other files like this
content_css: system_url+'js/tiny_mce/css/green.css',

Comment: seems there's a bug in tinymce ... it's not working . but the function is correct . thanks

absolute URL with TinyMCE


If a linear space can be represented as the direct sum of two sets of subspaces, how do I show that the subspaces are equivalent?

Question: I need some help with proving the following.
"Let linear space $X = \oplus_{j}U_{j}$ where ${U_{j}}$ is a set of non-trivial subspaces of $X$. Let subspace $V_{j}$ be such that $X = \oplus_{j}V_{j}$ and that $U_{j} \subset V_{j}$. Show that $U_{j} = V_{j}$."
I'm pretty sure I understand the individual concepts, but I'm really struggling to put them together into a proof.
Answer: Fix $j$. Let $y \in V_j$. Then we can write $y =\sum x_i$ with $x_i \in U_i$ for all $i$. Note that $x_i \in V_i$ for all $i$. Another decomposition of $y$ as sum of elements of $V_i$'s is $0+0+...+y+0+...$ where $y$ is in the $j-$th place. By uniqueness we get $y=x_j$ Hence $y \in U_j$.
Comment: @FMcA Any vector in $X$ can be written as a sum of that type because it is given that $X$ is the sum of $X_i$'s.
Comment: @EricWofsey Thank you I have corrected my answer.
Comment: @KaboMurphy Thanks. I assumed that X was finite dimensional, but probably shouldn't have. Why can we write y as a sum of x terms?
Comment: And we can take that step here because the question assumes that X is the direct sum of the $U_{i}$s? Is that a reasonable way to think of it?


View with relationship to custom entity via computed property

Question: View with relationship to custom entity via computed property
I have nodes connected to a custom entity (called here "myentity") via a computed property, like this:
  $info['node']['properties']['myentity'] = array(
    'label' => t("Myentity"),
    'type' => 'myentity',
    'computed' => TRUE,
    'queryable' => TRUE,  // setting this to FALSE doesn't change anything
    'entity views field' => TRUE,
    'getter callback' => 'mymodule_node_property_myentity_get',
  );

The callback function extracts some values from the node and calls another function, which fills these values into an entity field query, returning the wanted myentity instance.
This entity connection is working, so I can get the property "myprop" of myentity via an entity API wrapper $node_wrapper->myentity->myprop->value().
Now I want to add myprop in a simple view for nodes. After creating a relationship to myentity, "Content: Myentity" shows up in the "Add fields" list, as well as all of myentity's properties.
Selecting "Content: Myentity" works - myentity's default label is displayed in the view output. (With some magic - the displayed SQL query is SELECT node.nid AS nid FROM {node} node).
However, selecting "Myentity: Myprop" does not work. Even before executing the view, Drupal shows a SQL error:
SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "myentity" LINE 1: SELECT node.nid AS nid, myentity.myprop AS myentity_myprop, no... ^

The displayed SQL query here is SELECT node.nid AS nid, myentity.myprop AS myentity_myprop FROM {node} node. myentity is referenced in the select clause, but not in the from clause, nor is there any join statement.
Has somebody managed to add properties of a custom entity, connected via a computed node property, to views?
Answer: Finally figured out a workaround: Pull every needed entity property as a "virtual field" into the node itself.
// define additional property information for node
function mymodule_entity_property_info_alter(&$info) {
  $properties = & $info['node']['properties'];
  foreach (array('myprop') as $property) {
    $properties[$property] = array(
      'label' => $info['mymodule']['properties'][$property]['label'],
      'description' => $info['mymodule']['properties'][$property]['description'],
      'type' => $info['mymodule']['properties'][$property]['type'],
      'computed' => TRUE,
      'queryable' => TRUE,
      'entity views field' => TRUE,
      'getter callback' => "mymodule_node_property_verbatim_get",
    );
  }
}

// getter callback
function mymodule_node_property_verbatim_get($data, array $options, $name, $type, $info) {
  $myentity = mymodule_get_from_node($data);
  return !empty($publication->{$name}) ? $publication->{$name} : array();
}

// obtain the related entity from the node
function mymodule_get_from_node($node) {

  // some custom code to get myentity

  return $myentity;
}

Thus, the properties can be adressed as views fields as well as for any other purposes. It's possible to extend this to access properties of nested entities, too.
One drawback, however: The fields cannot be used as views sort criteria.


Laravel: Point laravel subdomain to custom domain

Question: Route::group(['domain' => '{subdomain}.example.com'], function($subdomain)
{
    Route::get('new-lead', 'Home@new_lead');
}

I am creating multiple subdomains, and everything is working fine but now I need to point the subdomain to a custom domain for example.
I have created
xyz.example.com and now want to point a custom domain on this subdomain.
xyz.example.com -> xyz.com (or any other custom domain)
Please guide me on how can I point the custom domain to the Laravel subdomains.
Answer: You can achieve that using redirects:
Route::get('/your-domain', function () {
    return redirect('xyz.com');
});

Or if you want to redirect to external webpage, do this return Redirect::to('www.anyurl.com');
Resource: https://laravel.com/docs/10.x/redirects
Comment: this is only a redirect, i need to point 3rd party domain how can i point on the laravel subdomain this is the issue.
Comment: You can't point 3rd party domain to laravel domain within laravel application. You need to do that on a domain level. You can set up redirects in the dashboard of your domain provider.
Comment: I need support from DevOps and laravel. We need to complete this like shopify.


Como abrir um form atrás de um form já aberto Delphi

Question: Como abri uma form atrás de um outro form já aberto? Esse form que está aberto tem um tempo para fechar, quando fechar, preciso que o segundo form esteja aberto de forma modal.
Answer: abra normalmente e use o comando SendToBack para enviar para trás
 form.show;
 form.SendToBack;

Comment: valeu pela dica, só que quando fecha o form que esta na frente ele esta indo para traz de tela principal o segundo form
Comment: pode fazer tratamentos para corrigir, tenta usar o BringToFront no onClose
Answer: Utilize a propriedade PopupMode e PopupParent dos formulários.
Considere 3 Formulários:
FormPrincipal é o formulário principal;
FormBackend é o formulário que deverá ser Modal e ficar por trás do FormCadastro;
FormCadastro é o formulário que aciona FormBackend, mas que deve ficar acima desse FormBackend;
Considere que a ordem de chamada dos formulários será:
FormPrincipal -> FormCadastro -> FormBackend
Considere que a ordem de apresentação dos formulários deve ser:
1 FormCadastro
2 FormBackend
3 FormPrincipal
Utilize as propriedades PopupParent e PopupMode para resolver a ordem das janelas.
Segue tradução de trecho da documentação oficial:

A propriedade PopupMode controla como o formulário de nível superior
se comporta em relação ao estilo WS_POPUP do Windows. Uma janela que
possui o estilo WS_POPUP está sempre acima de seu "proprietário" na
ordem Z. Você pode usar a propriedade PopupMode em conjunto com a
propriedade PopupParent para evitar a aparência de um aplicativo
travado causado por um diálogo modal aparecendo atrás de outro
formulário na tela.

Leia mais na documentação oficial: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Forms_TForm_PopupMode.html
Propriedade alterada em FormBackend:
PopupMode := pmExplicit;
PopupParent := FormPrincipal;

Propriedade alterada em FormCadastro:
PopupMode := pmExplicit;

Procedure alterando ordem pelo PopupParent:
procedure TFormCadastro.butAtivarBackendClick(Sender: TObject);
begin
   FormCadastro.PopupParent :=  FormBackend;
   FormBackend.PopupMode:=pmAuto;
   FormBackend.ShowModal;
end;

Projeto de teste: Projeto teste PopupParent


Product of two lower triangular matrices is a lower triangular matrix

Question: For my univerity studies I had to prove this:
$ Let \,\, n \,\ \in N \,\, and \,\, L1,\, L2 \, \in R(n \times n) \,\, be \,\, both \,\, lower \,\, triangular \,\, matrices.$
$ Show \,\, that \,\, L := L1L2 \,\, is \,\, also \,\, a \,\, lower \,\, triangular \,\, matrix.$
I proved it like this (and I need some verification for the proof):
$L_{ij} := (L1L2)_{ij}$
$Now \,\, just \,\, look \,\, at \,\, (L1L2)_{ij} \,\, where \,\, j > i.$
$(L1L2)_{ij} = \sum_{r=1}^n l1_{ir}l2_{rj} = \sum_{r=j}^i l1_{ir}l2_{rj} = \sum_{r=1}^n l1_{ir}l2_{rj} = \begin{cases}
0,  & \text{if $j>i$ is even} \\
a \in R, & \text{else}
\end{cases}
$
$\Rightarrow \text{L is lower triangular}$
$\square$
Comment: This is incomprehensible. You have $\sum_{r=1}^nL1_{ir}L2_{rj}=\sum_{r=j}^iL1_{ir}L2_{rj}$ which obviously is unjustified and then you turn it back to the original indexing with utter no reason for doing this at all.  The is you claim for no reason whatsever if $0$ if $j> i$ is even (which is imparsible; I assume you mean if $j$ is even) although there is no reason why that would be-- and is some identified constant $a$ if not.  What is $a$ and why is it equal to $a$?  And then you claimed this means it is lower triangular but those $a$ terms mean it is not.
Answer: Let me call the matrices $A$ and $B$ to avoid too many subscripts. Fix $i<j$. Then
$$
(AB)_{ij} = \sum_{k=1}^n A_{ik}B_{kj}.
$$
But either $i<k$ or $k<j$ holds (because the negation $k\leq i<j\leq k$ is impossible), so $A_{ik}=0$ or $B_{kj}=0$. Therefore all the addends are zero and $(AB)_{ij}=0$.

Analysis of the OP's proof
When you write
$$
\sum_{r=1}^n L1_{ir} L2_{rj} = \sum_{r=j}^i L1_{ir} L2_{rj},
$$
what are you trying to say? Notice also that the starting index of the summation is larger than the ending one. What is it that you want to express?
The next step in your computation then is just reverting back to the previous formula. Why is that?
Finally, what does "$j>i$ is even" mean? And what about $a\in R$?
In summary, I would not consider your proof a proof at all.
Comment: It's hardly "another" way of proving.  It's clearly the exact attempt you were attempting but mangled to incomprehensibility but done correctly.
Comment: alright thank you both. That was exactly the reason for my question, I was doubting the rigidity of my "proof".
Comment: I mean thank you for your time and showing me another way of proving this but my question was if my prove is rigerous like I formulated it?
Comment: Well in that case, not so much. I'll expand my answer
Comment: @Mathmeeeeen What I showed you is not "another" way of proving it. It's *the* way to express rigorously this simple fact. What you wrote cannot be considered a proof
Answer: Let $A=[a_{ij}]$ and $B=[b_{ij}]$ be two $n \times n$ lower triangular matrices.
By definition
\begin{equation}
a_{ij}=b_{ij}=0~~\text{if}~~~i<j.
\end{equation}
Let $AB=[c_{ij}]$. It is sufficient to show that $c_{ij}=0$ whenever $i<j$ where
\begin{equation}
c_{ij}=\sum_{k=1}^n a_{ik}b_{kj}.
\end{equation}
Case I: $k \leq i <j$.
In this case, $b_{kj}=0$ for $k,j\in \{1,2,\ldots,n\}$ with $k<j$.
Case II: $i < k$
In this case, $a_{ik}=0$ for $i,k\in \{1,2,\ldots,n\}$ with $i<k$.
Hence, for $i<j$, we have
\begin{eqnarray}
c_{ij}&=&\sum_{k=1}^i a_{ik}b_{kj}+\sum_{k=i+1}^n a_{ik}b_{kj}\\
&=& 0+0\\
&=&0
\end{eqnarray}


Storing multiple test reports using Allure

Question: I run my tests with Jenkins and I use Allure Framework for test report generation. I need to save and switch between different test reports for different launches on Jenkins, is there any way/plugin for doing this?
Comment: Could you please specify a bit more information about your problem? Jenkins plugin saves reports http://i.stack.imgur.com/9OqNM.png
Comment: That's solves my problem :)
Comment: Actually it's not quite clear from the question, what system you're talking about. For example, if you run your tests on your local PC - then you can just rename folders and you're good. Now we already know that you're talking about Jenkins, but you should've made that clear in the original post. I suggest you to rename the question title since I can only propes a change to the post body.
Answer: There is Jenkins plugin for Allure;


Subquery with aggregate function in a union

Question: I am building upon a SQl statement from the following post: Union two different tables with a primary ID field
There are two tables (md_master & cd_personal_checks) that I am trying to union into one view.
Here is my current statement.
CREATE VIEW ViewCR AS

SELECT id  + 100000000000000000 AS id, a.external_code + CAST(id AS varchar(15)) as crUniqueId,
       m.check_amount, 'C' as crType, m.postprint_date as activationDate,
       m.postprint_date as creationDate, m.memo_explanation as reasonLine1, m.check_no
  FROM MD_Master m
  Join accounts a on m.account_tag = a.acct_id
 WHERE (m.postprint_tag = 2) OR (m.postprint_tag = 4) OR
       (m.postprint_tag = 5) OR (m.postprint_tag = 7)

 UNION ALL

SELECT id + 200000000000000000 as id, 'PERCHK' + CAST(id AS varchar(15)) as crUniqueId,
       check_amount, 'P' as crType, business_date as activationDate,
       business_date as creationDate, identify_description as reasonLine1, check_no
  FROM cd_personal_checks

HOWEVER, I have reached another obstacle. I need to get data from another table (which has a link to each of the two tables mentioned above)
In both select statments above I need to add a field called "dispositionAmount" which is the check_amount - SUM(md_cr_pending.current_amount)
md_cr_pending table has a master_id field that links with md_master.id
md_cr_pending table has a cd_personal_check_id field that links with cd_personal_checks.id
Thanks for any help
Comment: posting the third table sturcture and the references would make it easier.
Answer: Since you did not post the third table and the forignKeys I only can help with this:
CREATE VIEW ViewCR AS

    SELECT id  + 100000000000000000 AS id,
    a.external_code + CAST(id AS varchar(15)) as crUniqueId,
    m.check_amount,
    'C' as crType,
    m.postprint_date as activationDate,
    m.postprint_date as creationDate,
    m.memo_explanation as reasonLine1,
    m.check_no,
    m.check_amount - sh.sumAmount As Difference
    FROM MD_Master m
    Join accounts a on m.account_tag = a.acct_id
    INNER JOIN (SELECT forignKeyID,
                SUM(md_cr_pending.current_amount) as sumAmount
                FROM Table 3
                Group BY forignKeyID) sh ON sh.forignKeyID = m.ID
    WHERE (m.postprint_tag = 2) OR (m.postprint_tag = 4) OR
          (m.postprint_tag = 5) OR (m.postprint_tag = 7)

    UNION ALL

    SELECT id + 200000000000000000 as id,
    'PERCHK' + CAST(id AS varchar(15)) as crUniqueId,
    check_amount,
    'P' as crType,
    business_date as activationDate,
    business_date as creationDate,
    identify_description as reasonLine1,
    check_no,
    check_amount - sh.sumAmount As Difference
    FROM cd_personal_checks
    INNER JOIN (SELECT forignKeyID,
                SUM(md_cr_pending.current_amount) as sumAmount
                FROM Table 3
                Group BY forignKeyID) sh
                ON sh.forignKeyID = cd_personal_checks.ID

Comment: Not sure i quite understand your answer, but I replaced table 3 with md_cr_pending. is that correct? Also, i can't quite figure out what the foreignkeyID is.
Comment: The reference between the tables. The connection what you called "link"
Comment: Couple changes to my field names to replace your  Table3 and ForeignKeyId and it worked!  Thanks!


Non-trivial intersection of all non- trivial normal subgroups of a finite group

Question: Is it possible to give a full description of all finite groups that have a non-trivial intersection of all their non-trivial normal subgroups?
Thanks,  Michiel
Comment: It is not possible to simply  list all of the groups with this property, even in the case of $p$-groups with cyclic centres.
Comment: Such groups are described [here](https://groupprops.subwiki.org/wiki/Monolithic_group)
Comment: This is equivalent to having a unique minimal normal subgroup.  Such a group is often called monolithic, and the minimal normal subgroup is the monolith. If the monolith is non-abelian, then the group has a pretty restricted structure. Otherwise, not that much can be said.
Comment: They are the groups with a unique minimal normal subgroups. In the case of $p$-groups, they are the ones with cyclic centres. The difficulty with this kind of question is what exactly do you mean by a "full description". What sort of answer are you looking for?
Comment: @Crostul That is hardly a description! It is little more than a definition.
Comment: @ Derek: with full description I mean "a as complete list as possible ". Examples of such groups are the simple groups, $Q_8$, $S_3$,...
Comment: Thanks Derek. 'Characterizing' these groups is maybe a better wording than 'describing' or 'listing' them
Answer: Here is a description of the finite groups $G$ with a minimal normal nonabelian subgroup $N$.
In this case, $N \cong S^n$ for some $n \ge 1$, where $S$ is nonabelian and simple. We can embed $S$ in its automorphism group $A$ by identifying it with the subgroup of inner automorphisms of $S$.
Then $G$ is a subgroup of the wreath product $W = A \wr S_n$, such that $N$ is the subgroup $S^n$ of the base group of $W$, and $G$ projects onto a transitive subgroup of $S_n$.
Any group $G$ satisfying those conditions has $N$ as a unique minimal normal subgroup.


Need filter on value of a field in a specific node of different content type in Views

Question: I have content type pick_topic, containing an entity ref taxonomy field topic. There is one node of this type. It defines the topic of the month. Several views blocks and pages need to only display content nodes with this topic value. Example: taxonomy topics: dogs, cats, rabbits.
The user (site manager) edits this node and selects a topic from dropdown. Say it is dogs. My view of another content type, articles, contains topic field. How can I filter the view based on the pick_topic topic value equal to the article topic field value, in this case dogs?
Answer: I don't know of a way to do this all in the interface, but if you add a contextual filter in the view for the topic field on the article content type, you can programmatically set the contextual argument in hook_views_pre_view.
First, load your pick_topic node like:
\Drupal::service('entity_type.manager')->getStorage('node')->load(PICK_TOPIC_NID);

Then load the field value. See How do I access a field value for an entity (e.g. node) object?
Then set the view argument.
function MY_MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'MY_VIEW_ID' && $view->current_display == 'MY_VIEW_DISPLAY_ID') {
    // Load your pick topic node.
    // Load your pick topic field value.
    // Set the view argument, term id.
    args[] = $my_pick_topic_field_value_tid;
  }
}

Answer: This is a very common request, to display lists of related content that share the same Taxonomy term as the node where the Views Block is displayed.
You can do that by adding a Contextual Filter Content: Has taxonomy term ID to your articles Views with these settings (only choose topic Vocabulary in your case):

Since your Views list a different content type, it's not necessary to also add another contextual filter to remove the current node from the Views block.
If your articles Views don't have a Block display, create one now, by duplicating the one you've been editing above, duplicate as Block. Edit the Block name to something meaningful so you can easily find it on the Block list.
Now you add that Block to a region the usual way. Besides selecting a region you'll also have to choose the Content: ID Node from URL on Block settings (this comes from our Contextual filter), and on the Visibility settings (in Vertical tabs) under Content types choose Pick topic content type (I have Article ticked in image below, but you have to choose the Content type where you want the block to display, which is Pick topic in your case).

This means that the Views Block will list article titles, but the Block will be visible on pick_topic node pages.
Without the Contextual filter the Views Block will list all articles.
With the Contextual filter (set as above) will restrict that list to only those articles that have the same term as the node where the Block is being displayed.
Comment: prkos, can you please explain how to "add your Block listing articles to show only on **pick_topic** content type. Views block lists **articles** content type. How can it can filter to just articles that contain the taxonomy term stored in the **pick_topic** content type?
Comment: I edited the answer with the Block clarification. Yes your Views Block lists articles, but that Block needs to be displayed on Pick topic nodes. The Block will know through the Contextual filter what Taxonomy terms are active on the page where the Block is displayed. The Contextual filter then influences the results (articles list) to restrict them to only those that share the same term.
Comment: This worked perfectly! Thanks for your help and clarification.


Having trouble with :dependent => :destroy and before_filter

Question: Two models, an Account model (has_many :users) and a User model (belongs_to :account, :dependent => :destroy).
My User model has the following:
def protect_master_user
  unless User.find_all_by_account_id_and_is_master(self.account_id, true).count > 1
    false
  end
end

I'm trying to protect the master users from being deleted. How can I override this if the parent (Account) is deleted? I've tried :dependent => :destroy and :delete to no avail.
EDIT: fixed code.
Answer: There are two ways to do this: has_many :users, :dependent => :delete_all, or with an additional custom callback in Accounts. The :delete_all method is simpler, but not advised, because it means that none of your other call backs will happen on the user record.
The correct solution is a custom before_destroy callback in Account, working in tandem with the callback in user.
class Account < ActiveRecord::Base
  has_many :users

  before_destroy :destroy_users
  protected
    def destroy_users
      users.each do |user|
        u.account_id = nil
        u.destroy
      end
    end

end

class User < ActiveRecord::Base
  belongs_to :account

  before_destroy :protect_master_user

  protected
    def protect_master_user
      unless account_id.nil? ||! master ||
        User.find_all_by_account_id_and_master(self.account_id, true).count > 1
        errors.add_to_base "Cannot remove master user."
        return false
      end
    end
end

If the account.id is nil we short circuit the unless and the destroy continues. Same goes for if the user is not a master user. Why do we need to check if there's more than one master user if the object being destroyed isn't a master user either?
Again, delete could be used in place of destroy. But it skips any *_destroy callbacks you have or will ahve in the future.
Comment: Thanks for your reply, however this is not working for me. What you suggested makes sense, but I think User destroy is first. Any other ideas?
Comment: Weird. I thought I had it working yesterday. I've updated it to use a custom call back and described why a :dependent => :delete_all is no good.
Comment: Thanks, I had come up with the same solution but wasn't sure if deleting users from the Account model was the way to go. Thanks again.
Answer: I had this very same question and conundrum recently and found the best way to deal with this was to handle it in the controller as I really only care if a user is trying to delete the last Master user rather than if the system is doing it:
   class UsersController < ApplicationController
     def destroy
       user = current_account.users.find(params[:id].to_i)
       if allow_removal_of_user?(user) && user.destroy
         redirect_to users_path, :notice => "User sucessfully deleted"
       else
         flash[:error] = user.errors.empty? ? "Error" : user.errors.full_messages.to_sentence
         render :edit
       end
     end

   private
     def allow_removal_of_user?(user)
       if user == current_user
         errors.add(:user_removal, "Can't delete yourself")
         false
       elsif user.only_user? || (user.master_users_for_account.count == 1 && user.master_role?)
         errors.add(:user_removal, "Can't delete last Master user")
         false
       else
         true
       end
     end
   end

Hope this helps somebody!


How to replicate existing files using GlusterFS

Question: I am testing GlusterFS to replicate data across two test servers. I have followed this excellent step by step Howto and everything worked flawlessly.
I have successfully added the peer, created a volume and glusterfs-mounted the gluster volume on a empty mount point. Files touch'ed or copied into that mount point do appear on the peer. No problem here.
But how can I replicate existing data without copying it to a already mounted gluster volume? I have the feeling that I am missing something trivial but what?
Answer: You need to move the data off it's current filesystem and onto the gluster filesystem.
Answer: Mounting a distributed filesystem, is like creating another partition on your hard disk. The elder partition has your data, while the new one is empty.
Gluster ensures that wherever it is mounted, files will be in sync.
Like a newly created partition, it doesn't contain anything.
You need to move your stuff to the new "partition" (glusterfs). If you use cp, it's better to use the archive mode in order to preserve timestamps, permissions etc etc.


performance issue: inner join across multiple tables

Question: I've been trying to speed up this query but can't seem to figure out what the issue is.
I'm on Postgres 11.8.
observations has ~250M rows
report_items has ~35M rows
report_sections has ~3M rows
Query
SELECT "observations".* FROM "observations"
INNER JOIN "report_items" ON "observations"."report_item_id" = "report_items"."id"
INNER JOIN "report_sections" ON "report_items"."report_section_id" = "report_sections"."id"
WHERE
    "observations"."deleted_at" IS NULL AND
    "report_items"."deleted_at" IS NULL AND
    "report_sections"."deleted_at" IS NULL AND
    "report_sections"."report_id" = '87996789-795f-402c-af8c-181d27eb6dc0';

Explain Plan
Gather  (cost=1000.23..1261158.89 rows=3691 width=539) (actual time=921.292..988.896 rows=0 loops=1)
  Workers Planned: 3
  Workers Launched: 3
  ->  Nested Loop  (cost=0.23..1259789.79 rows=1191 width=539) (actual time=916.410..916.410 rows=0 loops=4)
        ->  Nested Loop  (cost=0.11..715317.61 rows=176 width=16) (actual time=916.409..916.409 rows=0 loops=4)
              ->  Parallel Seq Scan on report_sections  (cost=0.00..710432.51 rows=20 width=16) (actual time=916.409..916.409 rows=0 loops=4)
                    Filter: ((deleted_at IS NULL) AND (report_id = '87996789-795f-402c-af8c-181d27eb6dc0'::uuid))
                    Rows Removed by Filter: 693631
              ->  Index Scan using index_report_items_on_deleted_at_and_report_section_id on report_items  (cost=0.11..243.89 rows=121 width=32) (never executed)
                    Index Cond: ((deleted_at IS NULL) AND (report_section_id = report_sections.id))
        ->  Index Scan using index_observations_where_deleted_at_null_on_report_item_id on observations  (cost=0.11..3086.96 rows=2211 width=539) (never executed)
              Index Cond: (report_item_id = report_items.id)
Planning Time: 0.497 ms
Execution Time: 988.949 ms

Thank for the help in advance!
EDITED:
Here are the indexes on the report_sections table: https://share.getcloudapp.com/xQuDqj0K
Comment: Are there many rows in `report_sections` where `deleted_at` is NULL?
Comment: @LaurenzAlbe yes, about 92% of the 2.8M rows.
Answer: The sequential scan of report_sections is taking the bulk of the time.
Is there a reason why report_sections.report_id is not indexed?
Comment: Thanks, Mike! I am seeing that I have an index on `report_sections.report_id`. Here are the indexes in place: https://share.getcloudapp.com/xQuDqj0K
Comment: @jdixon04  I apologize for assuming that it was not indexed.  The question is why it opts for a seq scan.  Have you tried to `analyze` the table?
Answer: This index would speed up processing:
CREATE INDEX ON report_sections (report_id) INCLUDE (id)
   WHERE deleted_at IS NULL;

Then VACUUM the table and try again; you should get a fast index only scan.


How do I use the form hook alt to edit fields of inline entity form?

Question: I am trying to use the hook_form_alter to modify the fields of an Inline entity form in a commerce product display node.
I know how to edit a normal field but this does not work for an entity form field. How do I go about editing a field, for example changing the price field label?
Thanks
Robert
Answer: As per IEF's API docs, you've got:

hook_inline_entity_form_entity_form_alter()

Perform alterations before an entity form is included in the IEF widget.
hook_inline_entity_form_reference_form_alter()

Perform alterations before the reference form is included in the IEF widget.
The reference form is used to add existing entities through an autocomplete field

hook_inline_entity_form_table_fields_alter()

Alter the fields used to represent an entity in the IEF table.
The fields can be either Field API fields or properties defined through hook_entity_property_info().

I think the first would be most appropriate here, probably something like (guessing at the array keys here, they might be different):
<code>function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['commerce_price']['#title'] = t('New title.');
  }
}
</code>
Comment: Hey Clive, thanks for this great answer!  It helped me a lot. Can you also explain how can I work with the submit handler of IEF?  because $entity_form['actions']['submit']['#submit'][] is not working for me. Any help would be greatly appreciated!