How to know when to call base method or override methods in observable collection

Question: i have some questions when watching this tutorial.
i wonder when i overwrite methods, how do i know if i need to call the base method?
public CustomerCollection(IEnumerable<Customer> customers, OMSEntities context) : base(customers)

also why do i need to do
protected override void InsertItem(int index, Customer cust)
{
    this.context.AddToCustomers(cust);
    base.InsertItem(index, cust);
}

protected override void RemoveItem(int index)
{
    this.context.DeleteObject(this[index]);
    base.RemoveItem(index);
}

what does the 2 lines in each method do? and why the need for such similar method. if i overwrite methods for delete and add why not update too?
Answer: You call the base method when you're method is just additional functionality decorating what the base method does, you don't call the base method when you are replacing it's functionality wholesale.
And if you don't know what the base method does, you wouldn't be overriding it, so in knowing what it does and why you're overriding it, you should be able to make this decision in accordance.
Comment: then about the 2nd question? "what does the 2 lines in each method do? and why the need for such similar method. if i overwrite methods for delete and add why not update too?"
Comment: @jiewmeng: Probably because the this.context already has a reference to the object so changes to it will appear to the this.context object, so it doesn't need to be added or removed, and so the base class updating the item is enough. I can't say as though I know what "this.context" refers to precisely.
Comment: context is the "Entity Container Name" of my data model, i dunno whats that too
Answer: For the first part of your question if you do not add a :base(parameter) to the end of a constructor it will actually put a :base() there for you behind the scenes. if there is no base() you will get a compile exception. you need a chain of constructors all the way down to object(). adding that :base(parameter) is just a way of choosing a different constructor other than the default one.
For the second part. It is a good rule of thumb that if you are overriding a method to provide some kind of additional functionality you should call the base method instead too (so you get its functionality), if you are trying to replace the functionality instead of add to it you do not need to call the base(as you are replacing it :) ).
Comment: then about the 2nd question? "what does the 2 lines in each method do? and why the need for such similar method. if i overwrite methods for delete and add why not update too?"
Comment: The first line is is finding the object context in the current class (this could be in your custom class or in the parent if it is a protected or public item) and either calling AddToCustomers and passing cust to it or calling DeleteObject and passing this[index]. Then after that it will call the base version of the function passing the same parameters. So this is basically like copying the first line and editing the base function and pasting it at the top


How to create dynamic partial view in ASP.Net MVC footer section

Question: i am working on one application where i need to display last updated date and time of data from database to layout view footer section so that it will display on all the pages of application
Answer: You have two options

create a Base View Model and make your layout strongly typed for this all your model should be inherited from BaseVM and in every Action you will have to populate the properties of BaseVM along with the model related to the Action method.
Create an Action Filter, which will I recommend.
for details check this
https://www.sharpencode.com/article/MVC/filters-in-asp-net-mvc/actionfilter


Dimension of $\text{Sym}^n(\mathcal{H})$

Question: Let $\{A_i\}$ be a set of $d-$dimensional matrices. $A_1\otimes A_2$ refers to the tensor product or Kronecker product of $A_1$ and $A_2$. We now look at symmetric tensor products i.e. linear combinations of terms like $A_i\otimes A_i\otimes...$
I came across a result (just after (5) in this paper) that claims that the space of any linear combination of these i.e.
$$\left\{B: B=\sum_{i} p_{i} A_{i}^{\otimes n}, \quad p_{i} \in \mathbb{R}, A_{i} \in \mathbb{C}^{d \times d}\right\}$$
has a dimension bounded by $(n+1)^{d-1}$. Naively, I would have expected the dimension of $B$ to be $d^n$. How is this result obtained?
Comment: Yes, you are indeed using terminology incorrectly. To make things as unambiguous as possible: it seems that you are talking about the dimension of the subspace given by $$
\{B:B = \sum_{i}p_i A_i^{\otimes n}, \quad p_i \in \Bbb C, A_i \in \Bbb C^{d \times d}\}.
$$
Is my interpretation correct?
Comment: Perhaps you should explicitly mention that you're interested in $\text{Sym}^n(\mathcal H)$ (for a finite dimensional Hilbert space $\mathcal H$).
Comment: What do you mean by the "dimension" of a matrix?
Comment: @Omnomnomnom apologies if this is wrong terminology but I mean the dimension of the linear space of $B$. I understand that the matrix still has $d^n$ elements. I can edit if this terminology is correct. Thank you.
Comment: @Omnomnomnom yes, thank you for that. I only had real $p_i$ in mind but I will now edit to correct the terminology.
Comment: @Omnomnomnom thank you for your comments and improving my question.
Answer: It is well known that for a $d^2$-dimensional space $V$, the dimension of $\operatorname{Sym}^n(V)$ is given by
$$
\binom{n + d^2 - 1}{d^2-1} = \frac1{(d^2 - 1)!} \cdot (n + d^2 - 1)(n+d^2 -2) \cdots (n+1)\\
= \frac{n+d^2-1}{d^2 - 1} \cdot \frac{n+d^2 - 2}{d^2 - 2} \cdots \frac{n+1}{1} \\
\leq (n+1)\cdot (n+1) \cdots (n+1) = (n+1)^{d^2 - 1}.
$$
This is the bound used in the paper.


Convergence of weak solution for second order parabolic equation (Evans)

Question: I am trying to understand how weak convergence works in the theorem of existence of weak solution from Evans (Theorem 3, chapter 7.1), in particular how pass from (30) to (31). Here the theorem with proof
Does (31) follows from (30)? Is it necessary, passing from (30), to have (31) or can I have (31) only with weak convergence of sequence?
Answer: (31) does follow from (30). If the two sides of (31) are different on a positive measure set of times, then possibly restricting to a smaller set you can assume without loss of generality that $$ \langle \mathbf{u}',v\rangle + B[\mathbf{u},v;t] > \langle\mathbf{f},v\rangle$$ on a positive measure set of times. Then you should be able to cook up a test function $v$ (which depends on both space, and more crucially, time) to force the same inequality in (30), leading to contradiction. Something like the Lebesgue differentiation theorem should get you started.
(30), or some analogue, is required to conclude a pointwise a.e. equality like (31). It is well known that weak convergence implies nothing whatsoever about pointwise convergence: there are weakly convergent sequences that do not converge pointwise anywhere, e.g. the typewriter sequence. This is typical in PDE: if you want to generate a solution with nice properties by using a sequence that converges weakly to it, it is typical that at some point the weak convergence needs to be upgraded to some stronger notion of convergence by using the properties of the PDE.


linear model estimator proof

