Is there an intuitive characterization of distance correlation?

Question: I've been staring at the wikipedia page for distance correlation where it seems to be characterized by how it can be calculated. While I could do the calculations I struggle to get what distance correlation measures and why the the calculations look as they do.
Is there a (or many) more intuitive characterization of distance correlation that could help me understand what it measures?
I realize that asking for intuition is a bit vague, but if I knew what kind of intuition I was asking for I would probably not have asked in the first place. I would also be happy for intuition regarding the case of the distance correlation between two random variables (even though distance correlation is defined between two random vectors).
Answer: This my answer doesn't answer the question correctly. Please read the comments.
Let us compare usual covariance and distance covariance. The effective part of both are their numerators. (Denominators are simply averaging.) The numerator of covariance is the summed cross-product (= scalar product) of deviations from one point, the mean: $\Sigma (x_i-\mu^x)(y_i-\mu^y)$ (with superscripted $\mu$ as that centroid). To rewrite the expression in this style: $\Sigma d_{i\mu}^x d_{i\mu}^y$, with $d$ standing for the deviation of point $i$ from the centroid, i.e. its (signed) distance to the centroid. The covariance is defined by the sum of the products of the two distances over all points.
How things are with distance covariance? The numerator is, as you know, $\Sigma d_{ij}^x d_{ij}^y$. Isn't it very much like what we've written above? And what is the difference? Here, distance $d$ is between varying data points, not between a data point and the mean as above. The distance covariance is defined by the sum of the products of the two distances over all pairs of points.
Scalar product (between two entities - in our case, variables $x$ and $y$) based on co-distance from one fixed point is maximized when the data are arranged along one straight line. Scalar product based on co-distance from a var*i*able point is maximized when the data are arranged along a straight line locally, piecewisely; in other words, when the data overall represent chain of any shape, dependency of any shape.
And indeed, usual covariance is bigger when the relationship is closer to be perfect linear and variances are bigger. If you standardize the variances to a fixed unit, the covariance depends only on the strength of linear association, and it is then called Pearson correlation. And, as we know - and just have got some intuition why - distance covariance is bigger when the relationship is closer to be perfect curve and data spreads are bigger. If you standardize the spreads to a fixed unit, the covariance depends only on the strength of some curvilinear association, and it is then called Brownian (distance) correlation.
Comment: What still **evades me** is why a lower power, e.g. default $\alpha=1$, which shrinks and decenters the deviations obtained at the double centering, makes dCOV the statistic which has its unique property: it is 0 iff X and Y are statistically independent. Because I haven't got intuition or knowledge of it I'm afraid that my answer's 2nd paragraph is misinterpretation or simplification. I therefore inclined to delete my answer. Can you say anything?
Comment: @Rasmus, I still don't have a clear intuition, like you; and the math idea behind dCov is too complex for me. Here is what I think. As've said above, with $\alpha=2$, $d_{ij}^\alpha$, when being doubly centered, are expanded by simple Newton's binomial and consequantly the entries of the matrix $A$ (see Wikipedia) become just deviations from the mean; and thence dCov degenerates into sqrt(usual cov). This is clear.
Comment: (Cont.)  But with $\alpha=1$ double centered matrix convey values which are obtained as infinite, produced by Taylor series expansion. The key point (that I can't grab) is that somehow these values of $A$ then relate to the empirical _characteristic function_ of the distribution, and this is that relatedness which make dCov to be a measure of any, linear and nonlinear, independence.
Comment: The second paragraph made it click for me. I don't' know why I didn't see that in the wikipedia page... Thanks!
Comment: Just wondering, where in http://en.wikipedia.org/wiki/Brownian_covariance#Distance_covariance is the numerator from your example (or how to get from your numerator to the wikipedia version)? Wikipedia just describe how to calculate the square of the distance covariance and I'm having a bit of trouble matching your description against the description there...
Comment: @Rasmus, my "numerator formula" agrees with the wikipedia formula of squared sample distance covariance. But I missed one (important) nuance that distances $d$ are transformed by double centering. I might have to edit my answer, therefore. I hope to find time to return in few days, if not tomorrow.
Comment: Yes, the double centering has been puzzling me. Would be greatly appreachiated if you had the time to clarify that! :)
Comment: @Rasmus, double centering of distances is familiar to me well. It is done on _squared_ distances. In a univariate situation the result is deviations from the mean, so we get exactly the formula of my 1st paragraph. Indeed, in the above wikipedia article section "Generalization" it is said that with power for distances $\alpha=2$ dCOV actually reflects usual covariance. This I understand well.
Comment: Well, I'm sure more evades e than it evades you :) Maybe keep the aswer but add your extra question at the end, maybe someone will be able to "fill it in" later?
Comment: @ttnphns maybe this helps? (PDF) https://www.researchgate.net/profile/Gabor_Szekely3/publication/243786506_E-Statistics_The_energy_of_statistical_samples/links/5609857f08ae840a08d3b06a.pdf
Comment: Starting with 5. (page 10), as stated in Proposition 3 (page 12), basically you need a strictly negative definite kernel for this to work. It turns out using $\mathbb{E}{\left[{\left| X - Y \right|}^2\right]}$ (etc.) you have only a *conditionally* negative definite kernel which only works in certain situations (such as, in case of normal covariance, for linear dependence) - But any $\left|\cdot\right|^\alpha$ with $0<\alpha<2$ will work, and so will, for instance, $\text{log}{\left(\left|\cdot\right|^2+1\right)}$ which would correspond to a Laplace kernel.
Comment: @kram1032, thank you for the paper! I'll read it later. But, really, why don't you issue an answer to the question if you know what to say. It would make good for everybody including myself.
Comment: @ttnphns Because I'm not entirely sure that would answer the question here. I'm still trying to make sense of it myself. That's why I said "*Maybe* this helps?" - I really am not sure whether it would. (My background very much isn't statistics and I'm not confident I could give a decently phrased answer at all)


Memory reserved is not freed after changing ng-view content

Question: I have audio player application implemented in AngularJS, but it consumes large amount of RAM. The sequence of actions I'm doing is the following:

route to login page
login then go to the next page
logout
repeat steps from 1 to 3 several times

The surprise is that the memory for the first step is 38 MB, then it increase to be 211 MB after the second step, after the third step it's 249 MB and so on, so it's accumulative and no memory is being freed after any of ng-view changes
Here it is sample of my code:
index.html page

app.js file
var app = angular.module('myApp', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', '$httpProvider',
    function ($routeProvider, $locationProvider, $httpProvider) {
        $routeProvider.when('/login', {
            templateUrl: 'login.html',
            controller: 'loginController'
        });

        $routeProvider.when('/', {
            templateUrl: 'home.html',
            resolve:{/** resolve function for login checking */}
            controller: 'homeController'
        });
    }]);

I tried the solution of cleaning $templateCache as cleared in this question, but it can't be a solution in my case as I tried it and the problem not in the template itself, but something wrong with DOM and Controller data
How can I handle this memory issue, so when I change the view in ng-view It won't consume all this memory (as it's not the template size)
Update 1:
I switch between views when login or logout using $location.path('/route') after resolving the data of login and after checking the server's response after logout, so could it be the problem?
Update 2:
I created a plunker that simulate the increase of memory when switching views too much (of course it's not the actual numbers as it's a simulation)
Comment: I'm also facing the same issue that you mentioned here. but can't find any solution related to this issue.
Additionally, i have around 300 to 400 controllers on my page (which would have their own events bound to them).

Please note that I have not explicitly added any events to controls using "$on", so I cannot deregister them using destroy event.

can you provide any solution to this issue?
Answer: Interesting, it seems like the loginController isn't being cleared from memory. You may have to try triggering $destroy() yourself to clear that controller. This assumes that it is being loaded multiple times.
Another few resources that may help: blog post about $destroy()
somewhat similar github issue
Comment: yes neither the loginController nor the homeController is cleared from memory, as trying to login again take the memory up to ~460 MB and so on.
Answer: I think you need to implement angular-websocket based approach, similar to Trello, whereby after a certain amount of time you ask the user to update their page to receive new updates to the system or to refresh if their socket connection has timed out? Depending on your setup you may find this tutorial useful: Writing an AngularJS App with Socket.IO.
Read the last update of accepted answer of your referred question.


Não consigo acessar valores fora de uma função fs.readFile()

Question: Não consigo pegar o valor repassado a váriavel taxValues fora de fs.readFile()
const fs = require('fs')
const xml2json = require('xml2json')

const taxValues = {}

function ReadXml(taxValues) {
  fs.readFile( '01.xml', 'utf-8', function(err, data) {
    const xmlNFe = xml2json.toJson(data);

    const convertToJson = JSON.parse(xmlNFe)
    const captureTax = convertToJson.nfeProc.NFe.infNFe.det.imposto

    const icms = captureTax.ICMS.ICMS00.vICMS
    const ipi = captureTax.IPI.IPITrib.vIPI

    taxValues = {
      valorIPI: ipi,
      valorICMS: icms
    }
    console.log(taxValues)
  });

  return taxValues

}

console.log(taxValues)

module.exports = { ReadXml, taxValues }

Rota:
routes.get('/tax', async (req, res) => {
  ReadXml.ReadXml()
  res.send(ReadXml.taxValues)

})

Comment: taxValues é uma constante, não pode redefinir o seu valor, use um `let taxValues`
Comment: Já fiz isso, não retorna também
Comment: já viu que sua função é um call back certo? se não esperar o resultado retornar, no momento que passar pelo console.log ainda não deve ter resultado e vai estar vazio
Comment: veja esse exemplo simulando um callback: https://jsfiddle.net/fj7cm43o/1/
Comment: Verifique esta resposta: https://stackoverflow.com/a/10058879/1331430
Answer: O problema que você está enfrentando se dá por conta do entendimento errado da função readFile e da atribuição à constante (const taxValues).
A função readFile recebe o nome do arquivo, a codificação e uma função que é chamada QUANDO o arquivo é finalmente lido. Enquanto a leitura não ocorre, o JavaScript executará as instruções seguintes e só depois vai chamar a sua função.
Por exemplo, o código abaixo
let x;

fs.readFile('my-file.txt', 'utf-8', (err, data) => {
  x = data;
});

console.log(x);

Vai imprimir na sua cara, um belo undefined, pois o console.log(x) é executado ANTES da função (err, data) => { x = data; }.
Outro problema se dá por conta da declaração constante de taxValues. Como ela é uma constante, e não uma variável, a linha taxValues = {valorIPI: ipi, valorICMS: icms } não vai funcionar, pois você está tentando modificar o valor de uma constante.
Para resolver o seu problema, no seu caso específico, você vai precisar da versão síncrona do fs.readFile, mas tenha em mente que utilizar código síncrono em excesso é uma péssima prática em JavaScript, pois pode levar o código a ser bloqueado.
Dito isso tudo, o seu código pode ser corrigido para
const fs = require('fs');
const xml2json = require('xml2json');

const data = fs.readFileSync( '01.xml', 'utf-8');

const xmlNFe = xml2json.toJson(data);

