random variable, random sum

Question: I have problem to show the following. Maybe someone has an idea :/
Let $X_1,...,X_n$ be i.i.d. copies of a random variable X with $|X|<1$. Let $S_n=X_1+..+X_n$. Then for any $A>0$:
$\mathbb{P}(|S_n-n\mathbb{E}[X]|\geq An)\leq C_A e^{-c_An}$
for some constants $C_A,c_A>0$ depending on $A$.
I have tried this before:
$\mathbb{P}(|S_n-n\mathbb{E}[X]|\geq An)= \mathbb{P}(|\sum_{i=1}^nX_i-\mathbb{E}[X]|\geq An)= \mathbb{P}(|\frac{1}{n}\sum_{i=1}^n X_i-\mathbb{E}[X]|\geq A)\leq \mathbb{P}(\frac{1}{n}\sum_{i=1}^n| X_i-\mathbb{E}[X]|\geq A)$
Comment: What have you tried so far?
Comment: I have tried this before:) (see above)
Comment: I have adjusted my answer, based on your try. Good luck!
Answer:
Hint: Markov's inequality

(Extended version for monotonically increasing functions)
Edit (based on your try):
Let us bring you closer to the right direction. Observe that your problem is a special case of the famous

Hoeffding's inequality, see https://en.wikipedia.org/wiki/Hoeffding%27s_inequality

Essentially, the statement is slightly more general than your scenario, but you will get definitely inspired by its proof! Observe, it makes use of Markov's inequality (as I hinted).
Comment: Thank you very much! I have it! :-)
Comment: You're welcome. It is customary to (upvote and) accept this answer, since the answer has helped you. It would be very kind.

random variable, random sum


Para que serve os { } no código abaixo? e qual a definição?

Question: $objeto->{'getEndereco' . ucfirst($tipo)}()->getCep();

Comment: Parece que você quer fazer isso:

$objeto->getEnderecoComercial()->getCep();
Comment: exato, mas qual a definição? e é uma boa pratica?
Answer: Documentação oficial
Serve basicamente para definir o início e o final do nome do método que deve ser invocado. Como o nome varia conforme o valor de $tipo, fazer apenas:
$objeto->'getEndereco' . ucfirst($tipo)()->getCep();

Irá gerar um erro de sintaxe, pois o PHP não saberá o que fazer com uma constante após o operador ->.

Syntax error, unexpected ''getEndereco'' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