Question: For a linear model, the noncentered form is
$Y_i=\beta_0+\beta_1x_{i1}+...+\beta_kx_{ik}+\epsilon_i$ ---(a)
the centered form is
$Y_i=\alpha+\beta_1(x_{i1}-\bar{x}_1)+...+\beta_k(x_{ik}-\bar{x}_k)+\epsilon_i$ ---(b)
And we know that the matrix form of the centered form is
$Y=[j_n,X_c] (\alpha,\beta^*)'+\epsilon$ where $X_c=(I-\frac{1}{n}J_n)X$, $X=[X_1,...,X_k]$.
We could show that the estimators for $\alpha$ and $\beta^*$ are $\hat{\alpha}=\bar{Y}$ and $\hat{\beta}^*=(X_c'X_c)^{-1}X_c'Y$
My question is:
How to show $\hat{\beta}^*$ is the same as the last three elements of $\hat{\beta}=(X_a'X_a)^{-1}X_a'Y$, where $X_a=[j_n,X]$. What is the relationship between $\hat{\alpha}$ and the first element of $\hat{\beta}$?
Comment: What you ask to show isn't true.  You seem to assume there are just three explanatory variables.  Because this question concerns the relationship between the uncentered and centered formulas, perhaps you will find https://stats.stackexchange.com/a/108862/919 helpful: it shows how centering amounts to one row-reduction pass ("Gaussian elimination") in solving the original (uncentered) equations.
Comment: That's how the question was asked....But if you assume there are only three explanatory variables, how would you prove it?
Answer: The key to answering the question is to use the inverse of a 2x2 block matrix.  The following formula is useful.  Suppose $\boldsymbol{A}$ and $\boldsymbol{D}$ are invertible, then
\begin{eqnarray*}
\begin{pmatrix}
\boldsymbol{A} & \boldsymbol{B} \\
\boldsymbol{C} & \boldsymbol{D}
\end{pmatrix}^{-1} &=& \begin{pmatrix}
\left(\boldsymbol{A}-\boldsymbol{B}\boldsymbol{D}^{-1}\boldsymbol{C}\right)^{-1} & 0 \\
0 & \left(\boldsymbol{D}-\boldsymbol{C}\boldsymbol{A}^{-1}\boldsymbol{B}\right)^{-1}
\end{pmatrix} \begin{pmatrix}
\boldsymbol{I} & -\boldsymbol{B}\boldsymbol{D}^{-1} \\
-\boldsymbol{C}\boldsymbol{A}^{-1} & \boldsymbol{I}
\end{pmatrix}.
\end{eqnarray*}
Consider the partition $\boldsymbol{X}_a = \left[\boldsymbol{j}_n, \boldsymbol{X}\right]$.  Likewise, we shall partition the regression parameters into an intercept term and slope terms
\begin{eqnarray*}
\boldsymbol{\beta} = \begin{pmatrix}
\beta_0 \\
\boldsymbol{\beta}^{\ast}
\end{pmatrix}.
\end{eqnarray*}
Clearly, $\widehat{\boldsymbol{\beta}} = \left(\boldsymbol{X}_a^{\prime} \boldsymbol{X}_a\right)^{-1}\boldsymbol{X}_a^{\prime} \boldsymbol{y}$.  Therefore,
\begin{eqnarray*}
\begin{pmatrix}
\widehat{\beta}_0 \\
\widehat{\boldsymbol{\beta}}^{\ast}
\end{pmatrix} &=& \begin{pmatrix}
n & \boldsymbol{j}_n^{\prime} \boldsymbol{X} \\
\boldsymbol{X}^{\prime} \boldsymbol{j}_n & \boldsymbol{X}^{\prime}\boldsymbol{X}
\end{pmatrix}^{-1} \begin{pmatrix}
\boldsymbol{j}_n^{\prime} \boldsymbol{y} \\
\boldsymbol{X}^{\prime}\boldsymbol{y}
\end{pmatrix} \\
&=& \begin{pmatrix}
\left(n -\boldsymbol{j}_n^{\prime} \boldsymbol{X} \left(\boldsymbol{X}^{\prime} \boldsymbol{X}\right)^{-1}\boldsymbol{X}^{\prime} \boldsymbol{j}_n\right)^{-1} & 0 \\
0 & \left(\boldsymbol{X}^{\prime} \left[\boldsymbol{I}_n - \frac{\boldsymbol{J}_n}{n}\right]\boldsymbol{X}\right)^{-1}
\end{pmatrix} \begin{pmatrix}
\boldsymbol{j}_n^{\prime}\left[\boldsymbol{I}_n - \boldsymbol{X} \left(\boldsymbol{X}^{\prime} \boldsymbol{X}\right)^{-1}\boldsymbol{X}^{\prime}\right]\boldsymbol{y} \\
\boldsymbol{X}^{\prime}\left[\boldsymbol{I}_n - \frac{\boldsymbol{J}_n}{n}\right]\boldsymbol{y}
\end{pmatrix}
\end{eqnarray*}
Comment: Thanks for the answer! But I have one more follow-up question. The first element I got is $\frac{j_n'(I-X(X'X)^{-1}X')Y}{j_n'(I-X(X'X)^{-1}X')j_n}$. What's the relationship with $\hat{\alpha}=\bar{Y}$? I tried to simplify $\frac{j_n'(I-X(X'X)^{-1}X')Y}{j_n'(I-X(X'X)^{-1}X')j_n}$ but the denominator turns 0 (I assume $Mj_n=j_n$?)
Comment: Clearly $\widehat{\beta}_0 = \widehat{\alpha} - \frac{j_n^{\prime}}{n} \boldsymbol{X} \widehat{\boldsymbol{\beta}}^{\ast}$.  Next, use the Sherman-Morrison formula to reduce the term $\left(\boldsymbol{X}^{\prime} \left[\boldsymbol{I}_n - \frac{\boldsymbol{J}_n}{n} \right] \boldsymbol{X}\right)^{-1}$ and it should simply to the formula you are working with.  Just work in the other direction.  https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula
Comment: How did you get $\hat{\beta}_0=\hat{\alpha}-\frac{j_n'}{n}X\hat{\beta}^*$ so qucikly?
Comment: I might need more details.....
Comment: Compare the model in centered form and uncentered form.  In the uncentered form, we have the intercept term $\beta_0$, not depending on changing covariates, whereas in the centered form we must collect all terms $\alpha - \frac{\boldsymbol{j}_n^{\prime}}{n} \boldsymbol{X} \boldsymbol{\beta}^{\ast}$ to obtain the total intercept term.  You can reparametrize these into the single term $\beta_0$.
Comment: I got it. Thank you so much

linear model estimator proof


Using a HashMap and reflection to call methods with variable argument types

Question: So, I have the following scenario:

I have a class named AIInstruction, which is not actually meant to be instantiated by itself, but trough a child class.
I have a bunch of classes called AIInstruction_*** which extend AIInstruction. Every single one of these classes has a single constructor, but differ in the type and amount of parameters they need.
And I have a manager class which looks something like this:
public class AIControls
{
    public static HashMap<String, Class<? extends AIInstruction>> INSTRUCTION_DICTIONARY = new HashMap<String, Class<? extends AIInstruction>>();
    static {
        INSTRUCTION_DICTIONARY.put("rotateTowards", AIInstruction_rotateTowards.class);
        INSTRUCTION_DICTIONARY.put("moveToPoint", AIInstruction_moveToPoint.class);
        // (etc...)
    }

    LinkedList<AIInstruction> _instruction_queue;

    public AIControls()
    {
        _instruction_queue = new LinkedList<AIInstruction>();
    }

    public void addInstruction(String instruction, Object... params)
    {
        /*
        ???
        */
    }
}

What I want to do inside addInstruction, is creating an instance of the class whose key inside the INSTRUCTION_DICTIONARY is instruction, and add this new instance to the _instruction_queue LinkedList.
The params varargs are meant to be the parameters that the constructor method of the class reffered to by instruction needs.
From what I researched, I found that reflection is pretty much the way to go. I have never used reflection before, so I guess I might be missing a thing or two. This is how far I have managed to go:
public void addInstruction(String instruction, Object... params)
{
    Class<?> the_class = INSTRUCTION_DICTIONARY.get(instruction);
    Constructor<?> the_constructor = the_class.getConstructor(/* ??? */);
    AIInstruction new_instruction = the_constructor.newInstance(params);

    _instruction_queue.add(new_instruction);
}

However, that code has basically two problems:

I'm not sure what to put in place of the /* ??? */. I guess I should be putting the types of the parameters, but they could be anything, since every AIInstruction subclass has very different constructors (in types and amount of parameters).
I'm not sure either if the newInstance call will work, because the params array contains instances of type Object.

Any help is greatly appreciated, thank you!
Answer: You can use Class.getConstructors() to get an array of all constructors in the class. Assuming you only have one constructor, you can simply check for size to prevent OOB Exceptions, and save [0] as your Constructor.
It doesn't look like you need to know what type of parameters that constructor takes, but if you do you can always use Constructor.getParameterTypes(). This could also be used to identify between, as stated before, multiple constructors if that were to be the case.


Aplicar maskMoney em campos adicionados dinamicamente

Question: Tenho um formulário onde eu adiciono valor, data, detalhes_transacao, porém, estes campos são adicionados dinamicamente através de um javascript.
O problema é que a máscara de valor (maskMoney) funciona somente no primeiro campo, que está visível na tela... quando os campos são adicionados dinamicamente, não funciona.
HTML

            Amount
            <input type="text" class="form-control border-input money" id="debit[0][amount]" name="debit[0][amount]" placeholder="Amount" value="">

            Date
            <input type="date" class="form-control border-input" id="debit[0][ddate]" name="debit[0][ddate]" placeholder="Date">

            Details
            <input type="text" class="form-control border-input" id="debit[0][details]" name="debit[0][details]" placeholder="Details of Transaction">

Javascript
// Transactions Debit
$(document).ready(function() {
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $("#debit-after"); //Fields wrapper
    var add_button      = $(".debit-transaction-edit"); //Add button ID
    var total_debit    = $("#debit_total_rows").val();

    var x = total_debit; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();

        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('

<input type="text" class="form-control border-input money" placeholder="Amount" value="" id="debit['+ x +'][amount]" name="debit['+ x +'][amount]">

<input type="date" class="form-control border-input" placeholder="Date" id="debit['+ x +'][ddate]" name="debit['+ x +'][ddate]">

<input type="text" class="form-control border-input" id="debit['+ x +'][details]" name="debit['+ x +'][details]" placeholder="Details of Transaction">

'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field_debit_edit", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent().parent().remove(); x--;
    })
});

Class que eu aplico para valores: money
$(document).ready(function(){
    $('.money').maskMoney();
});

Resultado em Tela
Comment: Não entendi porque me negativaram, podem explicar?
Answer:
O problema é que, quando você adiciona somente
  $('.money').maskMoney();, no início, ele só funciona para os elementos que são carregados na atualização da página. Então, para resolver esse problema, você deve, em todas as vezes que adicionar um novo elemento que contenha uma máscara, a
  função do plugin, que é o $('.money').maskMoney();.

Eu fiz umas edições no seu código para ficar mais fácil, entretanto, não tira a essência do problema que você estava enfrentando.

O problema está resolvido.

// Transactions Debit
$(document).ready(function() {
$('.money').maskMoney();
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $("#debit-after"); //Fields wrapper
    var add_button      = $(".debit-transaction-edit"); //Add button ID
    var total_debit    = $("#debit_total_rows").val();

    var x = total_debit; //initlal text box count

    add_button.click(function(e){ //on add input button click

        e.preventDefault();
   ++x;
            $(wrapper).append('

<input type="text" class="form-control border-input money" placeholder="Amount" value="" id="debit['+ x +'][amount]" name="debit['+ x +'][amount]">

<input type="date" class="form-control border-input" placeholder="Date" id="debit['+ x +'][ddate]" name="debit['+ x +'][ddate]">

<input type="text" class="form-control border-input" id="debit['+ x +'][details]" name="debit['+ x +'][details]" placeholder="Details of Transaction">

'); //add input box

            document.getElementById("debit["+ x +"][amount]").focus();

            $('.money').maskMoney();

    });

    $(wrapper).on("click",".remove_field_debit_edit", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent().parent().remove(); x--;
    })
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />

            Amount
            <input type="text" class="form-control border-input money" id="debit[0][amount]" name="debit[0][amount]" placeholder="Amount" value="">

            Date
            <input type="date" class="form-control border-input" id="debit[0][ddate]" name="debit[0][ddate]" placeholder="Date">

            Details
            <input type="text" class="form-control border-input" id="debit[0][details]" name="debit[0][details]" placeholder="Details of Transaction">

<button class="debit-transaction-edit">Add</button>

Adicione o código: $('.money').maskMoney(); todas as vezes que
  você adicionar um novo campo.

 if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('

<input type="text" class="form-control border-input money" placeholder="Amount" value="" id="debit['+ x +'][amount]" name="debit['+ x +'][amount]">

<input type="date" class="form-control border-input" placeholder="Date" id="debit['+ x +'][ddate]" name="debit['+ x +'][ddate]">

<input type="text" class="form-control border-input" id="debit['+ x +'][details]" name="debit['+ x +'][details]" placeholder="Details of Transaction">

'); //add input box

         //Adicione este fragmento de código:
         $('.money').maskMoney();

        }

Comment: Funcionou como deveria, muito obrigado.
Comment: Só para teste, ao clicar nele, são adicionados os campos que você deseja.


recovering vm data from crashed XenServer install

Question: We're using xenserver 5.6 from citrix to run our virtual machines. The box is old and creaky, and the hard drive went. (We had a super limited budget of $0 at the time). Turns out the only machine on there we actually needed, was the only one not backed up...
anyway, we've replace the hard drive, and reinstalled xensever. however while trying to find our old vm disk images, i have no idea where they sit, and i'm beginning to think they're on a lvm partition?
is there anyway to access the disk images from the old vm's on this hard disk, which is attached to the xenserver machine via a usb->sata converter?
Answer: Is the disk containing the disk images intact ?
If you are able to see the disk Storage repository in xenserver. You should be able to reattach the SR by using:
<code>xe sr-introduce
</code>
You should not by any means use the sr-create command since this will delete the old data.
Some more information would be helpful about your setup.


Aparecer resultado na mesma página com php

Question: Estou basicamente iniciando os estudos com PHP e o que estou tentando fazer é simples. Gostaria de exibir o resultado de um cálculo numa mesma página.
Segue a estrutura do meu projeto:

Meus códigos:
index.php:
<?php include "header.php"; ?>

<?php include "footer.php"; ?>

header.php:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

<form action="calc.php" method="POST">
    <input type="text" name="num1">
    <input type="text" name="num2">
    <select name="cal" id="">
        <option value="add">Add</option>
        <option value="sub">Subtract</option>
        <option value="mul">Multiply</option>
    </select>
    <button type="submit">Calculate</button>
</form>

calc.php:
<?php

 include 'includes/calc.inc.php';

$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$cal = $_POST['cal'];

$calculator = new Calc($num1, $num2, $cal);
echo $calculator->setCalc(); //gostaria de mostrar na mesma página

calc.inc.php:
<?php

class Calc{
    public $num1;
    public $num2;
    public $cal;

    public function __construct($num1, $num2, $cal){
        $this->num1 = $num1;
        $this->num2 = $num2;
        $this->cal = $cal;
    }

    public function setCalc(){
        switch($this->cal){
            case 'add':
                $result = $this->num1 + $this->num2;
                break;
            case 'sub':
                $result = $this->num1 - $this->num2;
                break;
            case 'mul':
                $result = $this->num1 * $this->num2;
                break;
            default:
                $result = "Error";
                break;
        }
        return $result;
    }
}

Recupero os valores na index.php com o arquivo calc.php. E no arquivo calc.php eu passo os valores para o calc.inc.php para que neste os cálculos sejam realizados e seja retornado o valor final para o calc.php. O problema é que no method é redirecionado para a página calc.php e o resultado é exibido nesta outra página, sendo que eu gostaria que aparecesse na mesma página da index.php.
Tentei fazer algo com Header("Location: index.php") mas isto faz com que a página atualize, então, não resolveu.
É possível fazer o que quero? Aceito diferentes tipos de soluções!
Comment: Você pode verificar se foi disparado o `POST`, caso seja `POST` é só exibir o resultado.
Answer: No seu index adicione o calc.php
<?php include "header.php"; ?>
<?php include "calc.php"; ?>
<?php include "footer.php"; ?>

No calc.php verifique se foi enviado algum post.
<?php
if (isset($_POST)) {
  include 'includes/calc.inc.php';

  $num1 = $_POST['num1'];
  $num2 = $_POST['num2'];
  $cal = $_POST['cal'];

  $calculator = new Calc($num1, $num2, $cal);
  echo $calculator->setCalc();
}
?>

E não esqueça de trocar a action para index.php
<form action="index.php" method="POST">

Comment: claro que está bem simples, foi mais para te passar a lógica.
Comment: Deu certo a sua proposta! Contudo, apareceu mensagens de erro na página index.php:

Notice: Undefined index: num1 in C:\xampp\htdocs\...\calc.php on line 6

Notice: Undefined index: num2 in C:\xampp\htdocs\...\calc.php on line 7

Notice: Undefined index: cal in C:\xampp\htdocs\...\calc.php on line 8
Error

Consegue me ajudar nisso?
Comment: Ajustei! no if(isset($_POST)){} faltou colocar o nome do que eu gostaria de verificar! E também estava faltando o nome do botão! Então no header.php no Calculate foi adicionado a propriedade name="submit"... Resultado final: Calculate e no if: if (isset($_POST['submit'])) {} e o resultado final deu certo!
Comment: Boa! É isso aí. Com o tempo você vai pegando a prática e fica automático testar com isset se o campo que vai ser usado existe. Acabei não colocando eles pq foquei no conceito apenas. Flw.
Answer: calc.php
include 'includes/calc.inc.php';

$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$cal = $_POST['cal'];

$calculator = new Calc($num1, $num2, $cal);
$result = $calculator->setCalc(); //gostaria de mostrar na mesma página

header("Location: index.php?cal=$result");

header.php
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

<form action="calc.php" method="POST">
    <input type="text" name="num1">
    <input type="text" name="num2">
    <select name="cal" id="">
        <option value="add">Add</option>
        <option value="sub">Subtract</option>
        <option value="mul">Multiply</option>
    </select>
    <button type="submit">Calculate</button>
</form>

<?php
  if (isset($_GET["cal"])){
      echo $_GET["cal"];
  }
?>

Na calc.php foi usado a sintaxe de cabeçalho "Location" passando como valor do parâmetro o resultado do calculo

header("Location: index.php?cal=$result");

Na header.php recuperamos esse valor para aparecer na index.php

<?php
  if (isset($_GET["cal"])){
      echo $_GET["cal"];
  }
?>

Na verdade, o trecho de código imediatamente acima, não precisa ser incluído na Na header.php, pode ser incluído na index.php ou na footer.php, dando assim oportunidade de se colocar o resultado no local exato onde quer que ele apareça dentro da página.
Comment: Testei aqui e deu certo da sua maneira! Dei um +1 para sua resposta porque ela foi útil sim, mas a resposta do Cleytinho foi o que mais correspondeu, por isso selecionei ela como correta! Mas grato mesmo assim... É uma alternativa para solucionar o mesmo problema.


how to tell python 3 to skip over non-digit characters from a csv file

Question: I'm using python 3.4.3
I am very new to python and stack overflow, I'm trying to calculate averages from csv columns, some boxes contain question marks and wont let me convert them to float (obv) does anyone know how I can tell python to skip over the question marks or just remove them? Any feedback would be much help thanks.
average0 = 0
average1 = 0
average2 = 0
def average(rowNum, averageNum):
    with open('positive.csv', newline='') as f:
        reader = csv.reader(f)
        the_numbers = [float(row[rowNum]) for row in reader]
        averageNum = sum(the_numbers) / len(the_numbers)
        averageWith.insert(rowNum, averageNum)
def main():
    average(0, average0)
    average(1, average1)
    average(2, average2)
main()

Comment: `the_numbers = [float(row[rowNum]) for row in reader if isinstance(row[rowNum], (int, float))]` is the best way to do it
Answer: if the strange characters are known (i.e only '?') perhaps something like this?
    the_numbers = [float(row[rowNum]) for row in reader if row[rowNum] not in "?"]
    #replace "?" with a string of any strange characters

BTW, that code has something weird somewhere else: averageNum is an inmutable object: passing it as an argument and modifying its value inside the function won't change it outside of it. If that's what you wanted i suggest you to make your average() function return said average.
Comment: Thanks allot that works perfect. I agree I just couldn't think of a clean way to return the averages within average()
Answer: You could try something like this
the_numbers = []
for row in reader:
  try:
    the_numbers.append(float(row[rowNum]))
  except:
    pass


How to play measures 5 through 7 of Mozart's Turkish March

Question: How do you play this highlighted part from Turkish March on the keyboard?

Press GAB together?
Or 1 after the other with GA quickly? It sounded weird after the first bar that way.
Do I press E that is highlighted (bass clef) beginning from the main note (B) or do I press it when beginning to play G in the "superscript" note? (When googling I figured out these are called Grace notes but I am still a bit unsure how to do it in this piece).
Comment: With so much now available to watch and listen to on you tube in particular, it's always worth spending a little time finding any piece in question, and checking out how others play it. So much instant gratification!
Answer: The G and A are grace notes. In this piece they should be played separately and quickly, before the beat, leading to the B, which occurs on the beat.
The left-hand E should occur on the beat at the same time as the right-hand B.
The passage can be heard played in this way in the below Lang Lang recording. Notice that he plays them so quickly that they sound nearly simultaneous.

Daniel Barenboim plays it similarly.

As does Maria João Pires.
Comment: Good on you for the example videos of famous performances of the piece, that's usually a good quick sanity check on interpretation questions like this one.


Prove that $d_X$ is a metric on $X$, where $X$ is the set of all closed subsets of the unit disk in $\mathbb{R}^2$.

Question: Consider the closed unit disk $$D = \big\{(x, y) \in\mathbb{R}^2\,\big| x^2+y^2\leq 1\big\} \subseteq \mathbb{R}^2$$ with
the metric $d$ induced from the Euclidean metric on $\mathbb{R}^2$, and let $X$ be the set of all closed
subsets of $D$. For $A\in X$ and $x \in D$, define
$$\text{dist}(x, A) := \min_{a\in A}\,
d(x, a)\,.$$
For $A, B \in X$, define
$$d_X(A, B) := \max
\left\{\max_{a\in A}\,\text{dist}(a, B),\max_{b\in B}
\text{dist}(b, A)\right\}\,.$$
Show that $d_X$ defines a metric on $X$.
How can I prove that $d_X$ satisfies the triangle inequality?
Answer: Hint.  For simplicity, I shall write $\delta$ for $\text{dist}$.  Note that, for $A,B,C\in X$, we have
$$\begin{align}d_X(A,B)&+d_X(B,C)\\&\geq \max\left\{{\small\max_{a\in A}\,\delta(a,B)+\max_{b\in B}\,\delta(b,C)}\,,\,\,{\small\max_{b\in B}\,\delta(A,b)+\max_{c\in C}\,\delta(B,c)}\right\}\,.\end{align}$$
Next, verify that
$$\max_{a\in A}\,\delta(a,B)+\max_{b\in B}\,\delta(b,C)\geq \max_{a\in A}\,\delta(a,C)$$
and that
$$\max_{b\in B}\,\delta(A,b)+\max_{c\in C}\,\delta(B,c)\geq \max_{c\in C}\,\delta(A,c)\,.$$
One probably important remark is that every set in $X$ is a compact subset of $\mathbb{R}^2$.


laravel: global middleware stack for bypassing ngrok browser warning doesn't work

Question: created this middleware and attached it to global middleware stack but doesn't work. still getting the browser warning on browser.
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class NgrokMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('ngrok-skip-browser-warning', '1231');

        return $next($request);
    }
}

anyone knows what happens here?
Comment: Why not use some other service like https://pinggy.io or Cloudflare Tunnel ? It seems you are editing request headers. You need to edit response header instead.
Answer: The headers need to go in the response rather than the request. In practice, the response is what comes out of the $next function.
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class NgrokMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->header('ngrok-skip-browser-warning', '1231');
        return $response;
    }
}