const convertToJson = JSON.parse(xmlNFe);
const captureTax = convertToJson.nfeProc.NFe.infNFe.det.imposto;

const icms = captureTax.ICMS.ICMS00.vICMS;
const ipi = captureTax.IPI.IPITrib.vIPI;

const taxValues = {
  valorIPI: ipi,
  valorICMS: icms
};

module.exports = taxValues;

E, assim, a sua rota ficaria
const taxValues = require('./caminho/para/o/seu/arquivo.js');

routes.get('/tax', (req, res) => {
  res.send(taxValues);
});

Comment: Funciona, mas acho que seria mais interessante refatorar para a leitura assíncrona do arquivo, exportando uma função, por exemplo, `readTaxValues`.
Comment: De fato, uma leitura assíncrona é sempre melhor se ela for feita várias vezes. Mas nesse caso, me pareceu não haver necessidade de ler o mesmo arquivo várias vezes, então faz mais sentido ler uma vez só na inicialização do processo do Node.
Comment: De qualquer forma, vou escrever uma outra resposta com um código assíncrono
Answer: Na outra resposta que eu dei, eu sugeri o uso de uma versão síncrona da função fs.readFile. No entanto, essa solução só é boa se o arquivo for lido uma única vez antes do servidor iniciar a sua execução. Se você precisa ler o arquivo sempre que uma requisição chegar, não é uma boa ideia usar um método síncrono, pois, como eu disse, isso pode bloquear a execução de alguns códigos e deixar outros usuários do servidor esperando sem motivo.
Um jeito de lidar com esse problema seria criar a sua própria função com um callback, o que pode ser feito assim
const fs = require('fs');
const xml2json = require('xml2json');

function getTaxValues(callback) {
  fs.readFile( '01.xml', 'utf-8', function(err, data) {
    const xmlNFe = xml2json.toJson(data);

    const convertToJson = JSON.parse(xmlNFe);
    const captureTax = convertToJson.nfeProc.NFe.infNFe.det.imposto;

    const icms = captureTax.ICMS.ICMS00.vICMS;
    const ipi = captureTax.IPI.IPITrib.vIPI;

    const taxValues = {
      valorIPI: ipi,
      valorICMS: icms,
    };

    callback(taxValues);
  });
}

module.exports = getTaxValues;

Com a rota sendo
const getTaxValues = require('caminho/para/o/seu/arquivo.js');

routes.get('/tax', (req, res) => {
  getTaxValues(taxValues => {
    res.send(taxValues);
  });
});

Essa solução, em particular, é um tanto feia... Tem vários níveis de callbacks encadeados... A melhor solução de fato para esse problema seria utilizando a versão com "promises" da biblioteca fs em conjunto com a sintaxe async e await. Essa seria assim
const fs = require('fs').promises;
const xml2json = require('xml2json');

async function getTaxValues() {
  const data = await fs.readFile('01.xml', 'utf-8');

  const xmlNFe = xml2json.toJson(data);

  const convertToJson = JSON.parse(xmlNFe);

  const captureTax = convertToJson.nfeProc.NFe.infNFe.det.imposto;

  const icms = captureTax.ICMS.ICMS00.vICMS;
  const ipi = captureTax.IPI.IPITrib.vIPI;

  return {
    valorIPI: ipi,
    valorICMS: icms,
  };
}

module.exports = getTaxValues;

E a sua rota, então,
const getTaxValues = require('caminho/para/o/seu/arquivo.js');

routes.get('/tax', async (req, res) => {
  const taxValues = await getTaxValues();

  res.send(taxValues);
});


return view with parameter

Question: Basically I have MVC site with few tabs on my page, that uses JavaScript.
Then I have JavaScript method that reads this URL and uses AJAX to select appropriate tab like so:
function onbodyLoad(URL) {

    if (URL.indexOf("Login/Register") != -1) {
        var index = 4;
        var $tabs = $('#tabs').tabs();
        $tabs.tabs('url', index, "/Login/RegistrationConfirmation");
        $tabs.tabs('select', index + 1);
        $tabs.tabs('select', index);
    }
}

Now I am checking few properties for null in httppost method in controller and return a view. It works but the style is missing so had to do it the above way.
Would it be possible to write to page URL "Success" if no error and if they null write to url "Error". so in above function I can check the URL and forward to appropriate tab.
Or maybe write an actionresult method with parameter and return that. But have no idea...anyone can shed some light please
Hope it makes sense.

Update:
On my controller i did this to add parameter to my register view:
RouteValueDictionary rvd = new RouteValueDictionary();
rvd.Add("ParamID", "1");
return RedirectToAction("Register", "Login", rvd);

And Jquery I did this to read the url and select that tab :
if (URL.indexOf("Login/Register?ParamID=1") != -1) {
    var index = 2;
    var $tabs = $('#tabs').tabs();
    $tabs.tabs('url', index, "/Login/Register");
    $tabs.tabs('select', index + 1);
    $tabs.tabs('select', index);
}

I can see the url with parameter but the jquery dont seem to work, it just says cannot be found. any help please?
Comment: a "tab"? What is that, a plugin?
Comment: it is jQuery UI Tabs plugin (http://docs.jquery.com/UI/Tabs#theming)
Comment: copy the more exact error maybe? :) this is too vague for me.
Answer: If you look at the API, you might be able to find the ajaxOptions-option for the tab initialization.
$tabs.tabs({ ajaxOptions: { async: false } });

$tabs.tabs({ ajaxOptions: { async: false } });
And more appropriate:
// Definition of the tabs variable, note in particular the argument 'ajaxOptions'
var $tabs = $('#example').tabs({
    ajaxOptions: {
        success: function() {
            $tabs.tabs('select', getIndex() + 1);
            $tabs.tabs('select', getIndex() );
        },
        error: function() {}
    }
});

function getIndex() {
    return 4;
}

function onbodyLoad(URL) {

    if (URL.indexOf("Login/Register") != -1) {

        var $tabs = $('#tabs').tabs();
        $tabs.tabs('url', index, "/Login/RegistrationConfirmation");
    }
}

Would that be helpful..?
P.S. I didn't test this.

return view with parameter


Custom theme region for page

Question: I would like to be able to custom theme a region for specific pages, is this possible? If so how?
For example I have a ragion called rightbar and I know the region can be themed using region--rightbar.tpl.php but is there a way of theming this using something like page--node--1--region--rightbar.tpl.php?
Or am I going to have to condition the region--rightbar.tpl.php script?
Answer: Use the following code:
/**
 * Implements hook_preprocess_region().
 */
function YOURTHEME_preprocess_region(&$vars) {
  // Make sure we are on a single node page
  // This code will allow you to add the following templates for regions:
  // region--node-NID.tpl.php
  // You can update the conditions to anything you want and rename the template
  // suggestions.
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $vars['theme_hook_suggestions'][] = 'region__node_' . arg(1);
  }
}

Comment: will this allow me to specify a specific region?
Comment: Never mind I've worked it out, thanks for this though, it was a useful guide!
Answer: I used the following code to achieve a solution to my answer.
/**
* Implements hook_preprocess_region().
*/
function care_preprocess_region(&$vars) {
    // Make sure we are on a single node page
    // This code will allow you to add the following templates for regions:
    // region--RNAME--node-NID.tpl.php
    // You can update the conditions to anything you want and rename the template
    // suggestions.
    if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
        $vars['theme_hook_suggestions'][] = 'region__' . $vars['region'] . '__node_' . arg(1);
    }
}

Custom theme region for page


Alternating projection algorithm fails to find an intersection

Question: The projection onto convex sets (POCS, alternating projections) algorithm is a method to find the intersection of convex sets by projecting onto them consecutively. It has been proven that this method converges for any starting point $x_0$.
In the example below I try to apply the algorithm and find that it converges to a local minimum:

To determine the point $x_{i+1}$ on the ellipse $E_2$ starting from a point $x_i$ on the ellipse $E_1$, I find the closest point to $x_i$ on $E_2$. The final point of this procedure is $x_N$. This shows that the algorithm converged to a local minimum, yielding the local minimal distance $|x_N-x_{N-1}|$ (you can also picture two rectangles to see the same issue, and it will converge after 1 iteration).
Had I chosen the point $y_1$ to start from, I would have found the nearest intersection. Alternatively, had I gone through the path of the dashed line (projecting into the point on $E_1$ that is further away) instead of selecting the closest point on ellipse $E_1$, I would have found an intersection as well.
In the literature I find no mention of ending up in local minima and it seems to contradict the proof.
Can someone explain to me what is going on and how I can make sure that I always find an intersection if it exists?
Answer: I misunderstood the objective of the algorithm. I intended to find a point where the boundaries intersect. Instead, the algorithm finds a point in the overlap of $E_1$ and $E_2$. Thus, it will converge at $x_1$ already.
Comment: If you mean on the boundaries as in the meaning a projection, then POCS doesn't guarantee that.


new[n] and delete every location with delete instead the whole chunk with delete[]

Question: Is this valid C++ (e.g. not invoking UB) and does it achieve what I want without leaking memory? valgrinds complains about mismatching free and delete but says "no leaks  are possible" in the end.
int main() {
  int* a = new int[5];
  for(int i = 0; i < 5; ++i)
    a[i] = i;

  for(int i = 0; i < 5; ++i)
    delete &a[i];
}

The reason I'm asking: I have a class that uses boost::intrusive::list and I new every object that is added to that list. Sometimes I know how many objects I want to add to the list and was thinking about using new[] to allocate a chunk and still be able to delete every object on its own with the Disposer-style of boost::intrusive.
Answer: No way. You cannot call delete on what was not allocated by new or you get heap corruption.
You see, that array created by new[] didn't allocate n individual objects, but one array. The second object of the array is in the middle of the allocation block.
Comment: Exactly.  And, when you allocate something with new (or new[]), it stores a notation in a table somewhere that the particular block of memory is allocated.  The corresponding delete (or delete[]) calls will look for that notation.
Comment: "You cannot call delete on what was not allocated by new or you get heap corruption."
You get a crash!
Answer: You can add a bit so each object remembers whether it was the first in the contiguous array. This is tricky:

totally incompatible with delete object syntax
incompatible with inheritance
disposer instead calls destructor explicitly, eg object.~ListItem()
must still use array operator new[]
be sure to dispose objects in reverse order, unlike your included example
destructor implements reflective ownership of the array by its first element:

.
ListItem::~ListItem() {
    if ( m_own_my_subarray ) {
        operator delete[]( this ); // does not invoke any destructor!
                 // "this" must be exactly the result of new[]!
    }
}

