AppEngine - Client closed keepalive connection

Question: I have deployed my Symfony 4 app to Google App Engine (Flexible environment).
The build seems to have worked, but loading the app on in Chrome results in error:
<code>Oops! An Error Occurred
The server returned a "500 Internal Server Error".
Something is broken. Please let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused.
</code>
The app engine log is here:
<code> 2019/02/02 04:33:13 [info] 9#9: *6 client 172.17.0.4 closed keepalive connection
 A
 GET 404 191 B 0 ms Chrome 71 /favicon.ico A  GET 404 191 B 0 ms Chrome 71
 GET 500 930 B 6 ms Chrome 71 /connect/google A  GET 500 930 B 6 ms Chrome 71
 GET 307 316 B 6 ms Chrome 71 / A  GET 307 316 B 6 ms Chrome 71
 172.17.0.4 - - [02/Feb/2019:04:32:13 +0000] "GET /connect/google HTTP/1.1" 500 930 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
 172.17.0.4 - - [02/Feb/2019:04:32:13 +0000] "GET / HTTP/1.1" 307 316 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
 2019/02/02 04:29:08 [info] 9#9: *1 client 172.17.0.4 closed keepalive connection
 A
 GET 500 930 B 6 ms Chrome 71 /connect/google A  GET 500 930 B 6 ms Chrome 71
 GET 307 316 B 5 ms Chrome 71 / A  GET 307 316 B 5 ms Chrome 71
 172.17.0.4 - - [02/Feb/2019:04:28:08 +0000] "GET /connect/google HTTP/1.1" 500 930 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
 172.17.0.4 - - [02/Feb/2019:04:28:08 +0000] "GET / HTTP/1.1" 307 316 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
 GET 404 191 B 10 ms Chrome 71 /favicon.ico A  GET 404 191 B 10 ms Chrome 71
 GET 500 930 B 207 ms Chrome 71 /connect/google A  GET 500 930 B 207 ms Chrome 71
 172.17.0.4 - - [02/Feb/2019:04:27:50 +0000] "GET /connect/google HTTP/1.1" 500 930 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
 GET 307 316 B 271 ms Chrome 71 / A  GET 307 316 B 271 ms Chrome 71
 172.17.0.4 - - [02/Feb/2019:04:27:49 +0000] "GET / HTTP/1.1" 307 316 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
 A
A  2019-02-02 03:22:43,817 INFO success: nginx entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

A  2019-02-02 03:22:43,817 INFO success: php-fpm entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)

A  [02-Feb-2019 03:22:42] NOTICE: ready to handle connections

A  [02-Feb-2019 03:22:42] NOTICE: fpm is running, pid 7

A  2019/02/02 03:22:42 [notice] 8#8: start worker process 9

A  2019/02/02 03:22:42 [notice] 8#8: start worker processes

A  2019/02/02 03:22:42 [notice] 8#8: getrlimit(RLIMIT_NOFILE): 65536:65536

A  2019/02/02 03:22:42 [notice] 8#8: OS: Linux 4.9.0-8-amd64

A  2019/02/02 03:22:42 [notice] 8#8: nginx/1.10.3 (Ubuntu)

A  2019/02/02 03:22:42 [notice] 8#8: using the "epoll" event method

A  2019-02-02 03:22:42,339 INFO spawned: 'nginx' with pid 8

A  2019-02-02 03:22:42,338 INFO spawned: 'php-fpm' with pid 7

A  2019-02-02 03:22:41,335 INFO supervisord started with pid 1

A  2019-02-02 03:22:41,329 WARN No file matches via include "/etc/supervisor/conf.d/*.conf"

A  2019-02-02 03:22:41,329 CRIT Supervisor running as root (no user in config file)
</code>
I don't understand this error. How can I resolve?
Comment: App Engine 500 (Internal Server Error) almost always means that your code threw an unhanded exception that was caught by the runtime. Therefore I would suggest to check your php code .
Answer: As clarified in this other similar case here, this type of issue, indeed, is related to the code, where it's not well written and then, the runtime is caughting the exception from it. In this situation, it's recommended to take a look at your code and look for exceptions that are not being handled by your code.
An alternative is to check in the Cloud Dashboard - as mentioned here - for more details in the Error Reporting, so you can get more information from the stack trace.


Tratar dados recebidos por AJAX

Question: Boa tarde, eu estou enviar um valor via AJAX/Jquery que me acciona a funçao index do controlador notificações.
Ao receber um dado valor, eu quero que a funçao me direccione para outra página. Acontece que, ao receber esse dado valor, a função nao me redirecciona para outra página mas imprime-me essa página na consola.
Como é que faço para que me redireccione para a página?
O código que estou a utilizar é o seguinte:
$( document ).ready(function() {
        $('#notifications').click(function(){
          $.ajax({
            url: '<?=base_url("notificacoes")?>',
            type: 'POST',
            data: {
              key: 'olá'
            },
            success: function(data) {
              console.log(data);
            }
          });
        });
      });

Controller :
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Notificacoes extends CI_Controller {
    public function index(){
        return $this->load->view('norm');
    }
}

Botão :
<button class="btn btn-secondary pr-2" type="button" id="notifications" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                    0
                    </button>

Comment: O `data` retorna o endereço de uma página? Se for, basta usar `location.href=data`
Answer: O AJAX tem a principal finalidade de realizar requisições sem a necessidade de recarregar a página, ou seja, os valores retornados do servidor após a requisição serão manipulados pelo cliente sem a necessidade destes serem renderizados pelo servidor.
Para resolver o seu problema, não é necessário utilizar o ajax neste requisição, pois você solicitará ao servidor uma página diretamente ao invés de fazer a requisição, receber a resposta para então, fazer o redirecionamento.
Você pode fazer utilizando o JQuery:
$(document).ready(function() {
  $('#notifications').click(function() {
    window.location.href = '<?= base_url("notificacoes") ?>'
  });
});

Ou usando o próprio atributo HTML onclick:
<button class="btn btn-secondary pr-2" type="button" id="notifications" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="javascript:location.href='<?= base_url("notificacoes") ?>'">

    0
</button>

Answer: Você pode fazer da seguinte forma caso queira validar o que esta vindo do ajax vc pode colocar o que veio do ajax em uma variavel como no exemplo retorno e fazer um if conferindo se é o que você quer, se for direciona para a url desejada:
$( document ).ready(function() {
        $('#notifications').click(function(){
          $.ajax({
            url: '<?=base_url("notificacoes")?>',
            type: 'POST',
            data: {
              key: 'olá'
            },
            success: function(data) {
              var retorno = JSON.parse(data);
                    if (retorno == 'ok') {
                        window.location.href = "http://...";
                    }
            }
          });
        });
      });

mas caso a sua data do ajax já seja a url que você quer, pode ser feito da seguinte forma, porém o data já deve esta formatado para url:
$( document ).ready(function() {
        $('#notifications').click(function(){
          $.ajax({
            url: '<?=base_url("notificacoes")?>',
            type: 'POST',
            data: {
              key: 'olá'
            },
            success: function(data) {
              window.location.href = data;
              //caso precise concatenar pode fazer assim
              window.location.href = "http://..."+data;
            }
          });
        });
      });

Tratar dados recebidos por AJAX


Angular 7 - Switching Kendo UI theme on runtime

Question: I am using Kendo UI with Angular 7 application. The application needs to support changing themes on the fly. For example, some user might like to have Light mode while others will prefer the Dark mode.
Kendo UI has a very good support for themes but the problem is that themes can only be set on the compile time.
As per their recommendations, specifying the theme should be a part of the angular.json file, like the following.
"styles": [
   "node_modules/@progress/kendo-theme-bootstrap/dist/all.css",
   "src/styles.scss"
]

but this will only compile to embedded CSS inside the root page. We cannot change it on the fly.
The alternative approach I am considering is to add the CSS to index.html like,
<link rel="stylesheet" href="node_modules/@progress/kendo-theme-bootstrap/dist/all.css">

and to try this solution.
Is this the right way to solve the problem or there is a better solution than this one?
Comment: i got it working with second approach. put css in index.html file and make it enable/disable. Please let me know if you need help.
Comment: I am looking for the same. If you find anything then please update here.
Comment: @dips. Thanks. I went for the second approach just like you did. No doubt, great minds think alike :p
Answer: Kendo wrote an article that is helpful: Dynamically Changing the Kendo UI Theme at Runtime.  Just use href="assets/my-theme.css" instead of their CDN.  I export a light theme and a dark theme using their ThemeBuilder.  In free tier you have to create, export, then delete the project as only one is allowed at a time.
index.html
<!doctype html>

  <meta charset="utf-8">
  <title>My App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" type="text/css" id="theme" href="assets/my-app-light.css" />

  <app-root></app-root>

app.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })
  export class AppComponent implements OnInit {
    public themeLinkElement: HTMLLinkElement | undefined = undefined;

    constructor() { }

    public async ngOnInit() {
        const darkTheme: boolean = Boolean(localStorage.getItem("darkTheme") ?? "false");

        if (darkTheme) {
            this.themeLinkElement = document.getElementById('theme') as HTMLLinkElement;
            this.themeLinkElement.href = "assets/my-app-dark.css";
        }
    }
}


Articles listed in custom order

Question: I have a Drupal 7.31 installation.
I have 3 rows in homepage, in which are listed 3 articles for each of them. Here a partial screenshot of Edit View for the first row, in which Sort criteria actually is set to "Publishing Date".

My customer asks me to be able to directly re-arrange the order and I found something about the "DraggableViews" module. I tried to follow two guides (DraggableViews and Custom Sort Drupal Content with the Draggable Views Module) without success.
Reasons are both:

Options and settings that I found in my installation are different from which are listed in tutorials
In both cases, I have to change "Format" in "Table" but doing so results in a wrong display template also in the website, corrupting layout. So I have to remain with "Unformatted List" for output.