Comment: this doesn't work. I tried this


integral of $\int_0^\infty \frac{ x^3 \cos(x)}{x^6 + 1} \mathrm{d}x $

Question: How does someone solve
$$\int_0^\infty \frac{ x^3  \cos(x)}{x^6 + 1} \mathrm{d}x $$
Is this analytically possible? I have no idea and I think if it is, it must be probably be solved via the Fourier/residue theorem or something like that.
Comment: It can be written in terms of cosine-integral function and sine-integral function. The reason is rather simple: we can compute $$\int_{0}^{\infty} \frac{\cos x}{x - z} \, dx$$ for $z \in \mathbb{C} \setminus [0,\infty)$ in terms of those special functions, and your integral can be written as a linear combination of integrals of this form. I strongly suspect that it cannot be reduced to a simpler closed form. On the other hand, if $0 \leq m < n$ are even integers then $$\int_{0}^{\infty} \frac{x^m \cos x}{x^n + 1} \, dx $$ can be written in elementary form by residue computation.
Comment: It's definitely possible, according to wolframalpha the answer is 0.118802...I'm not sure how to evaluate it though by hand
Comment: @SangchulLee Thank you very much, I will try!
Answer: As Sangchul Lee commented, we could use partial fractions to get
$$\frac{ x^3  \cos(x)}{x^6 + 1}=\sum_{i=1}^6 a_i \frac{\cos(x)}{x-b_i}$$ and then use $$\int_0^\infty \frac{\cos(x)}{x-c}\,dx=-\text{Ci}(-c) \cos (c)-\text{Si}(c) \sin (c)-\frac{1}{2} \pi  \sin (c)$$ (provided that $\Im(c)\neq 0\lor \Re(c)\leq 0$). This would be quite tedious but doable.
To my surprise, a CAS gave
$$\int_0^\infty \frac{ x^3  \cos(x)}{x^6 + 1} \,dx=\frac{1}{2} \sqrt{\frac{\pi }{3}} G_{1,7}^{4,1}\left(\frac{1}{46656}|
\begin{array}{c}
 \frac{1}{3} \\
 0,\frac{1}{3},\frac{1}{3},\frac{2}{3},\frac{1}{6},\frac{1}{2},\frac{5}{6}
\end{array}
\right)$$ where appears the Meijer G function (see here and here).
Its numerical value is $0.118802427933651$.
Comment: Thank you very much! What is CAS? (Computer arithmetic/algebraic Simulation?)
Comment: @WaldoRozir.**Computer Algebra System**. Have a look at  https://en.wikipedia.org/wiki/Computer_algebra_system
Answer: It may be solved by calculus of residue, i.e. considering a suitable line integral over a simple closed curve on $\mathbb{C}$. For example, the famous Dirichlet (improper ) integral $\int_0^\infty \frac{\sin(x)}{x}\,dx$ is computed by this trick.
Comment: Not an answer until you show *which* curve does the job.
Comment: And $\int_{0}^{+\infty}\frac{\sin x}{x}\,dx$ has a nice closed form, but the same does not apply to $\int_{0}^{+\infty}\frac{\cos x}{x+1}\,dx$, for instance. By partial fraction decomposition the integral considered by the OP depends on values of $\text{Si}$ and $\text{Ci}$.
Comment: Unfortunately, the integrand is an odd function. If $x^3$ is changed to $x^4$, then we can consider integration from $(-R,0)$ to $(R,0)$ along the $x$-axis, then along the upper semi-circle with radius $R$ and center $O$ and let then let $R\rightarrow\infty$.


How to make use of angle sum and difference identities to find the value of sine and cosine?

Question:
Calculate: $\cos\left({5\pi\over12}\right)$ and $\cos\left({\pi\over12}\right)$