Veja que o próprio erro diz que seria esperado uma T_STRING, que neste caso será apenas getEndereco, sem aspas, ou uma variável ou o caractere {. Ou seja, os caracteres {} indicam ao PHP para interpretar o valor interno como o nome do método e não como uma constante qualquer.
Executar o código apresentado:
$objeto->{'getEndereco' . ucfirst($tipo)}()->getCep();

É análogo a fazer:
$endereco = call_user_func([$objeto, 'getEndereco' . ucfirst($tipo)]);
$endereco->getCep();

Porém, em certas situações fica mais prático apenas encadear as chamadas utilizando {}. É possível, ainda, encadear essa notação. Por exemplo:
$foo = "Hello";
$bar = "foo";

echo "${${'bar'}} world"; // Hello world

Pois {'bar'} é interpretado como bar, então ${'bar'} é tratado como a variável $bar, cujo valor é "foo". Logo, {${'bar'}} será interpretado como foo e ${${'bar'}} será tratado como a variável $foo, exibindo seu conteúdo, "Hello".

Em versões PHP 7+ é possível, também, utilizar {} junto com use para importar múltiplas classes de um mesmo namespace:
use Meu\Namespace\{ClasseA, ClasseB, ClasseC};

Em versões anteriores seria necessário fazer:
use Meu\Namespace\ClasseA;
use Meu\Namespace\ClasseB;
use Meu\Namespace\ClasseC;

Comment: Não conheço reflection do java, vou dar uma pesquisada, vlw.
Comment: @ALE_ROM, para mais fonte sobre `reflection` em Java: https://stackoverflow.com/a/37632/4438007; mas como eu e o AndersonCarlosWoss conversamos no chat, é muito forçada a comparação, até removi meu comentário que comparava
Answer: Isto serve para accesar o objeto de forma dinâmica. Vamos supor que o $tipo tenha o seguinte conteúdo:
$tipo = 'Residencial';

// Forma correta dinâmica
$objeto->{'getEndereco' . ucfirst($tipo)}()->getCep();

// Forma correta direta
$objeto->getEnderecoResidencial()->getCep();

// Todas as duas opções acima irão acessar a função do objeto e obter o getCep:
$objeto->getEnderecoResidencial()->getCep;

// Formas INcorretas
$objeto->'getEndereco' . ucfirst($tipo)()->getCep();
$objeto['getEndereco' . ucfirst($tipo)]()->getCep();
$objeto['getEnderecoResidencial']()->getCep();

Answer: Em PHP há N formas de se escrever uma string, uma delas é a chamada Sintaxe complexa.
O nome não é realmente devido a complexidade da sintaxe, mas sim devido à expressões complexas que podem ser escritas desta maneira.
Conforme a própria documentação:

Qualquer variável escalar, elemento de um array ou propriedade de um
  objeto com uma representação de uma string pode ser incluída com essa
  sintaxe. Simplesmente escreva a expressão da mesma forma como
  apareceria fora da string e então coloque-o entre { e }. Já que que {
  não pode escapado, esta sintaxe será somente reconhecida quando o $
  seguir, imediatamente, o {. Use {\$ para obter um literal {$.


Create object with properties and values from another object using ES6 object destructuring

Question: I'm constantly confused whether object destructuring in javascript applies in certain situations, and I've just come across one. In this code I am simply taking properties from the this object and assigning them to the same property/value on a new data object:
const data = {
    rating: this.rating,
    title: this.title,
    text: this.text,
    name: this.name,
    location: this.location,
    email: this.email,
    files: this.files
};

Can some sort of object destructuring be used to accomplish this instead or is it unrelated to this use-case?
Comment: Did you want ALL properties or selected ones
Comment: @JaromandaX Just the selected ones I show in the example.
Answer: You can use the spread operator if you want all the own properties of this:
const data = {
  ...this
}

If you only need a selective few, you can delete the unnecessary properties afterwards, or set them to undefined (although that's different from non-existent/deleted properties):
const data = {
  ...this,
  unwantedProp: undefined,
}

Comment: That's not destructuring, that's only spread syntax use.
Answer: You could use something like this
const choose = (src, ...keys) => keys.reduce((result, key) => ({ ...result, [key]: src[key] }), {});

example usage

const choose = (src, ...keys) => keys.reduce((result, key) => ({ ...result, [key]: src[key] }), {});

const src = {
    rating: 1,
    title: 2,
    text: 3,
    name: 4,
    location: 5,
    email: 6,
    files: 7,
    not_me: 8
};

const data = choose(src, 'rating', 'title', 'text', 'name', 'location', 'email', 'files');
console.log(data);

In your case, you'd use this instead of src when calling choose
Comment: Very cool solution. Though I was more curious if there was a simple way to do this inline with destructuring. I was not looking to create a new function like you have with `choose`. Seems like the answer may just be "no".
Comment: No, can't think of anything without creating a function


How to adapt the equations for stochastic gradient descent for batch gradient descent for neural networks?

Question: I'm following along this lecture on neural networks. The professor derives equations for the gradient of $e(w)$: $\frac{\partial e(w)}{w_{ij}^l}$ for every $w_{ij}^l$ where $e(w)=e(h(x_n),y_n)$ is the error on one data point $(x_n,y_n)$ and $w$ are the weights in the network.
For a node, $s$ is the input and $x=\theta(s)$ the output after applying some activation function $\theta$. Here, $0 \leq i \leq d^{l-1}$ represents the input layer, $1 \leq j \leq d^{l}$the output layer, and the network has $1 \leq l \leq L$ layers.
Starting at around the 50:00 mark, $\frac{\partial e(w)}{w_{ij}^l}$  is found to equal $\frac{\partial e(w)}{s_j^l}\frac{\partial s_j^l}{w_{ij}^l} =\delta_j^l x_i^{l-1}$. For the final layer, $\delta_1^L=\frac{\partial e(w)}{\partial s_1^L}$ can be calculated directly since $e$ is a function of $s_1^L$ and $y_n$. Then for every layer before the final layer, $\delta_i^{l-1}=\frac{\partial e(w)}{\partial s_i^{l-1}}=\sum_{j=1}^{d^l}\delta_j^l w_{ij}^l\theta'(s_i^{l-1})$.
These equations were derived with stochastic gradient descent in mind, but I'm wondering how they can be modified for mini-batch (or batch) gradient descent?
Comment: The changes you have calculated for each training example just need to be accumulated over many training examples (the size of the batch) so that the total changes can be applied ever few examples.
Comment: @ajax2112 My question is how this accumulation is computed, for a batch size $B$, do we accumulate the gradient for each point in the batch (after $B$ backpropagations) then average them, or is it something more complicated?
Comment: Yes you accumulate the gradient for each point in the batch across the batch. However, it is common to take a sum of all of these gradients rather than an average, given that some of the values will be positive and some will be negative you can kind of treat them like a sum of vectors.
Answer: Let $e_k$ be the error when you input the $k$-th training sample in a batch of size $B$. The gradient calculation will be modified as follows:
$$\nabla_w (e)=\sum_{k=1}^B\nabla_w(e_k)$$
When $B=1$ it becomes SGD update, when $B$ is the full training size it becomes batch update, and when in between it becomes mini-batch GD.
Comment: Are we doing backpropagation for each point individually then averaging each $\frac{\partial e(w)}{w_{ij}^l}$ for all points in the batch? So for a batch size $B$, we do both forward and backpropagation $B$ times but the weight are updated at a different frequency as determined by $B$?
Comment: correct @Yandle, average or sum (doesn't matter because we can adjust learning rate). And, weights are updated when the batch is finished.
Comment: One question. weight derivative in stochastic gradient descent includes product of delta for next layer and input for current layer as op mentioned in his post. When moving to batch gradient descent which input should we choose? `δljxl−1i ` - In this the x part can be multiple values, do we average these as well?
Comment: Each summand (gradient) here is obtained for a single input, and the gradients are accumulated/averaged. The expression $\nabla_w(e_k)$ has the input expressions in it, so this is already accounted there.


Sticky header jumps when scrolling in Internet Explorer

Question: There's a sticky red bar in a container in the middle of a page. I want this red bar to stay on top when scrolling down and stop before the end of the grey container. Without using position fixed for the collapsed red bar (which caused some problems when I tried it), how can this be accomplished without the red bar jumping in Internet Explorer? Here's a much simplified version of what I am working on to demonstrate what I have so far.
http://codepen.io/codingninja/pen/aKmno
Here's the jQuery I'm using:
var initialHeight = 0;
var wrapperHeight = 0;
$(document).ready(function(){
  wrapperHeight = $('.wrapper').outerHeight();
  initialHeight = $('.sticky-header').outerHeight();
});
$(window).scroll(function(){
  var stickyContainer = $(".sticky-header");
  var containerTop = $(".wrapper").offset().top;
  var containerDistance = containerTop + wrapperHeight;
  var containerLength = stickyContainer.length;
  if(containerLength > 0) {
    var currentPos = $(this).scrollTop();
    var height = initialHeight;
    if(currentPos > containerTop && currentPos + initialHeight < containerDistance) {
      stickyContainer.addClass("collapsed");
      stickyContainer.css("top", Math.max(0, $(this).scrollTop()-containerTop));
      $('.filler').css("height", height);
    }
    else {
      stickyContainer.removeClass("collapsed");
      stickyContainer.css("top", "auto");
      $('.filler').css("height", 0);
    }
  }
});

Thanks in advance.
Answer: I found the answer. Position fixed actually does work, but there is one case where it is inconsistent in Chrome and Firefox in regards to widths within the sticky header for what I am working on. It's not in the demo, but this issue may be able to be solved with some thinking.
CSS change
.collapsed {
  height: 50px;
  font-size: 20px;
  position: fixed;
  top: 0;
}

JQuery
var initialHeight = 0;
var wrapperHeight = 0;
$(document).ready(function(){
  wrapperHeight = $('.wrapper').outerHeight();
  initialHeight = $('.sticky-header').outerHeight();
});
$(window).scroll(function(){
  var stickyContainer = $(".sticky-header");
  var containerTop = $(".wrapper").offset().top;
  var containerDistance = containerTop + wrapperHeight;
  var containerLength = stickyContainer.length;
  if(containerLength > 0) {
    var currentPos = $(this).scrollTop();
    var height = initialHeight;
    if(currentPos > containerTop && currentPos + initialHeight < containerDistance) {
      stickyContainer.addClass("collapsed");
      $('.filler').css("height", height);
    }
    else {
      stickyContainer.removeClass("collapsed");
      $('.filler').css("height", 0);
    }
  }
});

Comment: This solution is still not perfect. The sticky jumps when it reaches a certain point in scrolling.


Find the volume bounded by the $xy$ plane, cylinder $x^2 + y^2 = 1$ and sphere $x^2 + y^2 +z^2 = 4$

Question:
Find the volume bounded by the $xy$ plane, cylinder $x^2 + y^2 = 1$ and sphere $x^2 + y^2 +z^2 = 4$.

I am struggling with setting up the bounds of integration.
First, I will calculate the 'first-quadrant' piece of the volume.
$z$  will traverse from $0$ to $2$.
$x$ should start from the cylinder and go to the edge of the current circle of the sphere:
$$\sqrt{1-y^2} \le x \le \sqrt{4-x^2-z^2}$$
However, the same applies to $y$: (I am only calculating half of the volume right now, where the smaller circle is the lower bound):
$$\sqrt{1-x^2} \le y \le \sqrt{4-y^2-z^2}$$
However, this cannot work as both $x$ and $y$ are dependent.
What is the error?
Comment: Another thing: I understand what is the region bounded by the sphere and the cylinder. But what does it mean to add the $xy$ plane to the picture. It just divides the previous region in two.
Comment: I'm going to suggest that you draw a picture of the $y = 0$ slice of this situation. That should give you some insights on how best to set up the integral. (In particular, you'll have to decide what "bounded by" means, which isn't clear to me at all, and I've assigned hundreds of problems like this over the years...)
Comment: Of course, you did not mean $x^2+x^2=1$. What did you mean?
Comment: @JoséCarlosSantos Thank you for pointing this out. Fixed!
Comment: Apparently @JoséCarlosSantos and I are thinking along the same lines. :)
Comment: If you start with $z$-limits between $0$ and $2$ then your next step is to consider sections of the body with $z=$const, which makes it necessary to split your integral in two parts (sections with the cylinder and those with the sphere). It is less convenient then to introduce the cylindrical coordinates from the beginning.
Answer: Let $f(x, y) = \sqrt{4-(x^2 + y^2)}$ be the function which for each point closer than $4$ to the origin of the $xy$-plane gives the height of the top half of $x^2 + y^2 + z^2 = 4$ over that point. Then what you want is the integral of this function, over the unit disc.
Expressed in polar coordinates, this is given by
$$
\int_0^{2\pi}d\theta\int_0^1r\sqrt{4-r^2}dr
$$
Answer: There are several ways to calculate the triple integral
$$
V=\iiint_B\,dxdydz
$$
where $B$ is a tower (cylinder) with a roof (sphere).
One way as you do is to split the integration as
$$
V=\int_0^2\Big(\iint_{B_z}\,dxdy\Big)dz.
$$
Here $B_z$ is the intersection of the body $B$ with the plane of constant $z$ (horizontal slices). It is troublesome as the body should be split into two parts (one for the tower and one for the roof). It is more convenient here to do the vertical splitting
$$
V=\iint_{x^2+y^2\le 1}\Big(\int_0^{\text{top of the sphere}}dz\Big)dxdy.
$$


Java script: obter o elemento por ID diz que é NULL

Question: Estou aprendendo a programar em javascript e fiz um pequeno código para fazer a soma de dois números. Eu coloquei para que o resultado fosse sobreescrito em cima de "resultado", mas isso não é feito. Ao usar o inspecionar elemento do chorme ele diz que 'out1' não pode receber null.

Trecho de código em HTML:

Fazendo a soma

<input type="number" name="txtn1" id="n1" />
<input type="number" name="txtn2" id="n2" />
<input type="button" value="Calcular" onclick="somar()" />

Resultado

Comment: Vc tem que pegar os valores dentro da função e faltou colocar `.value`, além das aspas como citado na resposta abaixo.
Answer: O nome do ID tem que ser passado como string.
Ao invés de (n1) e (n2), tem que ser ('n1')  e ('n2') ou  ("n1")  e ("n2"), aspas simples ou duplas para indicar que é string.
Outro ponto é que precisa informar o que deseja do elemento, o que no caso, você deseja o valor do mesmo, logo tem que adicionar o ".value" ao final.
Depois é que tudo se repete a cada vez que clicar no botão, então tudo faz parte da função somar, ou seja, move-se tudo para dentro da função.
Exemplo corrigido e funcionando no snippet abaixo:

function somar() {

    var n1 = window.document.getElementById('ns1').value; // <<-- Aqui é 'n1' com aspas simples ou duplas

    var n2 = window.document.getElementById('n2').value; // <<-- Aqui é 'n2' com aspas simples ou duplas

    var n11 = Number.parseFloat(n1);
    var n22 = Number.parseFloat(n2);
    var result = n11 + n22;
    var out1 = window.document.getElementById('out');
            out1.innerHTML = `${result}`
}

Fazendo a soma

<input type="number" name="txtn1" id="ns1" />

<input type="number" name="txtn2" id="n2" />

<input type="button" value="Calcular" onclick="somar()" />

Resultado:

Espero ter ajudado.
Comment: Obrigado. Sua resposta e a do colega abaixo me ajudou a solucionar a dúvida.
Comment: Fiz as alterações recomendadas mas ainda sem funcionar.
Comment: Ajustei a resposta lá com os ajustes, agora está 100%.
Answer: Há alguns erros no seu código, vamos por partes.
1º) Para pegar um elemento HTML com o método document.getElementById(), você deve passar para ele uma string, o que não acontece. Você está passando aí uma variável, só que nessa variável não tem o nome do elemento HTML que deseja pegar.
2º) O mesmo acontece dentro da função somar(), onde, em vez de uma string, você passa uma variável para o método document.getElementById(). Portanto, quando você passa um argumento para um método sem o uso de aspas, o interpretador vai entender que aquele argumento é uma variável, constante, função, etc. Quando ele não encontra, dá um erro, como acontece no seu código.
3º) Com o método document.getElementById(), você está tentando pegar o elemento, não o valor que está dentro dele. Para pegar o valor de um  input, você deve fazer document.getElementById('nomeDoElemento').value.
Dito isso, teoricamente seu código deve funcionar assim:

    n1 = window.document.getElementById('n1').value;
    n2 = window.document.getElementById('n2').value;

    function somar() {
        var n11 = Number.parseFloat(n1);
        var n22 = Number.parseFloat(n2);
        var result = n11 + n22;
        var out1 = window.document.getElementById('out');
        out1.innerHTML = `${result}`
    }

Fazendo a soma

<input type="number" name="txtn1" id="n1" />
<input type="number" name="txtn2" id="n2" />
<input type="button" value="Calcular" onclick="somar()" />

Resultado

No entanto, ele AINDA NÃO FUNCIONA COMO O ESPERADO. A gente recebe um NaN (not a number) quando clicamos no botão somar, isso porque, quando clicamos, dentro da função somar(), n1 e n2 são null. O motivo pelo qual elas são null, é que estão declaradas no topo do código, e como o código é interpretado de cima para baixo, ao passar por essa parte do código, o interpretador tenta atribuir o valor do input a eles, MAS O INPUT AINDA NÃO FOI REDENRIZADO NESSA PARTE, ou seja, ainda não existe.
Para contornar isso, podemos, por exemplo, declarar as variáveis n1 e n2 somente dentro da função somar(), assim, quando clicarmos no botão somar, teremos a certeza de que eles não receberão null, visto que os inputs (elementos HTML) já terão sido renderizados.
Assim, o código correto é o seguinte:

    function somar() {
        var n1 = window.document.getElementById('n1').value;
        var n2 = window.document.getElementById('n2').value;
        var n11 = Number.parseFloat(n1);
        var n22 = Number.parseFloat(n2);
        var result = n11 + n22;
        var out1 = window.document.getElementById('out');
        out1.innerHTML = `${result}`
    }

Fazendo a soma

<input type="number" name="txtn1" id="n1" />
<input type="number" name="txtn2" id="n2" />
<input type="button" value="Calcular" onclick="somar()" />

Resultado

Comment: Obrigado, resolveu meu problema. E obrigado por dispor do seu tempo para explicar detalhadamente, me ajudou a entender melhor.


Missing data per questionnaire for a specific group

Question: I am trying to view how many missing I have per questionnaires for a specific group of participants. i.e.
I have a dataframe i.e.
id Result QA1 QA2 QA3 QA4 QA5 QA6 QB1 QB2 QB3 QB4 QB5 QB6
1   1      1   3    2   2  3   3   3  NA    1   1  2   1
2   1      2   NA    2   2  2  1   1   3    2   1  2   3
3   2      3   2    3   1  1   1   2   1    1   NA 3  NA
4   1      2   1    NA  3  2   NA  1   3    3   1  2   1
5   6      1   1    3   2  1   3   2   1    1   1  1  NA

Say I want to know how many missing there are in questionnaire A for all results that are coded by 1, how can I do this? Any suggestions?
Comment: Please provide reproducible example. You can use `dput()` to get it
Comment: Something like ``sum(is.na(yourdataframeorcolumn))`` can help.
Comment: Yes, however this only gives me the missing for that column. What I want is the missing for 28 different columns given a specific result (result is also a column) so I want the missings for say column 1:28 given that column 29 = 1
Comment: @Sotos I can't provide the data I am working with that's why I only put the column names as an example
Comment: You can create sample dummy data. In general have in mind that the best way to get help here in SO, is to include reproducible example and expected output. [Have a look at this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)
Comment: I updated my question. Thanks!
Answer: You can create a function which takes as arguments the dataframe, the questionnaire and the code, i.e.
fun1 <- function(df, questionnaire, code){
  d <- sum(is.na(df[df$Result == code,grepl(questionnaire, names(df))]))
  return(d)
}
fun1(df, 'A', 1)
#[1] 3

fun1(df, 'B', 1)
#[1] 1

fun1(df, 'A', 2)
#[1] 0


How to check if something is in a subspace?

Question: Can someone help me with this problem ?

Show that for  every $A$,$B$ $\in {U}$ : $AB-BA \in {U}$

$$U:=\bigl\{A \in \mathbb{R}^{3\times3} \mid \operatorname{Tr}(A)=0 \bigr\} $$
Comment: So you need to show that the trace of $AB-BA$ is $0$. Equivalently (by linearity) $tr(AB)=tr(BA)$. This is a property of the trace function.
Answer: To write the comment of @JustDroppedIn as an answer,
let $U:=\bigl\{M \in \mathbb{R}^{3\times3} \mid \operatorname{Tr}(M)=0 \bigr\},$ and take any $A,\;B \in U.$
Let $C=AB-BA.$  The trace is a linear map, so Tr$(C)=$Tr$(AB)-$T$r(BA)$.
Furthermore, Tr$(AB)=$Tr$(BA).$
(That can be shown from the component-wise definitions of matrix multiplication and trace.)
Thus, Tr$(C)=0$ and $C \in U$.

Note that we did not need to use the fact that Tr$(A)=$Tr$(B)=0$ to prove that Tr$(AB-BA)=0.$
For any two $n\times n$ matrices, the trace of their commutator vanishes.


Is this function strongly convex?

Question: Let $A,B$ be two intervals in $\mathbb R$ and let $f:A\times B\to \mathbb R$ be a continuous function.
Assume that $f$ is convex in both $x$ and $y$.
Is the following function $g:A \to \mathbb R$  strongly convex w.r.t. the Euclidian norm?
$$g(x):=\int _{B} |f(x,y)-f(x_1,y)|^2dy.$$
Comment: what about $f(x,y) = x^2-1$ for $A= [-1,1]$ and $x_1 = 1$?
Answer: @user251257 is correct: the function $f \colon [- 1, 1] \times [0, 1] \to \mathbb R$, $(x, y) \mapsto x^2$ is convex in both arguments and continuous.
Let $x_1 \in [- 1, 1]$.
Then
\begin{equation*}
g(x)
= \int_{0}^{1} | x^2 - x_1^2 |^2 \, \text{d}y
= (x^2 - x_1^2)^2
\end{equation*}
is not strongly convex: for $x \in [-1, 1]$ we have
$$
\nabla^2 g(x)
= 12 x^2 - 4 x_1^2
$$
and for e.g. $x = 0$ and $x_1 \ne 0$ this is negative.

Is this function strongly convex?


Dendrogram in Hybrid Hierarchical Clustering and Cut-off criterion (Calinski-Harabasz presently)

Question: I have questions regarding the dendrogram and the cut-off related to hybrid hierarchical clustering performed on data, as depicted below and taken from this paper

Questions regarding Panel A (dendrogram)

The clustering itself is done using the Euclidean Distance - however the dendrogram is depicted using the squared Euclidean Distance. They don't explain why that is in the paper - is there a common reason for doing so?
In the corresponding paper, it is mentioned that the similarity and dissimilarity are calculated by comparisons on a subject-to-subject basis. Now regarding the dendrogram, I understand that I can read the y-axis as follows: For instance C1a and C1b are around 700 units apart from each other, whereas C1 and C2 are over 2000 units apart (and hence more distinct).
My question however: The vertical line corresponding to C1b is longer than the vertical line corresponding to C1a. Does that mean that the subjects in C1b have a different range (bigger) of distances between each other than those in C1a? Does the distance between C1a and C1b correspond to the maximal distance found between subjects within each of the clusters?

Questions regarding Panel B (CHC criterium)
The paper states the following: "Panel (B) shows the Calinski-Harabasz criterion (..) Because the CHC did not exhibit a typical pattern (i.e. elevation at some cluster level), we defined stability (i.e. minimal change from one cluster number to the next) as our goal in deciding where to cut the dendrogram."

I am not sure if I understand this - would you not want to chose the
number of clusters which is in terms of CHC most distinct from
another choice of numbers? And, maybe more importantly: Since the CHC
is more and more decreasing here, does it make any sense to chose
more than 2 clusters?

Many thanks - any help is greatly appreciated,
Pegah
Answer:
The clustering itself is done using the Euclidean Distance - however
  the dendrogram is depicted using the squared Euclidean Distance. They
  don't explain ...

From the looks of the dendrogram one might suppose they have used Ward's linkage or something similar. It optimizes SSwithin and traditionally Y axis on the dendro with that method shows pooled SSwithin or squared distance, see. This link also warns against relying on the look of Ward's dendrogram like that.

Does that mean that the subjects in C1b have a different range
  (bigger) of distances between each other than those in C1a?

Vertical branch length is the leap of decompression a group experience when it gets merged with some other group. But specific meaning of "decompression" depends on the linkage method.

Since the CHC is more and more decreasing here, does it make any sense
  to chose more than 2 clusters?

To me, no. In this particular example, it is pretty obvious that the 2-cluster solution is the best, according to CH criterion. We, however, don't know if it is any better than 1-cluster solution (i.e. no clusters) - to check for that, I would recommend to plot the data to inspect visually; you might also want to use Gap criterion which, by simulations, can test for 1-cluster solution.
On the other hand, it is true that one should - in general case - pay attention also to potential sharp elbows on such plots, - not only to the peaks (or canyons), see. This is because clustering criterions (like CH) are difficult to "standardize": they have their own biases, including "biases" towards k of clusters. CH, for example, often prefers more clusters than, for instance, BIC criterion which penalizes for k.
Still, in your current example I can't think out a justification for authors' we defined stability (i.e. minimal change from one cluster number to the next) as our goal in deciding where to cut the dendrogram without knowing their context, and the word stability looks to me strange here. I see no anything ragged / elbows on the plot except that between 2 and 3.
Internal clustering criterions such as CH are only one of several ways to select k or to validate clustering results.
Comment: `Decompression` [linkage methods](http://stats.stackexchange.com/a/217742/3277) differ in how they define distance between two clusters (groups, sets of points). Hence, the closer are the 2 clusters are when they merge (i.e. the lower they merge on the dendro) - the more _dense_ is the emergent cluster. The distance represent density of the new cluster. So, vertical branches - their lengths - tell of the amount of decompaction the cluster receives at its birth.
Comment: Many thanks, that was already very helpful. The paper seems to be quite incomplete in the description of the methods used unfortunately. "Decompression": Could it be understood roughly as the change from the maximal (or alternatively: minimal etc.) distance between points in a cluster? Linkage: The only thing they mention which I did not refer to is that they perform hybrid clustering with "tree-structured vector quantization" (with reference to some standard text book), though I thought that is just a way to represent the data. On the specific subject, it is just clustering of psychological..
Comment: ..profiles of subjects (each subject has 6 dimensions on which they can have some score)..


How to inter change of norm and limit in the Banach algebra?

Question: Let $f\in L^{1}(\mathbb T)$ and define the Fourier coefficient of $f$ : $\hat{f}(n)=\frac{1}{2\pi} \int _{-\pi}^{\pi} f(t) e^{-int} dt; (n\in \mathbb Z)$.Consider the space,
 $$A(\mathbb T):= \{f\in L^{1}(\mathbb T): \hat{f}\in \ell^{1}(\mathbb Z), \  \text {that is,} \  \sum_{n\in \mathbb Z} |\hat{f}(n)| < \infty \}.$$
$A(\mathbb T)$ is normed by the $L^{1}-$ norm on $\mathbb Z$:
$$||f||= \sum_{n\in \mathbb Z} |\hat{f}(n)| < \infty; \ \text {for} \ f\in A(\mathbb T). $$
We also note that $A(\mathbb T)$ is a Banach algebra under pointwise addition and multiplication.
Fix $r\in (0, \infty)$, and let $f\in A(\mathbb T)$ such that $||f|| \leq r$ and for this $f$; I want estimate for norm of $e^{if}$ like this, $||e^{if}||\leq e^{r}$.
Here is my attempt:
Note that, $e^{if}= \sum_{n=0}^{\infty}\frac{(if)^{n}}{n !} = \lim_{N\to \infty} \sum _{n=0}^{N} \frac{(if)^{n}}{n!}  $; so
$$||e^{if}||= ||\lim_{N\to \infty} \sum _{n=0}^{N} \frac{(if)^{n}}{n!}|| \leq  \lim_{N\to \infty} ||\sum _{n=0}^{N}\frac{(if)^{n}}{n!}||$$
My question is: How do I justify the above inequality: the inter change of norm and limit ?
(Once I do that, then I think, $\lim_{N\to \infty} ||\sum _{n=0}^{N} \frac{(if)^{n}}{n!}||\leq \lim {N\to \infty} \frac{||(if)^{n}||}{n !}$ (by triangle inequality of norm)) and then by algebra property ($||fg||\leq ||f||\cdot || g ||$) and norm propery ($||\alpha f||= |\alpha| ||f||$); we get, $\lim_{N\to \infty} ||\sum _{n=0}^{N} \frac{(if)^{n}}{n!}|| \leq \lim_{N\to \infty} \frac{||f||^{n}}{n!}$ and since $||f||\leq r$, we will get, $\lim_{N\to \infty} ||\sum _{n=0}^{N} \frac{(if)^{n}}{n!}||\leq e^{r}$ )
Or, am I missing something completely and  I need to change my approach ? Bit vague question: Can we expect to do such things in any Banach algebra or there is something special about $A(\mathbb T)$ ?
Answer: In every Banach space absolutely convergent series converge and you have
$$\|\sum_{n=0}^\infty x_n\|\le \sum_{n=0}^\infty \|x_n\|.$$ The proof is exactly as in the case of real or complex numbers (the partial sums form a Cauchy sequence and the bound for the norms of the partial sums carries over to the limit). Therefore, your attempt is perfectly okay.
Comment: Prof. J ; thanks a lot; -\).


How to prove that the French railways metric is a metric

Question: I am trying to work just one case of showing that the French railways metric defined by a metric space $(\mathbb{R}^2,d)$ is actually a metric:
$$d(x,y) = \begin{cases} \|x-y\|, & \text{if $x,y,0$ are collinear;} \\
\|x\| +\|y\|, & \text{otherwise} \end{cases}$$
I am trying to show the case that if $x=y$, then $d(x,y)=0$. I have been able to show that if $x=y$, then $\|x-y\|=0$, but am having a hard time showing that if $x=y$, then  $\|x\| +\|y\|=0$. Thank you!
Comment: The second case is irrelevant, $x,x,0$ are collinear.
Answer: If $x=y$ then we have that $x,y,0$ are collinear since $x,x,0$ i.e. $x,0$ are always collinear.
So in case $x=y$ we have $d(x,y)=\|x-y\|=\|x-x\|=\|0\|=0$
(There is no need to consider $d(x,y)=\|x\|+\|y\|$)


View display plugin "entity reference" not using translation

Question:
UPDATE: This bug was just fixed in Issue
  2174633 and
  Drupal v8.7.9 will no longer have this problem.

For some of my entity reference fields I'm using "Views: Filter by an entity reference views" as reference method. I've configured those views to use the current interface language for rendering (with fallback to default lang).

The interface language selection basically works (in other view blocks, or when previewing in /admin/structure/views), but it does not work when used as source for an entity reference field:

In my admin interface I'm using I've got a paragraph with an ER field using such a view as source. The paragraph always shows the title in default lang
On the frontend I've got a webform select field using the same view as source. The select options are always rendering in default lang.
When using the default reference method I do get translated titles in both use cases.
As stated above, the correct language is used in preview on /admin/structure/views

How can I select the correct language for my view-filtered ER fields?
(Please note that I can not use the interface language as filter criteria, because this would disable the language fallback.)
Comment: Under filter criteria section, remove "Content: Default translation" and add "
Content: Translation language (= Interface text language selected for page)"
Comment: This would disable the fallback functionality to default language if the entity is not translated into the current interface language.
Comment: Facing the same problem. I'm using the view for getting the list of ER. And inside the view titles are translated. But when I'm using the view from webform module for selecting the options I'm always getting content titles in default language. @Hudri, did you find solution for this?
Answer: Comparing TermSelection::getReferenceableEntities and ViewsSelection::getReferenceableEntities it seems like the Views entity reference selection plugin doesn't translate the entity before returning the entity labels. It should work with a core patch adding one line:
/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php:
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
  $display_name = $this->getConfiguration()['view']['display_name'];
  $arguments = $this->getConfiguration()['view']['arguments'];
  $result = [];
  if ($this->initializeView($match, $match_operator, $limit)) {
    // Get the results.
    $result = $this->view->executeDisplay($display_name, $arguments);
  }

  $return = [];
  if ($result) {
    foreach ($this->view->result as $row) {
      $entity = $row->_entity;
      // add this line to translate the entity
      $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity);
      $return[$entity->bundle()][$entity->id()] = $entity->label();
    }
  }
  return $return;
}