Comment: It has to be compatible with inheritance as I use the intrusive::list_base_hooks.
Comment: @pmr: `ListItem` can be inherited from **something** of course, but the destructor must be as shown. For the same reason and in the same sense, C-style arrays of objects are incompatible with inheritance.
Comment: @pmr: I mean ListItem can *inherit* from something like `list_base_hook`. Could you describe how I'm not answering your question, or acknowledge with an upvote? This isn't an easy kind of question to answer, and I have a pet peeve about knee-jerk "it's impossible" responses…
Comment: The intention of my comment wasn't to say "it's impossible", I just wanted to add the requirement. I still don't get the "incompatible with inheritance" part of your answer. Did you mean "cannot be extended"?
Comment: @pmr: sorry, the "impossible" thing wasn't referring to you; never mind that. By "incompatible with inheritance" I simply mean that you can't encapsulate the functionality of managing an enclosing array in a base class, at least not with the code I posted. The requirements are essentially the same as those for constructing and destroying the array of objects, which is essentially what you are reimplementing with more basic building blocks.


Azure - Origem de gravação de BLOB em camada Quente

Question: Senhores tudo bem?
Na minha conta Azure está exibindo um alto consumo de: "Operações de Gravação de LRS Quente - Blob de Bloco em Camadas - 192% 1,92 / 1 10K" imagem a seguir:

Nos últimos 3 dias esse número que nunca passou de 0% passou a subir exponencialmente e gostaria de entender a origem, mas não consigo identificar.
Conferi nas áreas de upload de minha aplicação e usando a ferramenta do "Microsoft Azure Storage Explorer" meus blobs estão todos em camada Fria, não houve gravação em camada quente.
O que fiz de diferente nestes últimos dias:

Habilitar logs de query lenta no MySql
No meu Web App fiz cache em arquivos que usa o armazenamento alocado no "Plano de Serviços"
Habilitei alguns webJobs que simplesmente fazem uma chamada para meu App, não mexe com armazenamento tais operações
Tenho 4 Web Apps no mesmos Plano de serviços, somente 1 tem log habilitado e o log é salvo no Sistema de Arquivos.

Em relação à conta de armazenamento eu avaliei os logs, e os logs que tem batem com os logs gerados pelo meu sistema todos em camada fria. Abaixo segue métricas de utilização da conta de armazenamento.

Dia 16 segundo a análise de custos foi quando houve um volume de gravação elevado, mas daqui não consigo saber onde e por qual origem se deu esse volume de operações, pois no meu entendimento segundo o gráfico anterior de consumo, dia 16 quase não houve operações de gravação em relação ao período como um todo.
Onde consigo identificar estas operações? pois no dia 16 não existem logs de blob:
Answer: Depois de muito batalhar a resposta que tive da Microsoft foi que arquivos com taxa de acesso alta de leitura serão considerados como "quente" mesmo que esteja na camada "fria".
Apesar de estranho essa foi a única resposta congruente que recebi.


Prove that the radical of an ideal is an ideal

Question: Let $R$ be a commutative ring with unity. For an ideal $I$ of $R$, I am attempting to prove $\sqrt{I}=\{x\,|\,x^n\in I\}$ is an ideal.
Closure under multiplication with $R$ seems straight forward: for $x\in\sqrt{I}$ and $r\in R$, $(rx)^n=r^nx^n\in I,$ so $rx\in\sqrt{I}.$
My question relates to proving closure under addition.  What I have currently is that if $x^n, y^m\in I$ and assuming $m\leq n$, then $x^n\left(x^n+2nx^{n-1}y+\dotsb+\binom{2n}{n}y^n\right)+y^m\left(\binom{2n}{n+1}x^{n-1}y^{(n-m)+1}+\dotsb+y^{2n-m}\right)=(x+y)^{2n},$ implying that $(x+y)\in\sqrt{I}$.
It seems like even if I am correct there is probably a more straight-forward way of doing this. I searched this site and found and answer that I don't understand, so I'm worried I might be missing something.
Comment: That's the proof I know, but also you're missing the coefficients in the binomial expansion. Also $n+m$ works as an exponent.
Comment: In fact $n+m-1$ works.
Comment: I understand now.  I didn't get why binomial expansion worked, but I didn't do anything any differently... except forget the coefficients. Thanks @jgon
Answer: You can use the nilradical, which is the set of all nilpotent elements of R.
Notice that if I is the ideal of the ring R and r(I) is the radical of I and $x^n$ is in I, then $x^n + I = I$ so $(x + I)^n = I$. Thus $r(I) = f^{-1}(N(R\setminus I))$ where $N(R\setminus I)$ is the nilradical of $R\setminus I$ and f is the function from R to $R\setminus I$ defined by $f(x)=x + I$.


Obter dimensão original da imagem com JavaScript

Question: Tenho uma imagem carregada na minha página HTML dentro da tag , há alguma forma de saber dimensão do arquivo original dela por JavaScript?
Digamos que eu queira dar um console.log(larguraImagem, alturaImagem);.

Note que o tamanho que eu quero saber é o original que está no
  servidor e não o que está sendo exibido na tela porque este pode estar
  sendo redimensionado pelo CSS.
Answer: Creio que a única maneira cross-browser que inclui browsers antigos é assíncrona, criando uma nova imagem com o construtor new Image.
Para browsers modernos podes usar o naturalHeight e naturalWidth (exemplo em baixo)
Uma aplicação prática seria assim:

function getImgSize(image) {
  const newImg = new Image();
  return new Promise((res, rej) => {
    newImg.onload = function() {
      const height = newImg.height;
      const width = newImg.width;
      res({
        width: newImg.width,
        height: newImg.height
      });
    }
    newImg.src = image.src;
  });
}

const img = document.querySelector('img');
getImgSize(img).then(size => console.log(size));
img {
  width 10%;
}

Com naturalHeight e naturalWidth:

function getImgSize(image) {
  return {
  width: image.naturalWidth,
  height: image.naturalHeight
  }
}

const img = document.querySelector('img');
const size = getImgSize(img);
console.log(size);
img {
  width 10%;
}

Comment: Excelente resposta! Obrigado.
Answer: Pesquisando achei o seguinte cod:
var img = document.getElementById('imageid');

var width = img.clientWidth;
var height = img.clientHeight;

so que isso vai retornar o tamanho dela de acordo com o DOM isso é o tamanho dela exibido no seu navegador ( isso é influenciável pela css )
para resolver isto você deve utilizar o seguinte comando:
var originalwidth = img.naturalHeight;
var originalheight = img.naturalWidth;

com este comando você pega os tamanhos originais da imagem independendo do DOM
Answer: Pode fazer assim...

let imagem = document.getElementById('imagem')

let width = imagem.clientWidth;
let height = imagem.clientHeight;

alert(width + ' - ' + height)


Apache Caching disabled when client sends If-Modified-Since header

Question: I'm trying to get Apache to cache the results from running an expensive PHP script (it accesses a third party server which has rate limiting) but it seems if the client sends an If-Modified-Since header the cache is bypassed.
CacheEnable disk /script.php
CacheLock on
CacheLockMaxAge 60
CacheIgnoreHeaders Set-Cookie
# prevent client explicitly requesting un-cached content
CacheIgnoreCacheControl on
CacheDetailHeader on

The php script sets the following headers in its response:

Last-Modified set to the current time, e.g. Sun, 20 Jun 2021 11:30:20 GMT
Expires set to the current time plus 60 seconds, e.g. Sun, 20 Jun 2021 11:31:20 GMT

If I issue the following request:
GET /script.php HTTP/1.1
Host: example.com
Connection: close

Then the caching works correctly and the php script is only run once a minute with other requests being served from the cache.
However issuing the following request:
GET /script.php HTTP/1.1
Host: example.com
Connection: close
If-Modified-Since: Sun, 20 Jun 2021 11:30:30 GMT

Runs the php script every time with:
X-Cache-Detail: "cache miss: attempting entity save" from example.com

in the response.
I'm using Apache 2.4.29 on Ubuntu 18.04.
Comment: Can you try setting the two headers ?

`"CacheIgnoreNoLastMod On"` and `"CacheIgnoreHeaders If-Modified-Since"`
Comment: @SreerajKarichery no change from setting those settings in mod_cache
Comment: there might be a chance to use `
Header unset Last-Modified
Header unset If-Modified-Since
` or similar
Comment: @djdomi no, no change. I think I'd already tried that, I'm not sure the headers are removed before mod_cache sees them
Comment: thats why you should try to remove it :)
Comment: By thee way, i found maybe some intressting point to you: https://stackoverflow.com/questions/10847157/handling-if-modified-since-header-in-a-php-script
Answer: Mod-Cache Manual from Apache.org
https://httpd.apache.org/docs/2.4/mod/mod_cache.html
Using Custom Logs to identify the problem
CustomLog "cached-requests.log" common env=cache-hit
CustomLog "uncached-requests.log" common env=cache-miss
CustomLog "revalidated-requests.log" common env=cache-revalidate
CustomLog "invalidated-requests.log" common env=cache-invalidate

Enable the X-Cache-Detail header
CacheDetailHeader on
Set to Ignore Query Cache Control Strings
CacheIgnoreCacheControl On
CacheIgnoreQueryString on

Using a Session token like url.com/my.php?jsessionid=123 should not be cached or even seperatly
CacheIgnoreURLSessionIdentifiers jsessenionid

Use MINIMUM modified factor, that uncached request will be delivered 0.0 = 0% or 1.0 = 100%
CacheLastModifiedFactor 0.99

Set Minimum time for Valid caching (Default 0)
CacheMinExpire 3600

Remove if-Modfied Header before it will take action
Header unset Last-Modified
* Can also be used in htaccess

This is more to debug at first as it would not Fit in a Comment but should help to Inc raise the Caching of any Object.
Comment: `CacheDetailHeader` is already on. `CacheIgnoreCacheControl` is already on. `CacheIgnoreQueryString` is undesirable as the query string changes the returned result. `CacheIgnoreURLSessionIdentifiers` wont change anything as there is no session ID in the URL. `CacheLastModifiedFactor` and `CacheMinExpire` only apply when `Expires` isn't specified. `Header unset` doesn't seem to affect `mod_cache`'s behaviour
Comment: There's a second way but it makes it a bit more confusing, use Nginx in front of the Apache, it has more control over the caching.


How to restyle GeoField's proximity filter controls?

Question: Background
I am using the modules: geocoder geofield addressfield geophp ip_geoloc libraries to create a store locator view. The user can search the available stores using an exposed GeoField proximity filter.
Question
How can I restyle the GeoField's proximity filter controls? I would like to change the edit box for distance to a select with fixed values, and hide the distance units select defaulting it to miles.
Answer: I had a similar issue with editing the exposed form. Form alter is not the right way to go though. You'll need to use element info alter. Take a look at this custom module I threw together for editing the geofield proximity search. You can see what I did, and add/modify functionalities for your needs (although I think i did exactly what you wanted).
Comment: I used cojomojo's module as a starting point, it helped me a lot.
Answer: Something like
<code>function yourmodule_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'views_exposed_form') &&  ($form['#id'] == 'views-exposed-form-your-view')) {
    $form['proximity']['default_radius']['#type'] = 'select';
    $form['proximity']['default_radius']['#options'] = array(10, 20, 30);
    $form['proximity']['radius_unit']['#type'] = 'item';
  }
}
</code>


C DBus : Fails when calling method returning string