What is the easiest way to find $\cos\left({5\pi\over12}\right)$ and $\cos\left({\pi\over12}\right)$ (without a calculator)? If I know that $\frac{5\pi }{12}=\frac{\pi }{4}+\frac{\pi }{6}$ and $\frac{\pi }{12}=\frac{\pi }{3}-\frac{\pi }{4}$, then I can apply angle sum and difference identities. But how do I know $\frac{5\pi }{12}= \frac{\pi }{4}+\frac{\pi }{6}$ and $\frac{\pi }{12}= \frac{\pi }{3}-\frac{\pi }{4}$ in the first place. I know $ \frac{\pi }{4}+\frac{\pi }{6} = \frac{5\pi }{12}$ and $ \frac{\pi }{3}-\frac{\pi }{4}=\frac{\pi }{12}$ but I can't go the other way round.
I gave $\frac{5\pi}{12}$ and $\frac{\pi}{12}$ as an example, I want the general solution for any value in pi rational form $\frac{\pi p}{q}$.
Comment: My approach to such problems is to consider known values as building blocks, and then use trial and error to express the unknown values in terms of the known values.  For example, the trig functions of the following special angles are generally known: $\{0, \pi/6, \pi/4, \pi/3, \pi/2\}.$  Also, I know of three separate derivations (Geometry, Real Analysis, Complex Analysis) for $(\pi/10)$, so that gets added to the list.  Also, [half-angle formulas](https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Half-angle_formulae) gives you $(\pi/12)$. ...see next comment
Comment: Further, [angle-sum formulas](https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Angle_sum_and_difference_identities) then gives you (for example) $(5\pi/12).$  Therefore, the general procedure is to consider known values/formulas as building blocks, and try to attack the unknown values with your building blocks.
Comment: @user2661923 I am not able find the value of $(\pi/10)$ using the identities. Can you please share the derivations you know? Also, you should convert your comments to an answer. Thank you!
Comment: I am not allowed to *answer* your question, because you haven't really *shown* work, in accordance with [this article](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) and my interactions with the mathSE *answer police* are distasteful to me.  Using trig identities, you should be able to derive $\sin(5x) = 16\sin^5(x) - 20\sin^3(x) + 5\sin(x).$  Lettting $y = \sin(2\pi/5) = \cos(\pi/10)$, noting that (therefore) $y > 0$ and also noting that $y$ must be a root of $[y(16y^4 - 20y^2 + 5)] = 0,~$ you have a routinely solvable quadratic equation in $(y^2)$.
Answer: 1 equation and 2 unknows is, generally, an overdetermined system.
In this case, pick any solution for $\dfrac{5\pi}{12} = \dfrac{p_1\pi}{q_1} + \dfrac{p_2\pi}{q_2}$, and sum $\pm \dfrac{p_3\pi}{q_3}$ in a smart way
$$\dfrac{5\pi}{12} = \left( \dfrac{p_1\pi}{q_1} +  \dfrac{p_3\pi}{q_3} \right) + \left( \dfrac{p_2\pi}{q_2} -  \dfrac{p_3\pi}{q_3} \right)$$
$$\dfrac{5\pi}{12} = \dfrac{\pi}{6} + \dfrac{\pi}{4} = \dfrac{\pi}{3} + \dfrac{\pi}{12} = \dfrac{3\pi}{10} + \dfrac{7\pi}{60} = \dots $$
Answer: We want to find the values of $\displaystyle\cos\frac{5\pi}{12}$ and $\displaystyle\cos\frac{\pi}{12}$.
Recall the sum to product formulae below:
$$\begin{align}\cos A+\cos B&=2\cos\frac{A+B}{2}\cos\frac{A-B}{2}\\
\cos A-\cos B&=-2\sin\frac{A+B}{2}\sin\frac{A-B}{2}\\\end{align}.$$
In our case, let $A=5\pi/12$ and $B=\pi/12$. Then we find that
$$\begin{align}\cos\frac{5\pi}{12}+\cos\frac{\pi}{12}&=2\cos\frac{\frac{5\pi}{12}+\frac{\pi}{12}}{2}\cos\frac{\frac{5\pi}{12}-\frac{\pi}{12}}{2}=2\cos\frac{\pi}{4}\cos\frac{\pi}{6}\\
&=\frac{\sqrt6}{2}\tag{1}\\
\cos\frac{5\pi}{12}-\cos\frac{\pi}{12}&=-2\sin\frac{\frac{5\pi}{12}+\frac{\pi}{12}}{2}\sin\frac{\frac{5\pi}{12}-\frac{\pi}{12}}{2}=-2\sin\frac{\pi}{4}\sin\frac{\pi}{6}\\
&=-\frac{\sqrt2}{2}\tag{2}.\end{align}$$
Adding equations $(1)$ and $(2)$ together and dividing by $2$, we find that
$$\cos\frac{5\pi}{12}=\frac{\sqrt6-\sqrt2}{4}$$
and subtracting equation $(2)$ from equation $(1)$ and dividing by $2$ gives
$$\cos\frac{\pi}{12}=\frac{\sqrt6+\sqrt2}{4}.$$

However, this method is not always guaranteed to work, for the simple reason that $\cos x\pi$ does not always have a closed form for  rational $x$.

I hope that helps. If you have any questions please don't hesitate to ask :)
Answer: We know that
$$\begin{align}
\cos{\pi\over 4}&=\sin{\pi\over 4}={\sqrt{2}\over 2}\\
\cos{\pi\over 6}&=\sin{\pi\over 3}={\sqrt{3}\over 2}\\
\cos{\pi\over 3}&=\sin{\pi\over 6}={1\over 2}\\
\cos(x+y)&=\cos{x}\cos{y}-\sin{x}\sin{y}\\
\cos(x-y)&=\cos{x}\cos{y}+\sin{x}\sin{y}\\
\sin(x+y)&=\sin{x}\cos{y}+\cos{x}\sin{y}\\
\cos(x-y)&=\sin{x}\cos{y}-\cos{x}\sin{y}\\
\end{align}$$
With the above you should be done.
Answer: After practicing a lot of problems in trigonometry, I realized that I need to know the values of sine and cosine only at $\{ \pi/6, \pi/4, \pi/3\}$, and the double angle, half angle and sum and difference identities. @marwalix et al. answered the same.
By applying the double angle formula (i.e. $\sin \left( 2\theta \right) =2\sin \theta \cos \theta$), I found the value of $\{\pi/5, 2\pi/5\}$:
$$\dfrac{\pi }{5}=2\cdot \dfrac{\pi }{10}$$
$$\dfrac{2\pi }{5}=2\cdot \dfrac{\pi }{5}$$
By applying the half angle formula (i.e. $\sin \dfrac{\theta }{2}=\sqrt{\dfrac{1-\cos \theta }{2}}$, $\cos \dfrac{\theta }{2}=\sqrt{\dfrac{1+\cos \theta }{2}}$), I found the value of $\{ \pi/12, \pi/8\}$:
$$\dfrac{\pi }{12}=\dfrac{1}{2}\cdot \dfrac{\pi }{6}$$
$$\dfrac{\pi }{8}=\dfrac{1}{2}\cdot \dfrac{\pi }{4}$$
And finally, by applying $\sin(\alpha \pm \beta) = \sin \alpha \cos \beta \pm \cos \alpha \sin \beta$, and $\cos(\alpha \pm \beta) = \cos \alpha \cos \beta \mp \sin \alpha \sin \beta$, I found the value of $\{ \pi/12, 3\pi/10, 3\pi/8, 5\pi/12\}$:
$$\dfrac{\pi }{12}=\dfrac{\pi }{3}-\dfrac{\pi }{4}=\dfrac{\pi }{4}-\dfrac{\pi }{6}$$
$$\dfrac{3\pi }{10}= \dfrac{\pi }{10}+\dfrac{\pi }{5}=\dfrac{2\pi }{5}-\dfrac{\pi }{10}$$
$$\dfrac{3\pi }{8}=\dfrac{\pi }{4}+\dfrac{\pi }{8}, \dfrac{5\pi }{12}=\dfrac{\pi }{4}+\dfrac{\pi }{6}$$
The values that I found at $\{0, \pi/12, \pi/10, \pi/6, \pi/5, \pi/4, 3\pi/10, \pi/3, 3\pi/8, 2\pi/5, 5\pi/12, \pi/10\}$ are as follows:
Comment: Nice table, did you make it? How?


$G$ connected planar graph, less than 12 vertices, then $\chi (G) \leq 4$

Question: The problem is:
Let $G$ be a connected planar graph with less than 12 vertices.
a) Prove that G has a vertex with degree $\leq 4$.
b) Prove that $\chi (G) \leq 4$. (Do not use the Four Color Theorem)
I did prove part a) satisfactorily I think at least =/
My question is about part b).
I am thinking showing part b) by contradiction may work. I am thinking perhaps something concerning a particular vertex with degree at most $4$, deleting this vertex, showing a $4$ coloring is still possibly, any hints? =/
I am also thinking I could use Euler's Formula but I am not sure of how I would relate $n+r-e=2$ back to the chromatic number.
(I should have stated it said to do the problem without the four color theorem)
Answer: I think you can change the standard proof of "any planar graph is 5 colorable" to this case.
Assume by contradiction that this is not true. Pick a planar graph which is not $4$ colorable, and has at most 11 vetices, with the smallest number of vertices
Now, by the previous part, this graph has a vertex of degree at most $4$. Remove that vertex. The smaller graph is 4 colorable.
Add the vertex back in. It is connected to 4 vertices. If two have the same color, you are done. If all four vertices have different colors, repeat the argument from the 5 color theorem to recolor the four neighbours..
Comment: Two bugs: (a) "at most 12 vetices" -> "at most 11 vertices".  (E.g. the icosahedron is an example of a 5-regular 12-vertex planar graph.)  (b) "has a vertex of degree $4$" -> "has a vertex of degree at most $4$".
Comment: Ok thank you very much. I have been behind in this class and I am trying to get caught up to save my grade, if the gods shall be it so lol


Android ImageView changing alpha Animation

Question: I have four images that need loaded.  I want one animation to play, wait 500ms, another one play, wait 500ms, etc..  All the animation does is change the alpha from 255 to 0 and then back to 255.  All four imageViews need that animation.
I am having two problems currently.
1.) All of the images play at the same time.
  2.) The next time the method is called, the animations don't work.
public void computerLights()
{

    ImageView green = (ImageView)findViewById(R.id.imgViewGreen);
    ImageView red = (ImageView)findViewById(R.id.imgViewRed);
    ImageView blue = (ImageView)findViewById(R.id.imgViewBlue);
    ImageView yellow = (ImageView)findViewById(R.id.imgViewYellow);

    AlphaAnimation transparency = new AlphaAnimation(1, 0);

    transparency.setDuration(500);
    transparency.start();
    green.startAnimation(transparency);
    red.startAnimation(transparency);
    blue.startAnimation(transparency);
    yellow.startAnimation(transparency);
}

Answer: I'm not sure if this is the most elegant solution, but you could achieve this pretty easily with a handler that you can send messages to at 500ms intervals.
private int mLights = new ArrayList<ImageView>();
private int mCurrentLightIdx = 0;
private Handler mAnimationHandler = new Handler(){

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        ImageView currentLightIdx = mLights.get(currentLight);

        AlphaAnimation transparency = new AlphaAnimation(1, 0);

        transparency.setDuration(500);
        transparency.start();
        currentLight.startAnimation(transparency);

        currentLightIdx++;
        if(currentLightIdx < mLights.size()){
            this.sendMessageDelayed(new Message(), 500);
    }
};

public void computerLights()
{

    ImageView green = (ImageView)findViewById(R.id.imgViewGreen);
    ImageView red = (ImageView)findViewById(R.id.imgViewRed);
    ImageView blue = (ImageView)findViewById(R.id.imgViewBlue);
    ImageView yellow = (ImageView)findViewById(R.id.imgViewYellow);

    mLights.add(green);
    mLights.add(red);
    mLights.add(blue);
    mLights.add(yellow);

    mAnimationHandler.sendMessage(new Message());
}