Edit:
This won't be necessary anymore, when https://www.drupal.org/project/drupal/issues/2174633 is fixed, then resolving the underlying problem, that the selection plugin ignores the views output.
Comment: @JDrupal, this code means that the rendered output you configure in UI and you see in the preview doesn't matter. The selection plugin uses the configured display only for the SQL query to get the filtered entities. So the only thing matters is the filter for the default translation to avoid duplicates. The added `getTranslationFromContext` method gets the best translation candidate fitting the context, if there is no translation then the original entity is returned.
Comment: Will this work if the entity doesn't have a translation?
Comment: This solution works fine for me.
Comment: This solution does work for me. One minor caveat though: After applying this patch, you no longer can force a foreign `Rendering language` (see middle column in Views UI), it will *always* use the translation context (e.g. you no longer can create a german page and force the view to display translated english node titles within the german page).
Comment: You could never do this as explained in the last comment, also the fields selected are ignored and it's always the title which is displayed. You have to wait until the the issue mentioned in the edit is fixed. Then you can configure the rendered result in UI, like select and format fields and choose the rendering language.
Answer: Here's a UI solution if you don't want to apple a core patch.
You'll need to use the translation_views module.
Here's a screenshot of the needed filter configuration:

The logic is simple, if the node has no translations then show the original language, otherwise show the translation language.
I use the translation_views module to get the Translation counter filter.
Comment: Interesting approach, I'm already using translation_views on my projects, but can't test it right now due workload. Why are you using `Original language = Site default` instead of `Default translation = true` in the first filter group? I think with default translation the fallback would work in both directions, while original language would only work one-way from default to other.
Comment: I think that was a mistake, updated the answer. Looking forward to hear from you when you have tested it :)
Comment: I've tested this and it does not work for me, I still do get the default/original language. I think that the filter logic is correct, but I guess this solution is afftected by the same bug as described by @4k4's answer
Comment: Seems strange are you using the latest version of Drupal core, and have you remembered to use OR between the filter groups in views?
Comment: No, not using dev, I'm running latest stable v8.7.6. This answer certainly is interesting for people without composer, but I'm using `cweagans/composer-patches` so core patches are no problem for me.
Comment: It worked for me using 8.7.6 but maybe you need to apply the patch.
Comment: After applying the patch from the other answer this filter logic does work. But after applying patch the original logic from the question also works, so this solution sadly does not really help. But using translation counter was an interesting idea, thanks for your work. To bad it is affected by the same bug, this workaround would have been helpful for folks who don't want to patch core.
Comment: OK, it's cool that it now works!!
Comment: Maybe I just am not following, but does this force the view to render in the languages that you specify?
Answer: I have created a patch for @4k4's answer that also uses dependency injection.
To apply this patch:
Take the code snippet below and paste it into a new file e.g test.patch.
Then run git apply /path-to-file/test.patch.
For a UI only solution, see my other answer.
diff --git a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
index 79707af..e092ba9 100644
--- a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
+++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
@@ -4,6 +4,7 @@

 use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