Question: Cant please someone tell me why the code below crashes when executing, (compilation goes OK) it in rotated X environment 90 to left.
<code>    DBusGConnection *connection;
    DBusGProxy *proxy;
    GError *error = NULL;
    gchar *name = NULL;

    g_type_init ();

    //Get the connection and ensure the name is not used yet
    connection = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error);
    if (connection == NULL) {
            g_warning ("Failed to make connection to system bus: %s",
                            error->message);
            g_error_free (error);
            exit(1);
    }

    proxy = dbus_g_proxy_new_for_name (connection,
                    "to.some.Service",
                    "/to/some/Object",
                    "to.some.Interface" );

    dbus_g_proxy_call(proxy, "getStatus", &error, G_TYPE_INVALID, G_TYPE_STRING, &name, G_TYPE_INVALID);
    printf("Name is: %s\n", name);
    return 0;
</code>
Comment: If it's really only crashing when the display is rotated 90 degrees, I'm pretty sure it's got something to do with the exact service you're calling. Please specify which service it is.
Comment: The service is defined by me and I think its working OK, because I've written a analogue python script (the same as above script) which returned correct values.
Comment: Actually above code is working OK at the first start of X. But fails to run normally if the display's orientation is rotated.
Comment: Downvoted as question is specific to your code and not generally useful to others.
Answer: Got answer. Actually the service is running in Python and the returned value was not string ... as a consequence of not being strong types in python. So returning str(status) but no status solved my problem.


Using Traefik to apply a ratelimit to a subpath in kubernetes

Question: How do I use the Traefik ingress controller to apply a ratelimit to just a subpath, while serving up the service at the root /?
For example I have a service called my-webapp and I want to serve it under / but ratelimit /api/. I tried creating an ingress with the rules:
- host: my-webapp.io
  http:
    paths:
    - backend:
        serviceName: my-webapp
        servicePort: 80
      path: /api/

and the annotations:
traefik.ingress.kubernetes.io/rate-limit: |
      extractorfunc: client.ip
      rateset:
        api-rateset:
          period: 1s
          average: 10
          burst: 20

as well as an ingress with the path / hoping that the more specific ingress would take priority for the /api/ path, but it doesn't seem to be the case.
Comment: Thank you for posting your thoughts, It helped me finding my issue. Actually I was using "" do define the YAML inside the YAML but as you did well you have tu use | :D
Answer: After investigating by adding a custom response header to each ingress to determine which ingress was used, I figured out the /api/ ingress does take priority. Applying ratelimits to this ingress and not the broader one appears to work, I'm not sure why it wasn't working earlier.


redirect /node?page=1 to main page

Question:
I have already indexed drupal-8 website's pages with pattern like - node?page=1; node?page=2 and so on
I would like to redirect them to site's front page

Tried:

I have tried with the redirect module but its not working
Answer: One way is to redirect page using events subscriber.
src/custom_module.services.yml
services:

    custom_module.custom_redirect:
        class: Drupal\custom_module\EventSubscriber\CustomRedirect
        tags:
          - {name: event_subscriber}

src/EventSubscriber/CustomRedirect.php
<?php

namespace Drupal\custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class to redirect.
 */
class CustomRedirect implements EventSubscriberInterface {

  /**
   * Check redirection.
   */
  public function Redirection(GetResponseEvent $event) {
    $attr = $event->getRequest()->attributes;
    $route_name = $event->getRequest()->get('_route');
   //Check route name and attr
    if ($route_name == 'check route name') {
        $front = \Drupal\Core\Url::fromRoute('<front>')->toString();
        $event->setResponse(new RedirectResponse($front));
      }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['Redirection'];
    return $events;
  }

}

Answer: mytheme.theme
function mytheme_preprocess_page(&$variables) { // <-- your theme may already have one
  // redirect if URL has a "page" param.
  if (!empty(\Drupal::request()->query->get('page'))) {
    $front = \Drupal\Core\Url::fromRoute('<front>')->toString();
    $response = new \Symfony\Component\HttpFoundation\RedirectResponse($front);
    $response->send();
  }
}

Comment: You can't do this from a preprocess hook, see https://drupal.stackexchange.com/questions/287393/how-to-get-the-uncached-version-of-request-headers

redirect /node?page=1 to main page


Archimedean property usage.

Question: I was reading a solution to a problem and I found this statement: "Let $\epsilon > 0$ then there exists a positive integer $n$ such that $1/n < \epsilon.$"
Is there is an educated justification for this sentence? Is this by Archimedean property? Could anyone explain this to me, please?
Comment: Emptymind. Have a look at the drawing in this link. https://en.m.wikipedia.org/wiki/Archimedean_property
Answer: Indeed, this follows directly from the Archimedean property of $\mathbb{R}.$ See e.g. Abbott Theorem 1.4.2 (he proves this directly), or Rudin Theorem 1.20 (a) by setting $x = \epsilon$ and $y = 1$.
For completeness, Rudin's statement is:
If $x,y \in \mathbb{R}$ and $x > 0$ then there exists a positive integer $n$ such that $nx > y.$
Answer: $\Bbb R $ is Archimedean means that
$$(\forall (x,y)\in (0,+\infty)\times \Bbb R) \;\; (\exists n\in \Bbb N) \;\; : \; nx>y$$
now, you apply this with
$$y=1 \text{ and } x=\epsilon$$
Answer: Yes, by the Archimedean property, there exists $n\in\mathbb N$ such that $n\times \epsilon>1$, so then $\dfrac1n<\epsilon$.
Answer: You can use the archemedian principal two ways.
If $M = \frac 1\epsilon$ and $d = 1 > 0$ then there is an $n$ so that $n = n*d > M =\frac 1\epsilon$ and so $\frac 1n < \epsilon$.
Or if $M = 1$ and $d = \epsilon$ then there is and $n$ so that $n*\epsilon > 1$ and so $\frac 1n < \epsilon$.

Archimedean property usage.


dúvida sobre o select no css

Question: Olá, gostaria de criar um espaçamento nos option do meu select, alguém pode me explicar como
<form method= "POST" class="mb-0" action="includes-site/enviar.php" id="formcadastro" >

        Primeiro Nome
        <input type="text" name="nome" class="form-control"id="nome">

        Email
        <input type="text" name="email" class="form-control" id="email">

        Telefone
        <input type="text" name="phone" class="form-control" id="phone" onkeypress="mascara(this)">

    Qual Melhor forma de atendimento?
    <select name="atendimento" id="Atendimento" class= "form-control">

    <option value="" disabled selected>Clique e Selecione</option>
    <option value="WhatsApp">Whatsapp</option>
    <option value="Email">Email</option>
    <option value="Ligação">Ligação</option>

    </select>

        <input type="submit" class="btn btn--primary btn--block mt-10" value="enviar">

    <input type="hidden" name="titulo" value="<?php echo $tit;?>">

</form>

Comment: Que tipo de espaçamento você precisa? Poderia dar um exemplo de como gostaria que ficasse?
Answer: use "padding".

padding: 5px 5px 5px 5px;

superior, direito, inferior e esquerdo é a ordem das regras de padding.
Se não quiser abreviar, use:

padding-top: 5px;
padding-right: 5px;
padding-bottom: 5px;
padding-left: 5px;

Lembrando, você pode alterar o valor de "5px" pro que quiser. Em porcentagem, pixels, "em", todas as opções disponíveis.
Comment: Entendi, mas estou com dúvida de como chamar a classe no style, pode me explicar por favor?
Comment: Claro.
Use:

option{
     *insira aqui o código*
}
Comment: Como "option" não é class nem id, não precisa nem de "." nem de "#" pra chamá-la.
Comment: Você também pode inserir uma class="option", mas acredito ser redundante, já que você consegue fazer sem :)
Answer: O padding é o mais recomendado neste caso, ele vai criar um espaço interno. O importante é que você defina para todos os lados, senão acaba jogando o conteúdo da  para um lugar que não deseja.
padding: 5px;

ooooooooou, você pode fazer para todos um por um:
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;

Comment: Isso não funciona
Comment: Pode me mandar o seu código então?
Comment: Com padding é que não é amigo, agora como faz eu não sei, vc poderia ter testado seu código antes de postar. Responder qq coisa na ajuda, principalmente se não funciona...
Answer: Correção: Funciona apenas no <Select>
Você também pode usar uma classe (ou ID) no  e manipular o padding ou margin do option, tipo:
select {
 padding:5px;
}

Comment: Isso não funciona
Comment: Editei... Após testar percebi que funciona apenas no Select
Answer: Use padding nos options
No CSS
.option {
    padding: 10px;
}

No HTML
<option class="option" value="" disabled selected>Clique e Selecione</option>
<option class="option" value="WhatsApp">Whatsapp</option>
<option class="option" value="Email">Email</option>
<option class="option" value="Ligação">Ligação</option>

Comment: Isso não funciona
Comment: @Geremias, poste a sua solução para ajudar o cara
Answer: De uma maneira rápida você pode usar a tag br
, ou pode usar CSS para adicionar margin ou padding dependendo do que quer fazer.
Edit:
Não notei que era espaçamento entre as opções, não é possível usar o
 entre option
Sorry :/
Comment: Isso não funciona
Comment: tentei usar o br e não funcionou, será que coloquei errado? Obrigado pela ajuda! ^^
Comment: Então use o CSS adicionando uma classe no elemento e adicionando o CSS
Comment: :/ realmente, mas obrigado por tentar ajudar. ^^/

dúvida sobre o select no css


How to prove whether this grid puzzle is unsolvable/solvable?

Question: [Disclaimer: I have researched a bit before this post and I have found no other questions that address my problem specifically, hence this post]
So I have been made a puzzle concept in a python program of mine, you have a 4 x 4 grid of lights, all of which are off at the start of the puzzle, your goal is to turn all the lights on.
The positions of the grid of lights is as follows:
1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16

The way you change the state of the lights is that you click the lights in the grid, each individual light affects a fixed set of lights in the grid unique to that individual light only. To clarify with an example: Imagine I click the first light in the grid, and it inverts the state of the lights at positions 1, 5, 8 and 10, and on clicking the light at position 2 of the grid it inverts the state of the lights at positions 2, 7, 9 in the grid.
(From now on, I will be calling this as "mapping", for example: the mapping of light 2 is to lights 2, 7, 9)
If you know of the game LightsOut, its like that except the lights inverted are spread across according to a formula I used, instead of being the neighbors of the light clicked.
(if you are confused still and need clarification, refer to the pictures I have linked at the end of this question, I hope that will resolve any queries, if any topic is unclear then I will edit this post to explain in a better way)
So now moving on to the question I have:
I have a certain mapping for the lights which is as follows:
Light 1  inverts lights 1, 5, 8, 11, 14

Light 2  inverts lights 7, 10, 13, 16

Light 3  inverts lights 2, 9, 12, 15

Light 4  inverts lights 1, 4, 5, 11, 14

Light 5  inverts lights 3, 7, 13, 16

Light 6  inverts lights 2 , 5, 9, 15

Light 7  inverts lights 1, 4, 7, 8, 11

Light 8  inverts lights 3, 6, 10, 13