It's not important that custom order is made with Drag&Drop, an order specified with dropdowns could be ok, but how to not affect view display, but only order?
Comment: Check for the [weight module](https://www.drupal.org/project/weight); it could help.
Comment: I read about needs to set "table" format to use it (the same as with DraggableViews). As I said, I need to mantain "Unformatted list" as output format
Answer: You can maintain a weight field with list option enabled for your content type and sort your view from your weight(an integer). In views sort criteria section put the weight criteria top if there are any others. Same answer I gave here
Answer: You could try the Node Queue Module, which will allow you to completely control what shows up in your view and in what order.
Basically, you add a nodequeue, add your three pieces of content to the queue and set the order. The nodequeue can automatically create a view for you (configurable), which you can then customize any way you want.
I've used the Weight module and definitely prefer node queues.
Comment: I can recommend using NodeQueues as well. We've had many clients using the queues to control content and it's order on landing pages, homepage, etc. It's relatively easy to understand also for non-technical person, it's drg&drop and autocomplete for adding content to it. What's a bit confusing for non-Drupal person is the name 'queue' - so they many times expect the content would disappear from the queue once the queue is saved - might be worth explaining :-).
Comment: Thank you. I'm working on a website not developed by my agency so there is not any documentation or someone to ask "why" he did something in some way..... You're speaking about _customizing a newly created view_ but I'm afraid about needs to change actual code. I would like to simply work on Drupal configuration to activate a different sorting method on existing items and not re-style their output.... can you understand my fears? :-)
Answer: I (also) highly recommend using the Draggable views module – and since it can actually be a bit difficult to get the first steps going here's some basics that should help:

Configure your (fields) view as you like. Be sure to add the field Content: Nid to the list and check Exclude from display on the next screen.
When you're done clone that view and set the Format of the clone to table. I usually name it the same as my fiest view and append a "_sort" to the name to that I know how is who. This will be your client's interface to sort the entries.
Add the Draggableviews: Content [Provide a draggable functionality.] to the list of fields to your _sort-table and then rearrange the fields' order so that the draggable field is first in the list.
Add Draggableviews: weight to the sorting criteria of both views. Choose your _sort-table under Display sort as to connect them.

This is basically the workflow i use everytime I install a sortable list view. I actually use quite a lot of them. Even for 'events' etc. draggable views can make sence since sometimes the client e.g. wants the "current" event before the "upcoming" event, even though  that woudn't be in coreect chronological order. Anyways – I hope I didn't miss any important details.
Answer: You use a separate view to organise the order of your nodes. So create table view to organise the view and link this view to the management menu and give the view a URL like admin/structure/yournameofview (this will appear under the structure menu for your client)
Once you have organised your nodes, go back to your "live" view and apply the draggable weight to the sort order.
You may need to create a relationship for this to work.

Articles listed in custom order


Soma de uma coluna não está dando o valor esperado

Question: Tenho uma tabela fictícia com duas colunas e alguns dados nela, conforme a imagem.

Quando eu executo a minha instrução SQL a seguir, o resultado da consulta é 22. O resultado não deveria ser apenas 12? Eu não consegui entender o porquê.
Alguém poderia me explicar?
SQL:
SELECT sum(a.coluna1)
  FROM dados AS A
 WHERE EXISTS (SELECT TRUE
                 FROM dados AS B
                 WHERE (a.coluna1/b.coluna2) >= 1);

Comment: Resolveu sua questão ?
Comment: **Vote hoje! Vote amanhã! Vote sempre! Vote consciente!** O seu voto é muito importante para nossa comunidade, contribua conosco e ajude a tornar a Stack Overflow em Português (SOpt) cada vez maior. Você pode saber mais em: [**Vote cedo, vote frequentemente**](https://pt.meta.stackoverflow.com/questions/159/vote-cedo-vote-frequentemente)
Answer: Esse seu SQL não faz muito sentido, acredito que o que você quis fazer foi o seguinte:
 SELECT sum(coluna1)
 FROM dados
 WHERE ((coluna1/coluna2) >= 1)

Vê se dessa forma funciona.
O que esse SQL que eu te mandei faz, é somar os valores quando a coluna1 / coluna2 for maior ou igual a 1.
Answer: O problema é que na subquery você diz que a linha atual da tabela A quando dividida por qualquer linha da tabela B, o resultado for maior/igual a 1, você irá somar o valor da coluna 1.
Usando a sua mesma sintaxe, para resolver esse problema, basta especificar que no subselect a linha de onde se pega a coluna B deve ser a mesma linha da coluna A, Veja o exemplo:
SELECT sum(a.coluna1)
  FROM dados AS A
 WHERE EXISTS (SELECT TRUE
                 FROM dados AS B
                 WHERE a.coluna1 = b.coluna1 and (a.coluna1/b.coluna2) >= 1);

Porém, Este código não faz muito sentido...
Como o colega Isaias demonstrou, não faz muito sentido dar um subselect com Exists para fazer esse calculo, basta fazer como ele fez.
Answer: Analisando seu SQL:
SELECT sum(a.coluna1)
  FROM dados AS A
 WHERE EXISTS (SELECT TRUE
                 FROM dados AS B
                 WHERE (a.coluna1/b.coluna2) >= 1);

Ele retorna 22 porque você diz para ele somar a coluna a.coluna1 quando a condição passada na cláusula WHERE entre "()" existir, ela retornou TRUE, portanto ele somou, caso retorna-se FALSE ele não somaria nada.

Acredito que seria isso que você queria:
SELECT SUM(a.coluna1)
  FROM dados AS a
 WHERE id IN (SELECT id
                FROM dados AS b
               WHERE (a.coluna1 / b.coluna2) >= 1);

Assim, sua consulta irá somar os dados da coluna a.coluna1 onde o id existir dentro da condição passada na clausula WHERE entre "()".


How to move web applications between different machines both running IIS 6.0?

Question: I am trying to move a number of websites / web applications (dozens) scattered over several servers to a new home. Both the source and destination are running IIS 6.0, but are not on the same network (ie different hosting providers and no VPN between the two).
I have had a look at Internet Information Services 6.0 Migration Tool and if that's the best on offer will have to use it, but I was wondering if there were any other solutions available.
Answer: The Web Deployment Tool is the new way to do that.  It allows migration of IIS6 to 6, 6 to 7 and 7 to 7.  It allows you to migration other things besides the site configuration.  For example, COM+, registry, content, SSL certs.
http://www.iis.net/extensions/WebDeploymentTool
Answer: I have used [IIS Export utility] before with good results. The free version has always worked fine for me. You can export directly to the new server if it is on the same network, or to a database that you can then move to new server and import.


Network card capable of capturing a tonne of packets and not dropping them?

Question: Edit:
Our server is trying to capture packets at between 500-600Mb/s, but is dropping packets 'due to kernel'.
Data is being written to SSDs, and isn't bottleneck there.
What things should I look for in a network card when choosing one that would be capable of handlind this kind of volume?
Not looking for product recommendations. Just advice on underlying technologies.
Thanks
Comment: If you don't quantify this it can't possibly be answered.  `A tonne` isn't quantitative; if you mean, eg, "*capture packets at 1Gb wireline speed*", please say so.  This is also perilously close to a request for product recommendations, which are off-topic for ServerFault (and all SE sites); it's only the last sentence that saves it from a close vote from me.  If it does get closed, don't take it personally, but please do read the help documents on what questions are permissible before posting again.
Comment: Thanks MadHatter. I'll reword the question to have it make more sense.
Comment: reworded original question, as per MadHatters advice!
Comment: Much better!  But it would also be interesting to see what you maen by "*due to kernel*".  If there are logs about dropped packets, can you paste a few in?  If not, could you tell us why you think it's a kernel issue?  OS details would be useful, too, in case there are OS-specific issues to address.
Comment: I think based on Tonnys advice below, the bottleneck is the mobo based NIC I'm using, it's advertised at 1Gb throughput, but on stress testing it, only achieved half of that (with other components performing ok).

thank you for your advice anyway!
Comment: Glad to hear you have an answer you're happy with!  In case you don't know, local etiquette is that you accept it by clicking the "tick" outline; this drives the SF reputation system for both you and the author of the answer.  My apologies if you already know this.
Answer: You will need a NIC with a PCI-e interface or a PCI-X. And it has to have a Intel or Broadcom gigabit chipset (or 10 Gb of course). Some (recent) Atheros chipsets work well too. The hardware design of other brands of chipsets just isn't up to it.
If you are using on-board adapters check the motherboard documentation how these hook up to the bus. I have seen slightly older server-boards that used PCI for the on-board NIC's even though the motherboard was PCI-e.
If you run on Windows you can try to use Microsoft own NetWork Monitor (netmon) tool to capture the traces. (Output is compatible with WireShark). Netmon integrates closer with the OS than WinPCap which is used by WireShark and may give you a little more throughput.
Anyway: 0% packet loss doesn't exist. Due to the x86 architecture and the way the Windows kernel works you will see a lost packet sometimes. It just can't guarantee the delivery of every IO packet that comes through the hardware.
(That is one of the reasons that high-end network monitor devices are so bloody expensive. They need very special hardware and a custom OS to make guaranteed wire-speed capturing at any speed possible.)
I run regular 1 Gb/s captures at wirespeed for several hours at a time.
I don't need to see realtime what is captured. That really helps in keeping the capture performance up. The GUI would really slow things down.
I use a medium spec workstation PC (First generation Core-i7, 32G RAM, Win7 64-bit) with SAS disk (not SSD).
Netmon gives me slightly better captures then WinPCap (About 1 dropped packet per minute, versus about 1.3 packets/minute.)


Attitude true for Markov Chains(Maybe duplicate)

Question: Suppose, that we have a Markov-chain with finite domain. For all $i,j$ elements $P_{i,j}>0$, where $P$ is our matrix. Show, that reversible(sorry, I forgot that out) stationary distribution exists only, and only if for all $i,j,k$
$$P_{i,j} P_{j,k} P_{k,i} = P_{i,k} P_{k,j} P{j,i}$$
What I tried to was to make $i$ fix and I made $\pi_j=c\frac{P_{i,j}}{P_{j,i}}$ distribution, but I am stuck how to go forward.
Any help appreciated :)
Answer: Not true at all.  Any irreducible aperiodic finite Markov chain has a unique stationary distribution.  This follows e.g. from the Perron-Frobenius theorem.
Comment: Sorry, I forgot one word out of my question, maybe you want to see it now(reversible) :)
Answer: For a counterexample, consider $$P=\begin{bmatrix}\frac16& \frac13& \frac12\\ \frac14& \frac 18& \frac58\\\frac15& \frac7{10}&\frac 1{10} \end{bmatrix}. $$
Then $P_{ij}>0$ for all $i,j$ so the process is aperiodic and the (unique) stationary distribution is given by any of the rows of $\lim_{n\to\infty}P^n$. However, $$P_{12}P_{23}P_{31} = \frac13\cdot\frac58\cdot\frac15 = \frac1{24} $$
and $$P_{13}P_{32}P_{21}=\frac12\cdot\frac7{10}\cdot\frac14=\frac7{80} $$ are not equal.


Why is $\mathbb{P}(X<Y) = \mathbb{P}(Y<X)$ for two independent random variables with same mass function?

Question: Let $X$ and $Y$ be independent random variables taking values in the positive integers and having the same mass function. Why is it that
$$ \mathbb{P}(X<Y) = \mathbb{P}(Y<X). $$

I understand that
$$ \begin{align*}
\mathbb{P}(Y>X) &= 1- \mathbb{P}(Y\le X)\\
 &= 1- \mathbb{P}(X=Y) - \mathbb{P}(Y<X).
\end{align*}$$
For the mass function $f(x)=2^{-x}$, $x=1,2,\dots$ I found that
$$ \mathbb{P}(X=Y) = \sum_{x=1}^\infty f(x)f(x) = \sum_{x=1}^\infty4^{-x}=\frac{1}{3}. $$
This yields that
$$ \mathbb{P}(X<Y)+\mathbb{P}(Y<X)=\frac{2}{3}. $$
So if $\mathbb{P}(X<Y)=\mathbb{P}(Y<X)$ I see that this is $\frac{1}{3}$, but I don't understand why they are the same.
Comment: The variables are independent and identically distributed, in other words, how can you tell which one is X and which one is Y? I mean, if I tell you I've randomly drawn two balls from two different urns with the same distribution of coloured balls inside. How can you tell which ball was drawn from which urn?
Comment: @Raskolnikov Ah yeah, I think I get it. Thanks! That kind of examples are really useful.
Answer: not even sure they have to be independent (after all correlation is symmetric), but in the independence case:
$$\begin{align}\mathbb{P}(Y\lt X) &= \mathbb{P}(Y-X \lt 0)\\
&=\int\limits_{\mathbb{R}}\mathbb{P}(Y-X \lt 0\;|\;X=t)\cdot\phi_X\cdot\mathrm{d}t\\
&=\int\limits_{\mathbb{R}}\mathbb{P}(Y\lt t )\cdot\phi_X\cdot\mathrm{d}t\end{align}\\$$
And similarly: $\mathbb{P}(X\lt Y) =
\int\limits_{\mathbb{R}}\mathbb{P}(X\lt t )\cdot\phi_Y\cdot\mathrm{d}t\\$, but since $\phi_X=\phi_Y$ (the respective densities) and $\mathbb{P}(X\lt t )=\mathbb{P}(Y\lt t )$ the two probabilities are equivalent; (someone please correct any flaws in this!) Cheers
Comment: Your argument very much uses independence, when you declare that $P(Y-X<0\mid X=t)=P(Y<t)$.
Comment: you're completely right, sorry not awake yet, will edit!
Comment: edited to remove the claim that the argument proves redundancy of independence, hope that is better? still convinced for 2 RVs independence is not required, just haven't written out a proof of this (unless am mistaken here too) Anyway thanks very much for pointing out error.