After the first message is sent the handler will continue to send messages every 500ms until all of the animations have been started.


$\frac{1}{\sqrt{1+\lambda x_1}}+\frac{1}{\sqrt{1+\lambda x_2}}+...+\frac{1}{\sqrt{1+\lambda x_n}}\leq \frac{n}{\sqrt{1+\lambda}}$

Question: Let $x_1, x_2,...,x_n$ be positive numbers such that $x_1x_2...x_n=1$.

For $n \geq 3$ and $0<\lambda\leq\frac{2n-1}{(n-1)^2}$, prove that $$\frac{1}{\sqrt{1+\lambda x_1}}+\frac{1}{\sqrt{1+\lambda x_2}}+...+\frac{1}{\sqrt{1+\lambda x_n}}\leq \frac{n}{\sqrt{1+\lambda}}$$

My initial thought:
What if I let $v_i=\lambda x_i$, so the given condition will become $$\prod_{i=1}^{n}v_i=\lambda^n$$ and $$\lambda=\left (\prod_{i=1}^{n}v_i\right)^{1/n}\leq \frac{2n-1}{(n-1)^2}$$
$$\therefore \frac{1}{\sqrt{1+\lambda x_1}}+\frac{1}{\sqrt{1+\lambda x_2}}+...+\frac{1}{\sqrt{1+\lambda x_n}}=\sum_{i=1}^n\frac{1}{\sqrt{1+v_i}}\leq \frac{n}{\sqrt{1+\lambda}}$$
But I have no idea how to proceed from here. Any alternative solutions/tricks/guidances are appreciated. Thank you in advance.
Comment: For $n=3$ and $\lambda=\frac{2n-1}{(n-1)^2}$ we obtain  known Vasc's inequality. In the general, by his HCF Theorem it's enough to prove your inequality for equality case of $n-1$ variables, which gives something very ugly.
Answer: The maximisers of $\displaystyle f(x) = \sum_{i=1}^n\dfrac{1}{\sqrt{1+\lambda x_i}}$ will be stationary points of the Lagrangian
$$
L(x_1, \cdots, x_n; \mu) = \sum_{i=1}^n\dfrac{1}{\sqrt{1+\lambda x_i}} - \mu x_1 \cdots x_n
$$
Solving the corresponding system, you'll see that the maximizer will satisfy $x_1=x_2 = \cdots = x_n$, which means that all $x_i$'s must be one in order to maximise $f$. The proof is "complete" by noting that  $f(1,1,\cdots, 1) = \dfrac{n}{\sqrt{1+\lambda}}$.
Still needs to be addressed:

Using second order conditions to show that this single stationary point of the Lagrangian is indeed a maximiser.
Showing that the objective function does not extend to the boundary with a value greater than $f(1,\cdots,1)$, making the stationary point a global maximiser in $\mathbb{R}^n_{>0}$.
Comment: I don't want to waste 1 point for downvoting you, but this is not the solution.
Comment: @NN2 Even without wasting a point, it would be useful to ellaborate.
Comment: @NN2 It is not... Every equation will be of the form $$2 \sqrt{1+\lambda x_i} = \frac{\mu}{x_i}$$
It is just a matter of using the restriction to get $\prod_{j\ne i} x_j = \frac{1}{x_i}$
Comment: It is impossible to solve the system of equations $\frac{\partial L}{\partial x_i} = 0$!
Comment: But how you solve all $n$ cubic equations with the constraint $\prod x_i = 1$? It's impossible.
Comment: @NN2 I don't need to solve the cubics, I just need to show that they all have a single real root. Since all the equations will be the same cubic, all $x_i$'s must be equal.
Comment: Not sure, as the cubic equation may have 3 roots.
Comment: The conditions $\lambda, x_i >0$ guarantee a positive derivative and therefore a single real solution.
Comment: Ok, I see. But for your 2nd point, the objective function $L$ is not decreasing towards the boundaries. Take for example $x_1 = x_2  =...=x_{n-1} = \epsilon$ and $x_n = \epsilon^{-(n-1)}$, then $L$ reaches its maximum $$L \xrightarrow{\epsilon \to 0} RHS$$
if $\lambda = \frac{2n-1}{(n-1)^2}$
Comment: @NN2 You are correct, I should rephrase it: it does not need to decrease towards the boundary, it is just that the boundary value must be smaller than $f(1,1, \cdots,1)$. As you mention, this is the reason for the condition $\lambda\leq \frac{2n-1}{(n-1)^2}$.
Comment: @Yes.
And now I think you are on the right track. Just some remaining points need to be solved.
Comment: @PierreCarre Let $n=3$,$\lambda=\frac{2n-1}{(n-1)^2},$ $x_1=\frac{b}{a}$, $x_2=\frac{c}{b}$ and $x_3=\frac{a}{c}$, where $a$, $b$ and $c$ are positives. Thus, we need to prove that: $\sum\limits_{cyc}\sqrt{\frac{a}{4a+5b}}\leq1.$ Now, try $a=b$ and $c\rightarrow0^+$, which says that your reasoning is wrong.
Comment: @MichaelRozenberg How does this invalidate my reasoning? The limit value, $\frac{13}{9}$, is smaller than $f(1,1,\cdots, 1)$, which is equal to $2$.
Comment: @PierreCarre It means $c\rightarrow0^+$ and after this $b\rightarrow0^+$. What do you say now?


AngularJS cleaning up and memory leaks

Question: https://docs.angularjs.org/guide/directive

Listeners registered to scopes and elements are
  automatically cleaned up when they are destroyed, but if you
  registered a listener on a service, or registered a listener on a DOM
  node that isn't being deleted, you'll have to clean it up yourself or
  you risk introducing a memory leak.

I don't understand one thing (actually I don't understand many things about Angular, but now I'm aimed exactly at this). Can anybody explain the difference between registered to scopes and elements" and "registered a listener on a service, or registered a listener on a DOM". What is the difference between elements and DOM in this sentence. And why in first case listeners are automatically cleaned up, but in second they aren't. What is being registered to elements and what is being registered on DOM?
Answer: Note we are speaking of two slightly different kinds of cleanup here:

Event listener functions may need cleanup.
Created elements may also need cleanup.

In these cases Angular cleans up for you:
// Watching scope vars
$scope.$watch("scopeVariable", function (newVal) { ... });
$scope.$watch("injectedService.serviceVar", function (newVal) { ... } );

// Listening to events from a scope
$scope.$on("event", function () { ... });

// Events of the element of a directive,
// within the directive 'link' function (the docs you referenced)
element.on('click', function() { ... });

In all these cases, it's not necessary to do any cleanup. Angular knows that some code is listening to events or watching variables, and can unregister them. For the element, since it will be removed, all closures  and related objects will be unreferenced, and thus later disposed by the garbage collector.
On the other hand, in the following cases Angular will not do cleanup for you:
// Listening to events from rootScope
$rootScope.$on("event", function () { ... });

// Subscribing to services events
someInjectedService.subscribeIncomingMessage(function () { ... });

// Adding elements outside directive container element
var body = $document.find('body').eq(0);
var newElement = angular.element('

');
body.append(newElement);

// Listening to events of elements outside your directive (ie. body)
body.on("click", function() { ... });

In these cases, Angular will never destroy your listeners, nor the created element added to the  of the document.
In raw words, I'd say Angular will just destroy everything inside your scope or contained in the DOM of your directive root element. Everything else you listen to, or elements that you create and place outside your directive, are your responsibility.
Quoting angular docs, you would do cleanup by listening to the destroy events:

Best Practice: Directives should clean up after themselves. You can
  use element.on('$destroy', ...) or scope.$on('$destroy', ...) to run a
  clean-up function when the directive is removed.

I personally add these methods only when there's something to clean up. You need to do this especially if you create elements of register for external events (ie. messages coming from websockets, or scheduled timeout events), otherwise you risk ending up with several listeners for the same event (usually causing misbehavior and sluggishness).

AngularJS cleaning up and memory leaks


EJB entity beans JAR & RESTeasy

Question: I am having trouble getting my entity beans to connect correctly to MySQL. Here's my set up:

JBOSS: 6
UBUNTU: 11.04
EJB: 3.1

I am currently trying to access entity beans via a JNDI remote call to a JARed session bean in the root of my EAR file.
My Entity beans map correctly to my database and work in one EAR file however I want to use the same entity beans in another EAR file in the same container so I have JARed my entity beans and I pull them into my second EAR file using my build script. I am pulling the exact same persistance.xml file as my first EAR file and it points to the same data source XML in the root of my deploy directory. I can define my persistence context and access my entity beans without error and I can compile and deploy my JBoss server without any exceptions. However I get this error when I try to access the entity beans after the container has deployed:
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [SELECT u FROM User u WHERE u.accountId=:accountId]

This is the query I am using:
List<User> users = entityManager.createQuery("SELECT u FROM User u WHERE u.accountId=:accountId")
        .setParameter("accountId", accountId)
        .getResultList();

Can anyone tell me if:

there is an issue with JARing entity beans
does RESTeasy need some special config to deal with entity beans
is it even possible to use JARed entity beans
could there be a config conflict if I am accessing the same datasource using two separate instances of the same entity beans in the same container

Thanks in advance for any help with this. I am really stuck.
ADDED (20/05/2011):
So I have now consolidated my entity and session beans into one jar and have altered the persistence.xml so include the auto detect property suggested by Nayan below:
<property name="hibernate.archive.autodetection" value="class"/>

but to no avail. I have the JAR registered in my application.xml and have added the JAR to the classpath in my build script.
Would it make any sense to put the JAR file into the root of the deploy directory and try to access it from there?
Answer: In your EAR, it seems that the entities packaged in jar aren't recognized, also check whether jar is present in classpath.
Try adding <property name="hibernate.archive.autodetection" value="class"/> in persistence.xml.
Else, try including class for persistent unit.
<persistence-unit name="unitName">
    <class>com.package.User</class>
    ...
 </persistence-unit>

Comment: Hi Nayan thanks for your reply. I have added an update to my original post. Please have a look and see if it makes any difference. Thanks
Comment: Check the JBoss startup logs, as it verifies the entity beans - named queries etc, so can find that entity beans are deployed properly for both EARs. Also have you tried the other option including class element in persistent.xml. Try deploying the second EAR independently on Jboss without the first one for verification.
Answer: The issue was with the location of my persistence.xml file. I have the persistence.xml file in a JAR with my sessions beans not with my entity beans where it was needed. Problem solved!

EJB entity beans JAR & RESTeasy


How to add one image to many buttons in ios using for loops

Question: I have 3 buttons on the interface and an image.  i wanted to make NSArray of these 3 button and assign them only 1 image.
but how can i do that.
can i use for loop to assign the image to button.
Comment: please add a small small of your code, and probably a sketch of the end goal vs what you have now.
Answer: If I understand your question well, which I'm not sure, you want to do something like this :
NSArray * buttons = @[button1, button2, button3];
for (UIButton * button in buttons) {
    [button setImage:image forState:UIControlStateNormal];
}

If I didn't understand your question, do not hesitate to be more precise.
Comment: Thanks you are great,solved my problem of for loop.
Answer: Yes, you can create an IBOutletCollection(UIButton) NSArray* (how to create IBOutletCollection arrays) property with all the buttons and assign the image using setImage:forState: method with the same UIImage:
UIImage* image = [UIImage imageNamed:@"myFile.png"];
for (UIButton* button in _buttons) {
    [button setImage:image forState:UIControlStateNormal]
}


Dimensions of Ovation roundback guitars?

Question: Ovation makes its roundback style guitars in a few different sizes, corresponding to the depth of the bowl:

Super Shallow
Shallow
Mid-Depth
Deep

I have one such guitar and am looking for a case for it, but I'm not sure which size it is - is there a list of dimensions for each of these?
Comment: The best option is to contact Ovation guitars, with the serial number of your guitar.
Comment: @Tim unfortunately the sticker with the serial code has come off.
Comment: Don't know specifically about Ovations, but most guitars have a number stamped on them, into the wood, often on the head, or sometimes on the heel of the neck.
Answer: From the 2003 Ovation Catalogue:
Answer: You can place the guitar on a flat surface and use a tape measure to measure the distance from the flat surface to the edge of the guitar face to determine the depth of the guitar, but be sure to allow for the additional height of the bridge when determining which guitar case to purchase. You may also choose to measure other dimensions on the guitar such as the neck length and width of the upper and lower bout, or you may choose to just take your instrument with you to the music shop and try different size cases to find one that fits best. That's the old fashioned method.


Libgdx project generation

Question: Whenever I try to create a project using libgdx.jar it says I need to have the latest Android API 28 but my SDK manager says I already have it.
Can anyone suggest what to do?
Answer: You will need to point the setup application to your sdk location. I recommend using this one instead, it allows you to set the sdk location in the app.

Libgdx project generation


Dado truncado no MySQL

Question: Uma tabela do banco de dados tem 5 colunas.
1ª id autoincremento [INT[11] NOT NULL]
2ª código do produto [varchar(15) NULL]
3ª nome do produto [varchar[80] NULL]
4ª custo do produto [double[10,2] NULL]
5ª imposto do produto [double[10,2] NULL]

Executando o SQL abaixo:
INSERT INTO
    `produtos`
    (
    `produto_cod`,
    `produto_nome`,
    `produto_custo`,
    `produto_imposto`
    )
    VALUES
    (
    '03202374756',
    'Produto teste XYZv2',
    '100.50',
    ''
    );

O campo "imposto do produto" não é obrigatório (mas também recebe valores de impostos se o usuário preencher o campo relacionado no formulário de cadastro), e pode-se passar o valor em branco, mas o SQL retorna um erro mesmo o campo sendo um valor NULL.

Data truncated for column 'prod_imposto_ipi'.
Answer: O erro ocorre, pois mesmo o campo produto_imposto aceitando nulo, está recebendo um valor, um valor de uma string vazia: ''.
Para corrigir essa situação, você pode optar por enviar o valor null para o campo produto_imposto:
INSERT INTO
    `produtos`
    (
    `produto_cod`,
    `produto_nome`,
    `produto_custo`,
    `produto_imposto`
    )
    VALUES
    (
    '03202374756',
    'Produto teste XYZv2',
    '100.50',
    null
    );

Ou remover esse campo do insert, já que ele aceita nulo e você não pretende gravar nada:
 INSERT INTO
    `produtos`
    (
    `produto_cod`,
    `produto_nome`,
    `produto_custo`
    )
    VALUES
    (
    '03202374756',
    'Produto teste XYZv2',
    '100.50'
    );

Criei um exemplo online: http://sqlfiddle.com/#!9/c0b5c95/1
Comment: Oi, ele não é obrigatório, mas o campo pode sim receber um valor.

Dado truncado no MySQL


C# na form 2 não mostra a string na label

Question: Não entendo porque mas o Form 2 não mostra o texto do label no form 1.
form 1
    private void button1_Click(object sender, EventArgs e)
    {
        string Username = textBox1.Text;
        HelloForm HF = new HelloForm();
        HF.Show();
        HF.Username = Username;
        this.Hide();
    }
}