Light 9  inverts lights 5, 8, 12, 15

Light 10 inverts lights 1, ,7, 10, 11, 14

Light 11 inverts lights 3, 9, 13, 16

Light 12 inverts lights 2, 5, 11, 15

Light 13 inverts lights 1, 4, 7, 13, 14

Light 14 inverts lights 3, 6, 9, 16

Light 15 inverts lights 2, 5, 8, 11

Light 16 inverts lights 1, 4, 7, 10, 13

Using this mapping I have been trying to solve from a state where all lights are off to where all lights are on for TENS of hours, I have made literally 83 algorithms to help in some cases, but I am unable to turn all of them on.
However when I made the 9th element 1 and the rest as 0, essentially modified the starting grid configuration, I was able to solve it using my algorithms.
SO FINALLY, my questions are:
1) Is it possible to solve this grid with the given mapping?
2) I want to know a proper method I can use to prove whether the puzzle is solvable with a given mapping, a general method I can apply to any mapping
3) The way I generate a mapping is very simple, mainly addition of one number to a list of numbers,  and its definitely not the standard, if you are aware of a better way to reliably generate mappings, that is used in professional games/ professional settings, please let me know, I realize that this may be considered more of a puzzle/ CS question, but if you know a way, please let me know, however the main answers I want are for Question 1 and 2
Here are the pictures for better understanding, however I have changed the lights in the program to be represented by 1s and 0s for more compatibility in mathematical understanding, 0 indicates off, and 1 indicates on:
Initial Grid Set-up
The grid when the first light is clicked (inverts lights at position 1, 5, 8, 11, 14)
The grid when the second light is clicked (inverts lights at position 7, 10, 13, 16)
End Goal configuration of grid
Comment: Are you familiar with linear algebra? If so, work in $M_{16}(\mathbb{Z_2})$ and figure out if the all 1 vector is in the range space.
Comment: To clarify, he means using a 16 by 16 matrix of "bits", eg working in modulo 2.  Your constraints can all be described as linear equations modulo 2.
Comment: Lookup Gaussian elimination. Look at first light. Instead of having 1 and 4 in your base operations, you'd have 1 and 1+4 in your base operations. Adding 1 to 4,7,10,13,16 gives a new set of operations which are just as strong as the previous ones, but only 1 flips row 1.  Do the same to the rest until you get that only light 1 flips 1, only light 2 flips 2, etc. then, to flip 1 to 16 first flip 1, then see what the smallest thing you need to flip, flip that one, keep going using the only operation that would flip the smallest one.
Comment: @Eric I don't know about the Gaussian elimination, but I get the idea that you're getting at. That's actually what I used in my algorithms, I tried to generate as many as I could that would flip the least amount of lights, the the least I could flip was 2, and there were around 8 of them but I was never able to get a single light flipped ever, which makes sense seeing the mapping. I'll look into Gaussian elimination as well though since it can help me in other places, thanks.
Answer: First, put your rules into a matrix:

Then, you can do something called "row reduction" modulo 2. This involves adding copies of some rows to other rows (where $1+1=0$) and possibly switching some rows around. A set of rules will be solvable from any initial state exactly when the row reduced matrix has a single 1 in each row and column. If we row reduce the above matrix we get:

We can see that there are states from which the game is not solvable. In fact, because there are three rows of zeroes, there are three conditions any game state that can reach the lights out position must satisfy.
You can get these equations by calculating the null space of the matrix, which is given by the three rows of this matrix:

If we let $L_i$ be $1$ if it is on and $0$ if it is off, then, unpacking the first row, we see that
$L_4+L_7+L_8+L_9+L_{11}+L_{15}+L_{16} \mod 2$ does not change under any of your above moves. This means that you can never go between the state of no lights turned on to the state of say, just $L_4$ turned on, or indeed any odd combination of $L_4,L_7,L_8,L_9,L_{11},L_{16}.$
In particular, to answer your question of whether you can go from the all lights on state to the all lights off state, since $L_4+L_7+L_8+L_9+L_{11}+L_{15}+L_{16}$ evaluates to $7=1\mod 2$ for all lights on, this is impossible.
The other two rows of the null space matrix give two other sums of lights that don't change (up to parity) under your moves.
Interestingly, if you look at the row reduced matrix, the $1$ in the upper left has only zeroes in its row. That means that you can toggle the first light in any game position using a combination of the legal moves.
Comment: @coffeemath right. Looks like the question I was answering was whether you could go from an arbitrary state to lights off, not just all lights on. Somehow, I missed that the OP was looking at a special starting state.
Comment: @coffeemath I've already proven that the OP's moves aren't sufficient because they preserve a sum of a particular set of 7 lights (as well as two other conditions). That sum is $1$ for all on, and $0$ for all off, mod 2. For the general case, something like what you propose might work, I'd have to think about it a bit.
Comment: If light number 1 changes the states of *all* of the lights, while all other lights do nothing, the initial matrix would have first row all 1's and all other rows 0. It would already be row-reduced. And one can go from no lights on directly to all lights on by throwing switch number 1. However this reduced matrix does not have a single 1 in every row and column.
Comment: ok so i have three queries after reading this question: 1) How did you get the row reduced form, did you perform elementary operations on the matrix? or did u get the row reduced echelon form?

2) How did you 3rd matrix, the 16x3 one?

3) when do we say the puzzle is solvable? When we have only 1 in each row in a diagonal? or if there is only 1 in each row in any position within the row?
Comment: @coffeemath however, the calculation of the null space and the three linear expressions that are preserved by the OP's rules are still correct, in particular implying that the game is not solvable from an all lights on state, since the first functional evaluates to 1 on the all lights on state.
Comment: @ateeq 1) I performed elementary operations: adding rows to other rows and switching rows in order to get the reduced echelon form. Modulo 2 there are no other operations. 2) For this one, i actually used a computer algebra package, though it can be done by hand. Wolfram Alpha could probably handle it. 3) Yes it could be in any position, but after rearranging the rows, it would be a nice diagonal line. Note that as coffeemath alluded to above, this condition says that the game is solvable from any initial configuration of lights, which is a stronger condition than what you asked.
Comment: @CheerfulParsnip Hmm okay, but regarding your last two lines, you're saying that the puzzle is solvable from any initial configuration of lights, but then in your answer you said that with the given light mapping, the puzzle is not solvable, so that's two contradicting statements. Am I misunderstanding something? If so can you clarify please
Comment: @ateeq sorry for being confusing. A good way to say it is that the puzzle is solvable from any initial state if the reduced matrix is a diagonal row of 1s. It is solvable from the all lights on state if the all lights on state evaluates to zero on all the rows of the null space. For your particular case, this doesn't happen, so it is not solvable from the all lights on state.
Comment: @CheerfulParsnip Ah now I understand, alright. Thank you for all your help. So as a final confirmation, the method to find out if the puzzle is solvable with any given mapping is:

`1) Create a matrix corresponding to given mapping

2) Perform elementary operations on it to get reduced echelon form (Sidenote: can Gaussian elimination be used?)

3) If there is only a single 1 in each row of the matrix then it is solvable, else not`

Did I get that right?
Comment: @CheerfulParsnip with my setup for the moves, if the initial board has all lights on, one could flip any of the 15 switches which alter nothing, and end with all lights on. Of course from an initial board which has at least one light on and at least one light off, my moves will not solve that board.
Comment: @coffeemath I agree. Did I say something that contradicts that?
Comment: @Ateeq your understanding is right if "solvable" means "solvable from any starting position."
Comment: @CheerfulParsnip Yes that would be right, since its inclusive of all 0s state. But anyways , thank you for all the help on this problem of mine.
Comment: @CheerfulParsnip I assume you have software which can row reduce over integers mod 2. If so, then it might be used to attack the question of whether or not all lights on can be reached from the specific starting board of all lights off. My idea is that you add a 17th column of all 1's to your 16x16 matrix, and then row reduce. If the state of all 1's cannot be reached, I think there would appear a row of 16 zeroes followed by a 1 in the augmented column. Would this constitute a test of whether or not one can go from all off to all on using the OP's moves? If so what happens?
Comment: @CheerfulParsnip Hey, sorry to contact you even though you've answered my question, but if possible could you tell me what I would have to do to the matrix in order to confirm if a mapping would work on a particular initial state, I want to implement that in my program and would really appreciate if you could tell me how.
Comment: @ateeq it's probably easiest to discuss with a smaller example, so I can illustrate all the steps. I will try to work on that later today.
Comment: @CheerfulParsnip Yes that's completely fine, and easier for both of us. I'm Thankful for any sort of help


Laravel Database 'Where' statement breaks Search

Question: I have been having a problem with the where statement in Laravel. I use this to get data from the database and then push it for live search:
$launchsitesatellite = DB::table('satellites')
    ->orWhere('satname','LIKE','%'.$request->search.'%')
    ->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')

I need to add this to filter the results coming from the database: ->where('site', $site_code).
I tried adding it the where statement I have above, but it broke my live search and resulted in a 500 server error when I tried typing something in my input. I can use ->where('site', $site_code) to just display the data from the database but not search it.
My question is: Why does the ->where('site', $site_code) query break the search and how would you fix it?
EDIT: My controller snippet:

if ($request->ajax())
{
    $output="";
    $launchsitesatellite = DB::table('satellites')
        ->orWhere('satname','LIKE','%'.$request->search.'%')
        ->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
    if ($launchsitesatellite)
    {
        foreach ($launchsitesatellite as $key => $launchsitesatellites) {
        $output .='
'.
                ''.$launchsitesatellites->satname.'	'.
                ''.$launchsitesatellites->norad_cat_id.'	'.
                ''.$launchsitesatellites->object_type.'	'.
                '
';
        }
    }

    return $output;
}
else {
    $launchsitesatellite = DB::table('satellites')->where('site', $site_code)->get();

    return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
}
Comment: Where's the semicolon to terminate where `$launchsitesatellite` gets defined (or is it a copy-paste error)?
Comment: @ChrisForrence - Sorry, forgot to add one in for the snippet. Fixed now.
Answer: You have to isolate or statements. Try this:
$launchsitesatellite = DB::table('satellites')
    ->where(function($q) use ($request) {
        $q->orWhere('satname','LIKE','%'.$request->search.'%')
          ->orWhere('norad_cat_id','LIKE','%'.$request->search.'%');
    })
    ->where('site', $site_code)->get();