Let $x_n = \sum_{ j=1}^n \frac1j$. Show that for every $k$ we have $\lim _{n→∞} |xn+k −xn| = 0$, yet {$x_n$} is not Cauchy.

Question: The problem goes
Let $x_n = \sum_{j=1}^{n} \frac{1}{j}$. Show that for every k we have $\lim_{n \to \infty}|x_{n+k}-x_n|=0$, yet {$x_n$} is not Cauchy.
My proof for this goes: By Cauchy Condensation, $x_n = \sum_{j=1}^{n} \frac{1}{j}$ converges iff $\sum{1}=n$ converges. So {$x_n$} does not converge since {$n$} does not converge, which implies that {$x_n$} is not Cauchy.
Is my wrong?
Comment: Your proof seems fine, assuming that you've already shown Cauchy sequences must converge. Otherwise just show $|x_n-x_m|$ exceeds any $\epsilon$ for large enough $n,m$.
Answer: A direct proof
is quite straightforward.
If
$x_n
= \sum_{j=1}^{n} \frac{1}{j}
$
then
$x_{n+k}-x_n
= \sum_{j=n+1}^{n+k} \frac{1}{j}
\lt \sum_{j=n+1}^{n+k} \frac{1}{n}
=\dfrac{k}{n}
\to 0
$
as
$n \to \infty$.
To show that
$x_n$ is not Cauchy,
do the traditional thing
and choose
$m \ge 2n$.
Then
$x_m-x_n
=\sum_{j=n+1}^{m} \dfrac1{j}
\ge\sum_{j=n+1}^{m} \dfrac1{m}
=\dfrac{m-n}{m}
=1-\dfrac{n}{m}
\ge 1-\dfrac{m/2}{m}
=\dfrac12
$.
Note that,
if $m \ge kn$,
then
$\begin{array}\\
x_m-x_n
&=\sum_{j=n+1}^{m} \dfrac1{j}\\
&\ge\sum_{j=n+1}^{kn} \dfrac1{j}\\
&=\sum_{i=1}^k \sum_{j=(i-1)m+1}^{im} \dfrac1{j}\\
&\ge\sum_{i=1}^k \sum_{j=(i-1)m+1}^{im} \dfrac1{im}\\
&\ge\sum_{i=1}^k \dfrac{m}{im}\\
&=\sum_{i=1}^k \dfrac{1}{i}\\
&=x_k\\
\end{array}
$
Since
$x_{2n}-x_n \ge \dfrac12$,
$x_k$ is unbounded
as $k \to \infty$
so that
$x_m-x_n$
can be made arbitrarily large
by making $m$ large enough
compared with $n$.
For example,
since
$x_{2^k}
\ge \dfrac{k}{2}
$,
$x_{2^kn}-x_n
\ge x_{2^k}
\ge \dfrac{k}{2}
$.


Can't get the list of worksheets in a workbook stored in sharepoint using microsoft-graph-api

Question: I'm not able to get the list of worksheets in a workbook for some reason. this might be related to my other issue which is can't add records in a excel table
this is the full error message that is returned to me when calling this endpoint: https://graph.microsoft.com/v1.0/sites/OurSiteId/drives/OurDriveId/Items/OurFileId/workbook/worksheets
<code>{
    "error": {
        "code": "MaxRequestDurationExceeded",
        "message": "We're sorry. We couldn't finish what you asked us to do because it was taking too long.",
        "innerError": {
            "code": "gatewayTimeoutUncategorized",
            "message": "The service wasn't able to complete the request within the time limit.",
            "innerError": {
                "code": "MaxRequestDurationExceeded",
                "message": "We're sorry. We couldn't finish what you asked us to do because it was taking too long."
            },
            "date": "2020-11-24T12:55:28",
            "request-id": "c28bc40e-4ba6-4606-8c5a-ea0663cafa29",
            "client-request-id": "c28bc40e-4ba6-4606-8c5a-ea0663cafa29"
        }
    }
}
</code>
there appears to be a file size limit of a workbook as described here file limit in sharepoint but still, the file that I am working is only 40mb (limit is 50mb) and I am already encountering access issues on the file.
The file that I am working already has more than a million records, is that possibly the cause of the issue?
Comment: It may be the case, but just make sure you can open the excel file in your browser/onedrive and you can write the info manually. As a rule of thumb make sure that it doesn't contain any styles, any empty cells/columns, any macro's etc.
Comment: Moving this to answer. So it can be useful to others. Consider upvoting it. If you have more questions or update, go ahead and ask it,
Answer: It may be the case, but just make sure you can open the excel file in your browser/onedrive and you can write the info manually. As a rule of thumb make sure that it doesn't contain any styles, any empty cells/columns, any macro's etc


Laravel session table add additional column

Question: I want to add an extra column user_id on session table.
The reason is, some time there are spammer to sign up fake account, once I know that the user is spammer, I want to log the user out by deleting the session record.
Is it possible to achieve this?
Answer: This is the session migration schema:
Schema::create('sessions', function($table)
{
    $table->string('id')->unique();
    $table->text('payload');
    $table->integer('last_activity');
    $table->integer('user_id')->unsigned(); //// ADD IT!
});

You can add whatever column you like on it, Laravel won't mind.
Or you can create a new migration and make it add a column on that table.
$table->integer('user_id')->unsigned();

You can create a Model for it:
class SessionModel extends Eloquent {

}

And do whatever you need with it:
$session = SessionModel::find(Session::getId());
$session->user_id = 1;
$session->save();

But if you're thinking about adding more info to the payload, which is where Laravel keeps the session data, although I think it's possible, you'll have to dig a bit more in Laravel's code to do that.
Comment: @Antonio Carlos Ribeiro thank you. I was at same condition. I had query, can you let me know, that I am planning to lock login from single location at a time and so I am moving ahead with database Auth/session drivers. So login with same credential from another location show a message "Already loggied in from some another location". Would this approach be fine? Thanks
Comment: I get this error when ever I try to save session`SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' `
Comment: @EdmundSulzanok if you create a Model class for the session, you need to make sure you include `public $timestamps = false;`. Otherwise, your schema needs to include `$table->timestamps();`.
Answer: Short version of migration
if( Schema::hasTable('sessions') ) {
    $table->integer('user_id')->unsigned();
}

Need to check if exist session table. Or create it before:
php artisan session:table
php artisan migrate

https://laravel.com/docs/5.7/session#introduction
Answer: This is the session migration schema:
Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->unique();
        $table->integer('user_id')->nullable();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->text('device')->nullable();
        $table->text('payload');
        $table->integer('last_activity');
    });

To add the information to the payload after adding COLUMN to the TABLE, just change the DatabaseSessionHandler class.
path: vendor/laravel/framework/src/illuminate/Session
Ex:
1º Creates the function
protected function device()
{
    $agent = new \Jenssegers\Agent\Agent;

    if ($agent->isDesktop()){
        $device = 'desktop';
    }

    return $device;
}

2º add in function addRequestInformation (& $ payload)
protected function addRequestInformation(&$payload)
{
    if ($this->container->bound('request')) {
        $payload = array_merge($payload, [
            'ip_address' => $this->ipAddress(),
            'user_agent' => $this->userAgent(),
            'device' => $this->device(),
        ]);
    }

    return $this;
}

Ready, device added to the table when the user login.


Wordpress - erro ao iniciar o site

Question: Site em wordpress de um cliente de um colega saiu do ar.
Mensagem ao entrar no site:

PHP Warning:  require(wp-includes/compat.php) [function.require]: failed to open stream:
  No such file or directory in
  E:\home\tecnoservicebr\web\wp-settings.php on line 71
      PHP Warning:  require(wp-includes/compat.php) [function.require]: failed to open stream:
  No such file or directory in
  E:\home\tecnoservicebr\web\wp-settings.php on line 71
      PHP Fatal error:  require() [function.require]: Failed opening required
  'wp-includes/compat.php' (include_path='.;c:\php5\includes') in
  E:\home\tecnoservicebr\web\wp-settings.php on line 71

Imagino que seja porque o wordpress está buscando o arquivo com o caminho local, porem não sei mudar isso, alguem pode me ajudar, por favor?
Answer: O erro não é do caminho do WordPress. No wp_settings.php ele chama esse arquivo com ABSPATH e por isso o caminho vai estar sempre certo.
Normalmente os erros com compat.php são causados por algum problema com o diretório wp_includes. Este arquivo é o primeiro que o WordPress tenta ler deste diretório e se o diretório está com algum problema dispara esse erro. Existem dois erros comuns:

Diretório não existe (provavelmente o seu caso)
Permissões do diretório/arquivos estão erradas

Nos dois casos a solução mais rápida e simples é:

Apagar a pasta wp-includes (se ela existir).
Baixar novamente o pacote de instalação de br.wordpress.org
Descompactar o pacote e subir apenas a pasta wp-includes por FTP sem se conectar como "root" (isso evita erros de permissão).
Conferir se as permissões da pasta wp-includes e subpastas são 755 e dos arquivos 644.

O 3 e 4 são um pouco diferentes se o seu servidor é Windows.

Wordpress - erro ao iniciar o site


Distribution of $\mathbf{x}^\top \mathbb{A} \mathbf{x} + \mathbf{b}^\top \mathbf{x}$, when $\mathbf{x}\sim\mathcal{N}$?