+use Drupal\Core\Entity\EntityRepositoryInterface;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Core\Extension\ModuleHandlerInterface;
 use Drupal\Core\Form\FormStateInterface;
@@ -59,6 +60,13 @@ class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPlug
    */
   protected $currentUser;

+  /**
+   * The entity repository.
+   *
+   * @var EntityRepositoryInterface
+   */
+  protected $entityRepository;
+
   /**
    * Constructs a new ViewsSelection object.
    *
@@ -74,13 +82,16 @@ class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPlug
    *   The module handler service.
    * @param \Drupal\Core\Session\AccountInterface $current_user
    *   The current user.
+   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
+   *   The entity repository.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, EntityRepositoryInterface $entityRepository) {
     parent::__construct($configuration, $plugin_id, $plugin_definition);

     $this->entityTypeManager = $entity_type_manager;
     $this->moduleHandler = $module_handler;
     $this->currentUser = $current_user;
+    $this->entityRepository = $entityRepository;
   }

   /**
@@ -93,7 +104,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $plugin_definition,
       $container->get('entity_type.manager'),
       $container->get('module_handler'),
-      $container->get('current_user')
+      $container->get('current_user'),
+      $container->get('entity.repository')
     );
   }

@@ -231,6 +243,7 @@ public function getReferenceableEntities($match = NULL, $match_operator = 'CONTA
     if ($result) {
       foreach ($this->view->result as $row) {
         $entity = $row->_entity;
+        $entity = $this->entityRepository->getTranslationFromContext($entity);
         $return[$entity->bundle()][$entity->id()] = $entity->label();
       }
     }

Comment: I successfully applied this patch on Drupal v8.7.6 and it worked for me. Thanks!
Comment: So... why has this not being put into a bug ticket for Drupal?


Como Ler este json com PHP

Question: Como faço para ler esse arquivo JSON com PHP.
Tentei desta forma, porém não não funciona.
<?php

    $json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

    $obj = json_decode($json_str);

    foreach ($obj as $objeto){

        echo "numero: ".$objeto->numero;

        foreach ($objeto as $item){

            echo "Mensagem: ".$item->message. " - ";
            echo "Nível: ".$item->level. "
";
        }

        foreach ($objeto as $responsavel){

            echo "NOME: ".$item->nome;

        }

    }

?>

Answer: O json que apresentou não tem arrays é tudo objetos, por isso não fará sentido usar foreach para percorrer.
Para aceder aos campos que está a tentar aceder no código pode fazer assim:
echo "numero: ".$obj->numero;
echo "Mensagem: ".$obj->log->message. " - ";
echo "Nível: ".$obj->log->level. "
";
echo "NOME: ".$obj->responsavel->nome;

Exemplo no Ideone
Para conseguir usar os foreachs que tem no código, o json tinha que estar assim:
[{
    "numero": "1000",
    "log": [{
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    }],
    "responsavel": [{
        "nome": "Responsavel teste"
    }]
}]

Repare como agora tem os [ e ] em cada para indicar que é um array  de objetos, que podemos agora percorrer com foreach.
O código para percorrer também tem ligeiramente ajustado que tinha alguns erros:
$obj = json_decode($json_str);

foreach ($obj as $objeto){

    echo "numero: ".$objeto->numero;

    foreach ($objeto->log as $item){ //faltava aqui $objeto->log

        echo "Mensagem: ".$item->message. " - ";
        echo "Nível: ".$item->level. "
";
    }

    foreach ($objeto->responsavel as $responsavel){ //faltava aqui $objeto->responsavel

        echo "NOME: ".$responsavel->nome;

    }

}

Veja esta ultima versão também no Ideone
Answer: Por padrão o json_decode retorna um stdClass e para seu acesso não é possível usar o foreach.
Por outro lado você pode fazer json_decode retornar um array, que por sua vez é iterável. Nesse arquivo em específico, talvez não valha e pena e usar como objeto sugerido nessa resposta é mais simples:
$json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

var_dump(json_decode($json_str, true);

Como Ler este json com PHP


where and how can I deploy node js application that runs python scripts?

Question: I have a project that uses client and server in js. The server runs python's scripts. I tried to deploy the project to github pages and to heruko but I didn't succeed.. it works in the localhost but after I deploy the app it doesn't work.
this is one call for python script for example:
<code>const firstPython = (req, res) => {
  try {
    var dataToSend
    const python = spawn('python', ['BOT/sendMessages.py'])
    // collect data from script
    python.stdout.on('data', function (data) {
      console.log('Pipe data from python script ...')
      dataToSend = data.toString()
    })
    python.on('close', (code) => {
      console.log(`child process close all stdio with code ${code}`)
      // send data to browser
      res.send(dataToSend)
    })
  } catch (error) {
    console.log(error)
    res.status(500)
  }
}
</code>
I will be more specific- the problem is that when I deploy to heroku, this error is shown:
<code>     Downloading pytweening-1.0.4.tar.gz (14 kB)
     Preparing metadata (setup.py): started
     Preparing metadata (setup.py): finished with status 'done'
   ERROR: Could not find a version that satisfies the requirement pywin32==303 (from versions: none)
   ERROR: No matching distribution found for pywin32==303
</code>
!     Push rejected, failed to compile Python app.
!     Push failed
we defined to buildpacks in heroku:
heroku/python
heroku/nodejs
Comment: What does *"it doesn't work"* mean? Questions seeking debugging help (**"why isn't this code working?"**) should include the desired behavior, *a specific problem or error* and *the shortest code necessary* to reproduce it *as formatted text* **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. The code should be a [mre].
Answer: If it is just a project you are working on and does not have to be live all time I go with replit.com you app will function but once no requests are coming it'll go into sleep mode, it's a great tool for testing and for portfolio projects.
But, if your project requires to be on all time then I think you have to get a paid server.


Cauchy's integral formula or Bounds for analytic functions

Question: The problem is here.
Consider the polynomial $P(z)=a_0+a_1z+...+a_{n-1}z^{n-1}+z^n $. Show that, for all sufficiently large values of $r$, there must exist points $z_0, z_1$ on the circle $|z|=r$ such that $|e^{P(z_0)}|=e^{(1/2)r^n}, |e^{P(z_1)}|=e^{-(1/2)r^n}    $.
I tried to show that there exist $z_0, z_1$ with same modulus $r$ s.t $Re(P(z_0))= \frac{1}{2}r^n =-Re(P(z_1))$, but failed. I don't know why the statement 'sufficiently large values of $r$' is given. Also I thought Fundamental theorem of algebra, but I can't use the theorem to solve this problem. I learned Liouville's thm, maximal modulus property, Cauchy's integral formula and so on... but I can not use any of them! Please help me! Thank you for reading.
Answer: For $t\in U=\{t; |t|=1\}$ put $f(t)=P(rt)+\overline{P}(r/t)-r^n$, where $\overline{P}(z)=\overline{a_0}+\cdots+\overline{a_{n-1}}z^{n-1}+z^n$ is the polynomial with its coefficients conjugate to those of $P$. Then your problem is to show that the function $f$ (from $U$ to $\mathbb{R}$) takes the value $0$. Now, as $U$ is connected, and $f$ is clearly continuous, the image $I=f(U)$ of $U$ by $f$ is an interval $I$. We have $f(1)=P(r)+\overline{P}(r)-r^n=r^n+Q(r)$, with $Q$ polynomial with coefficients in $\mathbb{R}$ of degree $\leq n-1$. Hence for $r$ sufficiently large, it takes values $>0$. Do the same for $f(\exp(i\pi/n))$, and you show that for $r$ sufficiently large, it takes values $<0$. Hence for $r$ sufficiently large, as $I$ contain positive and negative numbers, it contain $0$, and  there exists $t\in U$ with $f(t)=0$.
I have not done the computations for the second case, but I suppose that it has a similar proof.


Oracle BI admin tool (.rpd file ) to MSBI

Question: I want to convert <code>.RPD</code> file generated from Oracle BI admin tool to MSBI.
Comment: I haven't tried it. I'm not getting the Idea of how it can be done.
Answer: There is no way to simply convert an .RPD file to a Microsoft BI solution. An RPD file is somewhat analogous to Microsofts BI Semantic Model which you can design using SQL Server Data Tools. In other words, you would have to rebuild your Oracle BI solution using the proper Microsoft tools.
Comment: Is there a way that AMO can be used in order to convert it. Can a utility be created in order to get the output.
Comment: Sure, anything is possible if you're willing to write code but the AMO API is not going to understand how to parse and read the RPD file. It's probably going to be a lot of work. What's your use case for this?
Comment: I got the .RPD file in XML format i.e the simplest form. In msbi ssas when I try to get the xmla code (it is too large and complex). I thought of mapping it through in order to get the output but was not successful.


VSCode on Linux Mint, integrated terminal not able to type anything

Question: Hi I'm running Linux Mint 19 and I have just installed vscode using the snapd package manager. I've not used vscode on linux before as my usual editor is emacs. However, on a fresh new install of vscode, the integrated terminal does not work, there is just a non blinking cursor in the top left of the screen, but no prompt and no keyboard strokes are registering. This appears to be a common problem as there are a lot of posts about it if googled, but they are all for Windows versions and none of the solutions that I'm able to try do anything. I've tried to open a new terminal window, but the same thing happens I just get two terminal windows that I now cannot use. I've also tried checking the box that says Code-runner: Run In Terminal, but that does nothing either. What can I do to get this to work please, I looks to me like it is just not connected to either a bash or Zsh(which I normally use). Any help on this would be appreciated.
Answer: Instead of starting vscode with its default shell script (usually located on /usr/share/code/bin/code), the integrated terminal only works for me when starting it directly from the compiled binary (typically found on /usr/share/code/code, which is the same as the launcher created by the installer:
/usr/share/code/code --no-sandbox --unity-launch %F

While I searched for a solution in the past I've also noticed that lots of folks solved similar problems just by adding --disable-gpu flag, so might be worth checking out as well.


Continuous function and Borel sets

Question: If $f:\mathbb{R}^p \rightarrow \mathbb{R}$ is continuous and $B\subset \mathbb{R}$ is Borel set, how to show that $f^{-1}(B)$ is also Borel set?
I was trying to construct a $\sigma$-ring of sets whose preimage is Borel, but they're not necessarily all borel in that sigma ring...
What would be the main idea for the proof here?
Answer: Hint: prove that $\mathcal A := \{B \in B(\Bbb R): f^{-1}(B) \in B(\Bbb R^p)\}$ is a sigma algebra containing the open sets, where $B(\Bbb R^d)$ is the Borel sigma algebra on $\Bbb R^d$.
Added:
This way, $\tau \subset \mathcal A$ (where $\tau$ is the usual topology of $\Bbb R$), "applying $\sigma$ both sides" we get $\sigma(\tau)\subset \cal A$, therefore $B(\Bbb R)\subset \cal A$. Which means that each $B \in B(\Bbb R)$ is in $\cal A$, i.e. $f^{-1}(B) \in B(\Bbb R^p)$.
Comment: @NoahSchweber thanks!
Comment: I just don't quite understand what would this lead us to. Say, I managed to prove that. We can take a countable union, we can take a complement show that under $f^{-1}$ they will be in this sigma algebra. But what's next?
Comment: @Ilia let's call this set $A$. If $\tau$ denotes the usual topology, we have $\tau \subset A \therefore \sigma(\tau) \subset A$ i.e. $B(\Bbb R)\subset A$. On the other hand clearly $A \subset B(\Bbb R)$.
Comment: @OpenBall I think I got it now. I proved that the collection $\mathcal{A}$ of all open sets whose inverse $f^{-1}$ is a Borel set is a $\sigma$-algebra (I think it would suffice to prove that it's a sigma ring). Borel $\sigma$-ring is the smallest $\sigma$-ring (or $\sigma$-algebra) that is contained in $\mathcal{A}$. Hence if we take any Borel set, then it's inside our set $\mathcal{A}$ and has a Borel set as its inverse.
Comment: Not open, sorry, just all sets for which preimage is Borel
Answer: Induction on Borel rank.
The base cases are if $B$ is $\Sigma^0_1$ (open) or $\Pi^0_1$ (closed). Well, $f$ is continuous, so by definition the preimage of an open set is open - that is, the $\Sigma^0_1$ case is handled. Similarly, since the preimage of a complement is the complement of the preimage, the $\Pi^0_1$ case is handled.
Now there are two kinds of induction step:

Successor: $B$ is $\Sigma^0_{\alpha+1}$ or $\Pi^0_{\alpha+1}$.
Limit: $B$ is $\Sigma^0_\lambda$ or $\Pi^0_\lambda$ for $\lambda$ limit.

The point is, in either case $B$ is a countable union (or countable intersection) of Borel sets of lower rank, and since unions and intersections commute with taking preimages, the preimage of $B$ is a countable union or countable intersection of (by the induction hypothesis) Borel sets, and hence Borel.
Comment: Note that it's crucial that we're working with *preimage*, not *image*. In general, the intersection of the images *contains* the image of the intersection (take $f:\mathbb{R}\rightarrow\mathbb{R}$ constant and let $A, B$ be disjoint subsets of $\mathbb{R}$).
Comment: I'm curious, why the downvote?
Answer: A Borel set is any set in a topological space that can be formed from open sets through the operations of countable union, countable intersection, and relative complement.
As the inverse images of open sets under a continuous function are open sets and inverse images of a countable union is the countable union of the inverse images, same for countable intersection and relative complement. We get the the inverse image of a Borel set under a continuous function is a Borel set.
Comment: What does this have to do with the question?
Comment: @NoahSchweber You were too quick to undervote. Unfair I would say! I was fighting with the poor editing capabilities of my tablet.

Continuous function and Borel sets


Como chamar um objecto dentro da criação de outro objecto

Question: Tenho uma classe Pessoa e uma Classe Data, a classe Pessoa cria uma pessoa a classe data cria uma data para usar como data de nascimento na classe Pessoa, como é que ao criar uma Pessoa crio uma data sem ter que usar o codigo completo no meio do objecto pessoa, o codigo criado até agora é este:
public static void main(String[] args) {
        Data d = new Data(0, 0, 0);
        Pessoa p = new Pessoa("Miguel", "Rua D. Maria", "7400604", objeto_data, "Solteiro");

    }

Answer: É possivel criar a data direto no comando, conforme o código abaixo:
Pessoa p = new Pessoa("Miguel", "Rua D. Maria", "7400604", new Data(0, 0, 0), "Solteiro");

Ou criar esta data no construtor da classe Pessoa.
Comment: ok era mesmo isso que eu me estava a esquecer, assim não preciso de criar a referencia ?
Comment: O comando `new` cria a referencia e passa direto para o metodo. Dessa forma nao precisa criar a variavel


Length and cardinality

Question: In physics, 1m is defined 'the length which light travels in certain time'.
And i've thought 2m has twice many elements than 1m.
But today i've realized intervals (0,1) and (0,2) are equipotent.
I was shocked because i've thought length and cardinality are similar concepts.
Cardinality is clearly defined in set theory. But what is length?
Answer: The best "approximation" of length in mathematics is "measure theory". This is an extensive field of mathematics that deals with "sizes" (called "measures") of sets.
You can define a measure on $\mathbb R$ on which the measure of an interval $(a,b)$ is equal $b-a$. This is called the Lebesgue measure, and it fits what you understand as "twice as big", since the measure of $[0,2]$ is two times the measure of $[0,1]$. The Lebesgue measure can also be defined on $\mathbb R^n$, and there, the size of the "rectangle" $$[a_1,b_1]\times[a_2,b_2]\times\cdots\times [a_n, b_n]$$
is equal to $$(b_1-a_1)\cdot (b_2-a_2)\cdots (b_n-a_n).$$
For initial further reading, look up the wikipedia page on measure theory
Comment: Then i have another question. At the start, how could we assign coordinate values to points before we don't know the concept of length?
Comment: @clfmclfm You don't have a concept of *length*, but you *do* have a concept of distance. So, in a 2D world, you simply say "the $x$ coordinate is the distance of the point from the $y$ axis".
Comment: @5sum Length is line's property or the thing which line has. And distance is 'relationship' between two points. Like this, length and distance is different concept. But the distance between two points is equal to the length of line whose end points are those two points. So i think if we don't know the concept of length, we also don't know the concept of distance. If i'm wrong please teach me what distance is.
Comment: @clfmclfm In mathematics, I would say this: You start with the set of real numbers, an uncountable linearly ordered set. Then, you can construct $\mathbb R^n$. Let's have $n$ fixed to $2$ for now, so you construct a plane.

The next step is you define a metric on $\mathbb R^2$. You *define* the distance between $a=(x_1,y_1)$ and $b=(x_2,y_2)$ as $d(a,b) = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}$. Now, you can talk about distances in the plane, but you *HAD* coordinate points even before you had distances.
Comment: @5sum Let's treat 1-dimension for simplicity. We use the set of real numbers R to easily handle the 1-dimensional Euclid plane E1. I think we can't assign proper coordinate value to E1 before we know the concept of distance. For example, we assigned 1 to point A and 2 to point B. And then we should assign 3 to point C which satisfies AB=BC. But because we don't know what length or distance is, we can't decide where to assign 3.
Comment: I suggest length is undefined notion
Comment: @clfmclfm No, you *start* with the numbers $1,2,3,4,5,6,7$ and all of the other real numbers. You do not need the concept of length to define real numbers. Then you *define* length between $1$ and $2$ to be $1$.
Comment: It's not what i meant. Let me say again. We know the concepts of real numbers and 1-dimensional Euclidian space both. First, we decide the origin point in Euclidian space and assign 0. Next, we choose any one point and assign coordinate value 1. But we can't assign coordinate value to any other point without knowing the concept of length. I agree that we don't need the concept of length to define real numbers. I believe that concept of number preexists before physical reality. But i think this is different problem.
Comment: @clfmclfm I understand what you are asking. The point I'm making is that your question is not about mathematics. In mathematics, you have real numbers, and you define length on them. So, mathematically, you have length on real numbers. How the concept of real numbers applies to the real world around us is a matter of either philosophy or physics.
Answer: Just talking in an heuristic way, you can think that the idea of length is similar to the idea of area or volume, which is generalized in mathematics to measure theory. In some sense, you'd like to associate a positive real number to a subset of a set such that if you consider the union of disjoint pieces you get the sum of measures of pieces, if you compute the measure of the empty set you get $0$. This is the closest idea to length. In fact you can define such a measure, the Lebesgue one, in a way that the measure of an interval $(a,b)$ is $a-b$. But don't forget that you are doing mathematics, so don't leave everything to usual intuition. In fact, also in measure theory strange things can happen. If you want a beautiful example look, e.g. on Wikipedia, at Banach-Tarski paradox. Notice also that cardinality has nothing to do with length, also if you think to finite sets. In fact you'd agree that in Euclidean Geometry points have no dimension. In particular a finite set of discrete points e.g. in $\mathbb{R}^{2}$ is supposed to have no "dimension", or "length" if you prefer, instead it's cardinality is different from $0$, so also in finite case cardinality is not useful to find a concept of length.
Answer: See 5xum's answer! Regarding this part:

Cardinality is clearly defined in set theory. But what is length?

Cardinality is meaningful for all sets, which is why it's typically encountered in a first course on set theory. Measure is a more complicated concept, which is typically first defined for subsets of $\mathbb R$ in a real analysis course. Just because $(0,1)$ and $(0,2)$ are sets doesn't mean that set theory tells us everything about them!

Length and cardinality


How To Build a DRY Image Gallery - in Django

Question: I've been tinkering with a small image gallery for my project for a few days now, but I feel that I'm not going about it in a very pythonic manner thus far in terms of this part of the project.
A lot of questions have risen during the tinkering, alas being new to python and django I cannot immediately see how I ought to go about improving what I'd like to improve in the code.
Here's the user profile model; I reckon it will sort of jump at you what I mean:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from PIL import Image, ImageOps
from ckeditor_uploader.fields import RichTextUploadingField

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email_visible = models.BooleanField(null=True)
    activation_key = models.CharField(max_length=120, blank=True, null=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    surname = models.CharField(max_length=30, blank=True, null=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    slogan = models.CharField(max_length=250, blank=True, null=True)
    bio = RichTextUploadingField(
                                external_plugin_resources=[(
                                    'youtube',
                                    '/static/ckeditor/ckeditor/plugins/youtube/',
                                    'plugin.js'
                                    )],
                                    blank=True,
                                    null=True,
                                )
    phone = models.CharField(max_length=20, blank=True, null=True)
    reddit = models.CharField(max_length=30, blank=True, null=True)
    facebook = models.CharField(max_length=30, blank=True, null=True)
    twitter = models.CharField(max_length=30, blank=True, null=True)
    youtube = models.CharField(max_length=30, blank=True, null=True)
    linkdin = models.CharField(max_length=30, blank=True, null=True)

    img_1 = models.ImageField(default='default.jpg', upload_to='images')
    img_2 = models.ImageField(default='default.jpg', upload_to='images')
    img_3 = models.ImageField(default='default.jpg', upload_to='images')
    img_4 = models.ImageField(default='default.jpg', upload_to='images')
    img_5 = models.ImageField(default='default.jpg', upload_to='images')
    img_6 = models.ImageField(default='default.jpg', upload_to='images')
    img_7 = models.ImageField(default='default.jpg', upload_to='images')
    img_8 = models.ImageField(default='default.jpg', upload_to='images')
    img_9 = models.ImageField(default='default.jpg', upload_to='images')

    def __str__(self):
        # return 'kartofler'
        return self.user.username
        # return f'{self.user.username} profile'

    def save(self, force_insert=False, force_update=False, using=None):
        super().save()
        # this part needs expansion.
        img = Image.open(self.image.path)
        if img.width > 300 or img.height > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

        #EXPERIMENT: THUMBNAIL MACHINE
        img_1 = Image.open(self.img_1.path)
        xpad = int(img_1.width/2)-45
        ypad = int(img_1.height/2)-45
        coords = (xpad, ypad, xpad+90, ypad+90)
        crop_img = img_1.crop(coords)
        crop_img.save(self.img_1.path)  # should save to a (colored) thumbnail folder in stead.
        crop_img = ImageOps.grayscale(crop_img)
        crop_img.save(self.img_1.path)  # should save to a (b/w) thumbnail folder in stead.

First off, there's clearly something iffy going on with the 9 imagefields at the bottom. It's not DRY and also what I'm trying to do in the bottom half of the def save() strikes me as problematic in light of the aforementioned 9 fields, as it strikes me that I'm creating a rather ugly monster. I'd like to iterate over those imagefields in stead of repeating myself or something similar.
The forms.py file connected to this model is equally "WET". The template which displays it all is obviously equally redundant in it's ways.
Also I'm confused as to how to create (and delete) subfolders in the media folder. I tried to do a cheeky string with a template variable and a raw string, but to no avail.
It would be very nice if I could create some sort of hierachy based off the usernames (and perhaps a timestamp).
Basically I'm asking for directions. If you happen to know of some good resources that I could read (or watch, it doesn't matter which), I'd be much obliged. If you've got a killer idea, this is obviously equally welcome.
Thank you kindly for reading along.
Answer: You should create another model for user photos.
import datetime
def upload_file(instance, filename):
    # you can add datetime
    now = datetime.datetime.now()
    # image/users/{username}/{now}/{filename}
    return os.path.join('users/%s/' % instance.profile.user.username, now, filename)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email_visible = models.BooleanField(null=True)
    activation_key = models.CharField(max_length=120, blank=True, null=True)
    name = models.CharField(max_length=30, blank=True, null=True)
    surname = models.CharField(max_length=30, blank=True, null=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    slogan = models.CharField(max_length=250, blank=True, null=True)
    bio = RichTextUploadingField(
                            external_plugin_resources=[(
                                'youtube',
                                '/static/ckeditor/ckeditor/plugins/youtube/',
                                'plugin.js'
                                )],
                                blank=True,
                                null=True,
                            )
    phone = models.CharField(max_length=20, blank=True, null=True)
    reddit = models.CharField(max_length=30, blank=True, null=True)
    facebook = models.CharField(max_length=30, blank=True, null=True)
    twitter = models.CharField(max_length=30, blank=True, null=True)
    youtube = models.CharField(max_length=30, blank=True, null=True)
    linkdin = models.CharField(max_length=30, blank=True, null=True)

class Profile_Photo(models.Model):
    profile = models.ForeignKey("Profile", related_name="photos", on_delete=models.CASCADE)
    photo = models.ImageField(upload_to=upload_file)

#You can access user photos like this
# user = request.user
# profile = Profile.objects.get(user=user)
# photos = profile.photos.all()

Comment: I woke up this morning with the same idea, and I realised how I could probably just have a single field and then load that 9 times, somehow.

Thank you all the same, and dare I say: I really like how you put that comment in there at the bottom. Everyone ought to add those in, cheers :)


Trying to create symlink - keep getting error: "File exists"

Question: I am trying to use Pow and create a symlink so that I can ultimately run my rails application locally at the following URL:
http://market_place_api.dev/
I am going through the API's on Rails tutorial, and when I follow the author's instructions on setting up Pow and a symlink, here is what is happening:

cd into a folder called "code", and created a new rails app: $ rails new market_place_api -T
Installed Pow: $ curl get.pow.cx | sh
Gone to the Pow directory: $ cd ~/.pow
And here is where the problem occurs.  The instructions say to symlink: $ ln -s /path/to/myapp
In my case, the app is located at this URL:  /Users/harrylevine/Dropbox/Coding/BLOC/code/market_place_api
So I enter into the command line: $ ln -s /Users/harrylevine/Dropbox/Coding/BLOC/code/market_place_api and I keep getting this error: ln: ./market_place_api: File exists

I have tried many variations of this, including:

applying this format:  ln -s target_path link_path

All to no avail.
How can I properly create this symlink so that I can ultimately run my rails application locally at the following URL:
http://market_place_api.dev/
Thank you.
Answer: The error means that there is already a file (or a sym-link) called market_place_api in that directory (~/.pow).
Check with $ ls -l to see what the file is. If it's the correct sym-link then you are ready to proceed with the tutorial.
Comment: This worked.  Thanks @algomatic !  I checked as you described, and there was a file already in there.  An incorrect one.  I removed it, and recreated the symlink using:  $ ln -s /Users/harrylevine/Dropbox/Coding/BLOC/code/market_place_api


Is GAP (graph accessibility) NP-Complete?

Question: Is the GAP (graph accessibility problem) NP-Complete ?
It has polynomial and non-deterministic polynomial algorithms that solve it, but I don't think this is a criteria that overrides the basic way of showing it's NP-Complete, by showing it is NP and NP-Hard => NP-Complete.
I heard both versions from older students than me.
So in the end, is it or not NP-Complete?
Comment: If it has a polynomial algorithm, how could it be NP?
Comment: From what my course material says, P is included in NP. Also to demonstrate that a problem is in NP you have to build a non-deterministic algorithm OR prove that a solution can be verified in polynomial time.
Comment: From how I understood your question, you have a non-deterministic algorithm for finding the solution. In that case, the problem is either not NP-Complete, or you just proved that `P=NP`, which while possible seems extremely unlikely ;).
Comment: P is INCLUDED (not EQUAL) in NP. The course material says that in order to demonstrate that a problem is NP-Complete it must be NP and NP Hard.
To show that is NP it states that you must provide an NP algorithm or show that the solution can be verified in polynomial time.
To show that is NP Hard it states that you must reduce a known NP Hard problem to the current one.
Also: http://www.nomachetejuggling.com/files/1000px-P_np_np-complete_np-hard-e1347048707765-245x300.png
Comment: Sorry, I keep mistyping ^^. I meant NP-Complete in my first comment and deterministic (not non-deterministic) in my second. So if you have a deterministic polynomial algorithm for finding a solution, your problem is in P. If it is also NP-Hard, it is NP-Complete. That would prove that `P=NP`.
Answer: Wikipedia says that the problem is NL-Complete, which means that it's also in P. This makes it extremely unlikely that it is NP-Complete. If it was, that would prove that P=NP, which is a very old and unsolved question. And it is widely assumed that P≠NP.
You won't be able to prove that it is not NP-Complete either, because that would prove P≠NP.
If you can prove that it is NP-Complete or that it is not NP-Complete, you will recieve an award of one million dollars.
So in summary the answer is: It seems very unlikely, but it is just as unlikely that you can prove anything in that direction :).


How can I match a string between two other known strings and nothing else with REGEX?

Question: I want to extract a string between two other strings. The strings happen to be within HTML tags but I would like to avoid a conversation about whether I should be parsing HTML with regex (I know I shouldn't and have solved the problem with stristr() but would like to know how to do it with regular expressions.
A string might look like this:
...uld select “Apply” below.

Primary Location: United States-Washington-Seattle
Travel: Yes, 75 % of the Time
Job Type: Standard
Region: US Service Lines: ASL - Business Intelligence
Job: Business Intelligence
Capability Group: Con/Sol - BI&C

LOC:USA
I am interested in Primary Location: United States-Washington-Seattle
 and want to extract 'United States-Washington-Seattle'
I tried '(?<=Primary Location:)(.*?)(?=
)' which worked in RegExr but not PHP:
preg_match("/(?<=Primary Location:)(.*?)(?=
)/", $description,$matches);
Answer: You used / as regex delimiter, so you need to escape it if you want to match it literally or use a different delimiter
 preg_match("/(?<=Primary Location:)(.*?)(?=
)/", $description,$matches);

to
preg_match("/(?<=Primary Location<\/b>:)(.*?)(?=
)/", $description,$matches);

or this
preg_match("~(?<=Primary Location:)(.*?)(?=
)~", $description,$matches);

Update
I just tested it on www.writecodeonline.com/php and
$description = "uld select "Apply" below.

Primary Location: United States-Washington-Seattle
Travel: Yes, 75 % of the Time
Job Type: Standard
Region: US Service Lines: ASL - Business Intelligence
Job: Business Intelligence
Capability Group: Con/Sol - BI&C

LOC:USA";
preg_match("~(?<=Primary Location:)(.*?)(?=
)~", $description, $matches);

print_r($matches);

is working. Output:

Array ( [0] => United States-Washington-Seattle [1] => United States-Washington-Seattle )

You can also get rid of the capturing group and do
$description = "uld select "Apply" below.

Primary Location: United States-Washington-Seattle
Travel: Yes, 75 % of the Time
Job Type: Standard
Region: US Service Lines: ASL - Business Intelligence
Job: Business Intelligence
Capability Group: Con/Sol - BI&C

LOC:USA";
preg_match("~(?<=Primary Location:).*?(?=
)~", $description, $matches);

print($matches[0]);

Output

United States-Washington-Seattle
Comment: Thanks. That's a good point and will avoid an error but it still doesn't match anything.
Comment: Thanks. It isn;t working locally - probably for some other reason, though, so I'll accept the answer.
Comment: Turns out that simplepie was converting  to  so that's why I was getting no matches. Grrrr


Creating an Editor Role and Reusing the Admin Menu and Overlay in Drupal 7

Question: I, like so many other Drupal users, wish to add an Editor role into my website.  I have already done this.  I want the Editor to be responsible for editing and publishing certain content, as well as create certain types of content.
I use the Admin Menu module so I get that very nice flyout-menu administrator toolbar.  Well, I want the editor to be able to use the same menu, only with certain items missing.  Not only do I want them to use the same menu, but I want it to appear in the same bar.  I also want the editor to be able to use the overlay as well, just as it appears for the administrator.
How do I do this?
Cheers.
Answer: Assuming you have the Administration menu module enabled, under People > Permissions check the following boxes:
Administration menu

Access administration menu

Node

Bypass content access control (note though, this gives the user permission to delete all content; if you don't desire this then you can micro-manage the permission on the individual content types, it's more box checking but also more secure)

System

Use the administration pages and help
View the administrative theme

Those are the core permissions that you need to have in order for a role to view the administration menu as well as menu items pertinent to managing site content.
Now, in order to make sure that the role is more or less secure, I would always uncheck every box whose label begins with "Administer...", as these permissions would be for administration roles.
Answer: See the Administration Menu Source to achieve this.

Use a different menu as the Administration Menu. Configurable per role.
Answer: See the Menu per Role module to achieve this. Here is a quote about it (from the module's project page):

... allows you to restrict access to menu items (*) based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
(*): We wrote "menu items", not "nodes" ... This module does not prevent users from accessing the destination nodes. It only changes the visibility of the menu items.


Button event trigger

Question: I am having trouble understanding as how do you trigger specific button event when using Ruby on Rails.  For example I have a mini form inside a table as so (View side of MVC):
<%= form_tag do %>
<% if student.floor_pref == '1st' %>
    <%= select_tag 'room', options_for_select(@first_floor.map { |value| [value,value]}, @selected_room) %>
<% end %>
<% if student.floor_pref == '2nd' %>
    <%= select_tag 'room', options_for_select(@second_floor.map { |value| [value,value]}, @selected_room) %>
<% end %>
<% if student.floor_pref == '3rd' %>
    <%= select_tag 'room', options_for_select(@third_floor.map { |value| [value,value]}, @selected_room) %>
<% end %>

<%= submit_tag 'Update' %>
<% end %>

How do I tell the controller that when the Update button is clicked inside the view to for example execute this code:
a = Student.find(3)

a.room_number = '2105'
a.save

Answer: Your button should be triggering a post-back to the server. You need to define an action in your controller, a route to reach that action, and set your forms action attribute to that route. Your action can then update the models and respond with a success or error message.
Comment: Can you show me how this is done using this example?  I am new to Ruby and asked this before but no one can seem to help.
Comment: Which part? I gave you three steps: Define an action in your controller, create a route, update your `` tag to include an `action="..."` attribute to reach your route. This is *extremely* basic Rails coding, and literally every tutorial written will tell you how to do this.
Comment: All three parts really.  I've used scaffolding to build my MVC and besides just declaring variables that run a query and return results inside a controller I really don't understand much beyond that point.  I've gone through couple of tutorials and they all show the same thing which really doesn't help me with this.
Comment: This is just basic example that is a part of bigger problem that I'm trying to figure out.  I feel that if I can get this working I can build on that and use the stuff I learned from tutorials to solve the problem.
Answer: u should specify a route(a controller action to which the data is to be submitted) in the form tag. refer http://apidock.com/rails/ActionView/Helpers/FormTagHelper/form_tag for more details. considering that ur action is for 'edit' action from students controller and that data is to be posted to 'update', the view can be defined as
<%= form_tag student_path(@student), :method => :put do %>
  ...
  <$= submit_tag 'Update' %>

and in the 'update' method, u can write the code to update student with the received params. I think u need to study basic rails functioning since it will save u time in future. u can refer http://guides.rubyonrails.org/getting_started.html Also, prefer using form_for rather than form_tag.
Comment: Thanks for the quick response.  In the form tag could I specify it as following:  <%= form_tag :controller => 'students', :action => 'update' do %>  ?  Only reason I'm asking this way is because I'm still learning the Ruby syntax and this makes more sense to me.  Thanks again.
Comment: yes. please have a look at http://stackoverflow.com/questions/9540291/difference-between-form-for-and-form-tag for difference between form_for and form_tag.
Comment: Sweet, that got me somewhere. Thanks! Data is updating fine now but the action I call in the controller as shown above 'update' doesn't have a view so when I click the update button it actually updates the room column but after that it displays the "Template is missing" page.  Is there a way that I can tell it after it perform the 'update' action to just go back to the 'index' page?  Thanks again!
Comment: u can redirect to any page if the object is created/updated successfully. check point 6.9 on rails guides for an example.
Comment: I see, thanks.  I'm going over that guide atm.  Thanks again for your help, it helped me solve the big problem I was originally having.  Now the web app works 100%

Button event trigger


Como pegar trechos específicos de um string em php

Question: Estou usando um API adaptado que me retoma o seguinte dado em XML
<?xml version="1.0" encoding="utf-8" ?>
<ajax>
    <cmd p="innerHTML" t="shurlmsg">
        <![CDATA[
This link is already on your list
]]>
    </cmd>
    <cmd p="js">
        <![CDATA[
           $('#shurlin').removeClass('ajaxloading');
           setTimeout("$('#shurlmsg').html('');", 4000);
           $('#noresult').remove();
           $('#urls').prepend('');
           $('#shurlin').val('');
           $('#shurlout').val('http://example.com/Um5-Cg').show().focus().select();
        ]]>
</cmd>

O que quero é pegar o URL encurtado http://example.com/Um5-Cg.
Comment: Você quer capturar a URL e encurtar ela em seguida? Ou você quis dizer "eu quero pegar essa url encurtada", se for isto então a resposta @xsquirrel parece ser um caminho.
Answer: Você pode pegar a URL usando expressões regulares.
$xml = <<<EOT
<?xml version="1.0" encoding="utf-8" ?>
<ajax>
    <cmd p="innerHTML" t="shurlmsg">
        <![CDATA[
This link is already on your list
]]>
    </cmd>
    <cmd p="js">
        <![CDATA[
           $('#shurlin').removeClass('ajaxloading');
           setTimeout("$('#shurlmsg').html('');", 4000);
           $('#noresult').remove();
           $('#urls').prepend('');
           $('#shurlin').val('');
           $('#shurlout').val('http://example.com/Um5-Cg').show().focus().select();
        ]]>
</cmd>
EOT;

preg_match("/\('#shurlout'\).val\('(https?:\/\/.*\/\S*)'\)/i", $xml, $resultado);

print_r($resultado);

echo $resultado[1];

Resultado:
Array
(
    [0] => ('#shurlout').val('http://example.com/Um5-Cg')
    [1] => http://example.com/Um5-Cg
)
http://example.com/Um5-Cg


How to locate scrapyd logs file on Linux server?

Question: The logs file generated by scrapyd occupies too much memory. I want to find it and delete it. How can I find it?
Answer: as per scrapyd documentation, the logs should be located in
/var/log/scrapyd/
 the main log file /var/log/scrapyd/scrapyd.log
there are other two logs which log console output and error
/var/log/scrapyd/scrapyd.out
/var/log/scrapyd/scrapyd.err
there will be individual logs for each project
 /var/log/scrapyd/PROJECT/SPIDER/ID.log

 you can delete the logs using rm command

but I suggest you implement log rotate  link instead of deleting the logs manually
Comment: I am wondering if this is still valid in 2021. The folder exists on my ubuntu 20.04 machine but is empty.
Answer: They are in the directory which you have specified in logs_dir
Or get the name of that log file and run
find / -name "name_of_file.log"

How to locate scrapyd logs file on Linux server？


Python: How to convert a string containing hex bytes to a hex string

Question: I'm thinking binascii is the module I'm looking for, but I can't quite seem to get the exact results for which I am looking.
Here's what I want to do.  I want to convert:
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> print len(s)
40

to
>>> hs = '\x35\x6a\x19\x2b\x79\x13\xb0\x4c\x54\x57\x4d\x18\xc2\x8d\x46\xe6\x39\x54\x28\xab'
>>> print len(hs)
20

Any Pythonistas know of a cool (or, frankly, functional) way to do this?
Answer: In all versions of Python, you can use the function
binascii.a2b_hex() (also known as binascii.unhexlify()):
>>> import binascii
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> binascii.a2b_hex(s)
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

In Python 3.x, you can use bytes.fromhex(s).
In Python 2.x, you can use the hex str-to-str codec:
>>> s.decode("hex")
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

The codec internally calls binascii.a2b_hex().
Comment: Now you can do `bytes.fromhex('356a192b7913b04c54574d18c28d46e6395428ab')`
Comment: Yep, that's exactly what I was looking for, and it was in the string class waiting for me.  Thanks, Sven!
Comment: You can also do s.decode("hex").upper() to get uppercase if that is important.
Comment: would you mind providing a Python 3.x version since this is the accepted answer (and will likely be so forevers)
Comment: @Marc The answer actually already included the Python 3 version without explicitly stating so – now made explicit.
Comment: @Marc As stated before, the last line works on Python 3.  The solution you found is nice as well.
Comment: @Marc Thanks for the feedback – I've tried to clarify the answer. :)
Answer: With binascii module:
>>> from binascii import unhexlify
>>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
>>> unhexlify(s)
'5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'

Comment: `unhexlify()` is only another name for `a2b_hex()` [binascii Documentation](https://docs.python.org/2/library/binascii.html#binascii.a2b_hex)


Clear example on how to use #theme for form API

Question: I cannot find a good example of how to accomplish custom theming on a field level within a form:
$form['test_2'] = array(
  '#type' => 'textfield',
  '#title' => t('Test Field #2'),
  '#required' => true,
  '#description' => t('This is a test field which we hook into.'),

  '#theme' => 'custom_func'
);

Inside my template.php I have:
function MYTHEME_theme() {
    return array(
      'custom_func' => array(
        'render element' => ??? // WTF goes here???
      )
    );
}

function MYTHEME_custom_func($variables) {
  return 'Something';
}

This code obviously does not work...what am I missing?
Comment: Have you looked at theme_form_element() ?
Comment: I have yes...its already implemented as part of my theme.. I do not believe that is what i need tho???
Answer: You're so close...the name of the render element is arbitrary, it's just a name so you can pick it up at the other end. Or, put more eloquently:

The name of the renderable element or element tree to pass to the theme function. This name is used as the name of the variable that holds the renderable element or tree in preprocess and process functions.

So:
function MYTHEME_theme() {
  return array(
    'custom_func' => array(
      'render element' => 'my_element',
    ),
  );
}

function MYTHEME_custom_func($variables) {
  $element = $variables['my_element'];

  // Use the values in the $element render array to build markup.

  return $element;
}

Comment: Thanks for the reply...your assistance is greatly appreciated :) will try when i get home later...
Comment: This worked great...kinda...the $element is not rendering though and returning an Array -- I passed $element and $variable to drupal_render() and MYTHEME_form_element() -- no success...I need to render the original form field plus or minus wrapping mark up -- any ideas?
Comment: Got it I think -- I passed $element to theme() and that seems to work now :)


macOS zsh completion for subcommands

Question: I have a script called , that takes a finite set of subcommands. Let's say this set is (foo bar qux). So the following are the acceptable CLI invocations this script:

, foo
, bar
, qux

(Each of the above may take further optional arguments to the right).
What is the minimal zsh completion code for this script that will work on macOS? Such that when I type ,  followed by <TAB>, the shell will autocomplete with those three options: foo, bar, and qux.
Answer: Here are the minimal steps for adding zsh completion to your , command:

Enabling compinit
autoload -U compinit

Enabling compdef
compinit

Defining a function for completing the first argument from/with a given set of values.
_,() { _arguments -C '1: :(foo bar qux)'; }

Setting the previous function _, as the completion function of the , command:
compdef _, ,

Now if you type Comma Space Tab, zsh should output:
bar  foo  qux

ASIDE
It's possible to add further completion to each sub-command bar/foo/qux; take a look at this documented example.
Comment: @SridharRatnakumar I tried to call the completion function of `git` from inside `_,` but it segfaults zsh!! I think it's worth to ask an other question for it.
Comment: Thanks! That "aside" is also helpful. Specifically I'd wish to *delegate* completion to the respective command. For example, `, git` should delegate to git's autocompletion. I can open a separate question for it if necessary.

macOS zsh completion for subcommands


Regression terminology, predictor vs IV vs?

Question: A reviewer has objected to our use of the term "predictor" in a multiple regression analysis using observational data. They argue that because the model is intended to be explanatory and not predictive, we should use some other term. Any suggestions? I'm not keen on, say, "independent variable" because this, at least to me suggests an experimental design with manipulation.
Comment: It's not up to the intention of the analyst whether a coefficient in a regression model can be interpreted as measuring the causal effect of that variable on the outcome or merely the predictive shift . Your last sentence indicates a causal interpretation isn't justified. If so I think predictor is fine (It's always fine. regression at the very least does at least that) but if the reviewer insists, maybe regressor.
Comment: It is OK to use word "predictor" in an "explanatory" study. Explaining is about predicting what has already occured. Does the reviewer mean "forecasting"?
Comment: Explanation is certainly lacking if the model isn't successful at prediction, namely of predicting the outcome conditional on other variables.  The term predictor isn't intended to be restricted to situations where predicting the future or even beyond the dataset is of primary -- or even any -- concern. .
Comment: In some fields (especially economics) IV is more likely to mean _instrumental variable_. For that and other reasons I discourage the abbreviation where I can. (It's perhaps less likely that a reader will take DV to mean _Deo volente_, but that's horrible too. DV saves  a few characters but no syllables over _outcome_ or _response_.
Answer: Feature or covariate are the terms that I use. Another that one might use is explanatory variable.


Subversion error: (405 Method Not Allowed) in response to MKCOL

Question: I am getting the following error while trying to commit a new directory addition.
<code>svn: Commit failed (details follow):
svn: Server sent unexpected return value (405 Method Not Allowed) in response to MKCOL request for '....
</code>
I have never seen this error before. How can I fix this problem?
Solution
I managed to solve the problem:

Delete the parent's directory of the folder giving the problem.
Do SVN Update.
A folder with the same name as the new one already existed in repository.
Delete this folder.
SVN commit.
Copy the new folder, schedule for addition and SVN commit.
Comment: Please add solutions as answers, rather than adding to the question
Comment: I hate svn giving error and stop. It look like a child sniveling all the time.

I reverted, than added then committed and magicly server acccepted.
Comment: Lacks information, like your configuration, your transport (HTTP/HTTPS), the messages on the server error log (the most important), if you are running a web-cache service between client and server, etc...
Comment: For google code repository see - http://stackoverflow.com/a/32636072/1406510
Answer: This error usually indicated the folder you're trying to add already exists in the repository - have you done an update recently, or did you do a non-recursive checkout to start with?
I've previously encountered this error - found a blog that told me what the problem was. Solution was a little more complex, remove the directory in question from my working copy (copying it somewhere else), run a recursive update, then merge the two directories together manually.
Edit: Opps - already answered in question body. And here I was all excited that I knew the answer to an unanswered question :)
Comment: @Andrew -- well, you answered the question properly... @Sergio should have answered his own question.
Answer: I had a similar problem with MKACTIVITY on googlecode.  It was because I had checked out the repository with http:, but check-ins required https:.
Comment: Great catch - I was just about to unleash the fury of the impatient programmer on my machine. :) You either need to recheckout the folder with https: (or if you're sneaky clear out the folder except for the .svn, then modify the contents of .svn/entries which has the url from http => https. Now the commit screen would show the https URL.)
Comment: http://stackoverflow.com/a/32636072/1406510
Answer: I got the same error and managed to resolve it:

SVN Rename the problematic directory to 'foo', or whatever
SVN Commit
SVN Rename back to the name you want
SVN Commit

I'm not sure if this works in all cases, but it's simpler than deleting the parent directory.
Comment: That simple solution resolved my issue. Thanks a lot! :)
Answer: Does your svn repository allow commits via HTTP? Some repositories, like SourceForge, allow anonymous checkout via HTTP, but require developers to check in via svn and SSH.
Answer: In my case, I was having problems checking in files within a folder.  I followed the steps Sergio outlined with a few changes.

Copied the problem parent directory.
Deleted .svn files in copied directory
svn delete /parent_directory
Commit
Create new directory in repo
Commit
Move sub directories from copied directory to repo
Commit
Copy individual files
Commit

I had a few files that I had challenges with.  I left them out of the repository, but recreated them with a new name.
Answer: I had this problem when I removed a directory form SVN, and then recreated it, when I committed the new added directory, SVN yielded this error. I solved the problem by running a SVN up on the new added directory, and then resolved the conflicts manually.
Answer: Using Unfuddle, a hosted svn service, I repeatedly see this error when the .svn gets trampled by file copying in the OS X finder. The svn incantation that worked for me:

revert
update
delete the folder using the remote url
add and commit the folder
Answer: In my case, I was adding a new directory that my local (client) metadata assumed to already be on the server and Cleanup did not rectify it. I backed up all the new and modified files, deleted everything (except the root .svn folder), ran Update to restore the files, and copied back into the directory the new and modified files I had backed up. I added the new files again and committed successfully.
Answer: In Eclipse it is easy to fix.
Team > Switch to another Tag/branch
Select, fully recursive and check Change working copy to specified depth
Press OK
The folder's icon change.
Right click and (team >) Mark Resolved.
That's it, now you can commit.
Comment: Bear in mind that Eclipse is a development tool, and not really the focus of ServerFault.
Answer: Make a backup of the folder.
Delete the folder in the repository (using Repo-Browser).
Commit again.
Works fine for me.
Marcus
Answer: i had similar problem, i backed up the directory (just for safety) than update the svn folder.
after that i could commit again. (and not used my backup)
Answer: I had an issue with e175002 200 OK. But I read that the path on the error message was talking about a wrong server, so the URL of my trunk was not the good one (http://localhost:80/path/to/my/trunk/) … wait ! LOCALHOST ?! ... And now I realize that it's because on my first rev my settings sent my project files to my repo locally …
So on your first rev make sure your settings for the IP of your server is not wrong because after that... your repo will contain wrong informations, and you'll have to find a way to modify those bad settings on it, or on every client that want to use your repo for the first time.
My fix was to check on every folder of my project…. on every folder there is the .svn folder that store informations, and on every .svn folder a file called "entries" … In this file there is a path to the server, I replaced the bad line by the good IP in every entries stored in every .svn folders. And then no more errors.
Hope it helps. :) sorry if it's hard to understand my post ^^' I'm a try-harder.