form 2
    public string Username { get; internal set; }

    private void HelloForm_Load(object sender, EventArgs e)
    {

        label1.Text = "Hello " + Username;
    }
}

Comment: Coloca a pergunta em português.
Comment: eu quero que no label 1 da form 2 apareça a string username da form 1
Comment: hehe, eu entendi o que você falou em inglês :P Mas o site é em português, entendeu?
Comment: obrigado eu não sabia editar para pt sou novo neste site só agora vi ali o botão de editar
Answer: Você precisa permitir que o label1 seja alterado por outra classe. Neste caso você deve alterar a propriedade Modifiers.

No seu caso não está funcionando porque a propriedade não possui o valor no momento que você a utiliza. Se você depurar, verá que no momento, Username possui o valor null. Neste caso indico você criar uma sobrecarga no construtor da classe.
public HelloForm(string _username)
{
    InitializeComponent();
    Username = _username;
}

e depois pode simplificar o botão, usando o novo construtor.
private void button1_Click(object sender, EventArgs e)
{
    HelloForm HF = new HelloForm(textBox1.Text);
    HF.Show();
    this.Hide();
}

Fiz o teste aqui e funcionou da forma que você precisa.
Comment: Já estava privado e é na label da form 2 não form 1
Comment: Então troca para public. Você quer acessar ela publicamente e não de forma privada.
Comment: Não funcionou..
Comment: Vê se ajuda agora.
Comment: ja da obrigado!!! mas nem tudo era perciso


Cannot redeclare drupal_get_hash_salt()

Question: I had a site and it was running fine on the live server but when I moved it to my local server it gave me this error.
<code>Fatal error: Cannot redeclare drupal_get_hash_salt() (previously declared in
D:\wamp\www\htdocs\projects\mysite\includes\bootstrap.inc:2248) in
D:\wamp\www\htdocs\projects\mysite\includes\common.inc on line 5045
</code>
I guess the problem occurred because of editing the variable
<code>$drupal_hash_salt = 'zU4q79TqFe0thQO-xGQbfbrFfKloUk9OYXfQ70J1nw0';
</code>
manually in setting.php file.
Does anybody have any idea how can I solve this problem?
Comment: I've tried to reproduce your problem but no dice, are you sure that removing that solves the problem? what do you have in that 5045 line of common.inc?
Comment: ON line 5046 I have the function **function drupal_get_hash_salt** as defined [Here](https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_get_hash_salt/7)
Comment: Just got this on a 7.24 upgrade (I know I am behind...) although it was line html/includes/common.inc on line 5065; this saved me many hours of pain.
Answer: You've got definitely a Drupal upgrade problem, drupal_get_hash_salt used to be in common.inc and was moved to bootstrap.inc in Drupal 7.23 version as you can see in https://www.drupal.org/node/1739986.
Something went wrong with your core update, I'd suggest you to backup your data and upgrade your files to the latest version, then run update.php and check everything is OK.
Comment: As you said "Upgrade your files to the latest version", I searched **Manually update Drupal core** and I find this article **https://www.drupal.org/node/1494290**. I followed all the steps and as soon as I reached to the 3rd last step I saw mysite working. Thank you for putting me in the right direction.

Cannot redeclare drupal_get_hash_salt()


loop em json em flask usando render_template

Question: Olá, eu tenho o seguinte json:
{"movies": "[{\"title\":\"Hercules\",\"rep\":99.96},{\"title\":\"In the Dark\",\"rep\":98.12},{\"title\":\"Titas\",\"rep\":96.61}]"}

e gostaria de percorrer ele jogando em uma tabela no html usando o render template do flask, ficou dessa forma:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

Flask

            Título
            Rep

          {% for movie in movies %}

            {{ movie.title }}
            {{ movie.rep }}

          {% endfor %}

porém eu tenho como resultado o seguinte:

Obs: o json foi gerado atraves de um dataframe utilizando o seguinte codigo:
m = df[['title','rep']].head(3).to_json(orient='records')
movies={'movies':m}
return render_template('index.html',movies=json.dumps(movies))

o que estou fazendo de errado?
Answer: O primeiro problema é que você está passando uma string para o método render_template ao usar o json.dumps. Você também não precisa converter o dataframe para json e depois em dicionário, daria para usar o método to_dict.
Além disso você poderia passar a lista diratamente no parâmetro, não precisaria adicionar ela a um dicionário.
Então, dessa maneira seu template deve funcionar como o esperado:
movies = df[['title','rep']].head(3).to_dict(orient='records')
return render_template('index.html', movies=movies)


Maximum number of monic polynomials $f(x)$ such that for some real $a$, $x(f(x+a) - f(x)) = nf(x)$ for a fixed $n<1000$?

Question: This was a problem that I did from a while ago that I am revisiting. I remember getting the answer as the maximum divisors of an $n < 1000$, which would be $n = 840 \rightarrow 32$ divisors and polynomials, but I can't remember how I came to that result. Anyone mind giving me a hand?
Comment: Interesting question! Do you allow the polynomial's coefficients to be arbitrary real (complex?) numbers, or are they restricted to integers? (Where is the problem from, BTW?)
Comment: Ok, turns out the intended answer is clearly polynomials with integer coefficients. However, the surprising fact is that for any real $n \neq 0$, there is a unique such polynomial of any given degree $d$, which has rational coefficients that are integer iff $d$ divides $n$.
Answer: Given $n$, you are trying to find monic polynomials $f$ such that for some real number $a$, we have $$x(f(x+a) - f(x)) = nf(x).$$
We will prove (proved in two ways below) that for any degree $d$, there is a unique polynomial of degree $d$ satisfying this constraint, and that this polynomial is
$$f_d(x) = x\left(x+\frac{n}d\right)\left(x+\frac{2n}d\right) \cdots \left(x+\frac{(d-1)n}d\right)$$
Observe that
$$\begin{align}
f_d\left(x+\frac{n}{d}\right)
&= \left(x+\frac{n}{d}\right)\left(x+\frac{2n}{d}\right)\dots\left(x+\frac{dn}{d}\right)\\
&= f_d(x)\frac{(x+n)}{x}
\end{align}$$
and so with $a = n/d$, we have $x(f(x+a)-f(x)) = nf(x)$.
Now, if we want integer coefficients, note that each polynomial $f_d(x)$ has integer coefficients if and only if $d$ divides $n$. So for a given $n$, the number of polynomials satisfying the constraint is the number of divisors $d$ of $n$, as we wanted to prove.

Proofs that $f_d(x)$ is the unique polynomial of degree $d$ satisfying the constraints: I see two approaches, and probably there may exist other better ones.
First proof. Suppose $f$ is of degree $d$, say $f(x) = x^d + c_{d-1}x^{d-1} + \dots + c_1x + c_0$. Then, let us compare coefficients of $x^d, x^{d-1}, \dots$ in $x(f(x+a) - f(x))$ and in $nf(x)$, and use the fact that they must be equal. We can either

expand all terms of $f(x+a)$ using the binomial theorem, or
use $f(x+a) = f(x) + a f'(x) + \frac{a^2}{2!}f''(x) + \dots$.

Either way, the coefficient of $x^d$ in $x(f(x+a)-f(x))$ is $ad$, and in $nf(x)$ is $n$, and so $a = n/d$.
Next, comparing coefficients of $x^{d-1}$ gives $c_{d-1}(d-1)a + \frac{d(d-1)}{2}a^2 = nc_{d-1}$, determining $c_{d-1}$. Similarly, comparing coeficients of other powers gives successively $c_{d-2}, \dots$, each got in terms of the earlier coefficients. Thus, as all coefficients $c_k$ are determined, there can be at most one polynomial of degree $d$ satisfying the constraint. As we have found and verified $f_d(x)$ above, it must be the unique one.
Second proof. As $x$ divides the left-hand side of the given equation $x(f(x+a)-f(x)) = nf(x)$, we conclude that it must divide the right-hand side, and therefore $f(x)$ is a multiple of $x$.
Plugging $f(x) = xg(x)$ into the equation and cancelling $x$, we get $(x+a)g(x+a) = (x+n)g(x)$. So either $a = n$ (in which case the periodicity $g(x+a)=g(x)$ implies that $g$ is the constant polynomial $g(x) \equiv 1$ and so $f(x) \equiv x$), or else $(x+a)$ divides $g(x)$.
Plugging $g(x) = (x+a)h(x)$ into the equation $(x+a)g(x+a) = (x+n)g(x)$ and cancelling the $(x+a)$ factor gives $(x+2a)h(x+a) = (x+n)h(x)$. So either $n = 2a$ (in which case $h(x) \equiv 1$, and $f(x) \equiv x(x+a)$) or else $(x+2a)$ divides $h(x)$.
Proceeding this way, we get that our polynomial is
$$f(x) = x(x+a)(x+2a)\cdots(x+(d-1)a)$$
for some $d$ such that $n = da$.