Comment: I'll add it to the answer for future readers, but, it is nice to see that Chris was able to help you with this!
Comment: I think he meant `WHERE site = ? AND (satname LIKE '%?%' OR norad_cat_id = '%?%')`.
Comment: That unfortunately did not work. I will post my full controller as maybe there might be something conflicting.
Comment: Any errors? Or this doesn't filter the results as you need?
Comment: @Laerte Whenever I search I get a 500 internal server error. Other than that there is nothing.
Comment: @D.777KLM Anything in the error log? (Laravel's log is stored in `storage/logs/laravel.log` by default, or it may be on in your server's error_log)
Comment: So, I think the problem is not related to the query. As Chris said, take a look at the logs, it should help.
Comment: @ChrisForrence Yes I get an error - `Undefined property: Illuminate\Database\MySqlConnection::$satname`. They are defined in my controllers so something must be going wrong here.
Comment: I was getting the error because I was not adding `->get()` to the query. Once I added that it got rid of the error.
Answer: Let's take a look at the code you have in your if-block:
if ($request->ajax())
{
    $output="";
    $launchsitesatellite = DB::table('satellites')
        ->orWhere('satname','LIKE','%'.$request->search.'%')
        ->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
    if ($launchsitesatellite)
    {
        foreach ($launchsitesatellite as $key => $launchsitesatellites) {
        $output .='
'.
                ''.$launchsitesatellites->satname.'	'.
                ''.$launchsitesatellites->norad_cat_id.'	'.
                ''.$launchsitesatellites->object_type.'	'.
                '
';
        }
    }

    return $output;
}

The error you're getting (mentioned here) is
Undefined property: Illuminate\Database\MySqlConnection::$satname

When you define $launchsitesatellite, you're adding where-clauses into the SQL statement, but never kick it off.
Instead, do this:
$launchsitesatellite = DB::table('satellites')
    ->orWhere('satname', 'LIKE', '%' . $request->search . '%')
    ->orWhere('norad_cat_id', 'LIKE', '%' . $request->search . '%')
    ->get();


Jekyll: Manually whitelist directories and files to be copied to _site directory

Question: Is it possible to specify a list of files or directories that one would like copied to the _site directory? I would like to copy those files as is, in the way the webpack-copy-plugin lets one use webpack to copy files from on place to another.
The files I want to copy are in _includes, in case this complicates things. I know I could make a top level directory in my project for these files I want copied to _site, but I want to keep things tidy and place everything in _includes (Jekyll already makes lots of files and folders in my project root, and I don't want any more).
I tried specifying the value for include in _config.yml, but this doesn't seem to be copying file to _site.
Any suggestions others can offer would be helpful!
Answer: Curious, specifying in _config.yml:
include:
  - _includes

Copies over everything from _includes, while specifying:
include:
  - _includes/assets

does not copy over anything. I'll just use the former.


django: how to load the static files with hash/md5 appending correctly?

Question: using Django 3
I followed the Django Doc
https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#manifeststaticfilesstorage
to export my static files with a hash appending.

settings.py production

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

static_root folder (output)

 static_root/
          staticfiles.json
 static_root/css/
               project_styles.87c2920e7bc3.css
               project_styles.css

everything is collected correctly.

Afterwards i uploaded everything to my apache static server.
And i set off / comment  the STATICFILES_STORAGE . That is how i understand the Doc´s? If i leave this setting on in production i get an 500 Error.

settings.py production

# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

After restarting my Django app in production, my site is still loading project_styles.css but not the hash Version  project_styles.87c2920e7bc3.css in my browser. Even if i delete project_styles.css Django will not serve the hash version.
Question

Did i miss some settings in the settings.py in production mode?
In the Doc´s they mention to set STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage but it shows no difference. And as it is mentioned it´s only for testing.
What i have to do to load the correct static hash version in production? do i have to set something in my templates, so that django will look into the json file for the correct hash version? Or do i have to name the hash file?
Answer: Alright, the Problem was that i wanted two different STATIC_ROOT Paths. One for Development and one for Production, because i want all my Development stuff in one Project folder. Because if you collectstatic with the STATIC_ROOT of your apache server, django will export it for instance into c:/var/www/your/server/static while i wanted it to  c:/webprojects/myproject_1/static_root_exports and later upload these files on my server separately.
So i set two different Path depending on DEV_STATIC off / on in my django-environ file. Django will set the correct Path.

.env

DEBUG=off
# --- applies media server & sets MEDIA_ROOT & STATIC_ROOT
DEV_STATIC=on

<...>

STATIC_ROOT_DEV=static_root_exports
STATIC_ROOT_PROD=/var/www/myUserName/html/myproject_assets/static

<...>

setting.py

# -- Set for Hash
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
# --- STATIC_ROOT
if DEV_STATIC == True:
    STATIC_ROOT = SERVER_DIR.joinpath(env('STATIC_ROOT_DEV'))
else:
    STATIC_ROOT = env('STATIC_ROOT_PROD')

Comment: Just a little observation but you should have different .env files for prod and dev so you don't have to be writing `if` for every setting in settings.py. You will simply have `STATIC_ROOT` in each env file and load it in settings without any `if`


Reward not increasing while training a Bipedal System

Question: I am completely new to reinforcement learning and this is my first program in practice. I am trying to train the bipedal system in the OpenAI gym environment using the policy gradient algorithm.
However, the reward never changes, either at episode 0 or at episode 1000 and I cannot figure out what is going wrong. Could anyone please help me..
TIA.
The code is as follows:
import torch
import torch.nn as nn
import numpy
from torch.autograd import Variable
import gym

def train(model, name):
    model.train()
    env = gym.make(name)
    env.reset()
    num_episodes = 20000
    max_steps = 10000
    optim = torch.optim.Adam(model.parameters(), lr=1)
    numsteps = []
    rewards = []
    avg_numsteps = []

    min_reward = -1000

    for episode in range(num_episodes):
        state = env.reset()
        probs = []
        rewards = []

        for steps in range(max_steps):
            action, log_prob = model.action(state)
            env.render()
            state, reward, finished, _ = env.step(action.squeeze(0).detach().numpy())
            env.render()
            probs.append(log_prob)
            rewards.append(reward)
            if finished:
                break

        if finished:
            Rewards = []
            for i in range(len(rewards)):
                G = 0
                p = 0
                for reward in rewards[i:]:
                    G = G + 0.9 * p * reward
                    p = p + 1
                Rewards.append(G)

            Rewards = torch.tensor(Rewards)

            discounted_reward = (Rewards - Rewards.mean()) / (Rewards.std() + 1e-9)

            gradients = []
            for log_prob, G in zip(log_prob, discounted_reward):
                gradients.append(-log_prob * G)

            optim.zero_grad()
            policy_gradient = Variable(torch.stack(gradients).sum(), requires_grad=True)
            policy_gradient.backward()
            optim.step()
            numsteps.append(steps)
            avg_numsteps.append(numpy.mean(numsteps[-10:]))
            rewards.append(numpy.sum(rewards))

            print("episode: {}, total reward: {}, average_reward: {}, length: {}\n".format(episode,
                                                                                numpy.sum(rewards),
                                                                                numpy.round(numpy.mean(
                                                                                rewards[-10:]),
                                                                                decimals=3),
                                                                                steps))

        if numpy.sum(rewards) > min_reward:
            torch.save(model.state_dict(), '/home/atharva/policyNet.pth')
            min_reward = numpy.sum(rewards)

def test(model, name):
    env = gym.make(name)
    model.eval()
    state = env.reset()
    with torch.no_grad():
        while True:
            action, log_prob = model(state)
            state, reward, finished, _ = env.step(action.squeeze(0).numpy())
            env.render()
            if finished:
                break

class PolicyNet(nn.Module):
    def __init__(self, inputs, actions, hidden_size):
        super(PolicyNet, self).__init__()
        self.num_actions = actions
        self.layer1 = nn.Linear(inputs, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.layer3 = nn.Linear(hidden_size, 2*hidden_size)
        self.layer4 = nn.Linear(2*hidden_size, hidden_size)
        self.layer5 = nn.Linear(hidden_size, actions)

    def forward(self, x):
        x = self.layer1(x)
        x = nn.functional.relu(x)
        x = self.layer2(x)
        x = nn.functional.relu(x)
        x = self.layer3(x)
        x = nn.functional.relu(x)
        x = self.layer4(x)
        x = nn.functional.relu(x)
        x = self.layer5(x)
        return x

    def action(self, state):
        state = torch.from_numpy(state).float().unsqueeze(0)
        actions = self.forward(Variable(state))
        #prob = numpy.random.choice(self.num_actions, p=numpy.squeeze(actions.detach().numpy()))
        log_prob = torch.log(actions.squeeze(0))
        return actions, log_prob

and the calling is as follows
from REINFORCE import PolicyNet, train

model = PolicyNet(24, 4, 256)
train(model, 'BipedalWalker-v3')

Answer: Your learning rate is way too high! High learning rate may lead your model to never converge (in fact, the loss may diverge). A learning rate that is way too low will make the training process unnecessarily long. There is a trade-off you have to find for yourself.
Tunning your learning rate may have a tremendous impact on the performance of your model. I can recommend you spending some time reading this (quite well written) blog post: https://machinelearningmastery.com/learning-rate-for-deep-learning-neural-networks/
For starters, try a learning rate that is in the range [0.01, 0.00001]. For instance:
optim = torch.optim.Adam(model.parameters(), lr=0.001)

Comment: The learning rate was 1e-2 to 1e-5 before and still did nothing happened.. so that is when I got frustrated and kept it as 1... I believe the model parameters are not being updated hence the reward and loss etc remain the same....
Comment: not sure if that will make a difference, but replace `actions = self.forward(Variable(state))` with `actions=self.__cal__(torch.tensor(state))`. By calling forward directly you skip some hooks that thare used in the backward pass.
Comment: Deep Reinforcement Learning is notorious for its sensitivity to hyperparameters. It could be a bug in your training, but often it gets down to finding the correct hyper parameters to make it work. You can check here for some examples that do work: https://github.com/VictorZuanazzi/Project_RL.git and https://github.com/VictorZuanazzi/ReinforcementLearning-2/blob/master/lab2.ipynb
Comment: Thanks a lot, will check them out.


Modify a text file in server?

Question: I need to modify the ape.conf file in my apache server. However when I access it through filezilla the file is read only. How do I modify it? Can I change permissions with SSH? Or what would be the correct way to do it?
Thanks
Comment: Please stop referring to this as your "apache server" and start telling us what operating system you are running, as well as using appropriate tags. Your question as written applies equally to all operating systems that can run Apache, yet the details of the answer can be different for each.
Answer: if you can connect through ssh ... why don't you modify your file with a text editor ?
Comment: step 1) ssh loginname@machine step2) cd /whereFileIs step3) nano fileName
Comment: I don't know how to do it...

Modify a text file in server?


Learning Indian Classical vs Learning Singing in general