Question: Let $\mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma)$ be a random vector following a multivariate normal density distribution. I am interested in the density function of the transformed variable
$$z = \mathbf{x}^\top \mathbb{A} \mathbf{x} + \mathbf{b}^\top \mathbf{x}$$
where $\mathbb{A}$ is a constant matrix and $\mathbf{b}$ a constant vector. Is there a name for the distribution associated with $z$?
I presume this related to the Chi-squared distribution, which is a special case of this problem. But I'm not sure my problem can be reduced to the Chi-squared distribution?
Any further ideas?
Update: Upon further thought and thanks to @whuber comment, I see the distribution of $z$ might not have a closed form. A less ambitious goal is then to compute the moments of $z$, starting with the mean, variance, ....
The mean is actually easy:
$$\langle z\rangle = \mathrm{Tr}(\mathbb{A}\Sigma) + \boldsymbol{\mu}^{\top}\mathbb{A}\boldsymbol{\mu} + \mathbf{b}^{\top}\mathbf{u}$$
Comment: It is a sum of a scaled non-central Chi-squared distribution and scaled versions of Chi-squared distributions.  It has no simple form unless $\mathbb A$ is a multiple of the identity.  When $b=0,$ all the distributions involved are Chi-squared -- equivalently, they are scaled $\Gamma(1/2)$ distributions -- and the thread at https://stats.stackexchange.com/questions/72479 shows what their sum looks like.
Comment: You can find answers in recent threads [initiated by Yaroslav Bulatov](https://stats.stackexchange.com/users/511/yaroslav-bulatov).  Alternatively, upon diagonalizing $\mathbb A + \mathbb A^\prime,$ recognize that $z$ is a constant plus a linear combination of independent non-central Chi-squared$(1)$ distributions and apply [the usual rules for computing with covariances.](https://stats.stackexchange.com/questions/38721)
Comment: Note that even $x'Ax$ does not have to be $\chi^2$ distributed.  Check the famous Cochran theorem.
Comment: The mean you presented should be (for general $A$ not necessarily symmetric) $E[z] = \frac{1}{2}\operatorname{Tr}((A + A^\top)\Sigma) + \frac{1}{2}\mu^\top(A + A^\top)\mu + b^\top\mu$.
Comment: @whuber Thanks. I realize the full distribution has no closed-form. So I decrease my ambitions. I would like now to compute the first moments of $z$ (mean, variance, maybe higher).
Comment: Thanks! @Zhanxiong I think you're missing some 1/2 factors ?
Comment: @becko What do you mean?  I had $1/2$ in the mean expression.
Comment: I think I should get your expression if I replace $A$ in mine, with $(A + A^T) / 2$, don't you agree? If I do that, I get extra 1/2 factors (so 1/4).
Comment: @becko Are you talking about the mean or variance?
Comment: The mean. I have done some numerical checks which seem to agree with my expression.
Comment: @becko No.  You expression doesn't agree with the well known result when $A$ is symmetric: $E[z] = \operatorname{tr}(A\Sigma) + \mu'A\mu + b'\mu$.  The "$1/2$" in your expression is redundant if you do not include the $A'$.
Answer: $\DeclareMathOperator{\Var}{Var}$
$\DeclareMathOperator{\Cov}{Cov}$
$\DeclareMathOperator{\tr}{tr}$
The variance of $z$ can be computed as follows (suppose $A$ is symmetric, which is standard when the quadratic form is discussed. For the non-symmetric case, rewrite $z$ as $z = x'Bx + b'x$, where $B = (A + A')/2$ and replace $A$ below with the symmetric matrix $B$).
In this thread, it is shown that when $x \sim N(\mu, \Sigma)$ and $A$ is symmetric,
\begin{align}
\Var(x'Ax) = 2\tr((A\Sigma)^2) + 4\mu'A\Sigma A\mu.
\end{align}
Therefore, to evaluate
\begin{align}
\Var(z) = \Var(x'Ax + b'x) = \Var(x'Ax) + \Var(b'x) + 2\Cov(x'Ax, b'x), \tag{1}
\end{align}
it suffices to evaluate
\begin{align}
\Cov(x'Ax, b'x) = E[x'Axb'x] - E[x'Ax]E[b'x].
\end{align}
Since $E[x'Ax] = \mu'A\mu + \tr(A\Sigma), E[b'x] = b'\mu$, the only difficult part left is $E[x'Axb'x]$.  To this end, write $x = \mu + y$, where $y \sim N(0, \Sigma)$, then
\begin{align}
& x'Axb'x = (\mu + y)'A(\mu + y)b'(\mu + y) \\
=& (\mu'A\mu + 2\mu'Ay + y'Ay)(b'\mu + b'y) \\
=& \mu'A\mu b'\mu + \mu'A\mu b'y + 2b'\mu\mu'Ay + 2\mu'Ayb'y + b'\mu y'Ay + y'Ayb'y
\end{align}
In my answer to this thread, it is argued that for $y \sim N(0, \Sigma)$, we have
\begin{align}
E[y'Ayb'y] = 0.
\end{align}
In addition,
\begin{align}
& E[\mu'Ayb'y] = E[y'b\mu'Ay] = \tr(b\mu'A\Sigma) = \mu'A\Sigma b,  \\
& E[b'\mu y'Ay] = b'\mu\tr(A\Sigma).
\end{align}
It thus follows that
\begin{align}
& E[x'Axb'x] = \mu'A\mu b'\mu + 2\mu'A\Sigma b + b'\mu\tr(A\Sigma), \\
& \Cov(x'Ax, b'x) = \mu'A\mu b'\mu + 2\mu'A\Sigma b + b'\mu\tr(A\Sigma) -
(\mu'A\mu + \tr(A\Sigma))b'\mu \\
&\phantom{\Cov(x'Ax, b'x)} = 2\mu'A\Sigma b.
\end{align}
Substituting
\begin{align}
& \Var(x'Ax) = 2\tr((A\Sigma)^2) + 4\mu'A\Sigma A\mu, \\
& \Var(b'x) = b'\Sigma b, \\
& \Cov(x'Ax, b'x) = 2\mu'A\Sigma b
\end{align}
into $(1)$, we get
\begin{align}
\Var(z) = 2\tr((A\Sigma)^2) + 4\mu'A\Sigma A\mu + b'\Sigma b + 4\mu'A\Sigma b.
\end{align}
Comment: @becko This is not right.  To see that, just set $b = 0$ first and compare your expression with [this answer](https://stats.stackexchange.com/questions/427332/variance-of-quadratic-form-for-multivariate-normal-distribution/598719#598719).
Comment: I get a similar expression, but off by some of the factors, and also the second-to last term I have is different.. I will do some numerical verifications to check
Comment: @becko As I wrote at the beginning of this answer, if $A$ is non-symmetric, then you need to replace $A$ in the last expression with $(A + A')/2$ -- that may be what you meant by "off some of the factors".
Comment: This is the expression I get for the variance: $\frac{1}{2}tr(\mathbb{A\Sigma A\Sigma}) + \mathbf{u}^{\top}\mathbb{A\Sigma A}\mathbf{u} + 2\mathbf{b}^{\top}\mathbb{\Sigma A}\mathbf{u} + \mathbf{b}^{\top}\Sigma\mathbf{b}$, assuming $A$ is symmetric.
Comment: Ah sorry, it's my fault. I was working with the expression $ z = \frac{1}{2}\mathbf{x}^{\top}\mathbb{A}\mathbf{x} + \mathbf{b}^{\top}\mathbf{x} + c$
Comment: So now I agree with your expression.
Comment: I still don't agree with the variance though ... if I take my expression in the previous comment, and multiply all the $A$ by 2, you see I never get the $6\mu A\mu b\mu$ term you get.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/141281/discussion-between-zhanxiong-and-becko).


Including a quadratic effect for an ordinal variable in a regression analysis

Question: It's common for many datasets to have ordinal versions of numerical variables, such as age groups (e.g. "Under 20", "20-30", "30-40", etc.) or time groups (e.g. "Less than 15 minutes", "15-30 minutes", "30-60 minutes", etc.).
Sometimes the continuous versions of these variables are suspected to have a curvilinear relationship with the outcome variable (e.g. age is positively association with income until retirement age and then has a negative trend).
In such cases when these variables are continuous, I would simply create a new squared version of it and include both terms in the model (e.g. regressing income on age and age2).
Is this still okay to do with ordinal variables? Using the time group variable above, it would look like this:
 Original Var. Label | Original Var. Coding | Squared Var. Coding
------------------------------------------------------------------
15 minutes or less   | 1                    | 1
15-30 minutes        | 2                    | 4
30-60 minutes        | 3                    | 9
1-2 hours            | 4                    | 16
2 hours or more      | 5                    | 25

Would this be okay in a regression analysis? If no, what are the alternatives? If so, are there any caveats?
Answer: If you are entering the categorical variable as a set of binary dummies, you are already allowing the relationship to have a very flexible form that should pick up the quadratic non-linearity that you are worried about. It will even pick more complicated patterns as long as the discretization cut points aren't picked to purposely obscure the relationship.
Your coding scheme will yield identical numerical results with the dummy coding since an indicator for x=5 is identical to an indicator to x'=25.
I would generally avoid entering the categorical variables as continuous.
Comment: Yes, that is right.
Comment: To clarify, are you saying that instead of having two variables--an ordinal one coded 1:5 and a squared version of that ordinal one--that I should instead take the original one and spin it out into five dummy variables instead (15 minutes or les = 1, otherwise 0; 15 to 30 minutes = 1, otherwise 0; etc.)?


Why "Stable" in Stable vector bundle and Stable homotopy theory?

Question: Why/what/how does stable mean in the

Stable vector bundle?

Stable homotopy theory?

Of course, it is described in the Wiki texts in a formal way. But I wonder what are the intuitions and concepts behind both stables in the text.
Another way to phrase it may be that when we remove stable, what makes the differences for vector bundle and homotopy theory?
Comment: @LeeMosher Stable vector bundles are intrinsically linked to stable homotopy theory through the fact that adding a trivial bundle and taking the Thom complex is the same as taking the Thom complex and suspending.
Comment: Those two meanings of "stable" look entirely unrelated to me.
Comment: Except that the link provided in this post for "stable vector bundle" does not seem to be related to the stabilization process in $K$-theory, instead it refers to constructions in geometric invariant theory. Is there some link between those? (I honestly don't know).
Comment: @LeeMosher Oh I'm sorry! I figured I knew what a stable vector bundle was and didn't need to look.
Comment: Thanks for the comments -- so for stable tangent bundle, stable tangential structure, and stable homotopy group, are these stable directly related?
Answer: Any good answer to this would be very long, so perhaps some people can answer with alternative perspectives.
Essentially stability removes "pathologies" that only happen in low dimensions. For example, there is only one tangent bundle to a manifold, but many normal bundles. However, if we make the codimension of our embedding large enough all normal bundles become isomorphic, so stabilization here allows us to talk about "the" stable normal bundle. There are other reasons to care about stable bundles, for example, most of our characteristic classes care only about the stable isomorphism type. And perhaps the most important reason is that stable bundles (or the slightly different virtual bundles), form a group rather than a monoid.
When it comes to homotopy theory, stable homotopy theory tends to be more algebraic than homotopy theory. This can be seen at the level of spaces. There is no natural group structure on $[X,Y]$ but if $X$ is a suspension, then this naturally has a group structure. Moreover, if $X$ is a double suspension, this is even nicer than a group, it is an abelian group.
One really concrete way of seeing the algebraic difference between spaces and spectra is through the following example: Quillen proved the remarkable result that (subject to a small connectivity assumption) spaces up to rational equivalence have the exact same homotopy theory as rational differential graded commutative algebras. The proof of this is rather involved.
Of course we can ask what spectra up to rational equivalence are? The answer is just rational chain complexes, and it is very easy to see. It follows from the fact that rationally every spectrum is equivalent to the generalized Eilenberg-MacLane spectrum with the same homotopy groups.
To me, chain complexes are entirely algebraic, but products on a chain complex can encode a lot of geometry (i.e. cup products on singular cochain complexes or de Rham wedge products, etc.)
Now what "pathology" is this a result of? I haven't thought about this in a while, but I think it is due to the fact that in the stable world the rational Eilenberg-MacLane space is equivalent to the rational Moore space (the rational sphere). However, unstably they are not equivalent. This is due to an unstable obstruction in the cohomology of the even dimensional Eilenberg-MacLane space, the cup square, so passing to the stable world this vanishes.
This will imply that Postnikov towers for rational spectra are all trivial, but for rational spaces they could have nontrivial k invariants. Of course, there is so much more that can be said, so I hope others, who assuredly know a lot more stable homotopy theory than me, can contribute


Change class signature, process old xml serialized instances

Question: Let's assume I have got a class like:
public class SomeObject
{
    public Guid InternalId { get; set; }
    public string Address { get; set; }
}

I store instances of this object into the ASP.NET profile. It get's XML serialized and everything is fine. Now I want to reduce the size of the profile, and I want to replace the long propertynames by something shorter:
public class SomeObject
{
    [XmlElement("id")]
    public Guid InternalId { get; set; }
    [XmlElement("ad")]
    public string Address { get; set; }
}

New objects get serialized just fine, and short, and everything. However: the XmlSerializer cannot deserialize the old XML files. Is there any hook I can apply to change a classes signature, but still be able to deserialize old instances.
I have the eventhandler XmlSerializer_UnknownElement, and then I can set the value of the target property myself, however I only have the value of the element as a string, so I should parse it by myself which is quite error-prone.
Answer: Two answers, one I know will work, the other I'm not sure.
1) Implement the IXmlSerializable interface in your class. Its very easy to do, and gives you complete control over how the class is serialized and deserialized.
http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx
2) Not sure if this will work, but try adding another XmlElementAttribute tag to your class properties. It compiles, but I'm not sure if it'll work.
public class SomeObject
{
    [XmlElement("InternalId")]
    [XmlElement("id")]
    public Guid InternalId { get; set; }
    [XmlElement("Address")]
    [XmlElement("ad")]
    public string Address { get; set; }
}

Comment: Double `XmlElements` only works to supply an `XmlChoiceIdentifier`. Writing all this code myself is somewhat of a last resort, I cán solve it too with `UnknownElement` but it gets hacky.


accessing datatables data via click binding

Question: I am using Jquery DataTables 1.7.6 with JQuery 1.8.6. I am trying to setup a datatable that has a button in one row and then capture the click of that button to move the row to another table. I'm having a problem getting at the data in the DataTable to call the add and remove functions.

Answer: I think the issue is that fnGetData returns a data object of the contents of a particular row, not the node itself.  But fnAddData and fnDeleteRow each require the TR node, not the data object.  Two ways to solve this:
Option 1: If you're certain that $(this).closest('tr')[0] is returning the entire TR element for the row you want, then change the first line of each of your click functions to:
var data = $(this).closest('tr')[0];

This should provide the functions in the next two lines the appropriate TR node to perform the action.
Option 2: If you're unsure that the $(this).closest('tr')[0] is returning the entire TR element (you can check this by console.log()-ing it to see if the appropriate content is returned) then I would consider using Datatable.net's fnGetPosition on the TD element that the button is in.  I've found it to be far more flexible and it will always return an element that you can use with fnAddData and fnDeleteRow.
Good luck!


Kronecker delta in multivariate Taylor expansion

Question: I find the following equation in a quantum theory book where multivariate Taylor expansion was discussed. The equation uses Kronecker delta to change the subscripts which looks bizarre to me, and it goes
$$\phi_{\alpha \beta}\left(\boldsymbol{R}_{i}+\boldsymbol{d}_{\kappa}-\boldsymbol{R}_{j}-\boldsymbol{d}_{\nu}\right)\left.u_{i \kappa, \alpha} u_{i \kappa, \beta}\right.=\left[\sum_{j^{\prime} \nu^{\prime}} \phi_{\alpha \beta}\left(\boldsymbol{R}_{i}+\boldsymbol{d}_{\kappa}-\boldsymbol{R}_{j^{\prime}}-\boldsymbol{d}_{\nu^{\prime}}\right)\right] \delta_{i j} \delta_{\kappa \nu}u_{i \kappa, \alpha} u_{j \nu, \beta},\tag{1}$$
where $\phi$ is a function of the difference of two coordinates, $\boldsymbol{R}_i+\boldsymbol{d}_{\kappa}$ and $\boldsymbol{R}_j+\boldsymbol{d}_{\nu}$. And $\phi_{\alpha\beta}$ is
$$\phi_{\alpha \beta}\left(\boldsymbol{R_{i}+d_{\kappa}-R_{j}-d_{\nu}}\right)=\frac{\partial^{2} \phi\left(\boldsymbol{R_{i}+d_{\kappa}-R_{j}-d_{\nu}}\right)}{\partial R_{i \alpha} \partial R_{i \beta}}.\tag{2}$$
with $R_{i\alpha}$ being the $\alpha$-element of coordinate $\boldsymbol{R}_i$. If $u_{i\kappa,\alpha}$ is the displacement of the coordinate $\boldsymbol{R}_i+\boldsymbol{d}_{\kappa}$ at $\alpha-$direction, then where does the summation in (1) come from? I'm trying to derive (1) using the properties of Kronecker delta but so far not much progress has been made.
Answer: The RHS of eq.(1) should be first written as:
$$\sum_{j^{\prime}\nu^{\prime}}\phi_{\alpha\beta}(\boldsymbol{R_i+d_{\kappa}-R_{j^{\prime}}-d_{\nu^{\prime}}})\delta_{jj^{\prime}}\delta_{\nu\nu^{\prime}}u_{i\kappa,\alpha}u_{i\kappa,\beta}$$
and then
$$\sum_{j^{\prime}\nu^{\prime}}\phi_{\alpha\beta}(\boldsymbol{R_i+d_{\kappa}-R_{j^{\prime}}-d_{\nu^{\prime}}})\sum_{j\nu}\delta_{jj^{\prime}}\delta_{\nu\nu^{\prime}}u_{i\kappa,\alpha}\delta_{ji}\delta_{\nu\kappa}u_{j\nu,\beta}$$
which gives
$$\sum_{j^{\prime}\nu^{\prime}}\phi_{\alpha\beta}(\boldsymbol{R_i+d_{\kappa}-R_{j^{\prime}}-d_{\nu^{\prime}}})\delta_{ij^{\prime}}\delta_{\kappa\nu^{\prime}}u_{i\kappa,\alpha}u_{j\nu,\beta}$$


Link na barra de StatusBar Delphi 10

Question: Preciso colocar um link na barra de status do sistema, clicando nela vai abrir uma outra função que já esta pronta, a StatusBar possui 3 panels e somente a 3 deve abrir quando clicar. Estou usando o evento OnDrawPanel para tentar formatar o texto em formato de link.
Segue o código:
procedure TfAAA001.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
begin
  if Panel.Index = 2 then
  begin
    StatusBar1.Canvas.Font.Color := clBlue;
    StatusBar1.Canvas.FillRect(Rect);
    StatusBar1.Canvas.TextOut(Rect.Right, Rect.Top + 1, Panel.Text);
  end;
end;

Assim a StatusBar não esta iniciando, alguém sabe como resolver.
Comment: Conseguiu realizar os testes com a resposta que propus?
Answer: O código está correto, porém para disparar o evento OnDrawPanel precisa setar a propriedade style do panel como psOwnerDraw.
Isto pode ser feito tanto em design ou via código.
Penso em algo no Create do form, algo como:
StatusBar1.Panels.Items[2].Style := psOwnerDraw;

Agora para o click:
var
  vPosicao: Tpoint;
begin
  vPosicao := ScreenToClient(Mouse.CursorPos);

  if vPosicao.x <= StatusBar1.Panels[0].Width then
    ShowMessage('Clicou no Primeiro')
  else if vPosicao.x <= (StatusBar1.Panels[0].Width + StatusBar1.Panels[1].Width) then
    ShowMessage('Clicou no Segundo')
  else
    ShowMessage('Clicou no Terceiro');
end;

Comment: resolvi de uma forma diferente mas foi com este conceito, usei 3 eventos, ondraw, onclick e onmousemouve

ondraw usei um codigo para formatar o statusbar specifico como um link, deixando azul, e sublinhado.

usando uma função parecida com esta sua eu recebia a posição no omousemove, que quando era a que eu queria trocava o cursor para um tipo de link.

e na onclick era a função para abrir realmente o link.

Link na barra de StatusBar Delphi 10


Interpretations of sets and set membership

Question: I apologize in advance if anything I say in the following is incorrect and I appreciate any corrections if anything is incorrect. My knowledge of set theory and logic is extremely limited, however, I try to read something about those topics on my own as I feel like it adds to "everyday mathematics".
In ZFC the notions of set and set membership are not defined but rather described axiomatically by the ZFC axioms. Thus, as far as I understand, sets are just that, whatever that is and by the axioms one can derive statements about those objects.
In naive set theory any collection of objects (where objects is a primitive notion as well; anything is an object) is viewed as a set intuitively representing the notion of a collection of abstract objects. Without precise axioms however, this leads to paradoxes such as Russels Paradox.
I heard of a philosophical view, which views mathematics as a game or a formal manipulation of strings, called formalism. However, if one motivates the axioms of ZFC a bit more platonistic, namely by formalizing objects that occur in the real world such as numbers, one would probably still view a set as a formalization of a collection of objects under certain restrictions, which are given by the axioms. In this case, I could view a statement such as $s \in S$ more intuitively as "$s$ names an object which is contained in the collection called $S$, whatever that object may be."
Question 0) I have no knowledge about interpretation/semantics of formal logical sentences and how it works exactly. Are there good references to study those? I am not sure how long it would take, but I would find it interesting to read about in my free time. It may have been incorrect, but I myself have always thought that mathematical statements always have a certain interpretation, which is why I think this might be an interesting topic for me to read about. I think that strictly speaking statements are formal at first without interpretation, but can be interpreted, right?
Question 1) Are sets in ZFC also interpreted as collections of objects or does one not use an interpretation at all? Since there are probably a wide variety of views, I should reformulate: Is it valid to interpret sets as a collection of objects and objects being a member of the set if and only if they satisfy the "$\in$" relation, or is it invalid?
Question 2) Is this view used by (some) professional mathematicians or is this view of a set as a collection mostly abandoned after encountering that naive set theory leads to contradictions? I myself am not sure which view is adopted in lectures for example, since only in introductory lectures it is explicitly mentioned that the naive view is adopted. However, I find it way easier to deal with the concepts by viewing sets as collections and elements as objects in the set. Therefore I wanted to ask whether it is valid to keep this view, or if this view is mostly abandoned.
A thought: I could view maths from a formalist point of view, but I myself find it more motivating and realistic to have a more platonic view. Wouldn't it be even more surprising that maths can be used in the real world if one adopts a purely formalistic view?
Comment: You might be interested in [model theory](https://en.wikipedia.org/wiki/Model_theory).
Comment: Qu.1) compare [von Neumann universe](https://en.wikipedia.org/wiki/Von_Neumann_universe) that is a hierarchy of "pure" sets satisfying the axioms of $\mathsf {ZFC}$, with set theories with [Urelements](https://en.wikipedia.org/wiki/Urelement) where the ground layer is based of (mathematical) objects that are not sets (e.g. numbers) and we build on top of it the hierarchy of sets: sets of numbers, sets of sets of numbers, ...
Comment: And YES, we describe (in a mathematical precise way) a *structure*, i.e. a universe of (mathematical) objects and their properties/relations and we show that the axiom of the corresponding theory a satisfied by (true) in the structure. In this way, we say that the said structure is a *model* of the theory. The same with the usual cartesian plane of well-known analytic geometry: it is a model of Euclidean plane into the "universe" of (pair of) real numbers.
Answer: Try the fine book by Michael Potter, Set Theory and its Philosophy (OUP)
Or for other, even more introductory, suggestions see the main chapter on set theory in Beginning Mathematical Logic: A Study Guide (www.logicmatters.net/tyl)
Comment: Thanks! Unfortunately I don't have access to the first book. Therefore, if you could provide any precise answers to my questions I would appreciate that a lot. I will have a look at the second book you mentioned, as well as the books mentioned in there assuming I have access to those.


Not able to split data frame in numpy

Question: Not able to use numpy split function to allocate subsets of dataframe to
cols =["fLength","fWidth","fSize","fConc","fConcl","fAsym","fM3Long","fAlpha","fDist","class"]
df = pd.read_csv("magic04.data",names = cols)
df['class'] = (df['class']=='g').astype(int)

train, valid, test = np.split(df.sample(frac=1), [int(0.6*len(df)) , int(0.8*len(df)), ])

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.9/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3628             try:
-> 3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:

17 frames
KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.9/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:
-> 3631                 raise KeyError(key) from err
   3632             except TypeError:
   3633                 # If we have a listlike key, _check_indexing_error will raise

Tried reading the documentation but didnt find anything useful.
Answer: The error in your code is that you are trying to use a numpy routine with a pandas data frame. The best way to approach this is to convert your df.sample into a numpy array and then use np.split().
Try this -  it runs perfectly well on my VSCode:
npsample=np.array(df.sample(frac=1))
train, valid, test = np.split(npsample, [int(0.6*len(npdata)) , int(0.8*len(npdata)), ])

Not able to split data frame in numpy


How do I merge properties in a Directory.Build.props file instead of overwriting properties?

Question: I have the following Directory.Build.props files:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LibraryPath>$(BOOST_ROOT)\lib32-msvc-14.2</LibraryPath>
    <IncludePath>$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LibraryPath>$(BOOST_ROOT)\lib64-msvc-14.2</LibraryPath>
    <IncludePath>$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LibraryPath>$(BOOST_ROOT)\lib32-msvc-14.2</LibraryPath>
    <IncludePath>$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LibraryPath>$(BOOST_ROOT)\lib64-msvc-14.2</LibraryPath>
    <IncludePath>$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
</Project>

Whenever I load a (C++) project in a subfolder (in visual Studio 2019), the project loses all inherited include and library paths:
Inherited Values:

I was thinking this might be due to me not appending to IncludePath and LibraryPath, so I did that and changed the props files as follow:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LibraryPath>$(LibraryPath);$(BOOST_ROOT)\lib32-msvc-14.2</LibraryPath>
    <IncludePath>$(IncludePath);$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LibraryPath>$(LibraryPath);$(BOOST_ROOT)\lib64-msvc-14.2</LibraryPath>
    <IncludePath>$(IncludePath);$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LibraryPath>$(LibraryPath);$(BOOST_ROOT)\lib32-msvc-14.2</LibraryPath>
    <IncludePath>$(IncludePath);$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LibraryPath>$(LibraryPath);$(BOOST_ROOT)\lib64-msvc-14.2</LibraryPath>
    <IncludePath>$(IncludePath);$(BOOST_ROOT)\</IncludePath>
  </PropertyGroup>
</Project>

Then reloading the project, results in missing inherited values, again.
I double checked to see if the macros are present, and they are (VC_ and WindowsSDK_ macros):

I also tried changing Directory.Build.props to Directory.Build.targets to make it load after the projects have been loaded, but then the file does not get loaded at all.
How can I make sure that my Directory.Build.props inherits the default values, and appends my custom options?
The reason I want to do this is because I'm migrating away from the deprecated Microsoft.Cpp.Win32.user.props file.
Changing the extention to .targets works only for the build process, but intellisense / visual Studio doesn't pick up on the include files, and shows a lot of error (before compilation). This is not preferable.
Comment: l am afraid you can not use `Directory.Build.props` to overwrite the values because it runs before  `Microsoft.Common.props` which defines the default inherited values. So it always cannot overwrite the system values but only create some custom properties for overwriting or using later.
Comment: It looks like this is non-solvable right now. Using `Microsoft.Cpp.Win32.user.props` is not an option as it's deprecated.
Comment: l wonder why you want to migrate them from `Microsoft.Cpp.Win32.user.props` file, and it is the best way to achieve it. I guess you just want to tie these Custom properties to a specific project instead of acting on all projects created in VS, or you just want to automatically migrate to a new environment with the project,these properties are only the address of the class library, and invalid address VS will be skipped without any other effect on VS. So you don't have to worry about it.
Comment: If you just want the project to migrate to a new environment, you can only need to reconfigure these properties into `icrosoft.Cpp.Win32.user.props`. So if you agree with me, you could consider accepting  my answer.
Comment: Actually, I would need to re-create what Linux has, global system wide include and library paths. I could put the props file on all the root drives so they would apply to all projects.
Comment: l think you can just import your `Directory.Build.props` into `Microsoft.Cpp.Win32.user.props` so that it can avoid missing  system property values.
Comment: Note that you can put your `UserMacros` `PropertyGroup` in Directory.Build.props, so it's available to everything, and just put your `IncludePath`/`LibraryPath` extensions in `Directory.Build.targets`.  This seems to work with intellisense.
Answer: Perry Qian's Answer needs an improvement.
Here are my concerns:

INCLUDE/LIB env vars are global for all projects that want to use this
method.
MSBuild args have to be set for every project
use of user.props is deprecated and also global for all projects

The problem with Directory.Build.props is that its included before $(IncludePath) and $(LibraryPath) are defined. You could manually set the default paths of VS, but this is bad practice.
To make use of the user.props successor Directory.Build.props and IntelliSense i suggest using AdditionalIncludeDirectories and AdditionalLibraryDirectories.
Here's an example of a Directory.Build.props configuration:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros">
    <BoostPath>$(BOOST_ROOT)</BoostPath>
    <BoostPlatform Condition="'$(Platform)'=='Win32'">lib32</BoostPlatform>
    <BoostPlatform Condition="'$(Platform)'=='x64'">lib64</BoostPlatform>
    <BoostDebug Condition="'$(Configuration)'=='Debug'">\debug</BoostDebug>
  </PropertyGroup>
  <ItemDefinitionGroup>
    <ClCompile>
      <AdditionalIncludeDirectories>$(BoostPath);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <AdditionalLibraryDirectories>$(BoostPath)\$(BoostPlatform)-msvc-$([System.Text.RegularExpressions.Regex]::replace($(PlatformToolset), "v(\d+)(\d)$", "$1.$2"))$BoostDebug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
    </Link>
  </ItemDefinitionGroup>
</Project>

If you want to set additional paths inside the project, make sure to add ;%(AdditionalIncludeDirectories) or ;%(AdditionalLibraryDirectories) respectively to include the paths from the props file.
Set the BoostDebug property to wherever you compiled the debug libs. In this example it would be lib32-msvc-14.2/debug/
The regex term $([System.Text.RegularExpressions.Regex]::replace($(PlatformToolset), "v(\d+)(\d)$", "$1.$2")) converts the platform toolset, for instance v142 to the lib path appendix 14.2.
For readability it would be better to initialize it in the PropertyGroup, but $(PlatformToolset) won't be initialized as early as the props file is parsed. Luckily AdditionalLibraryDirectories is evaluated during link time when $(PlatformToolset) will be set.
If you want better readability or need more complex operations on $(PlatformToolset), i suggest using the Directory.Build.targets config additionally. When this file is parsed, $(PlatformToolset) will already be initialized.
Example Directory.Build.targets:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros">
    <BoostToolset>$([System.Text.RegularExpressions.Regex]::replace($(PlatformToolset), "v(\d+)(\d)$", "$1.$2"))</BoostPlatform>
  </PropertyGroup>
  <ItemDefinitionGroup>
    <Link>
      <AdditionalLibraryDirectories>$(BoostPath)\$(BoostPlatform)-msvc-$(BoostToolset)$BoostDebug;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
    </Link>
  </ItemDefinitionGroup>
</Project>

Answer:
How can I make sure that my Directory.Build.props inherits the default
  values, and appends my custom options?

I think you cannot use Directory.Build.props to overwrite a system property in the Project Property UI.
From your info, the LibraryPath and IncludePath has lost there values. Please note this info about the Import order of Directory.Build.props:
Directory.Build.props is imported very early in Microsoft.Common.props, and properties defined later are unavailable to it. So, avoid referring to properties that are not yet defined (and will evaluate to empty).
Directory.Build.targets is imported from Microsoft.Common.targets after importing .targets files from NuGet packages. So, it can override properties and targets defined in most of the build logic, but sometimes you may need to customize the project file after the final import.
You can refer to this link.
In detail,Directory.Build.props like a step to initialize the project and always run before Microsoft.Common.props which set default values to most of the system properties such as LibraryPath and IncludePath. So at the beginning,it is normal that the values are empty . After this, when it executes the Microsoft.Common.props, it has this below:
<Includepath Condidtion="'$(Includepath)'==''">$(VC_IncludePath)......</Includepath >

And you have add $(BOOST_ROOT)\lib32-msvc-14.2 to Includepath in the Directory.Build.props, so when you execute next step, the Includepath has a value, so it will skip the operation of assigning system values and do not overwrite the values in this step and causes this strange behavior.
For Directory.Build.targets, it performs the override operation at the end, when both the includepath and LibraryPath properties have got the system values, and there is no problem with the override. But you can only get these values when you run the project, as you showed later.
In brief, Directory.Build.props is suitable for defining some properties which would be used or overwrote in later and Directory.Build.targets suits for overwriting the values which are already defined during build process.
Suggestion
1) To set the include directories, you can add them into your INCLUDE environment variable. you can set the INCLUDE and LIB variables, like so:
set INCLUDE=xxxx
set LIB=xxxx\lib32-msvc-14.2

And then add  /p:"VCBuildAdditionalOptions= /useenv" to MSBuild arguments so that it takes the INCLUDE and LIB variables.
You can refer to this.
2) Or you can use your initial function in the path C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.xxx.user.props to add the extra includepath,librarypath in it like:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets">
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IncludePath>C:\any-name\include;$(IncludePath)</IncludePath>
    <LibraryPath>C:\any-name\lib;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <ItemDefinitionGroup />
  <ItemGroup />
</Project>

Hope it could help you.


Nginx & Django & Gunicorn - Redirecting subdomain to app

Question: I did an extensive search on the topic but nothing could help me.
I am currently building a Django site, and using Nginx to reverse proxy to Gunicorn.
I am trying to separate my apps into subdomains. (blog.example.com, admin.example.com, user.example.com etc.)
I took care of the DNS records and they are working accordingly since my initial project was using only Nginx.
I can access the apps by navigating to the "subfolder" example.com/blog.
The config looks like this:
/etc/systemd/system/gunicorn.socket:

[Unit]
Description=Gunicorn socket for example.com

[Socket]
ListenStream=/run/example.sock

[Install]
WantedBy=sockets.target

/etc/systemd/system/gunicorn.service:
[Unit]
Description=gunicorn daemon for example.com
Requires=gunicorn.socket
After=network.target

[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          project.wsgi:application

[Install]
WantedBy=multi-user.target

/etc/nginx/sites-available/example:
server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/example/project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

I did add another serverblock for blog.example.com and added /blog on the proxy_pass line: proxy_pass http://unix:/run/gunicorn.sock/blog; hoping it will redirect to the app folder.
I am new to the socket method and do I don't know how to achieve the redirect.
I am aware that Nginx should handle the redirect and everything, but don't know to proceed further.
Any help is greatly appreciated.
Answer: You could have one gunicorn service per app:
/etc/systemd/system/blog.example.com.service
[Unit]
Description=gunicorn daemon for blog.example.com
Requires=gunicorn.socket
After=network.target

[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/blog
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/blog.example.com.sock \
          project.wsgi:application

[Install]
WantedBy=multi-user.target

/etc/systemd/system/admin.example.com.service
[Unit]
Description=gunicorn daemon for admin.example.com
Requires=gunicorn.socket
After=network.target

[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/admin
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/admin.example.com.sock \
          project.wsgi:application

[Install]
WantedBy=multi-user.target

Then point nginx to the respective .sock files:
/etc/nginx/sites-available/blog.example.com
server {
    listen 80;
    server_name blog.example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/example/project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/blog.example.com.sock;
    }
}

/etc/nginx/sites-available/admin.example.com
server {
    listen 80;
    server_name admin.example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/example/project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/admin.example.com.sock;
    }
}

Comment: Thank you for the input.

Unfortunately this results in a 502 - Bad gateway error.
It is also something I tried before.
Comment: Make sure the `.sock` files are existing and accessible by nginx. The error log of nginx should contain a clue too.
Answer: You should use separate service and socket files for every app and use explicit hosts instead of unix sockets.
Change the terms like unix:/run/blog with something like 127.0.0.1:8000 in your socket and service files. WorkingDirectory parameter should be same in all service files, it should point the directory contains manage.py. Finally you should set proxy_pass http://127.0.0.1:8000/blog/; in your nginx config.
/etc/systemd/system/blog.example.com.socket
Unit]
Description=Gunicorn socket for blog.example.comg

[Socket]
ListenStream=8000

[Install]
WantedBy=sockets.target

/etc/systemd/system/blog.example.com.service
[Unit]
Description=gunicorn daemon for blog.example.com
Requires=blog.example.com.socket
After=network.target

[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/blog
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind 127.0.0.1:8000 \
          project.wsgi:application

[Install]
WantedBy=multi-user.target

/etc/nginx/sites-available/blog-example:
server {
    listen 80;
    server_name blog.example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/example/project;
    }

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:9000/blog/;
    }
}


Groups and normal subgroups

Question: Let $H$ be normal subgroup of $G$, and $H\cap G'=\{e\}$ , $G'=\{[x,y]=xyx^{-1}y^{-1} \mid x,y\in G\}$. Prove that $\forall g \in G$ and $\forall h \in H: gh = hg$.
Answer: Note $gh=hg\iff ghg^{-1}h^{-1}=e$.
But, $H\triangleleft G\iff ghg^{-1}\in H$.
So, for all $g\in G,h\in H$, we have $ghg^{-1}h^{-1}\in H\cap G'=\{e\}$.

Groups and normal subgroups


New content doesn't appear in database

Question: I have the strangest thing going on here: I just created a new content type ('jobs'), and a new job (its node ID is 1706), but for some reasons there is no node that node ID in the database; even when I search for type = jobs, I get no result.
What could be the cause why I'm getting no results?
Answer: If the content was created it's also there in the database. Most obvious reason for you not finding it, would be silly mistakes, like a typo in the search, or you looked in the wrong database (either created the node the wrong place or looking in the wrong database).
It's not possible to have a node in a drupal site that doesn't exist in the database unless you believe in fairies ;)
Comment: also +1 for fairies :) (who cares if it's the right anwser ;-))
Comment: Haha :-) Although I like fairies, it's not of the mentioned options. I'm sure it's the correct database, I'm sure the content appears in the website and I'm sure the node isn't listed in the database... I'm using MySQL Workbench.
Comment: So you've probably hit a breach in the space/time continuum, because what googletorp said is an apodictic certainty : creating a node in Drupal is creating it in the database. That said, the mistake may not be so obvious : doesn't your software cache things locally or something like this ?

New content doesn't appear in database


Exception in thread "main" java.lang.NullPointerException at tab.setTable(tab.java:36)

Question: Exception in thread "main" java.lang.NullPointerException
    at tab.setTable(tab.java:36)

My code:
import java.awt.;
import javax.swing.;
import javax.swing.table.;
import java.awt.event.;
import javax.swing.;
import javax.swing.event.;
import java.net.*;
public class tab extends JFrame
{
    int a;
    JTable jt;
    Container c;
    static int k = 0;
    static int l = 0;
    static DefaultTableModel df;

    tab()
    {
        df = new DefaultTableModel(50, 0);
        jt = new JTable(df);
        df.addColumn("Request");
        df.addColumn("Acknowledgement");
        jt.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        c = getContentPane();
        JScrollPane jsp = new JScrollPane(jt);
        c.add(jsp);
        setVisible(true);
        setSize(800, 800);
    }

    static void setTable(String s) {
        df.setValueAt(s, k, 0);
        k++;
    }

    static void setTable1(String s) {
        df.setValueAt(s, l, 1);
        l++;
    }

}

Comment: Do you have an explanation for why you've made your methods/fields `static`? Just curious if you know the difference?
Comment: Vineeth, you really need to find out what `static` means, if you are to have any hope of getting this program to work.
Answer: If df should be static (as it is now), you shouldn't initialize it in the constructor (which initializes an instance of the class).
Initialize it in a static block instead :
static
{
    df = new DefaultTableModel(50, 0);
}

Comment: This might fix the compile error, but it really isn't going to work, now is it?
Comment: Then the OP is using the same tablemodel for all the tables - the cannot cause anything but problems.
Comment: @DavidWallace It will fix the NullPointerException. There's no compilation error to fix.
Comment: Sorry, you're right.  OK, it might fix the NPE, but it's STILL not going to make the program work!


How do I generate a form knowig its ID?

Question: Using Drupal 8, I want to use registration form outside user/register.
I can generate the user login form but I couldn't find how to get the user.register form.
So my question is, how can I render the user registration form?
Answer: The user register form is located in Drupal\user\RegisterForm. Check the annotation on the User class.
/**
 * Defines the user entity class.
 *
 * The base table name here is plural, despite Drupal table naming standards,
 * because "user" is a reserved word in many databases.
 *
 * @ContentEntityType(
 *   id = "user",
 *   label = @Translation("User"),
 *   handlers = {
 *     "storage" = "Drupal\user\UserStorage",
 *     "storage_schema" = "Drupal\user\UserStorageSchema",
 *     "access" = "Drupal\user\UserAccessControlHandler",
 *     "list_builder" = "Drupal\user\UserListBuilder",
 *     "views_data" = "Drupal\user\UserViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\user\Entity\UserRouteProvider",
 *     },
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },
 *     "translation" = "Drupal\user\ProfileTranslationHandler"
 *   },
 *   admin_permission = "administer users",
 *   base_table = "users",
 *   data_table = "users_field_data",
 *   label_callback = "user_format_name",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "uid",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/user/{user}",
 *     "edit-form" = "/user/{user}/edit",
 *     "cancel-form" = "/user/{user}/cancel",
 *     "collection" = "/admin/people",
 *   },
 *   field_ui_base_route = "entity.user.admin_form",
 *   common_reference_target = TRUE
 * )
 */

_entity_form: user.register pulls from here.
Answer: As users are entities in Drupal 8, best way to render user registration form is to render entity form of user.
So here is an answer:
$entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());

$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);

$form = \Drupal::formBuilder()->getForm($formObject);

print  \Drupal::service('renderer')->render($form);

This way you can render user.register form anywhere.

How do I generate a form knowig its ID?


Is there a way to find when a value was inserted into a particular cell on an Oracle database?

Question: There is a specific row in a table that I would like to research. I'd like to know when this row was inserted, when its individual fields were modified, the various values each field in this row might have had etc.. In short, its audit.. Is it possible ? How ?..
I'm using Oracle 11g
Comment: you don't provide enough information... what Oracle version ? How is audit configured on the DB (settings etc.) ? Is Flashback enabled ?
Comment: version - 11g. What other settings would u like to know ?.. It'd be helpful if you can also mention how to find those, as i'm not very familiar with oracle..
Comment: in Oracle there is an option to configure an "audit-trail" (several settings...), is that enable ? what are the settings of the audit-trail ? do have Flashback (another oracle option) enabled/configured?
Comment: There may be ways to configure these things (as @Yahia's comments have indicated), but they're not available by default. So if it's something that's already occurred, you're likely out of luck (unless someone else changed the default configuration)
Comment: FLASHBACK_ON is set to 'NO'..
Answer: You can enable auditing. If this is after the fact, no I don't think there's much you can do.
Answer: You can try LogMiner after the fact, but that depends on whether you've got access to the necessary redo log files.


"AttributeError: 'numpy.ndarray' object has no attribute 'cv2' " error. alraedy installed opencv-contrib-python and others also in different version

Question: import cv2

import numpy as np

import face_recognition

imgRohit = face_recognition.load_image_file('images/Rohit.jpg')

imgRohit = cv2.cvtColor(imgRohit.cv2.COLOR_BGR2RGB)

imgRohit_1 = face_recognition.load_image_file('images/Rohit_1.jpg')

imgRohit_1 = cv2.cvtColor(imgRohit_1.cv2.COLOR_BGR2RGB)

cv2.imshow('Rohit', imgRohit)

cv2.imshow('Rohit_1', imgRohit_1)

cv2.waitKey(0)

Comment: pls review the code, you are missing comma in following lines imgRohit =
imgRohit = cv2.cvtColor(imgRohit,cv2.COLOR_BGR2RGB)
imgRohit_1 = cv2.cvtColor(imgRohit_1,cv2.COLOR_BGR2RGB)
Answer: Instead of the dot in imgRohit = cv2.cvtColor(imgRohit.cv2.COLOR_BGR2RGB) between imgRohit and cv2.COLOR_BGR2RGB, It should be a comma.


Erro ao fazer um insert dinâmico em PHP

Question: O código que está a causar o erro:
<code>public function Inserir($tabela,$sql){

    ksort($sql);

    $Campos_nome=  implode('`, `', array_keys($sql));
    $Campos_valor= ': '. implode(', :', array_keys($sql));

    $novo=$this->prepare("INSERT INTO $tabela ( `$Campos_nome`)VALUES( $Campos_valor)");

    print "INSERT INTO $tabela (` $Campos_nome`)VALUES( $Campos_valor)";
    foreach ($sql as $key => $valor) {
        $novo->bindValue(":$key",$valor);
    }

        $novo->execute();

        if($novo->rowCount()>0){
            $novo->setFetchMode(PDO::FETCH_ASSOC);
            $valor=$novo->fetchAll();
        }
}
</code>
A mensagem de erro recebida:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /home/sam/Dropbox/Portal1/libs/Database.php on line 39
Comment: Imprima o insert e coloque o resultado na pergunta.
Answer: Experimente estes ajustes na linha a seguir:
<code>// Remoção do espaço nos primeiros ':'
$Campos_valor= ':'. implode(', :', array_keys($sql));
</code>
E, para debug, altere estas:
<code>$query = "INSERT INTO $tabela ( `$Campos_nome` ) VALUES ( $Campos_valor )";
$novo = $this->prepare( $query );
print hmlentities( $query );
</code>
Alternativamente, você poderia considerar parâmetros posicionais, e não nominados, para simplificar:
<code>$Campos_nome = implode( '`, `', array_keys( $sql ) );
$Campos_valor= '?'.str_repeat( ',?', count( $sql ) - 1 );

...

$i = 1;
foreach ( $sql as $key => $valor ) {
   $novo->bindValue( $i++, $valor );
}
</code>
Comment: funcionou perfeitamente.. thanks

Erro ao fazer um insert dinâmico em PHP


Sorting the Bars in Chart.JS Bar Graph

Question: I have been recently experimenting with ChartJS and have come into a problem regarding sorting the bars in descending order, from lowest to highest. I have tried to debug but found no luck.
Comment: is there any error message? What does it show?
Comment: hi, no this problem has been solved, however, I am looking for help in another issue. I would really really appreciate if you could help me on this issue. Thanks a million. I havent been able to get proper assistance on it.
Comment: Here is the link: https://stackoverflow.com/questions/51487777/updating-html-graph-with-mysql-query
Answer: Are you sure the "beforeupdate" is called when you click the "Sort Data" button, because it seems you use the wrong variable.
barChart → barGraph

UPDATED
The old one link
UPDATED
Here is the link
// Get the data from each datasets.
var dataArray = [];
$.each(chart.data.datasets, function() {
    dataArray.push(this.data);
});
// Get the index after sorted.
let dataIndexes = dataArray.map((d, i) => i);
dataIndexes.sort((a, b) => {
    return dataArray[a] - dataArray[b];
});
// create after sorted datasets.
var tempDatasets = [];
$.each(dataIndexes, function() {
    tempDatasets.push(chart.data.datasets[this]);
});
// apply it
chart.data.datasets = tempDatasets;

What data is returned using Ajax?
data = [{
    sample : "ALPINE",
    electric : 100,
    mpg: 200,
    urban: 300,
    vmt: 400,
    airtravel: 500,
    renewable: 100,
    conservation : 200,
    heating: 300,
    water: 400,
    cefficiency: 500,
    shiftc: 100,
    healthyd: 200
}];

Comment: Oh, I got it. so you copied and pasted, right? but you changed the data structure, there's no way that code working. That sort logic (your sort logic) only works if the data is gathered in one array. like this. However, do you want to implement the picture you uploaded? I'm not sure how it works. Why is the left label just one?
Comment: Yes, I want to implement the picture I uploaded, I want it to the same thing that the JS Fiddle is doing, where on clicking sort, all the bars will be sorted. Do you know how I can do this. It would really help. If you can modify the code for it to work, that would seriously help a lot. Thanks!!!!!
Comment: Since I also copied it, I don't quite understand the logic of getting a sort index, but I got it how to sort datasets. I edit my answer.
Comment: HiThanks so much for your help. However, the one problem is that im not getting my data from the database. So was my earlier code wrong in doing that. If you have any help on doing sorting functionality from the data in the database, that would be really appreciated.
Comment: I'm sorry I don't understand what you want clearly. What is the problem? Once you create a bar graph, where the data came from is nothing to do with this sort logic. If you mean that you can get the sorted data from the database(using order by), you just destroy and re-create a bar graph.
Comment: so your saying that the code which you gave in JS Fiddle for the sort logic should work when I apply it to my previous code. But when I apply it to my code, its not working properly even with the new sort logic code that you gave. Can you apply the sort logic code to the very original code that I had pasted above, so I can see how its supposed to really work. THanks for all your help!
Comment: I apply it your original code, but I change the ajax's URL to avoid error. Also, I don't get the data using ajax, so I set it manually. if the data structure is wrong what I thought, this code won't work.check 75 rows in the js fiddle. [here](https://jsfiddle.net/jznL3m92/1/)
Comment: yeah thats the thing, I need to get it via ajax, because my original graph pulls data from the database, so I cant set it manually.
Comment: I didn't use ajax, because I don't have an API, but you are using ajax to call your own code(localhost), so why don't you just return the correct format data?
Comment: OK, final question. The fact is that I can successfully both jsfiddle which are I wrote my answer. So it seems you use a different data structure from me. Please show me your data structure editing your question, just like I did.
Comment: ok, i updated the question with the new and modified code using the new sorting code i got from your js fiddle. Can you check yo see wats wrong. Yes, im pulling data from a database which is why i need to use ajax, thats my different data structure. But anyways, there is the edited code.
Comment: if you can, can you just copy paste my code into a js fiddle with a modifier, but if you can check for any wrong things with the datastructures. No output needs to be received but still so I can copy paste it to my IDE, without going back and forth. THANKS SO MUCH!!!!!
Comment: That's what that is?!, your variable "barChart" is declared in the wrong scope. you need to declare in advance, for example, putting "var barChart;" to at the under of "const CHART". And you need to rid of "var" from "var barchart = new Chart(CHART, {", like "barchart = new Chart(CHART, {".
Comment: OMG I LOVE YOU SO MUCH, THANK YOU
Comment: Really!?, I thought you can use a debugging tool which the browsers have, because you used "console.log", but not?. So now, let's accept my answer:)!

Sorting the Bars in Chart.JS Bar Graph


Como criar uma rota abstrata com controller global para seus filhos no AngularJS

Question: Estou criando uma aplicação onde vou criar algo semelhante a um "wizzard" do windows forms e para isso estou usando um roteamento da seguinte forma:
.state("vendaOrcamento", {
  url: "/vendaOrcamento",
  abstract:true,
  templateUrl: "templates/comercial/vendaOrcamento.html"
})
.state('vendaOrcamento.cliente', {
  url: "/cliente",
  views: {
    'tab-cliente': {
      templateUrl: "templates/comercial/vendaOrcamento/1cliente.html"
    }
  }
})
.state('vendaOrcamento.produtos', {
  url: "/produtos",
    views: {
      'tab-produtos': {
        templateUrl: "templates/comercial/vendaOrcamento/2produtos.html"
      }
    }
  })

Eu preciso que tanto para o filho cliente quanto para o filho produtos exista um objeto vendaOrcamento global, assim independente de qual filho eu estiver, eu sempre estarei trabalhando com o mesmo objeto sem perder os dados já tratados anteriormente, basicamente preciso disso:
$scope.vendaOrcamento = {
  cliente : {},
  produtos : {}
}

O meu problema é que não entendi muito bem como posso trabalhar assim, eu cheguei a tentar criar um Controller diretamente na view pai(vendaOrcamento) mas não deu muito certo... alguém pode me dar uma luz por favor?
Answer: Você pode tentar utilizar um factory para compartilhar dados entre controllers.
Existe bastante conteúdo pronto, só pesquisar algo como "share data between controllers".
Answer: Eu dei uma boa lida no que o @GuilhermeSantos disse e era uma opção bem funcional, mas acabei optando por uma value porque mesmo que a pessoa comece a edição mas saia dessa tela eu tenho como ao voltar pra mesma continuar de onde parou
Comment: De preferência para o uso de [`controller as`](http://toddmotto.com/digging-into-angulars-controller-as-syntax/)


Proving that $f^{(n)}(t) = p_n(1/t) e^{-1/t}, t\in(0, +\infty)$ where $p_n(x)$ is a polynomial of degree $\ge 2$.

Question: I want to prove that the n-th derivation of $f(t)=e^\frac{-1}{t}, t\in \mathbb{R}, t \gt 0$ is
$f^{(n)}(t) = p_n(1/t) e^{-1/t}, t\in(0, +\infty)$ where $p_n(x)$ is a polynomial of degree $\ge 2$ by induction.
Assuming it's true for $n$, I want to show that it's also true for $n+1$, which means that $f^{(n+1)}(t) = p_{n+1}(1/t) e^{-1/t}$. But I can't get any further.
$f^{(n+1)}(t)={f^{(n)}(t)}'={p_n(1/t)e^{-1/t}}'=
p_{n-1}(1/t)e^{-1/t}+p_n(1/t)1/t^2e^{-1/t}=e^{-1/t}(p_{n-1}(1/t)+p_n(1/t)1/t^2) =  ?)$
Comment: There is definitely no such degree bound there. Indeed you should find $p_{n+1}(t)=(p_n(1/t)-p'_n(1/t))/t^2$ which has growing degree.
Answer: By induction $P_0=1$ has degree $0$ since $f(t) =e^{1/t}$
Now Set $X= 1/t$ , and assume that $P_n$ is of degree $2n$ then after computation we have
$$f^{(n+1)}(t)= e^{-1/t}(p_{n-1}(1/t)+p_n(1/t)1/t^2 \\=e^{-1/t}(p_{n-1}(X)+p_n(X)X^2  )=  e^{-1/t}p_{n+1}(X) $$
clearly $$p_{n+1}(X)=p_{n-1}(X)+p_n(X)X^2  $$ is a polynomial degree $2n+2$ and $$f^{(n+1)}(t)= e^{-1/t} p_{n+1}(1/t)$$
Comment: Can you explain this equation: $$p_{n+1}(X)=p_{n-1}(X)+p_n(X)X^2$$. We add $p_{n-1}(X)$ (of degree 1?) and $p_n(X)X^2$ of which degree? And I can't see how that is a polynomial of degree $2n+2$. Thanks
Comment: @lolan496  from this   $$f^{(n+1)}(t)= e^{-1/t}(p_{n-1}(1/t)+p_n(1/t)1/t^2 =e^{-1/t}(p_{n-1}(X)+p_n(X)X^2  )$$ what do you as value of $P_{n+1}?$
Comment: I don't understand why $(p_{n-1}(X)+p_n(X)X^2 = p_{n+1}(X)$. What's the thought process behind it? What are we doing here? $p_{n-1}(X)$ has which degree? And when we multiply $p_n(X)X^2$ what do we get? Would be very nice if you could explain this part a bit more! Thank you
Comment: @lolan496 as realize this induction we assumme that $p_k$ has degree $2k$ then prove it for the next i.e $P_{n+1} $ which  turn out to have degree $2n+2$
Comment: @lolan496 you seems not happy about this answer
Answer: First we show that if $f(t)=e^{-\dfrac{1}{t}}$ for $t>0$ and if
$(\dfrac{d^n}{dt^n}f(t))= P_{n}(\dfrac{1}{t})\cdot e^{-\dfrac{1}{t}} $
Then:
$\dfrac{d}{dt}\cdot (\dfrac{d^n}{dt^n}f(t))=\dfrac{d}{dt} (P_n(\dfrac{1}{t})e^{-\dfrac{1}{t}})=e^{-\dfrac{1}{t}}\dfrac{d}{dt}P_n(\dfrac{1}{t})+P_n(\dfrac{1}{t})\cdot \dfrac{e^{-\dfrac{1}{t}}}{t^2}  $
$\implies \dfrac{d^{n+1}}{dt^{n+1}}f(t)=e^{-\dfrac{1}{t}}\dfrac{d}{dt}P_n(\dfrac{1}{t})+P_n(\dfrac{1}{t})\cdot \dfrac{e^{-\dfrac{1}{t}}}{t^2}$
$\implies P_{n+1}(\dfrac{1}{t})\cdot e^{-\dfrac{1}{t}}=e^{-\dfrac{1}{t}}\dfrac{d}{dt}P_n(t)+P_n(t)\cdot \dfrac{e^{-\dfrac{1}{t}}}{t^2}$
Cancelling $e^{-\dfrac{1}{t}} $ from both sides, we get,
$\implies P_{n+1}(\dfrac{1}{t})=\dfrac{d}{dt}P_n(\dfrac{1}{t})+P_n(\dfrac{1}{t})\cdot \dfrac{1}{t^2}$
$P_{n+1}(t)=\dfrac{d}{d(\dfrac{1}{t})}P_n(t)+P_n(t)\cdot \dfrac{1}{(\dfrac{1}{t})^2}$(by replacing $t$ with $\dfrac{1}{t}$)
Again $\dfrac{d}{d(\dfrac{1}{t})}P_n(t)=-t^2\dfrac{d}{dt}P_n(t)$
$\implies P_{n+1}(t)=t^2 P_n(t)-t^2\dfrac{d}{dt} P_n(t)$
Now as we know that the above is true iff $f(t)=e^{-\dfrac{1}{t}}$ for $t>0$ and
$(\dfrac{d^n}{dt^n}f(t))= P_{n}(\dfrac{1}{t})\cdot e^{-\dfrac{1}{t}} $ is true.
If somehow you can prove by induction $P_{n+1}(t)=t^2 P_n(t)-t^2\dfrac{d}{dt} P_n(t)$, you can arrive at $(\dfrac{d^n}{dt^n}f(t))= P_{n}(\dfrac{1}{t})\cdot e^{-\dfrac{1}{t}} $