How to navigate through a list

Question: I want to render all the 'name' elements inside 'rotas', but when i try it says map is undefined.  Any help is apreciated.
export default function SelecionaRota(props) {
    const data = {
        locais: [
            {
                name: 'Rio de Janeiro',
                rotas: [
                    {
                        name: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        name: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (

{estadoOrigem}

            { rota.locais.rotas.map(module => (

{module.nome}

            ))}

    )
}

Comment: looks like it should be `data.locais[0].rotas.map(...`
Comment: Yes it solved it, but how can i make it render more than one element inside 'locais'? For example, if i have another element inside locais named 'São Paulo' and another 'rotas' with other elements inside?
Comment: You'll need a nested map call
Answer: The top level variable is called "data" not "rota" and "locais" is an array not an object. To access rotas:
data.locais[0].rotas.map()
data.locais[1].rotas.map()
//etc

You probably want to iterate over losais like to access each item within.
Comment: I changed the object name before posting, that's mb. But it worked, thanks.
Answer: Here's an example of a nested map().
Note: Don't forget to add unique keys to each mapped element (and don't use index).

function SelecionaRota({ data }) {
  //const location = useLocation();
  //const { estadoOrigem } = location.state;

  return (

estadoOrigem

      {data.locais.map((locais) => (

{locais.name}

          {locais.rotas.map((module) => (

{module.name}

          ))}

      ))}

  );
}

const data = {
  locais: [
    { name: 'Rio de Janeiro', rotas: [{ name: 'RJ-SP', valor: 1200, }, { name: 'RJ-BSB', valor: 1400, },], },
    { name: 'City 2', rotas: [{ name: 'C2-BC', valor: 1200, }, { name: 'C2-EFG', valor: 1400, },], },
  ],
};

ReactDOM.render(<SelecionaRota data={data}/>, document.getElementById('root'));

Answer: First of all  rota.locais.rotas.map is wrong. You need to use data.locais[0].rotas.
Now as data.locais[0].rotas is an array you need to iterate it using for each. So it will be like this:
Array.from(data.locais[0].rotas).forEach(element => {

{element.name}

});

How to navigate through a list


Setting an EditText and a Button on top of a ListView

Question: I'm doing my first tutorial on Android and trying to display a EditText with a Button on top of a ListView.
This is where I've got, but the ListView is not showing.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

     <EditText
        android:id="@+id/edit_message"
        android:layout_height="wrap_content"
        android:hint="@string/new_name"
        android:layout_weight="1"
        android:layout_width="0dp"/>

     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_plus"
        android:onClick="openActivity"/>

    </LinearLayout>

    <ListView
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:id="@+id/listview1"
       android:fastScrollEnabled="true"
       android:background="@color/white"
       android:layout_below="@+id/linearLayout1"
       >
    </ListView>

</RelativeLayout>

I know something simple is missing but can't get there.
What am I doing wrong?
Comment: It's not showing even if you populate it with data from your adapter?
Comment: No, even with data. If I remove the LinearLayout all together, the ListView shows up with populated data.
Answer: Change one parameter of your LinearLayout:
android:layout_height="match_parent"

to
android:layout_height="wrap_content"

Your RelativeLayout is vertical and by setting height of LinearLayout to match_parent it's trying to allocate all the vertical space of the screen


Cross entropy-equivalent loss suitable for real-valued labels

Question: I am building a model whose outputs are between 0-1 and the goal is to minimize a cost function over the predicted values and labels. So far everything seems to be easy but my labels are real-valued and therefore, I cannot use the ordinary cross entropy loss function. For instance, suppose the predicted value is 0.2 and the label value is 0.2. Then simply applying the cross entropy will not give the output of 0 (as the desired output) and still generates gradients unnecessarily. Another problem is when the prediction value is greater than the corresponding label the cost ordinary cross entropy does not output sensible outputs. So I wonder, is there an equivalent version of the cross entropy function which deals with continuous [0, 1] labels?
I may note that I have used loss functions such as the L2, L1 and squared loss and so far the ordinary cross entropy loss is getting me the best results! So that's why I think a cross entropy loss which is suitable for continuous labels will even work better.
Answer: Cross entropy is defined on probability distributions, not single values. The reason it works for classification is that classifier output is (often) a probability distribution over class labels. For example, the outputs of logistic/softmax functions are interpreted as probabilities. The observed class label is also treated as a probability distribution: the empirical distribution (where the probability is 1 for the observed class and 0 for the others).
The concept of cross entropy applies equally well to continuous distributions. But, it can't be used for regression models that output a point estimate (e.g. the conditional mean) but not a full probability distribution. If you had a model that gave the full conditional distribution (probability of output given input), you could use cross entropy as a loss function.
For continuous distributions $p$ and $q$, the cross entropy is defined as:
$$H(p, q) = -\int_{Y} p(y) \log q(y) dy$$
Just considering a single observed input/output pair $(x, y)$, $p$ would be the empirical conditional distribution (a delta function over the observed output value), and $q$ would be the modeled conditional distribution (probability of output given input). In this case, the cross entropy reduces to $-\log q(y \mid x)$. Summing over data points, this is just the negative log likelihood!


Combining Several Random Forests Together - Is this Statistically Valid?

Question: I was reading this paper on the history of Bagging Estimators (https://www.stat.berkeley.edu/~breiman/bagging.pdf) and came across the following question (Why is bagging stable classifiers not a good idea?). Over here, the following point is mentioned:

Apparently, there are theoretical reasons that suggest that bagging "stable models" (e.g. Random Forests) is not advisable as this may in fact result in a loss in accuracy.
While this may be true, I noticed that the "randomForest" library in R (one of the most popular implementations of the Random Forest) has a function which allows you to directly combine several Random Forest models together (this looks like we are "combining" the three models together, not "bagging"):
# https://cran.r-project.org/web/packages/randomForest/randomForest.pdf
library(randomForest)
data(iris)
rf1 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf2 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf3 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)
rf.all <- combine(rf1, rf2, rf3)
print(rf.all)

I was just trying to better understand this point : If it is not advisable to bag together several "stable models" such as Random Forest - is there any reason that one of the main implementations would allow for these models to be "combined" together? Or do these theoretical warnings only refer to "bagging" stable models together and not "combining" stable models together?
Thanks!
Answer: The "combining" that is done in your code is just collecting the three random forests together into a single object, as a concatenation of the trees in each forest. The object rf.all is just a container to hold the trees: rf1 holds trees indexed as 1-50 (say), rf2 holds 51-100 and rf3 holds trees 101-150.
The combine method does not have any relationship to the quoted passage that is distinct from averaging the results of a single random forest object (e.g. the prediction of the ensemble rf1). In other words, if it's true that a single ensemble incurs a loss of accuracy, then it's true that combination of several ensembles must also share the same defect.


Smallest number consisting of only ones and zeroes, divisible by a given number.

Question: Problem statement: Link to the problem here. Find the smallest number consisting of only ones and zeroes, which is divisible by a given number n.
Solution approach:

Let's represent our numbers as strings here. Now, consider there are N
  states, where i'th state stores the smallest string which when take
  modulo with N gives i. Our aim is to reach state 0. Now, we start from
  state "1" and at each step we have two options, either to append "0"
  or "1" to current state. We try to explore both the options, but note
  that if I have already visited a state, why would I visit it again? It
  already stores the smallest string which achieves that state and if I
  visit it again with a new string it will surely have more characters
  than already stored string.

My doubt:
I don't understand the fact why we are not further visiting a number which has a state that has already been visited. I understand that another number which had the same state previously will be smaller. But what if the actual answer lies in the numbers obtained by appending ones or zeroes to the current number with the same state rater than the previous smaller number with the same state? Can we prove that we can safely ignore this larger number with the repeated state?
Comment: Yes... note that if $X$ and $Y$ are equal to $i$ modulo $N$, then $XZ$ and $YZ$ are also equal modulo $N$, where $Z$ is any string of additional digits.  So you can safely ignore the larger of $X$ and $Y$; i.e., you don't need to visit the state $i$ more than once.
Comment: Yes, you are right. Can you please add it as answer, so that i can accept it :)
Comment: I would use a breadth first search to solve this problem. Start with the number $1$ and enqueue it. While your queue is not empty, take a number off. If it is not the solution add two numbers to your queue: one with $0$ appended and one with $1$ appended. Since you queue is first in first out you will find the shortest solution.
Answer:
Note: This user correctly gave the answer in the comments,
  however did not post it as an anwer, even after i asked him to do so.
  So, after waiting for months, i am posting the answer here.

If X and Y are same modulo M, then XC + Z and Y C + Z also have same modulo M. Multiplication and addition might change the modulo's value, but it would be the same change for both numbers, hence they will end up with same modulo, which might still be difference from the initial modulo.
Also, this can be understood using residue sets as well, tough it might be an overkill. If we have a set S which has all it's elements unique modulo M, and has one entry for each modulo possible, i.e. it is an complete residue set, then multiplying all terms of the set with a constant C will give us another complete residue set. Now adding Z to all elements of the set will again give us a complete residue set. Now use this on two complete residue sets, which have all elements same expect X and Y. To finally get a complete residue set, operation on X and Y will have to correspond to the same modulo in the final set.
Comment: I think C must be relatively prime to the modulo for all this to be true.
Comment: Yeah, we can't use C which is not relatively prime to M in residue set. Tough, to get the same modulo M, we can use any C.


css style emails for mobile to roll/stack on top of each other

Question: I've been trying to style my emails like how Pinterest does it.
so in the web they show one way but in mobile they stack the td's on top of each other and things look bigger.
I'm very new to styling emails, any idea how to achieve this? or what to do and not to do?
Comment: Stack questions are for helping people when they are stuck with code or trying to understand something about a language. Asking for suggestions are considered to localized. Please edit your question to fit stack standards. Thanks.
Comment: I'm not sure what you exactly mean, I revised the title, but if you have a better suggestion for wording this let me know
Answer: Campaign Manager has a guide on creating mobile responsive emails - http://www.campaignmonitor.com/guides/mobile/
Answer: I found out.
I have to use @media in my stylesheet and also meta tag
<code>  %meta{ name: 'viewport', content: 'width=device-width, initial-scale=1.0, maximum-scale=1' }
</code>
some good tutorials:
http://www.campaignmonitor.com/blog/post/3442/mobile-email-design-in-practice/
http://mobile.smashingmagazine.com/2011/08/18/from-monitor-to-mobile-optimizing-email-newsletters-with-css/
Answer: Most email clients don't adhere to the same standards as web browsers. See this answer for some background on how to style emails. Best practices for styling HTML emails


REST for nested paragraphs

Question: I need to create a rest service that delivers the current data:

getNode(nid)
-> all node fields
   -> if field is entity reference (like file, human readable urls)
       -> include subfields
   -> if field is type of paragraph, include sub fields again in human readable form

It seems that Drupal is not yet ready for Rest without having to create new requests for every peace of content that is referenced with an id.
For example I have a Pinterest wall kind of output. Each item is created by using a paragraph element (sometimes with other references like taxonomy etc)
I want a clean, json list. Structured correctly without missing nested elements like paragraphs, file or taxonomy references. In this moment I just get the id's of the referenced elements.
Do I have to call now 100+ requests to collect all data for this wall?
1) Or should I make one request for collecting the node:
2) Another request to collect all 1st level entity references. Afterwards to store them in an array.
3) Afterwards making request for 2nd level entity references.
This seems horrible to me when it comes to questions about overhead and time.
Of course I have checked out some modules that should help with this issue:

rest_export_nested module
which does not work with paragraphs entity types
rest_views
does seem to output the fields as html instead of json. There is no real solution so far.

So what to do? Another way could be to create a view of paragraphs with target id of [NODE_ID]. But this would work just for 1st level paragraphs. The problem would still exist for nested paragraphs.
Is really the only way to create a custom module that creates it's own rest service?
Is the JSON API maybe another solution I haven't looked at so far?
Any input is appreciated.
Thanks.
Comment: Views "rest export" isn't quite built for this.
Answer: No. Core REST & REST Views aren't the right solution here. You don't need a custom module for this.
As you mentioned, JSON API module supports inclusion of entity references in a single resource request. Each entity requested has a property called relationships which are references to other entities that can be included with via the include parameter. References, within references (e.g. a node referencing a media entity, that references a file entity) are supported too, albeit with some work to follow references (e.g. when you a request inclusion via the include property you're given an array property, included, which you still have to sort through via id).
If you're looking for a Drupal API that follows entity references within returned entity objects, you should use the GraphQL module as it will allow you to define your own data spec that can expand entity references as you see fit.

REST for nested paragraphs


MariaDB: Host '127.0.0.1' not privileged

Question: My Ghost instance want to conntect to my MariaDB, but the error is:
Message: 'ER_HOST_NOT_PRIVILEGED: Host '127.0.0.1' is not allowed to connect to this MariaDB server'

Here my my.cnf:
[server]
skip-name-resolve
innodb_buffer_pool_size = 128M
innodb_buffer_pool_instances = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 32M
innodb_max_dirty_pages_pct = 90
query_cache_type = 1
query_cache_limit = 2M
query_cache_min_res_unit = 2k
query_cache_size = 64M
tmp_table_size= 64M
max_heap_table_size= 64M
slow-query-log = 1
slow-query-log-file = /var/log/mysql/slow.log
long_query_time = 1
bind-address = 127.0.0.1

[client-server]
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

[client]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
binlog_format = MIXED
innodb_large_prefix=on
innodb_file_format=barracuda
innodb_file_per_table=1

Answer: I suspect that your problem is that you've set skip-name-resolve.
By default, the MySQL/MariaDB user database contains only entries that allow access from localhost. But if you skip name resolution, then MySQL doesn't translate your connection from 127.0.0.1 to localhost, and thus can't match your connection to any host that's allowed to connect.
Remove skip-name-resolve and try again.
If you really want to keep this option, you'll need to create MySQL users who can connect from ::1 (and 127.0.0.1 if you still use IPv4) while skip-name-resolve is disabled, and then re-enable it.


how to insert data to the database table with hook_update_N

Question: i have just create a table inside the file mymodule.install , the database was created successfully but not for the hook_update_N , 8001,8002 and 8003 , they tell me '[success] No pending updates.' so the hook hook_update_N , 8001,8002 and 8003 does not insert anything
can anyone tell me why please ?
this is my code

/**
 * Installs the database schema.
 */
function mymodule_install() {
  drupal_install_schema('mymodule_post');
}

/**
 * Uninstalls the database schema.
 */
function mymodule_uninstall() {
  drupal_uninstall_schema('mymodule_post');
}

/**
* Creates the tables using the schema API.
*/
function mymodule_schema() {
  $schema['mymodule_post'] = array(
    'description' => 'description ',
    'fields' => array(
      'pid' => array(
        'description' => 'post id',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'title',
        'type' => 'text',
        'not null' => TRUE,
      ),
      'body' => array(
        'description' => 'body',
        'type' => 'text',
        'not null' => TRUE,
      ),
      'created' => array(
              'description' => 'created',
              'not null' => TRUE,
              'mysql_type' => 'timestamp',
            ),
    ),
    'primary key' => ['pid'],
  );
  return $schema;
}

function mymodule_update_8001() {

  //some codes
}

function mymodule_update_8002() {

  //some codes
}

function mymodule_update_8003() {
 //some codes
}
?>

Comment: You're using Drupal 6 code but numbering your updates as if you're using Drupal 8...
Comment: Yup, so it's not going to run 8003 again because it's already done it. Use `drupal_set_installed_schema_version` to reset it
Comment: Really !! , can you show me the code for drupal 8 please
Comment: Just remove the hook_install and hook_uninstall functions, they're not necessary (but also probably not causing your immediate problem). For that, check the module's current schema version with `drush ev "print drupal_get_installed_schema_version('mymodule');"` and see what current state it's in. Seems likely the current installed version is somehow greater than 8001/8002/8003, as your code looks otherwise fine
Comment: current state it's on 8003%
Comment: yes thanks it works now , where can i find this '8003' inside my database to change it without this function
Answer: You have to copy the table definition in a hook_update_n implementation. You can see an example of the this in 8.9.x Layout Builder layout_builder.install file.
https://git.drupalcode.org/project/drupal/-/blob/8.9.x/core/modules/layout_builder/layout_builder.install#L68
/**
 * Implements hook_schema().
 */
function layout_builder_schema() {
  $schema['inline_block_usage'] = [
    'description' => 'Track where a block_content entity is used.',
    'fields' => [
      'block_content_id' => [
        'description' => 'The block_content entity ID.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ],
      'layout_entity_type' => [
        'description' => 'The entity type of the parent entity.',
        'type' => 'varchar_ascii',
        'length' => EntityTypeInterface::ID_MAX_LENGTH,
        'not null' => FALSE,
        'default' => '',
      ],
      'layout_entity_id' => [
        'description' => 'The ID of the parent entity.',
        'type' => 'varchar_ascii',
        'length' => 128,
        'not null' => FALSE,
        'default' => 0,
      ],
    ],
    'primary key' => ['block_content_id'],
    'indexes' => [
      'type_id' => ['layout_entity_type', 'layout_entity_id'],
    ],
  ];
  return $schema;
}

/**
 * Create the 'inline_block_usage' table.
 */
function layout_builder_update_8602() {
  $inline_block_usage = [
    'description' => 'Track where a block_content entity is used.',
    'fields' => [
      'block_content_id' => [
        'description' => 'The block_content entity ID.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ],
      'layout_entity_type' => [
        'description' => 'The entity type of the parent entity.',
        'type' => 'varchar_ascii',
        'length' => EntityTypeInterface::ID_MAX_LENGTH,
        'not null' => FALSE,
        'default' => '',
      ],
      'layout_entity_id' => [
        'description' => 'The ID of the parent entity.',
        'type' => 'varchar_ascii',
        'length' => 128,
        'not null' => FALSE,
        'default' => 0,
      ],
    ],
    'primary key' => ['block_content_id'],
    'indexes' => [
      'type_id' => ['layout_entity_type', 'layout_entity_id'],
    ],
  ];
  Database::getConnection()->schema()->createTable('inline_block_usage', $inline_block_usage);
}

See the inline_block_usage definition is the same in layout_builder_schema() and  layout_builder_update_8602().
layout_builder_update_8602() manually creates the table via
Database::getConnection()->schema()->createTable('inline_block_usage', $inline_block_usage);


Is it possible in Hibernate to add/remove children of a OneToMany relationship without loading all the children?

Question: For the following domain:
class Parent {
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
   Set <Child> children;
)

class Child {
   @ManyToOne
   Parent parent;
   ... // setters, getters, other properties
}

I'm looking for a way to add child entities, without Lazy initializing children in the Parent object.
Ex:
child.set(parent) // is fine, since Parent is pretty lightweight.

parent.getChildren().add(child) // No good, since in this case it will attempt to
//load all the children of a Parent object.

From the first glance it felt like something that should have been easily achievable since in order to add a child all you need is just a parent id and an SQL insert statement to the Child table.
However when it comes to hibernate nothing is simple (In fact it's true for everything that uses caching) :-)
We are trying to scale a legacy application that was initially written to support tens of children,  but over time evolved to operate with thousands of children now and as you can imagine that doesn't scale well, since every time we need to add a child, we need to load the entire group in memory first what results in O(N) time and  O(N) space complexity (where N is a total number of children).
Have anyone run into a similar problem? Is there a way to solve it in hibernate, or hibernate is just not the best framework to use for this use case? How have you tackled it? Or any ideas, share of experience will be helpful.
I run into the following discussion:
"https://stackoverflow.com/questions/41119537/how-to-persist-a-hibernate-child-entity-without-loading-the-parent-side-set-coll"
That felt a bit sketchy to me since evicting cache might cause concurrency issues (especially when code will run on multiple servers)
Answer: Yes, it's possible.
class Parent {
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = PERSIST)
   Set <Child> children = new HashSet<>();

   public void addChild(Child child) {
      child.setParent(this);
      children.add(child);
   }
}
...

parent.addChild(child);

In this case, lazy initialization of Parent.children won't be triggered. You can check it out by enabling SQL logging (spring.jpa.show-sql=true).
EDIT 1
If you store children as Set, then you should override equals and hashCode correctly. Note that Hibernate entity is not a regular DTO. So, generating default implementation won't work properly. According to Hibernate Specification entity should not change its identity (equals/hashCode result) through all the lifecycle.
Here is the example.
@Entity
@Table(name = "ZZ_CHILD")
public class Child {
    ...
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Child)) {
            return false;
        }
        Child other = (Child) o;
        return Objects.equals(id, other.id) && id != null;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}

Or you can replace Set with List and everything is going to work without additional select as well.
Comment: Hm... are you sure about that? I'm seeing select from child table by parent id:

hibernate.SQL - select children0_.parent_PARENT_ID as parent_p3_141_0_, children0_.CHILD_ID as child_id1_141_0_, children0_.CHILD_ID as child_id1_141_1_, children0_.NAME as name2_141_1_, children0_.parent_PARENT_ID as parent_p3_141_1_ from ZZ_CHILD children0_ where children0_.parent_PARENT_ID=?
Comment: Wrapped my trials in a simple spring boot application and pushed it to git:
https://github.com/rbicherschii/stack-overflow/tree/main/parentChildTest

You can run it as:
./mvnw test

And see the hibernate log:
########################################################## RUNNING TEST CASE

########################################################## COMPLETING TEST CASE
Comment: @BickerskyRoman thank for detailed information. I found the source of the issue. I updated the answer
Comment: Oh wow! Thanks Semyon! Changing it to List definitely made it not to do the extra select! So lazy initialization is happening only when you are trying to iterate through the list not just getting an instance of the list, good to know!!!
Comment: Can you think of anything that can be done to remove a child without lazy initializing the entire list of children?
Comment: @BickerskyRoman I think the easiest way is to delete child by id directly
Comment: @BickerskyRoman does that answering question? If so, could you mark my post as an answer, please?
Comment: @SemyonKirekov, this guy got his answer and vanished! not bothering to mark the post as the answer. He is one of a kid. I upvoted your answer however I found a problem in the case of removing an item from the collection. It seems that lazy fetching does not work in this case.
Comment: @Mr.Q Thank you! But what do you mean by "not working"? Can you provide a reproducible example to me?
Comment: @SemyonKirekov as I previously said, remove operation fetches all the Child entities and does not work in a lazy manner. Now I noticed that you have already mentioned this in your GitHub commit message  "Adding test case for removeChild (but it's failing)"  But in general it is a good solution.