Question: Which of the following will give a better quality of voice and overall better skill in music- Learning Indian Classical music (probably on a western Instrument like harmonium whose frequencies are different) or singing by 'voice trainers'?
Comment: What is a 'voice trainer'?  Don't Indian classical musicians get trained?  Are you asking for the diff between Indian vocal training and Western vocal training?  Or in person training vs some type of online app.
Answer: Long story short: if you live in an area with strong Indian culture and are very familiar with Indian Classical music, start there. If you just think Indian music is cool, start somewhere else.
Either one is going to provide you with a lot of the fundamentals of vocal training (breath support, pitch, posture, etc.) Anything that doesn't overlap between the two (specific techniques, repertoire, community, etc.) will have very little crossover (unless you learn both and create a crossover yourself). Here are a few things to consider:
1. Location and local culture: If you live in an area where Indian Classical music is prevalent and it is more familiar to you it may be a good place to start (especially if you are not familiar with western vocal music). If you live in an area where Indian Classical isn't common and you are not already familiar with it (like, adolescent nostalgia familiar) and you just think it is cool, don't start with it (you can always pick it up later)
2. Resources: How difficult will it be for you to find educational books, teachers/tutors/mentors and decent repertoire? This is closely related to #1, but goes a step further. You may have grown up with Indian Classical, but if the only resources available to you teach western vocal technique, this is something to take into account.
3. Personal preference: Are you particularly passionate about one or the other? Don't skip out on what you enjoy because you think the other will be more beneficial. If you have the resources available to you (as described above) neither will give you a significant advantage over the other in terms of vocal training.
Finally, my personal recommendation: learn both. It's always a good idea to diversify, there are likely techniques from one that will at least teach you something about the other and most of the things you learn will apply to both anyway. Wherever you are, there are likely plenty resources for at least one of them and thanks to the interwebs I'm sure you could dig up a fair amount about the other.


Trouble in displaying an input element after the click of a button

Question: I have a function that is supposed to add an input element to an existing div. I have tried using appendChild and have tried concatenating the object to the innerHTML but none of these have worked. Is there something here that my newbie's brain is forgetting?
function addSong() {
  const additionDiv = document.getElementById('track-controls');
  const trackFileInput = document.createElement('input');
  additionDiv.innerHTML += trackFileInput;
  const trackFile = trackFileInput.value;
  console.log('file saved'+trackFile);
}

Kindly assume that the outer variables and IDs are all present in other parts of the code. This function is referenced in the onclick property of a button.
I have thoroughly checked for typos.
Answer: You've mixed two competing methods for editing the DOM.  innerHTML wants a string, but you're feeding it a DOM node instead (and then trying to concatenate that node with the existing html string).  For a DOM node, you want to append the element (or use other DOM manipulation methods):

function addSong() {
  const additionDiv = document.getElementById('track-controls');

  const trackFileInput = document.createElement('input');
  additionDiv.appendChild(trackFileInput)

  const trackFile = trackFileInput.value; // note this will always be an empty string
  console.log('file saved' + trackFile);
}

addSong()


Data Entry Form in Drupal

Question: I am new to Drupal and somehow managed to create a website with some basic pages I required using views. One of the main functionality that I need is a data entry form where a logged in user can enter details about members of his/her team like name, age, etc and this too for variable number of members. So far I could not find anything related. Has anyone tried anything related to this?
Thanks in advance.
Answer: Add fields to the existing content types 'Article' or 'Page' or create a content type based on your requirement.
Add fields name, age, etc
<code>admin >> strucuture >> content types >> Add content type
</code>
path (/admin/structure/types/add)
or manage fields of the existing content type (add or delete)
Ex: For Article content type you can manage fields at

admin/structure/types/manage/article/fields

Data Entry Form in Drupal


jQuery - get the selected options of a listitem collection?

Question: I have fields that a user would enter and i would pass it into jQuery and pass to a web service.
I can get textboxes values by:
var name =  $("#MainContent_txtName").val()
The problem I'm having is a multi-select that comprises of a list item collection.
If I was to do this server side, I would do something like:
foreach (ListItem li in listTitles)
{
   if (li.Selected)
   {
     selectedValue += li.Value + ",";
   }
}

And this would give me the string of selected values from the select list.
I'm having trouble getting it out from jQuery.
If I do
var titles = $("#MainContent_selectListTitles").val()

That is obviously incorrect because it won't bring back the selected list items.
I saw a post that suggested that I could retrieve it if I say option selected.
So I tried this:
var titles= $('#MainContent_selectListTitles option:selected');

The next thing I did was pop an alert to see what the titles were.  It just said [object, object].
So my questions are:

Is it possible to get the selected items from the list item collection concatenated into a string?
Or is it better that I get all the form values from a postback even on my code behind and then call the jquery function?  If this is an option, i've attempted to do this but have failed.  It tells me that it can't find the method. So i'm definitely not calling the jquery function correctly on postback of the button event.

THanks.
Comment: Ok, so I got it working now. Forgive me as this is my first time using jQuery.

I use this to get each selected option:
  $("#MainContent_msClaimantType :checked").each(function () {
          alert($(this).text());

Now this pops up an alert for each selected option.
So the question now becomes how do I concatenate the selected options into a variable?  thanks.
Comment: i would go with option #1 and i did similar to #1
Answer: I'm not surprised that you've got [object, object] in your alert - that's because you've had and array of selected items (actually, two items were selected) and alert displayed your array as [object, object] which is fine.
Having the following html markup:

        <select multiple="multiple" id="mySelect">
            <option value="test1" selected="selected">Test 1</option>
            <option value="test2">Test 2</option>
            <option value="test3" selected="selected">Test 3</option>
        </select>

And the following script:

Will probably solve your problem.
Actually, binding the data manually is a huge pain and I do recommend you to look on the modern MVVM libraries like knockout.js.
For instance:
http://knockoutjs.com/examples/controlTypes.html
Answer: First, make sure your item id is correct on client side that is "MainContent_selectListTitles". You can check it by "View Source".
If the ID is correct, follow this.
    $('#MainContent_selectListTitles').change(function () {
         var str = "";
         $('#MainContent_selectListTitles option:selected').each(function () {
              str += $(this).text() + " ";
              //pass str value to your web service here.
         });
    }).trigger('change');

Every time there is changes, it will call this function which means it will make your web service busy. You can move the above code to button click event if you want.
Comment: Thanks Mikhail and Jonas.
I actually had it working but tried your methods as well to prove that yours work as well.  Mine was actually very similar to what Jonas had.  I was a fool. I had var str = "" inside of the each(function).  No wonder why there was nothing in it when I tried to pass it via web service.

THanks for the help!


How can I render a custom values on specific column of Vuetify table?

Question: I need to display rules > details count in one of the column called conditions.
Note:

rules is an array, where rules.details.length = 2

I tried

code
headers: [
    { text: 'Priority', value: 'priority', width: '10%' },
    {
        text: 'Name',
        align: 'start',
        sortable: false,
        value: 'name',
        width: '30%'
    },
    { text: 'URL', value: 'url', width: '30%' },
    { text: 'Condition', value: '?????????', width: '20%' },
    { text: '', value: 'data-table-expand', width: '5%' }
],

How can I do that ?
Comment: I added an answer. Hope that will work as per your expectation.
Answer: I will recommend using computed to get new items with the property you need. You can change the property to whatever you need.
Or you can use v-slot:item.conditions like the example on the page of the link.
https://github.com/vuetifyjs/vuetify/blob/master/packages/docs/src/examples/v-data-table/slot-simple-checkbox.vue
The link is from here
https://vuetifyjs.com/en/components/data-tables/#simple-checkbox
Comment: I think your Codepen link is broken
Comment: It's not showing anything at all.
Comment: I think the link is OK now.
Answer: Observations/Suggestions :

As we use headers array to show the column names. You should not assign any dynamic value in that. Instead you can do this in the column data.
You can achieve this requirement by adding the condition value in mounted lifecycle hook.

Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      headers: [
        { text: "Priority", value: 'priority' },
      { text: "Name", value: 'name' },
      { text: "URL", value: 'url' },
      { text: "Condition", value: 'condition' }
    ],
      rules: [{
      priority: 1,
      name: "Alpha",
      url: 'https://example.com',
      urlGroup: '',
      condition: ''
    }, {
      priority: 2,
      name: "Beta",
      url: 'https://example.com',
      urlGroup: 'userGroup2',
      condition: ''
    }],
    }
  },
  mounted() {
    const rulesLength = this.rules.length;
    this.rules.forEach((obj) => {
        obj.condition = rulesLength;
    })
  },
  methods: {
    displayURLInfo(index) {
      if (this.rules[index].urlGroup != '') {
         return      this.rules[index].urlGroup
      } else {
        return this.rules[index].url
      }
    }
  }
})

<link rel="stylesheet" href="https://email@example.com/dist/vuetify.min.css"/>

  <v-app id="inspire">
    <v-data-table
      :headers="headers"
      :items="rules"
    >
      <template v-slot:item.url="{ index, item }">
    {{ displayURLInfo(index) }}
</template>
    </v-data-table>
  </v-app>


Doing calculations of decimal to binary and using one's complement

Question: what is 18 base - 13 base 10 using one's complement?
i do not know how to work it and how the one's complement works.
I know that 18 is equal to 10010(2) and 13 is 1101 (2) but I am not sure if I should subtract and then do the one's complement or do it before subtracting. so please help me. thank you.
Answer: Since everything is positive, you don't have to worry about one's complement.  Just subtract in base $10$ and convert to base $2$ or subtract the base $2$ values you have.


CentOS 6 + LDAP + NFS. File ownership is stuck on "nobody"

Question: I've been trying to get LDAP authentication and NFS exported home directories on CentOS 6 working for a few days now. I've gotten to the point that I can now login to the client machine using the username and password in LDAP.  On the client, /home and /opt are mounted in the fstab over NFS. However, every file in both /opt and /home is owned by nobody:nobody (uid: 99, gid: 99) on the client.
However my uid and gid appear to be properly set:
-bash-4.1$ id
uid=3000(myusername) gid=3000(employees) groups=3000(employees)

What else can I check? Here are some the config files on my client:
/etc/nsswitch.conf
passwd:     files sss
shadow:     files sss
group:      files sss

hosts:      files dns

bootparams: nisplus [NOTFOUND=return] files

ethers:     files
netmasks:   files
networks:   files
protocols:  files
rpc:        files
services:   files

netgroup:   files sss

publickey:  nisplus

automount:  files ldap
aliases:    files nisplus

/etc/sssd/sssd.conf
[sssd]
config_file_version = 2
services = nss, pam

domains = default
[nss]

[pam]

[domain/default]
auth_provider = ldap
ldap_id_use_start_tls = True
chpass_provider = ldap
cache_credentials = True
krb5_realm = EXAMPLE.COM
ldap_search_base = dc=mycompany,dc=com
id_provider = ldap
ldap_uri = ldaps://server.subdomain.mycompany.com
krb5_kdcip = kerberos.example.com
ldap_tls_cacertdir = /etc/openldap/cacerts

# Configure client certificate auth.
ldap_tls_cert = /etc/openldap/cacerts/client.pem
ldap_tls_key = /etc/openldap/cacerts/client.pem
ldap_tls_reqcert = demand

/etc/fstab
/dev/mapper/vg_main-lv_root /                       ext4    defaults        1 1
UUID=4e43a15d-4dc0-4836-8fa6-c3445fde756c /boot                   ext4    defaults        1 2
/dev/mapper/vg_main-lv_swap swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
storage1:/nas/home  /home  nfs   soft,intr,rsize=8192,wsize=8192
storage1:/nas/opt  /opt  nfs   soft,intr,rsize=8192,wsize=8192

authconfig output:
[root@test1 ~]# authconfig --test
caching is disabled
nss_files is always enabled
nss_compat is disabled
nss_db is disabled
nss_hesiod is disabled
 hesiod LHS = ""
 hesiod RHS = ""
nss_ldap is enabled
 LDAP+TLS is enabled
 LDAP server = "ldaps://server.subdomain.mycompany.com"
 LDAP base DN = "dc=mycompany,dc=com"
nss_nis is disabled
 NIS server = ""
 NIS domain = ""
nss_nisplus is disabled
nss_winbind is disabled
 SMB workgroup = ""
 SMB servers = ""
 SMB security = "user"
 SMB realm = ""
 Winbind template shell = "/bin/false"
 SMB idmap uid = "16777216-33554431"
 SMB idmap gid = "16777216-33554431"
nss_sss is disabled by default
nss_wins is disabled
nss_mdns4_minimal is disabled
DNS preference over NSS or WINS is disabled
pam_unix is always enabled
 shadow passwords are enabled
 password hashing algorithm is sha512
pam_krb5 is disabled
 krb5 realm = "EXAMPLE.COM"
 krb5 realm via dns is disabled
 krb5 kdc = "kerberos.example.com"
 krb5 kdc via dns is disabled
 krb5 admin server = "kerberos.example.com"
pam_ldap is enabled
 LDAP+TLS is enabled
 LDAP server = "ldaps://server.subdomain.mycompany.com"
 LDAP base DN = "dc=mycompany,dc=com"
 LDAP schema = "rfc2307"
pam_pkcs11 is disabled
 use only smartcard for login is disabled
 smartcard module = ""
 smartcard removal action = ""
pam_fprintd is enabled
pam_winbind is disabled
 SMB workgroup = ""
 SMB servers = ""
 SMB security = "user"
 SMB realm = ""
pam_sss is disabled by default
 credential caching in SSSD is enabled
 SSSD use instead of legacy services if possible is enabled
pam_cracklib is enabled (try_first_pass retry=3 type=)
pam_passwdqc is disabled ()
pam_access is disabled ()
pam_mkhomedir or pam_oddjob_mkhomedir is enabled ()
Always authorize local users is enabled ()
Authenticate system accounts against network services is disabled

Comment: Don't you need to connect your NAS to LDAP as well if you want it to see the same ID's than your guests?
Comment: Yanick, thanks for the reply. My NAS unit is actually just another CentOS box running a NFS daemon.  It's configured the same as my other LDAP clients and has the same "nobody" problem.
Answer: An note to add to this for google searchers - we had the same issue where no matter what we did, the nfs mount would not map the user ids correctly.
The issue was idmapd had cached the incorrect ids from the faulty configuration, and no fixing of the configuration would sort it.
The command on centos to fix this was nfsidmap -c (clear cache).
Hopefully this helps some desparate searcher..
Comment: You made my day. Without `nfsidmap -c` any changes made to `/etc/idmapd.conf` wasn't working.
Answer: Solved!
I happened to notice this line in /var/log/messages on my NFS server when I was attempting to mount an export from the remote client:
Feb 28 15:54:02 storage1 rpc.idmapd[1651]: nss_getpwnam: name 'nobody' does not map into domain 'localdomain'

This caused me to look at the first few lines of /etc/idmapd.conf:
[General]
#Verbosity = 0
# The following should be set to the local NFSv4 domain name
# The default is the host's DNS domain name.
#Domain = local.domain.edu

I then added Domain=subdomain.mycompany.com under the commented out "Domain" line. Saved, exited and then ran /etc/init.d/rpcidmapd restart and /etc/init.d/nfs restart.
Comment: This helped me. I will note that I had to make this change on both the server and all the clients.
Answer: Is your NFS server running Centos/RHEL 5 by any chance?
If so, it is exporting NFSv3. NFSv4 is now the default for Centos6 (and recent Ubuntu variants).
The quick fix is to add "vers=3" in the mounting options in /etc/fstab .
e.g.
//10.0.0.1:/home   /home   nfs   defaults,vers=3,rw,noatime   0  0
Comment: Thanks for the suggestion. The LDAP server, client, and NFS server are all running CentOS 6.2. I get a permission denied error on the client when I attempt to mount it with the version 3 option.
Comment: Are you testing this as the root user? Some useful light reading http://www.linuxtopia.org/online_books/rhel6/rhel_6_storage_admin/rhel_6_storage_s2-nfs-security-files.html . Might be worth enabling no_root_squash on the NFS server.
Comment: Solved (see answer below)! Thanks for getting me thinking more about NFS since I was looking mostly at LDAP.
Answer: I found a blog post that might resolve your issue: http://whacked.net/2006/07/26/nfsv4nfs-mapid-nobody-domain/ which I found from the following forum post: https://www.centos.org/modules/newbb/viewtopic.php?topic_id=32977
Comment: I posted this a tad late, but it looks like it was something similar that fixed it for you. Good stuff!
Answer: Everything being mapped to "nobody" sounds like all_squash is turned on.
Take a look at:
http://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-nfs-server-config-exports.html
and verify that the NFS server's /etc/exports file doesn't unintentionally squash the UIDs.  "no_all_squash" is supposed to be default, but you can try explicitly setting it and seeing what happens.
Comment: No luck, unfortunately. But interestingly, `mount storage1:/nas/opt /mnt/test` on the standalone client still gives me the "nobody" problem, yet the same command on the NFS server works without issue. I wish I knew whether this was a NFS or SSSD/NSS problem.
Answer: The fix for me is to make sure the DNS record exists for the local machine. Also helps if the reverse lookup record also exists. As a result, the nobody user and group was replaced by root. How simple is that?!? P.S. remember to reboot the local machine once the DNS records are created.


Where will the Copa Del Rey final 2014 be played?

Question: I cannot locate this information anywhere! I'm, of course, referring to the football (soccer) tournament played in Spain.
Answer: There has been no announcement as to where the final will be played. This will be announced by RFEF (Royal Spanish Football Federation, similar to the English FA) once the finalists are known to ensure the ground is neutral.
Odds on the location of the final can be found here.
Answer: The RFEF (Real Federación Española de Fútbol) officially announced that the Copa del Rey final for 2014 will be played in the Mestalla Stadium, Valencia (home of Valencia FC).
Source:
http://www.insidespanishfootball.com/97777/copa-del-rey-final-to-be-be-played-at-the-mestalla/
Comment: According to the article, it looks like they *un*officially announced the location.  It will be made official on March 4, assuming the participating teams agree to it and the board officially approves it.
Answer: According to recent revision of the Wikipedia article 2014 Copa del Rey Final:

The stadium will be determined on March 4

The reference given there is http://www.marca.com/2014/02/13/futbol/copa_rey/1392248737.html
I do not speak Spanish but using Google Translate I understood that the match will probably be played in Valencia, although the decision will not be official until the next meeting of the Board of the RFEF, scheduled for March 4.
Comment: It is worth mentioning that the Wikipedia article [was created after](http://en.wikipedia.org/w/index.php?title=2014_Copa_del_Rey_Final&action=history) this question was posted.
Comment: I have made the answer CW; if someone who speaks Spanish can add more details based on the above links, feel free to do so.


gcd of 2 polynomials over one Field included in another

Question: I am trying to find the gcd of those 2 polynomials
$x^5-2x^2+1$ and $x^3+3x^2-x-3$
In the book I use, there is a corollary just before this exercice saying that
Corollary :
Let $F$ $\subset$ $E$ be fields, and let $f(x),g(x)$ $\in$ F[$x$] $\subset$ E[x]. Then the gcd of $f$ and $g$ computed in $F[x]$ is the same as the gcd of f and g computed in $E[x]$.
My plan is then to find the gcd of those 2 polynomials in an "easy" fields, i.e $\mathbb{Z}_2[x]$
So, working in $\mathbb{Z}_2[x]$, our 2 polynomials become
$x^5+1$ and $ x^3+x^2-x-1$, is this true to start with ?
When I apply the euclidian algorithm, I find the quotient $q(x) = x^2-x+2$ and the remainder $r(x) = -2x^2+x+3$, i.e in $\mathbb{Z}_2[x]$, $q(x)=x^2-x$ and $r(x)=x+1$.
Applying again the algorithm i.e, euclidian division of $p(x)= x^3+x^2-x-1$ by $r(x)=x+1$, I find $r'(x) = 0$, $q'(x)=x^2-1$.
As the remainder is $0$, then the gdc of the 2 polynomials in $\mathbb{Z}_2[x]$ should be the former remainder, i.e $r(x)=x+1$ but it does not work in $\mathbb{Z}[x]$ !
Take $x=5$, the first polynomial gives 3076, the second one gives 192. The gdc should then be $x+1=5+1=6$ but $6$ does not divide $3076$.
In $\mathbb{Z}_2[x]$, the first polynomial gives $x^5+1=3126$, the second one $ x^3+x^2-x-1=144$
Here, 6 indeed divides those 2 numbers, why does it not work in  $\mathbb{Z}[x]$ ?
Which is not what is expected from the corollary.
Where did I go wrong ?
I tried to factorise the polynomial, they have a $1$ as a common root, so could $x-1$ be their gcd ? It is a common divisor but I do not know how to prove it is the greatest one.
Thanks very much for any help you can provide ! :D
Comment: $\mathbb{Z}$ is not a field, and $\mathbb{Z}/2\mathbb{Z}$ is not even a subring of $\mathbb{Z}$.
Comment: You need to also use that monic polynomials factor the same over $\mathbb{Z}$ and over $\mathbb{Q}$, which will then allow you to use the corollary with for example $\mathbb{Q}$ and $\mathbb{C}$ (assuming you can factor them completely).
Comment: Do polynomial division by that root and see that there are no further common roots over $\mathbb{C}$ (you can easily find the roots of one of them and check that they are not roots of the other).
Comment: Yes, that is a correct argument, since you use the corollary to calculate the gcd over $\mathbb{C}$.
Comment: Could you five me two fields I could use to solve this then ? Thanks for your answer !
Comment: $x-1$ is a common factor of those 2 polynomials, but as explained at the bottom of the post, I do not see how to prove it is the gcd
Comment: $x^5-2x^2+1=(x-1)(x^4+x^3+x^2-x-1)$ and $x^3+3x^2-x-3=(x-1)(x^2+4x+3)$, that's it ? Roots for the second one are -3 and -1, they are not solution for the first one then $x-1$ is the gcd ? Is that the correct argument ? Thanks
Comment: Thanks very much for this ! I'll pay attention to the "fields" I use the next time !
Comment: In order for this question to not appear unanswered, I would suggest you add an answer with your solution.
Answer: We factorize first the 2 given polynomials such that :
$x^5−2x^2+1=(x−1)(x^4+x^3+x^2−x−1)$ and $x^3+3x^2−x−3=(x−1)(x^2+4x+3)$
They have the common root $1$. The others roots of the second polynomials are {-3,-1} but they are not roots of the first one, i.e $x-1$ is the only (then the greatest) common divisor of those 2 polynomials.
Keep in mind we use the corollary given in the original post to justify this argument.
Thanks for your help