flock fd across child processes : if I use same fd do I risk that it gets assigned to other process lock?

Question: I'm writing a multiprocess bash script that runs several processes (continuously), there are some functions I need to launch, every function has a similar form described in man for flock :
function1 () {
    #.... preamble, variable initialization
    (
             flock -x -w 10 200 || exit 1
             # ... my commands ....
    ) 200>/var/lock/.`basename $0`$conf"-rtrr.lock"
}

Each function has its own fd (number) different from other, every function is independent from others .
The desired behavior is that I should be able to run the same function several times in parallel, the only condition is that only one instance described by function and its parameters can run in every moment.
It is not a problem if a function execution fails, the parent runs in a inifinite loop and launch it again.
For example if we consider this a list of running processes/functions :
OK
function1 a
function1 b
function2 a
function3 b

NO:
function1 a
function1 a
function2 b
function3 b

On every part I specify different lockfile names using something like :
/var/lock/${program_name}-${parameter}-${function_name}.lock

example lockfile , if called function1 with a :
/var/lock/program-a-function1.lock

The questions :

using same fd number across several processes, the ones launches the same function, do I risk that one child process overwrite the fd mapping of another child ? The risk is that a process may wait for a wrong lock.
Can I use a variable as fd ? For example a number which is a sort of hash of parameter ?
Otherwise, is there a way to not use fd while using flock command ?
Do you think, for this desired behavior, it is better to use simple files to get and release locks : ieg creating file when acquiring, deleting file when releasing and having an if on top to check lock file presence ?
Answer:
No risk. When a child process opens a file at some filedescriptor slot, it will overshadow the inherited filedescriptor (if one was inherited into that slot)
You can, but it's ill-advised. For max portability, you should use something less than 10. E.g., 9 like in the flock manpage example.
Yes, as the flock manpage describes, but that implies execing a command, which is not suitable for your case.
Sounds needlessly complicated

If I were you, I'd create lockfiles with > whose names would be derived from $0 (scriptname), ${FUNCNAME[0]} (function-name), and $* (concatenation of function arguments) and use them with a small filedescriptor like 9 like in the flock manpage. If you use basename on the scriptname $0, do it once and save the result in a global.
Example code:
#!/bin/bash

script_name="$(basename "$0")"

func1()(
    echo "$BASHPID: Locking $(readlink /dev/fd/9)"
    flock 9 || return 1
    echo "$BASHPID: Locked $(readlink /dev/fd/9)"
    echo "$BASHPID: WORK"
    sleep 1
    echo "$BASHPID: Release $(readlink /dev/fd/9)"
) 9>/var/lock/"$script_name-${FUNCNAME[0]}-$*"

func1 a &
func1 a &
func1 a &
func1 b &
func1 b &
func1 b &

wait

Possible output of the example code:
16993: Locking /run/lock/locks-func1-b
16985: Locking /run/lock/locks-func1-a
16987: Locking /run/lock/locks-func1-a
16995: Locking /run/lock/locks-func1-b
16994: Locking /run/lock/locks-func1-a
16987: Locked /run/lock/locks-func1-a
16987: WORK
16999: Locking /run/lock/locks-func1-b
16995: Locked /run/lock/locks-func1-b
16995: WORK
16987: Release /run/lock/locks-func1-a
16995: Release /run/lock/locks-func1-b
16985: Locked /run/lock/locks-func1-a
16985: WORK
16993: Locked /run/lock/locks-func1-b
16993: WORK
16985: Release /run/lock/locks-func1-a
16993: Release /run/lock/locks-func1-b
16994: Locked /run/lock/locks-func1-a
16994: WORK
16999: Locked /run/lock/locks-func1-b
16999: WORK
16994: Release /run/lock/locks-func1-a
16999: Release /run/lock/locks-func1-b

Comment: My favourite lock file strategy in this scenario is to use symlinks instead. `ln -s "pid=$$" /path/to/${0##*/}.pid` will fail if the lockfile exists, and is atomic, so you don't risk overwriting the file if two instances of the script/function get launched at the same time.
Comment: @ghoti If you forget about writing PIDs into those lockfiles (and PID files are a fundamentally flawed concept), then you're fine. Only one combo of scriptname, function-name, function-args will get the lock at a time and repeated truncation does no harm to a file that's meant to stay empty.
Comment: There exists a race condition between the line in your shell script which *creates* the lockfile and the line which *checks for* your lock file. Pid or something else, the point is to have an atomic operation that both reports on the availability of the lock and creates it simultaneously, thus eliminating the race condition. Creating a symlink satisfies that, since `ln -s` will fail if the target already exists.
Comment: The script I described (+ now added an example) doesn't check for a lockfile. It opens a lockfile (possibly creating it) and then locks the lockfile. I don't see where there could be a race in there.
Comment: @ghoti The reason I don't like PID files is that those are subject to races as at any point in time only the parent of a PID can be certain that PID hasn't been reaped and recycled (although that's kind of a slow race as PID recycling isn't exactly fast). Please correct me if you think I'm wrong.


How to move 100mb hidden system reserved partition on Windows Server 2008 R2 to other drive?

Question: I have a server with two 1.5TB hard drives. I was going to install a Windows Server 2008 R2 and create software RAID1 using Windows Disk Management Utility.
I instaleld Windows, open this console and that is what I see:
https://i.stack.imgur.com/KoC9a.png
Setup program created a System Reserved Partition at my second HDD.
I don't understand now, how can I create RAID1, because space, which supposed to be used for copy of disk C, now is used for this hidden partition.
So is there any way now to create correct RAID1? May it is possible to move this partition to the Disk 0, where I have plenty of free space?
Unfortunately I can't reinstall Windows and apply other options at the disk management step of the installation, because installation image is not longer connected to the server and I have no physical access to server, only remote desktop.
Answer: There's really no problem with any mirroring you want to do next. The soft-mirroring works on a partition basis so you can mirror C: to the second disk by just right-clicking it and selecting the right options (add mirror I think) - no problems there.
Also, you can create a second partition D: in the free space on Disk0 and then add a mirror to it on Disk1 as there's enough space...
...if you want to mirror both C: and create a new D: volume and mirror that one too - make sure to make it ~100MB smaller on Disk0 so the mirror will fit on Disk1 (or create it on Disk1 first to have it calculated for you ;)
The hidden partition is used to boot the system when you apply full-disk encryption (Bitlocker) and so on, which is recommended on remote systems with less than stellar physical safety ^^
Generally, install the server with the second disk unplugged if you're going to add software mirroring to the installation, it should do the trick.
What probably happened is that disk1 is set as the first boot disk in BIOS Setup and you selected the other disk to install to during Windows setup perhaps?
Comment: Thank you, Oskar
But I'm not sure this mirror will be fully functional.
Let's assume I mirror my C partition to the second drive.
What if Drive 0 fails? Will it be possible to boot the computer only from the Drive 1?
If Drive 1 failes, will the server boot from Drive 0?

As far as I understand, hidden partition contains some system files which are required to boot system? So how do I have to mirror this partition to make 2 drives independent, replacable and bootable?


Filter Map e Reduce

Question: Tenho a seguinte linha de código:
$scope.listDeColaboradoresObject.forEach(item => {
  item.listNmAssunto =
  $scope.relatorioTotalMensagensRespondidasColab
  .filter(x => x.nmUsuario == item.nmUsuario)
  .map(x => x.nmAssunto);
    item.listNmAssunto = $scope.removeDuplicates(item.listNmAssunto);

    item.listDtResposta = $scope.relatorioTotalMensagensRespondidasColab
    .filter(x => x.nmUsuario == item.nmUsuario)
    .map(x => x.dtResposta);

});

que percorre esse array:
0: {deTipoAtendimento: "012", nmAssunto: "Cartão extraviado", nmUsuario: "15", dtResposta: "2018", total: 1}
1: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Admin", dtResposta: "2018", total: 2}
2: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Administrador", dtResposta: "2018", total: 1}
3: {deTipoAtendimento: "012", nmAssunto: "Assunto Novo 012", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 3}
4: {deTipoAtendimento: "012", nmAssunto: "Assunto Teste GREAt", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 2}
5: {deTipoAtendimento: "012", nmAssunto: "Thais 23042018", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 2}
6: {deTipoAtendimento: "012", nmAssunto: "teste Alterado2", nmUsuario: "Administrador IMB", dtResposta: "2018", total: 1}

e que me retorna o seguinte array:
0: {nmUsuario: "15", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2975"}
1: {nmUsuario: "Admin", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2976"}
2: {nmUsuario: "Administrador", listNmAssunto: Array(1), listDtResposta: Array(1), $$hashKey: "object:2977"}
3: {nmUsuario: "Administrador IMB", listNmAssunto: Array(4), listDtResposta: Array(4), $$hashKey: "object:2978"}

Minha dúvida é como faço para que na hora do map eu insira tanto o nmAssunto quanto o dtResposta, dentro do mesmo *array
Answer: Basta criar o objeto com as duas propriedades e retorná-lo no callback do map
$scope.listDeColaboradoresObject.forEach(item => {

  item.listAssuntoResposta = $scope.relatorioTotalMensagensRespondidasColab
    .filter(x => x.nmUsuario == item.nmUsuario)
    .map(x => ({ nmAssunto: x.nmAssunto, dtResposta: x.dtResposta}) );

});

Como você está utilizando uma arrow function, a instrução declarada logo após o => é automaticamente interpretada como o retorno da função. Porém como você está declarando um objeto como retorno, é importante deixa-lo entre parenteses, ou o compilador/interpretador irá interpretar as chaves como o início do escopo da função, não como início da declaração de um objeto.
Comment: Muito simples, obrigado @user139742

Filter Map e Reduce


Custom Space State model using DLM in R

Question: DLM package in R can model linear space state models of the form:

I have a different category of equation which is also a linear polynomial equation of order 1 with constant coefficients. I would like to know if there is any way of modelling this custom set of equations( I want to optimize the parameters using MLE) :

Here wt and et are noise parameters with mean 0 and variance 1
As you can see here we have the parameters H and C attached with the noise terms whereas standard DLM has 1 as coefficient to the noise term.Also there is a constant intercept A
Is it possible to model it with DLM?
A,B,C are further used to calculate mean and speed of reversion using the below equations, so my main task here is to optimize A,B,C using MLE
Answer: Parameters $H$ and $C$ simply modify the variance of the respective noises.
Since dlm allows for general V and W matrices, I see no problem. You just fit the variances of the noises and then factor out $H$ and $C$ so that the noises have variance 1 if you so wish.
Concerning the intercept $A$, it seems to me that it merely adds a deterministic trend to the state. You might do the same including $A$ as an element of the state vector with variance zero.
Comment: Kindly check the edit to my question, I cannot add A to the state vector because I wish to optimize it along with the other parameters using MLE or EM algorithm.
Comment: I think if you add it to the state vector with variance zero, you will get after you run the Kalman filter a value which is its MLE estimate (assuming normality).

Custom Space State model using DLM in R


multi variable Lebesgue integrable function

Question: Let $f:[0,1]\times [0,2\pi]\to \mathbb R$ be an element of $L_1[0,1]$ of the first parameter and be a continuous function of the second parameter. Can we say that $f\in L_1([0,1]\times [0,2\pi])$?
Answer: Messing around a bit, I believe that
$$f(x,y) = \begin{cases} \displaystyle \frac{y}{y^2 + e^{-1/x}}, & x \ne 0 \\ 0, & x =0 \end{cases}$$
is a counterexample.
It is clearly continuous in $y$.  For any fixed $y \ne 0$, $f(\cdot, y)$ is a bounded function, hence in $L^1$, and $f(\cdot, 0) = 0$.  Since $f$ is nonnegative, by Tonelli's theorem we may compute $\iint_{[0,1] \times [0,2\pi]} f$ as
$$\begin{align*}
\int_0^1 \int_0^{2\pi} f(x,y)\,dy\,dx &= \frac{1}{2} \int_0^1 \left(\ln(e^{-1/x} + (2\pi)^2) - \ln(e^{-1/x}))\right)\,dx  \\
&= \frac{1}{2} \left(\int_0^1 \ln(e^{-1/x} + (2\pi)^2)\,dx + \int_0^1 \frac{1}{x}\,dx\right).
\end{align*}$$
The first integral is finite since the integrand is bounded, and the second integral is infinite.


Use row operation to find the determinant?

Question: Use row operations to find the determinant:

Can someone give me a full answer please?
Also can anyone tell me if the sign of the determinant matters ?
Row operations :
Det ( e(A) ) = <code>-det(A) ; if e is Ri interchanged with Rj</code>
Det ( e(A) ) = `Cdet(A) ; if e is CRi where C not equal to 0
Det( e(A) )   = det(A) ; if e is cRi + Rj
Where e i s a row operation.
Comment: Consider the row operation R1-R2.  If you replace R1 by R1-R2, the sign of the determinant does not change, because you did not change the sign of R1.  But, what you did was to replace R2 by R1-R2, which changed the sign of the determinant.  In effect, you multiplied R2 by negative one, and then added another row to it.  Your lecturer actually replaced R2 with R2-R1, which did not change the sign of the determinant.  Then she/he swapped two rows, which did change the sign of the determinant.
Comment: The sign of the determinant doesn't matter to me --- nothing about this determinant matters to me --- but it might matter to someone else. It depends on what you have planned for the determinant, that is, on why you are interested in the determinant in the first place. So, why are you interested in this determinant?
Comment: @Amzoti I am stuck on deciding how to subtract the rows. In my answer I said R1 - R2, then I interchanged R2 and R3. So it left me with (-1) |3 1 2 ; 0 1 4 ; 0 0 2| and the determinant of this gives -6. However my lecturer did it as : -R1 + R2, then interchanged R2 and R3 and was left with                (-1)|3 1 2 ; 0 1  4 ; 0 0 -2| which gave the determinant as 6. Is it that we have to subtract rows only by one method ?
Comment: Thanks louis, though I had to read your response a second time, your'e right.
Answer: When you perform $\mathrm R_1-\mathrm R_2$, the row $\mathrm R_1$ changes, the other two rows remain the same.
$$\begin{vmatrix}3&1&2\\3&1&0\\0&1&4\end{vmatrix}$$
$\mathrm R_1-\mathrm R_2$ gives $$\begin{vmatrix}0&0&2\\3&1&0\\0&1&4\end{vmatrix}$$
When you interchange rows $\mathrm R_2$ and $\mathrm R_3$, the sign of the determinant changes.
$$(-1)\begin{vmatrix}0&0&2\\0&1&4\\3&1&0\end{vmatrix}$$
For the row operations method, since you need to have an upper triangular matrix, you can exchange columns $\mathrm C_1$ and $\mathrm C_3$. In this step, just like the case of rows, the sign of the determinant would change again.
Interchanging columns $\mathrm C_1$ and $\mathrm C_2$ gives
$$(+1)\begin{vmatrix}2&0&0\\4&1&0\\0&1&3\end{vmatrix}$$
And now, the product of the diagonal elements gives $6$
Comment: I edited it.. :)
Comment: Isn't the determinant the product of all the diagonal elements of a n by n triangular matrix i.e (3)(1)(2) and recall we have that (-1) outside therefore the determinant will be (-1)*(3)(1)(2) = -6 ?
Comment: I'm not aware of finding the determinant by that method. How I would open the original determinant of your question is: $3[(1)(4)-(0)(1)]-1[(3)(4)-(0)(0)]+2[(3)(1)-(1)(0)]=3(4)-1(12)+2(3)=6$
Comment: that's the laplace method to find the determinant. I was looking for the row operation method. You kinda started of the way i was looking for by saying when you interchanged you will get a (-1) in front of the determinant. Also yea, the multiplication of the triangular  elements should give you the determinant. I would have referred you to some literature on that method but I am pressed for time at the moment.
Comment: Hmm.. Maybe if you could include a brief explanation of the row operation method in your question, I might be able to edit my answer to suit the method. :)
Comment: No problem, I just did.
Comment: There is no triangular matrix in the Tejas answer. "diagonal" in this context means upper-left to lower-right diagonal only, not lower-left to upper-right.
Answer: Perform row operations to get your matrix into upper triangular form. Then the determinant is the product of the main diagonal.
Comment: If you do any row swapping you have to multiply by $-1$ for each row swap.


Linked list program only printing last two nodes of list

Question: I wrote a program to create and print a single linked list. I have used structure pointer to structure pointer for modifying the list. When I print the list it only prints last two nodes added.
#include<stdio.h>
#include<stdlib.h>

struct node{
        int data;
        struct node *next;
};

struct node * createnode(int num){
        struct node * n;
        n=(struct node*)malloc(sizeof(struct node));
        n->data=num;
        n->next=NULL;
        return n;
}

void createlist(struct node **head,int num){
        struct node *temp=createnode(num);
        *head=temp;
        return;
}
void options(){
        printf("Enter your choice\n");
        printf("1.Add at end\n");
        printf("2.Add at beginning\n");
        printf("3.Add at location\n");
        printf("4.Print list\n");
}

void add_end(struct node **head){
        int info;
        printf("Value: ");
        scanf("%d",&info);
        if(*head==NULL){
                createlist(head,info);
                return;
        }
        struct node *temp=createnode(info);
        struct node **end=head;
        while((*end)->next!=NULL){
                (*end)=(*end)->next;
        }
        (*end)->next=temp;
}

void print2(struct node *head){
        struct node * temp=head;
        printf("\nList :");
        while(temp!=NULL){
                printf("%d ",temp->data);
                temp=temp->next;
        }
        printf("\n");
}

int main(){
        struct node *head=NULL;
        createlist(&head,5);

        int choice=0;
        options();
        scanf("%d",&choice);
        while(1){
                switch(choice){
                case 1:add_end(&head);
                       break;
                case 4:print2(head);
                       break;
                default:exit(0);
                }
                options();
                scanf("%d",&choice);
        }

        return 0;
}

Each time, I append 5 to 6 nodes at the end of list and when I print the list, it only prints last to nodes added.
I don't know it is wrong with add_end function or print function.
Comment: If you only have a single `int` as the list member, you can dispense with a `create_node()` function and simply do it all in a `add()` node function. If you use a `tail` pointer as well you get O(1) insertion at the end of the list. Two examples without `tail` pointer [Singly Linked List (node only, no wrapper)](https://pastebin.com/5MPLU4wB), with `tail` pointer [Singly Linked List of Integers (example)](https://pastebin.com/R2AewR3A)
Comment: Also, in C, there is no need to cast the return of `malloc`, it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714)
Answer: Your add_line routine incorrectly searches for the last node. The end variable is a pointer to pointer, so it is in a sense equivalent to the head parameter and it is not a temporary value, as it should be. Change the last lines to something like this:
void add_end(struct node **head){
    ...
    struct node *end = *head;
    while (end->next) {
           end = end->next;
           // Original line overwrites the 'head':  (*end)=(*end)->next;
    }
    end->next=temp;
}

Comment: Was that changing what the head pointer was pointing at, each time I append a node
Comment: Yes, you were overwriting the (*head) by assigning to (*end).


Is there a test for how appropriate a seemingly unrelated regression (SUR) is in the presence of possible endogeneity?

Question: I have two equations which I would like to use in a SUR about innovation and investment in a specific sector:
{sector innovation proxy}=a+b1{sector specific policies}+b2{general investment policies}+b3{controls}+e
{sector specific investment}=a+b1{sector specific policies}+b2{general investment policies}+b3{controls}+e
Both equations would use the same data set, except for the dependent variable.
Now, my colleagues suggested I have to be careful not to run into endogeneity problems, but could not point to a possible source of endogeneity.
I would like to have a test showing them that a SUR is warranted and that therefore I do not need to use the two equations in some sort of simultaneous equation model or a similar solution to counter endogeneity.
I am sorry if this is a rather basic questions (I am aware that endogeneity cannot be discovered by a statistical test), but I am generally wondering if there is a statistical justification or counter-indication for SUR.
Answer:
[...] but I am generally wondering if there is a statistical justification or counter-indication for SUR.

There is; it is a Breusch-Pagan test between the errors of the separate equations run as OLS. It is explained in this video. In short: the test shows if there is a correlation between the errors. If there is, there is a bias that could be removed by SUR.
Answer: first off when you run a sur model you cant use the same dependent variables in both equations because it will reduce to OLS. you should omit one dependent variable from one of the equations.


Compute the minimal radius $r$ such that $B_r(a) \cap B_r(b) \cap B_r(c) \ne\varnothing$

Question: Let $a, b, c \in \mathbf{R}^2$. I am interested in finding the minimal radius $r$ such that $r$ such that $B_r(a) \cap B_r(b) \cap B_r(c) \ne\varnothing$, where $B_r(p)$ denotes the closed ball of radius $r$ about $p$. I know how to check if there is such a triple intersection for a given $r$, but I did not manage to turn this into a way to compute $r$.
Comment: One can consider function $f(t)$, $t\in \mathbb{R}^2$, such that $f(t)$ is maximum of distances from $t$ to $a$, $b$, $c$. Then $r$ is minimum of $f(t)$.
Answer: Let $$M:=\{R\in\mathbb{R} |\,B_R(a)\cap B_R(b)\cap B_R(c) \neq \emptyset \}$$
$$r:= \min M$$
and
$$m:=\frac{1}{2}\max\{\text{dist}(a,b),\text{dist}(a,c),\text{dist}(b,c)\}$$
Then first we notice, that trivially
$$r\geq m.$$ Thus if $m\in M$, then $r=m.$
We have to distinguish two cases. The points $a,b,c$ form a triangle.
Case 1: The triangle is obtuse. Then you can show using the properties of obtuse triangles (see here) that indeed $m\in M$ and thus $r=m$.
Case 2: The triangle is acute. Here $m\notin M$. However in this case the circumcenter $O$ of the triangle lies inside of it, it has the same distance to $a,b,c$ respectively. Your solution is then $r=\text{dist}(a,O)$. You can see that this must be the minimal solution, because $B_r(a)\cap B_r(b)\cap B_r(c) = \{O\}$ which can not be optimized.
Case 3: The triange is right-angled. In this case the above solutions coincide $r = m = dist(a,O)$.
Comment: [+1] good answer.


Posicionar texto antes do conteúdo

Question: Queria fazer uma borda com conteúdo assim

Mas não sei como colocar o fale conosco dentro da borda, olha como esta minha imagem

Meu código

.Campos {
  margin-left: 90px;
  border: 10px outset #ffc70e;
  border-radius: 0px 25px 0px 0px;
  margin-top: 26px;
  width: 100%;
}

#conosco {
  text-align: center;
}

.titulos {
  margin-left: 40px;
  font-size: 15pt;
  color: #101010;
}

.campo {
  width: 300px;
  border-radius: 5px;
  margin-left: 40px;
}

Fale Conosco

preencher os campos abaixo:

Nome:(*)
<input type="text" class="campo">

Email:(*)
<input type="text" class="campo">

Telefone:(*)
<input type="text" class="campo">

Celular:
<input type="text" class="campo">

Como nós conheceu ?:(*)
<input list="opcoes" name="opcos" class="campo">
      <datalist id="opcoes" class="campo">
    <option value="Google">
    <option value="LikedInk">
    <option value="Facebook">
    </datalist>

Answer: Eu faria assim, não sei se tem outro modo de fazer.

.Campos {
  margin-left: 90px;
  border: 10px outset #ffc70e;
  border-radius: 0px 25px 0px 0px;
  margin-top: 26px;
  width: 100%;
}

#conosco {
  margin: auto;
  text-align: center;
}

.titulos {
  margin-left: 40px;
  font-size: 15pt;
  color: #101010;
}

.campo {
  width: 300px;
  border-radius: 5px;
  margin-left: 40px;
}

.fundo {
  margin: 0 auto;
  background-color: #ffc70e;
  padding: 15px;
}

Fale Conosco

preencher os campos abaixo:

Nome:(*)
<input type="text" class="campo">

Email:(*)
<input type="text" class="campo">

Telefone:(*)
<input type="text" class="campo">

Celular:
<input type="text" class="campo">

Comment: valeu man funcionou do jeito que eu queria obrigado
Comment: De nada cara, tmj.

Posicionar texto antes do conteúdo


Is it possible for a runner to advance if the batter doesn't hit the ball?

Question: Let's say the pitcher throws the ball but the batter does not hit it. Can someone at first,second or third proceed to the next base?
Answer: Yes, this is called a stolen base or a "steal" and is a relatively common occurrence in the game.
Comment: If you think that's a worthwhile debate, please start it on [meta](http://meta.sports.stackexchange.com/), not in comments. Just because you know lots about baseball doesn't mean everybody does; there are many parts of the world where the game just isn't played.
Comment: It is something easily researched.  Questions are supposed to be asked to find an answer that isn't easily googled or takes some sort of explaining.
Comment: Again: **take it to meta**.
Comment: Not downvotinng but there should be a baseline on questions answered and this question is definitely below it.  The next question on the list is "What is it called when a hitter gets to third on their hit?"  Also you didn't even cover the entire answer which would be a stolen base, passed ball, or any type of error.
Comment: Regardless, you can't update your answer or acknowledge that your answer was lacking in the comments.
Comment: @PhilipKendall This is already covered in the [help center](http://sports.stackexchange.com/help/how-to-ask). "...Sharing your research helps everyone. Tell us what you found and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself..." Because someone doesn't know about baseball doesn't absolve him/her from doing research.
Comment: Hillariously dry answer.
Answer: Yes Definately .. If the next base is empty then only you can run, if not empty then you are called out as two players on same base occur.
Reference Base Stealing
Comment: This is incorrect; two runners on the same base does not automatically mean an out - it is only *passing* the other runner that leads to an out. Of course, only one of the runners is entitled to the base so the other is at risk of being put out if tagged.


Help with a second order differential equation

Question: I am dealing with a differential Eq. with the form $y''+ p(t)y'+q(t)y = 0$, introducing the function $Y=sin(t^2)$, but in an awkward step forward I found that:
$sin(t^2)(q(t)-4t^2)+cos(t^2)(2tp(t)+2)=0$
turns into:
$(2tp(t)+2)=0$
I've been wondering how is this possible, I've used a lot of algebra and even the obvious solution $pc_1+qc_2=0$ but I still can't explain it myself, please help, thanks a lot.  This excersice can be found in Boyce Di Prima Book
Answer: Ok. I've finally found the right answer, I omitted the fact that p(t) and q(t) are continuous coefficients, thus they are finite, but if I fit t=0 in the t values $sin (t^2)$ eliminates its partners


Where to write hook_commerce_payment_method_info() in drupal8?

Question: I am migrating one of the drupal commerce related module from Drupal-7 to drupal-8.As I am newbie to D8, struggling to get proper structure in drupal-8. I have a hook that is hook_commerce_payment_method_info(). I am confused to where to write this hook. I am guessing it will be in .module file. please share your suggestions to me. So that I can move in right direction. Thanks in advance.
Answer: Payment methods are now called Payment gateways and they are plugins, like anything else.
So, look for the @CommercePaymentGateway annotation, like in this example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment_example/src/Plugin/Commerce/PaymentGateway/Onsite.php and the others in that folder.


Understanding dense sets

Question: My course notes state that $E$ dense in $X$ $\Leftrightarrow$ for each point $p\in X$ and $\epsilon>0$, there exists a  point of $E$ in $B(p,\epsilon)$. I would appreciate it some guidance in helping me develop an intuition for dense sets.
Here's my verbal proof:
$\Rightarrow X\subset\overline{E}$, so any point $p$ in $X$ is either a point in $E$ or a cluster point of $E$. The first case is trivial ($p$ is already a point in $E$). In the second case, by definition of a cluster point, setting any radius of an open ball centred at $x$ will yield a (different) point in $E$.
$\Leftarrow$ There are two cases: either $p$ is in $E$ or not. The first case is trivial, and $p$ is in $\overline{E}$. In the second case, following the same logic, setting any radius open ball centred at $p$ yields a point of $E$, and by induction, we get infinitely many points of $E$. As such, $p$ is a cluster point and therefore in $\overline{E}$.
I believe that my proof is generally correct, however I welcome anybody with any insightful perspectives or corrections to enlighten me on this notion :)
Comment: What is your definition of dense? The theorem you are trying to prove seems like the definition to me.
Comment: How precisely are you using induction in the second implication? Any radius guarantees a point in $E$, but then you have to say how you will get the next point and why it is different from the first.
Answer: It seems as though your course notes are taking "$\overline{E} = X$" as the definition of "$E$ is dense in $X$", at least, this seems to be what you're proving, so let's run with it.
Your forward direction ($\Rightarrow$) looks great!
Your backwards direction ($\Leftarrow$) is really close, and you have exactly the right idea! You let $p \in X$, and try to show that $p \in \overline{E}$. First, if $p \in E$, then life is good. It's obviously in $\overline{E}$ since $p \in E \subseteq \overline{E}$. So we're left with the case where $p \not \in E$.
Here you say

... setting any radius open ball centred at $p$ yields a point of $E$, and by induction, we get infinitely many points of $E$. As such, $p$ is a cluster point and therefore in $\overline{E}$.

This is exactly the right idea, but the technique is a bit sloppy. In particular, it's not clear what you're inducting on. What's your base case? Or your inductive case? Remember that (in most books) a cluster point of a set $S \subseteq X$ is a point $q$ so that every neighborhood of $q$ intersects $S \setminus \{ q \}$. This requires us to build a point in $B(q,\epsilon) \cap (S \setminus \{ q \})$ for uncountably many possible choices of $\epsilon$. While there are ways to do this by some kind of induction (for instance, using the fact that each $\epsilon$ is at least $\frac{1}{n}$ for some $n$), it's making things more complicated than they need to be.
Thankfully, we can sidestep this whole induction business by just showing the claim directly!
In our case, we know $p \not \in E$. So then $E \setminus \{ p \} = E$, and we can restate the definition that $p$ is a cluster point of $E$ as: "for every $\epsilon > 0$, we can find a point in $B(p,\epsilon) \cap E$".
But let's look again at our assumption for the right to left direction! Again, quoting from your question:

My course notes state that $E$ is dense in $X$ $\Leftrightarrow$ for each point $p \in X$ and $\epsilon > 0$, there exists a point of $E$ in $B(p,\epsilon)$

This assumption is precisely what we need! Since we have it, then, we're done.

Now, to answer the question regarding intuition for dense sets.
We should think of a dense set $E \subseteq X$ as being a set that's "close to every point of $X$". This tells us that we can approximate any element of $X$ by elements of $E$, which might be much nicer!
For example, look at $\mathbb{Q} \subseteq \mathbb{R}$. Every element of $\mathbb{R}$ can be approximated as closely as we like by a rational number. So if we want to prove something is true for all reals (for instance, that $2^{x+y} = 2^x 2^y$) we can prove it first for rationals (which is easier, since we can express $2^\frac{a}{b}$ in terms of repeated multiplication and radicals) then argue by continuity that the claim extends to all of $\mathbb{R}$!
For another, even more impressive example, look at $C^\infty([0,1]) \subseteq C^0([0,1])$. That is, the set of all infinitely differentiable functions $f : [0,1] \to \mathbb{R}$ as a subset of the set of continuous functions $[0,1] \to \mathbb{R}$.
At some point in your life you may have heard that most continuous functions aren't even once differentiable, let alone infinitely differentiable! (See here for instance)
What this density result tells us is that we can still approximate continuous functions by infinitely differentiable ones, and we can take these approximations to be as good as we like!
Then, if we want to prove something is true for all continuous functions, a very common strategy is to first prove it for infinitely differentiable functions (where we have access to all of calculus to help us!) then argue by continuity that it's true for all continuous functions.
In general, it's a common plan when given a space $X$ to find a dense set of "nice" objects $E$. Then we can (up to approximation) pretend that every element of $X$ is "nice", which helps us prove theorems!
It's worth thinking to yourself how this (extremely useful) notion is related to the geometric/physical notion of "denseness". It should make intuitive sense that the $\mathbb{Q}$ is dense in $\mathbb{R}$, for instance. After all, no matter where you look you can spot infinitely many rationals packed in around any real you like! Do you see how this intuition translates to the mathematical definition of "dense-ness"?

I hope this helps ^_^
Comment: Wow! Thanks for your time in writing an encouraging and informative answer, especially now that I realize how trivial it is haha.
Comment: And your analogy on how a dense set contains "nice" elements that help us "approximate" the ones of its corresponding set is very helpful--a great image for me to keep in the back of my head moving forward in Real Analysis.
Comment: Also, your answer, particularly your ∞([0,1])⊆0([0,1]) example, makes me understand the motivation behind the next section in my course: sequences, convergence, and continuous functions in general metric spaces!

Understanding dense sets


OneAuth Blank Callback

Question: I'm using Laravel and OneAuth to build a web application. The user can sign in with his/her Twitter or GitHub account.
This actually works perfectly on my local dev server (with the exception of GitHub because the callback URLs don't match localhost), but when I've uploaded it to production, I get a blank page (/connect/callback/twitter).
Anyone else experienced this with OneAuth?
There are no errors in the error log, and the page has a 200 status code.
Local server:

Mac OS X 10.8
MAMP
PHP 5.4

Production:

CentOS 5
Apache + PHP 5.3
Comment: Error reporting is enabled as far as I can tell. Errors get logged for everything else...
Comment: the callback url should be connect/callback/twitter
Comment: Sorry, my mistake. It is connect/callback/twitter, it was a typo.
Comment: Does it work with Github on production server? I don't see any reason why it's not working. unless your curl is not properly installed, which would cause SSL Certification issue.
Comment: It's the production server that's the issue. As far as I know, curl is ok since I can use it from the terminal without issues.
Comment: curl from terminal ~== curl from php. http://stackoverflow.com/a/10417888/1458318
Comment: Any solution to this? I am facing this issue.
Answer: Yeah i had this problem and the work around for this is to manually register your controller instead of doing ,
Route::controller(Controller::detect());

Do this,
Route::controller('connect');

FYI: If you are using nested controller the order in which you register matters.

OneAuth Blank Callback


ANOVA using count data

Question: I'd like to perform a two-way ANOVA on count data. I was told to first fit a GLM and then do the ANOVA.  My first problem is that
fit1 <- aov(glm(Branches~Accession*Location, data=branches, family=quasipoisson))
summary(fit1)

and
fit2 <- glm(Branches~Accession*Location, data=branches, family=quasipoisson)
Anova(fit2, test="F")

don't result in the same p-values.  What is the mistake here? Which is the right way of doing this, or is it wrong to do an ANOVA following a GLM anyway?
My second problem is that I don't know how I can do a post hoc test. For example, when I do a Tukey's test, should I use the ANOVA model of the GLM or the GLM itself?
Comment: Is that `Anova` from package car? Can you show at least the output you get from your code? For multiple comparison you should use package multcomp and its [`glht` function](http://www.inside-r.org/packages/cran/multcomp/docs/glht).
Comment: What does the help say the functions do? Is this - for example - a type I vs type III sums of squares issue?
Answer: I don't know how aov handles glm objects, but the documentation for aov mentions only lm objects.
My advice, then, is to not use aov, but just use car::Anova directly to produce an analysis of deviance table.  Another option is emmeans::joint_tests.
For post-hoc testing, I recommend the emmeans package, since it explicitly lists supported model objects.
if(!require(car)){install.packages("car")}
if(!require(emmeans)){install.packages("emmeans")}

set.seed(1234)

Accession = factor(rep(c("1", "2", "3"), 1, each=6))
Location  = factor(rep(c("A", "B"), 9))

Branches  = as.numeric(Accession) * 2 +
           as.numeric(Location) + rnorm(length(Accession), 0, 1)

Branches = round(Branches)

branches = data.frame(Accession, Location, Branches)

str(branches)

# # #

fit1 <- glm(Branches~Accession*Location, data=branches, family=quasipoisson)

summary(fit1)

library(car)

Anova(fit2)

   ### Analysis of Deviance Table (Type II tests)
   ###
   ### Response: Branches
   ###                   LR Chisq Df Pr(>Chisq)
   ### Accession            36.153  2  1.411e-08 ***
   ### Location              5.912  1    0.01504 *
   ### Accession:Location    1.841  2    0.39837
   ### ---
   ### Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

library(emmeans)

marginal = emmeans(fit1, ~ Accession)

pairs(marginal)

   ### NOTE: Results may be misleading due to involvement in interactions
   ###
   ###  contrast   estimate        SE  df z.ratio p.value
   ###  1 - 2    -0.3389399 0.1363010 Inf  -2.487  0.0345
   ###  1 - 3    -0.7680533 0.1260328 Inf  -6.094  <.0001
   ###  2 - 3    -0.4291135 0.1128866 Inf  -3.801  0.0004
   ###
   ### Results are averaged over the levels of: Location
   ### Results are given on the log (not the response) scale.
   ### P value adjustment: tukey method for comparing a family of 3 estimates

ANOVA using count data


2d pointer initializing in

Question: I have this data member in my class:cell** rep. I want to set size of the 2d  in constructor. I receive no error while compiling; but no result comes when i run it.
//main.cpp
    #include <ctime>
    #include <cstdlib>
    #include "cell.h"
    #include "world.h"
    using namespace std;

    int main(){
srand(time(0));
World Conway(6,6);
Conway.generateWorld();
int numAlive = 1;
do{
    numAlive = Conway.print();

    Conway.nextGeneration();

    cout<<"\n\t\t\t*****************\n\n";
    cin.get();
}while(numAlive);
cin.get();
return 0;
  }

//cell.h
#ifndef CELL_H
#define CELL_H
class Cell {
private :
    bool alive;
public :
    Cell() ;
    void setAlive(bool b);
    bool isAlive();
};
#endif

//cell.cpp
#include "cell.h" // class's header file
Cell::Cell(){
alive = false;
}

void Cell::setAlive(bool b){
alive = b;
}

bool Cell::isAlive(){
return alive;
}

//world.h
#ifndef WORLD_H
#define WORLD_H
#include "Cell.h"
class World {
private :
    bool ring;
    int lines, columns ;
    Cell** rep; //I could not write this with pointer
public :
    World (int l, int c) ;
    World (int l, int c, bool ring);
    ~World() ;
    int getLines();
    int getColumns();
    void generateWorld();
    int nbAliveNeighbor( int i, int j) ;
    int nbAliveNeighborRing( int i, int j);
    void nextGeneration();
    int print();    //the output of this function help me to end main loop

} ;
#endif

//world.cpp
#include "world.h" // class's header file
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

World::World (int l, int c) {
lines = l;
columns = c;
ring = false;
Cell **rep = 0;
// memory allocated for elements of rows.
rep = new Cell *[l];
// memory allocated for  elements of each column.
for( int i = 0 ; i < l ; i++ ) {
    rep[i] = new Cell[c];
}

}

World::World(int l,int c,bool r){
lines = l;
columns = c;
ring = r;
 }

int World::getLines(){
return lines;
}

int World::getColumns(){
return columns;
}

int World::nbAliveNeighborRing( int i, int j){
int n = 0;  //number of alives
for(int r = i-1; r < i+2; r++){
    for(int c = j-1; c < j+2; c++){

        //giving ring flexibility
        if(c < 0)
            c + columns;
        if(c >= columns)
            c - columns;

        if(r < 0)
            r + lines;
        if(r >= lines)
            r - lines;

        if(c==j && r ==i)
            continue;   //ignoring the cell itself

        if(rep[r][c].isAlive())
            n++;
    }
}
return n;
}

int World::nbAliveNeighbor( int i, int j) {
int n = 0;  //number of alives
for(int r = i-1; r < i+2; r++){
    for(int c = j-1; c < j+2; c++){

        //ignoring if it's out of range
        if(c < 0 || c >= columns)
            continue;
        if(r < 0 || r >= lines)
            continue;

        //ignoring the cell itself
        if(c==j && r ==i)
            continue;

        if(rep[r][c].isAlive())
            n++;
    }
}
return n;

}
int random(int a,int b){
return a+rand()%(b-a+1);    //including a & b
}

void World::generateWorld(){
int nAlive = (lines * columns)/ 4 + 1;
//why plus 1:
// because in random some are the same so we plus it with 1 so in the average
// the alive cells will be third of deads!

int randAry[nAlive];

for(int i=0, clm=0, row=0; i < nAlive; i++){
    randAry[i] = random(0,lines*columns);
    clm = 0;
    row = 0;
    while(randAry[i] >= lines){
        row ++;
        randAry[i] -= lines;
    }
    clm = randAry[i];
    rep[row][clm].setAlive(true);
}

}

void World::nextGeneration(){
if(ring){
    for(int i = 0; i < lines; i++){
        for(int j = 0; j < columns; j++){
            if(rep[i][j].isAlive()){
                if(nbAliveNeighborRing(i,j) == 3 || nbAliveNeighborRing(i,j) == 2)
                    continue;
                else
                    rep[i][j].setAlive(false);
            }
            else{
                if(nbAliveNeighborRing(i,j) == 3)
                    rep[i][j].setAlive(true);
            }
        }
    }
}
else{
    for(int i = 0; i < lines; i++){
        for(int j = 0; j < columns; j++){
            if(rep[i][j].isAlive()){
                if(nbAliveNeighbor(i,j) == 3 ||        nbAliveNeighbor(i,j) == 2){
                    continue;
                }
                else{
                    rep[i][j].setAlive(false);
                }
            }
            else{
                if(nbAliveNeighbor(i,j) == 3){
                    rep[i][j].setAlive(true);
                }
            }
        }
    }

}
}

int World::print(){
int n = 0;
for(int i = 0; i < lines; i++){
    for(int j = 0; j < columns; j++){
        if(rep[i][j].isAlive()){
            cout<<" * ";
            n++;
        }
        else
            cout<<" - ";
    }
    cout<<endl;
}
return n;
}

World::~World(){
delete rep;
}

Comment: at first in constructor i had put int** rep, that was an typing error. it must be Cell **rep. now I have edited it!
Answer: Your Cell** rep is never created. This should be done in the constructor. Now you're making int **rep = 0;, which doesn't seem to be used anywhere.
//int **rep = 0; //scratch this
rep = new Cell *[l];
// memory allocated for  elements of each column.
for( int i = 0 ; i < l ; i++ ) {
    rep[i] = new Cell[c];
}

Comment: writing int instead of Cell was an typing error when i was typing the question. but u have used the * correctly thank you!
Answer: Maybe that Cell.h is capitalized in include of world.h
Comment: no if it was so the compiler would have raised an error like not declaring Cell!
Answer: In class World data member rep is defined as
class World {
private :
    bool ring;
    int lines, columns ;
    Cell** rep; //I could not write this with pointer
...

However in the constructor you use a local variable rep that have type int ** and try to initialize that local variable that will be destroyed after exiting the constructor.
World::World (int l, int c) {
lines = l;
columns = c;
ring = false;
int **rep = 0;
// memory allocated for elements of rows.
rep = new int *[l];
// memory allocated for  elements of each column.
for( int i = 0 ; i < l ; i++ ) {
    rep[i] = new int[c];
}

Comment: at first in constructor i had put int** rep, that was an typing error. it must be Cell **rep. now I have edited it!

2d pointer initializing in


Iniciar uma thread novamente

Question: Tenho um evento no botão iniciar, sempre que carrego são geradas 3 threads que iniciam a contagem de 30 ate 0, a que chegar 1º ao 0 ganha. Mas contudo volto a carregar umas vezes no botão iniciar e a contagem começa em 30 e faz tudo igual, se continuar a carregar no botão iniciar mais uma ou duas vezes ele vai erros e deixa de correr a thread.
A minha questão é: Eu inicio três threads quando carrego no botão iniciar mas para voltar a fazer isso na mesma frame é preciso matar as threads ou interrompe las?
c1,c2,c3 são objetos Cavalo.

Classe CorridaCavalos
iniciar.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {
        c1.setMovimentos(30);
        c2.setMovimentos(30);
        c3.setMovimentos(30);

        c1.start();         //start iniciar o run da thread cavalo c1 - classe cavalo
        c2.start();
        c3.start();
    }

});

Classe Cavalo extends thread - onde defino instruções da mesma
@Override
public void run(){
try {
    while(movimentos > 0){
        sleep((long) (500*Math.random()));
        movimentos--;
        textField.setText(Integer.toString(movimentos));        //Converter Inteiro para String
    }
} catch (InterruptedException e) {
    interrupt();
}
}

Answer: Sim, é preciso finalizar as threads. Mais do que isso, você deve declarar suas instâncias de Cavalo dentro de actionPerformed(), para que a cada clique sejam criadas e  colocadas em execução novas threads:
iniciar.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {
        if (c1 != null) {
            c1.setMovimentos(0);
            c1.interrupt();
            c2.setMovimentos(0);
            c2.interrupt();
            c3.setMovimentos(0);
            c3.interrupt();
        }
        c1 = new Cavalo();
        c2 = new Cavalo();
        c3 = new Cavalo();

        c1.setMovimentos(30);
        c2.setMovimentos(30);
        c3.setMovimentos(30);

        c1.start();         //start iniciar o run da thread cavalo c1 - classe cavalo
        c2.start();
        c3.start();
    }

});

Observação: o comando interrupt() abaixo do catch é desnecessário.
Comment: Porque quando a `InterruptedException` é lançada a thread já está interrompida. Não é necessário interrompê-la novamente. Basta os `interrupt()` chamados dentro de `actionPerformed()`, que são os que causam o lançamento da `InterruptedException`.
Comment: Na verdade também esses `interrupted()` podem não ser suficientes. Acrescentei o comportamento de zerar os movimentos, o que faz as threads saírem dos loops, para os casos em que o `interrupted()` é chamado e a thread não se encontra em `sleep()`.
Comment: porque é que o interrupt() é desnecessário?

Iniciar uma thread novamente


If A is a large number and B is a larger number than A, find C which is the nearest number to A that goes into B x times.

Question: A = 2548788451252366445785585474844745854781554558547847844

B = 50135928365972237608005364328936872115615930177019003323815

x is unknown

Given A and B find C, where C must be the nearest integer to A that goes into B x times.
Note: C must be smaller than A or equal with A.
Calculating C manually will involve subtracting or dividing A from B x times until we get near A and therefore to C.
Is there a formula or maybe a SageMath or PARI method to calculate C?
Thanks.
Answer: You can just divide $B$ by $x$, then round down to the next whole number.  Any language that lets you handle integers this large will do that.  $A$ does not figure in this at all.
Based on the comment you are just asking for the remainder of the division of B by A.  Many languages have a modulo operator which will do this.  Often it is the percent sign, so you would write $C=B\%A$  You can do division with remainder in any language that can handle large integers.  If you can't do the modulo operation, you can do integer division and $C=B-\lfloor B/A\rfloor\cdot A$
Comment: The division is most certainly not exact. There will be remainders. But if we substract let's say A from B many times we will eventually get to a C number that's closest to A. Doing this manually with large numbers is very difficult. Hope it makes sense.
Comment: Thanks, but [x] is unknown so I cannot use this method. I will update the question to mention this fact.
Comment: Then what are you trying to answer?  Are you actually looking for a number that divides $B$ exactly?  You should say that.
Comment: I'm looking for the closest number to A that goes into B x times. I don't know x because if I knew that this would have been a simple task to answer.
Comment: Yes, you said that.  Do you mean it has to divide exactly?  Otherwise it doesn't give any information to say "goes into $B\ x$ times" without knowing $x$
Comment: So with smaller numbers:  if A=111 and B=570 then we do 570-111-111-111-111-111=15

C=15 in this case.

Not sure if I've explained correctly in the question but this number 15 is the nearest to 111 that is not larger than 111.  Maybe I am looking for a remainder but not sure if it's possible to calculate with larger numbers.


PHP exec not executing python script with module imports

Question: OK so im trying to get exec() to execute a script that works fine from idle.
If I try a simple script it works fine, such as:
hello = "hello"
world = "world"
print hello + " " + world

But the script I actually want to run wont work and I can only assume its because of the module import, the code is as follows:
import serial
port = serial.Serial('/dev/ttyAMA0', baudrate=19200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=5)
port.open

port.write("\x02\x00\x00\x00\x00\x02")

My PHP code is:
 <?php

   $result = exec('python python.py');#This works fine

   echo $result

   ?>

   <?php

   $result1 = exec('python proOn.py');# This wont work

   echo $result1

   ?>

Answer: Try this:
<?php

$command = escapeshellcmd('proOn.py');
$result1 = shell_exec($command);
echo $result1;

?>

refer this.
Comment: Didn't work unfortunately, tried everything in that link as well


Função .unload() - jQuery

Question: Eu faço duas requisições ajax para um arquivo externo do qual adicionam e removem produtos, porém isso não é muito relevante nessa questão. Eu queria que toda vez que a página fosse atualizada, a função removeCartaotoCart fosse acionada para que segundo o id do produto selecionado, o mesmo fosse retirado antes da página ser recarregada.
Código das requisições Ajax:
var productSelected = "";

            function addCartao(product){
                if( productSelected != "" ){
                    removeCartaotoCart(productSelected);
                  }
                $j('#cartaoMensagem'+product).hide();
                $j('#cartaoMensagemRemover'+product).show();
                $j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
                $j.ajax({
                  type: "POST",
                  url: "adiciona.php",
                  data: {
                    product: product
                  },
                  dataType: 'json',
                  cache : false,
                  beforeSend: function () {

                  },
                  success: function (retorno) {
                    var button = $j('#cartaoMensagemRemover'+product);
                    productSelected = product;
                    $j('.item-custom').append('

' + retorno['name'] + '
	1	 R$ ' + retorno['price'] + '
');
                    getSubTotal();
                    getGrandTotal();
                  },
                  complete: function () {

                  },
                  error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                  }
              });
            }

            function removeCartaotoCart(itemId){
                console.log('Entrou');
                console.log(itemId);
                productSelected = "";
                $j('#cartaoMensagemRemover'+itemId).hide();
                $j('#cartaoMensagem'+itemId).show();
                $j.ajax({
                    type:"POST",
                    url:"remove.php",
                    data:{
                        itemId: itemId
                    },
                    cache: false,
                    beforeSend: function(){

                    },
                    success: function(retorno){
                        var button = $j('#cartaoMensagemRemover'+itemId);
                        $j('.item-custom #trAppend'+itemId+'').remove();
                        getSubTotal();
                        getGrandTotal();

                    },
                    complete: function () {

                    },
                    error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                  }
                });
            }

        $j(window).unload(function(){
            console.log('Recarregando ...');
            console.log(productSelected);
            removeCartaotoCart(productSelected);
        });

Observação: Eu tentei fazer a função .unload(), mas me retorna erros ([object Object]) e o produto não é removido.
Answer: O problema é que não tem como fazer essa requisição pela função .unload(), pois além do erro, ele "quebraria" essa requisição no meio. No caso, ela deve ser feita no carregamento da página, por meio do seguinte código:
$j(document).ready(function(){
    console.log('Carregando ...');
    console.log(productSelected);
    removeCartaotoCart(productSelected);
});

Função .unload() - jQuery


Contagem de compartilhamento e curtidas do facebook no loop do wordpress

Question: Seguinte estou tentando colocar só uma contagem dos compartilhamento que tive no Facebook no loop do meu tema. Para isso achei a seguinte função e tentei modifica-la para minha necessidade.
Segue a função:
function ia_fb_count($url_post) {
//Get the transient value from database
$fbcount = get_transient( 'fblcount' );
    if ( empty( $fbcount ) ){
        //If no value stored, get the like count
       $file = file_get_contents("http://graph.facebook.com/?ids=$url_post");
            $jd = json_decode($file);
            $fbcount = number_format($jd->{'shares'});

        // Set the facebook likes transient value for 24 Hours
        set_transient('fblcount', $fbcount, 60*60*24 );
        // Also, return it at the same time
        return $fbcount;
    } else {
        // Transient Value is present, return it
        return $fbcount;
    }
}

Como eu chamo a função no meu tema:
<?php
   $url_post = the_permalink();
   echo ia_fb_count($url_post);
?>

Alguém poderia me ajudar?
Comment: @Qmechanic73 mais no meu tema não está aparecendo as contagem do shared e sim o link da url.. veja na imagem: http://www.tickimg.com.br/uploads/_url_faceboo.jpg preciso que apareça só a contagem de shared do facebook
Comment: @Qmechanic73 continua não chamando só a numeração e sim a url toda http://localhost/wordpress/?p=368851,588 .. acho que essa função não está pegando o link passando pelo o thema.. no $url_post .. só não estou sabendo e fazer como!
Comment: Fazendo isso manualmente retorna algum resultado?
Comment: @Qmechanic73 está retornando esse erro: http://localhost/wordpress/?p=36885
Warning: file_get_contents(http://graph.facebook.com/?ids=): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\wordpress\wp-content\themes\brasilseries\functions.php on line 135
Comment: Deve ser porque você está formulando errado a url, veja se desse [**jeito**](http://pastebin.com/sT3jKTAH) funciona.
Answer: A função que você está usando para pegar o permalink está errada. Essa função retorna o link com a tag html: <a href="<?php the_permalink(); ?>">permalink. É para imprimir o permalink e não para buscar a URL. No seu código deve utilizar a função get_permalink.
Como você está chamado essa função pelo tema, é importante buscar o ID do post. Assim você pode chamá-la fora do loop também.
<?php
   global $post;
   $url_post = get_permalink($post->ID);
   echo ia_fb_count($url_post);
?>

Por fim, se você está testando em um localhost o graph api vai retornar um erro porque ele não consegue achar a URL.


Como nomear variáveis e organizá-las no código no que vai além da PEP 8?

Question: Onde eu poderia encontrar dicas pra nomear variáveis, pra organizar o código, etc.?
Por exemplo, tenho uma classe e ela tem vários atributos, alguns dependem que um outro atributo tenha sido declarado antes, mas outros são independentes, como poderia ordenar qual colocar primeiro e depois? Exemplo:
<code>class Button(object):
    defs __init__(self):
        self.image = pygame.image.load()
        self.rect = self.image.get_rect()
        self.draw = True
        self.moved = False
        self.text = font.render(text, True, color)
        ...
</code>
Nunca li nada que dissesse como por em ordem os atributos, ordem alfabética talvez? E outra coisa tentei usar todos os nomes em inglês mas acabei esbarrando em alguns que eu nao consegui traduzir por exemplo vazas, truco...
Onde eu posso encontrar coisas assim?
Answer: Você poderia começar chamando de campos em vez de atributos, afinal a linguagem oficialmente chama outra coisa de atributo.
Não há regra sobre a ordem dos campos, em geral deveriam ser colocados em ordem que faça sentido, que ajude ler o código mais facilmente, por isso os que são dependências de outros deveria vir antes. Deveria ter um certo agrupamento, e considerar a importância deles. Só com o requisito dá para saber como fazer. Ordem alfabética costuma ser terrível e pode denotar outro problema.
Note que aí são variáveis usadas localmente. Particularmente não gosto dessa forma de inicialização, mas é coisa minha. E assim a dependência precisa ser respeitada.
Se tem dificuldade com o inglês, não o use. Melhor fazer em português do que fazer algo ruim em inglês. Nem em português eu sei do que está falando. Você pode procurar palavras em inglês no dicionário. Mas ele não ajudam muito porque não é o termo usado efetivamente em grande parte dos casos. Os nomes devem ser dados para expressar bem o que eles realmente são. Se o domínio que está solucionando é em português, faça em português. Se o domínio é em inglês e não sabe quais são os termos é o caso de pedir ajuda para outra pessoa que saiba, não só para traduzir.
Entender profundamente o problema e como resolvê-lo é muito mais importante, e feito isso a solução vem naturalmente. Não feito, nada salvará o código.
Note que a pergunta não tem nada a ver com Python, nomenclatura ou convenções em si. Tem alguma coisa estilo de codificação e com algo que não é programação.


Show that if $(a,n)=d>1$ and $k$ is any positive integer, then $a^k\not\equiv 1\pmod{n}.$

Question: So I know that if $(a,n)=1$, then $a^{\phi(n)}≡1\pmod{n}$ by Euler's Theorem. I also know that $d \mid a^k$ and obviously $d \mid n$. I know I probably need to use this in the proof, but I just don't know how to get started.
Comment: $a\equiv b \pmod n$ means $a = b + nk$
Answer: Given $(a,n) = d > 1$, suppose for the sake of contradiction that for some $k > 0$, $a^k \equiv 1 \pmod{n}$. Rewrite the equivalence as $(a/d)^kd^k \equiv 1 \pmod{n}$. This implies that $d^k$ is the multiplicative inverse of $(a/d)^k$ modulo $n$. Such an inverse exists if and only if $d^k$ is relatively prime to $n$; however, since $d \mid n$, we know $d^k$ and $n$ share a factor of $d > 1$. Therefore, $d^k$ is not relatively prime to $n$, so we have a contradiction.
Answer: Suppose $a^k \equiv 1\bmod{n}$. Write $a=da',n=dn'$.
Then $n' \equiv n' a^k = n' a a^{k-1} =n'da' a^{k-1} = na' a^{k-1} \equiv 0 \bmod n$.
This contradicts $0< n' < n$.
Answer: If $\gcd(a,n) = d > 1$ then $d \mid a^k, \forall k\in \mathbb{Z^+}$ and $d \mid n$.
Now let $a^k=(d\cdot x)^k$ and $n=d\cdot y$ then:
$$(d\cdot x)^k \equiv b \pmod {d\cdot y} \Rightarrow (d\cdot x)^k = d\cdot y\cdot q + b$$
$$(d\cdot x)^k - d\cdot y\cdot q = b \Rightarrow b \mid d(d^{k-1}x^k-y\cdot q)$$
Thus $gcd(d,b)=d$ and since we said $d>1 \cdots$


homomorphism on Rees algebra

Question: Let $R$ be a commutative ring and $I$ be an ideal of $R.$ Noting that $I^j I^k \subset I^{j+k},$ define a ring structure on the direct sum
$$\operatorname{Rees}_{R}(I) :=\bigoplus_{j \geq 0} I^j = R \oplus I \oplus I^2 \oplus \cdots .$$
The homomorphism sending $R$ identically to the first term in this direct sum makes $\operatorname{Rees}_R(I)$ into and $R$-algebra, called the Rees algebra of $I$. Prove that if $a \in R$ is a nonzero divisor, then the Rees algebra of $(a)$ is isomorphic to the polynomial ring $R[x]$ (as an $R$-algebra).
I have no idea on how to solve this. Any help is much appreciated.
Answer: In fact, $A := \operatorname{Rees}_R((a))$ is isomorphic to $R[x]$ as a graded $R$-algebra, if you're familiar with that notion. If not, then don't worry about that.
Hint: Observe that $(0, a, 0, 0, 0, \ldots) \in A$ generates $A$ as an $R$-algebra. This gives you an algebra epimorphism $\phi: R[x] \to A$, given by $\phi(x) = (0, a, 0, 0, \ldots)$. Show that this is an isomorphism. If $f \in \ker(\phi)$, what can you say about $f$?
Comment: thank you for the suggestion. I'll check.

homomorphism on Rees algebra


Continually adding fields to a form each time a button is pressed using AJAX

Question: I'm attempting to add fields dynamically to a form using AJAX in a block plugin however no action occurs when clicking on the button that is meant to add a field.
The code I'm currently is below
   class Standard extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $form_state->setCached(FALSE);
        $form['actions'] = array(
            '#type' => 'actions',
        );
        $form['column']['columnNum'] = array(
            '#type'          => 'value',
            '#default_value' => $this->configuration['columns_submit'],
        );

        $form['column_wrapper'] = array(
            '#type'       => 'container',
            '#attributes' => array(
                'id'         => 'column_wrapper',
            ),
        );
        for ($i = 1; $i <= $this->configuration['columns_submit']; $i += 1) {
            $form['column'][$i] = array(
                '#type'           => 'details',
                '#title'          => t('Column '.$i),
                '#open'           => FALSE,
                'group'           => 'Content',
                'body_text'       => array(
                    '#type'          => 'text_format',
                    '#title'         => $this->t('Body'),
                    '#default_value' => $this->configuration['column'][$i]['body_text_submit']['value'],
                ),
                'class'           => array(
                    '#type'          => 'textfield',
                    '#title'         => $this->t('Class'),
                    '#default_value' => $this->configuration['column'][$i]['class_submit'],
                ),

            );
        }
        $form['addcolumn'] = array(
            '#type'     => 'button',
            '#name'     => 'Add Column',
            '#value'    => t('Add column'),
            '#submit'   => array($this, 'addColumnSubmit'),
            '#ajax'     => array(
                'callback' => [$this, 'addColumnCallback'],
                'effect'   => 'fade',
                'wrapper'  => 'column_wrapper',
            ),
        );
        return $form;
    }
    public function addColumnSubmit(array&$form, FormStateInterface $form_state) {
        $this->configuration['columns_submit'] += 1;
        $form_state->setRebuild(TRUE);
    }
    public function addColumnCallback(array&$form, FormStateInterface $form_state) {

        return $form['column'];
    }

Nothing occurs when clicking the $form['addcolumn'] button. I've based my attempts on examples such as this one https://www.drupal.org/node/2723033. (I understand that is an example of it not working, but based on the comments it seemed like an error that was easily fixed)
I'd like to be able to continually add fields each time the button is pressed. Is there something wrong with my code? Is there a proper way to continually add fields when a button is pressed to a form using AJAX?

Update: I made another attempt which failed as well.
I used
    if (empty($form_state->getValue('columnNum'))) {
        $form_state->setValue('columnNum', 1);
    }
    $columnNum = $form_state->getValue('columnNum');

in BlockForm()
and
    $numColumns = $form_state->getValue('numColumns');
    $numColumns += 1;
    $form_state->setValue('numColumns', $numColumns);
    $form_state->setRebuild(TRUE);

in addColumnSubmit()
Answer: Assuming all your logic for $form['column'][$i] is correct, you can try replacing '#attributes'
$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#attributes' => array(
            'id'         => 'column_wrapper',
        ),
    );

With '#prefix' and '#suffix'
$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

And then in the callback get the values from the complete form.
public function addColumnCallback(array $form, FormStateInterface &$form_state) {
    $form = $form_state->getCompleteForm();
    return $form['column'];
}

I had a similar problem, Ajax does rebuild the form, but using "old" values, so after the $form['column'][$i] is completed and calculated, Ajax then just overrides it with the previous $form['column'][$i].
If that makes sense.


Lemma 1 - Banach-Mazur Game - Dan Ma's topology Blog

Question: I have been given a presentation for a course based on this particular post in Dan Ma's topology blog. The post itself is very clear and educational, but there is one proof that I'm not sure why it is complete.
Lemma 1 has a rather standard application of Zorn's lemma, but I feel that I'm missing something in the second paragraph of the proof.
Lemma 1: Let $X$ be a space, Let $O \subset X$ be a nonempty open set. Let $\tau$ be the set of all nonempty open subsets of $O$. Let $f: \tau \longrightarrow \tau$ be a function such that for each $V \in \tau$, $f(V) \subset V$. Then, there exists a disjoint collection $\mathcal{U}$ consisting of elements of $f(\tau)$ such that $\bigcup \mathcal{U}$ is dense in $O$.
The proof begins by explaining the trivial case of $O$ having just one point, then if I understand correctly everything holds in a rather obvious way, namely: the property of $f$ gives me the same set as an image and clearly this is dense in $O$.
Then, we assume $O$ has two points and the author shows that $\mathcal{P}$ (the set of all collections $\mathcal{F}$ such that $\mathcal{F}$ is a disjoint collection of elements of $f(\tau)$) is non-empty. For this, two disjoint open subsets of $O$ are taken based on the assumption that $O$ has at least two points.
Why must these subsets be disjoint? Isn't the author assuming anything in addition?
I underestand that by applying $f$ later those sets become exactly of the form of an element of $\mathcal{P}$ which is the goal of that particular part of the proof. I thought we could possibly assume they are disjoint and otherwise apply $f$ again and again until they are but no assumption really guarantees this process would stop.
Comment: At the end of the introductrory section of the post you linked to, the author states: "All topological spaces are assumed to be at least Hausdorff."
Comment: Oh, I feel so silly not having noticed that. The solution is rather nice so at least I know now we don't need that assumption at all
Answer: You are correct: unless the author is assuming that $X$ is Hausdorff, $O$ need not contain two disjoint non-empty open sets. However, the argument can easily be patched. If $O$ does not contain two disjoint non-empty open sets, let $\mathscr{U}=\{\tau(O)\}$; every non-empty open subset of $O$ meets $\tau(O)$, so $\bigcup\mathscr{U}=\tau(O)$ is dense in $O$, and we're done right away.
Comment: Thank you! I was going in circles trying to force something to be true when in fact it was missing something. Very elegant patch!
Comment: @Deborah: You're welcome!
Answer: In the introduction, before the heading Banach-Mazur Game, he says that all spaces are assumed to be Hausdorff.
And then if $O$ has at least two points, say $p \neq q$, we can find disjoint open  sets $U_p$ and $U_q$ around them and then $\{U_p \cap O, U_q \cap O\}$ is a starting point, one of the members of your poset of disjoint open subfamilies of $O$ etc.


How to build a single apk (not ".apks") but is splitted by abi from aab?

Question: Originally I use build variants to build two apks: myapp-armv7.apk and myapp-arm64.apk, for the 32bit and 64bit architectures, respectively. For example, the 32bit apk only contains native .so files for 32bit, while the 64bit apk only contains those for 64bit.
However, now I not only want these two apk files, but also want a myapp.aab bundle. The question is, how to build the 32bit and 64bit apk from this aab bundle?
I have tried Generate Apk file from aab file (android app bundle) . However, if I use --mode=universal, though I get an installable apk file, it contains both 32bit and 64bit .so files inside it, so it is really huge and we should not use it. If I do not use that flag, I get a bunch of apk files (i.e. an .apks file), but of course a user should only download one .apk file and click "install", so that is also not feasible.
Answer: AFAIK, this is not workable. Universal mode + unzip is a trick to extract what we are familiar with - the .apk. However, other use cases of BundleTool produce .apks only, which is our only choice to install for per device. Therefore, I think your question is about how to deploy those .apks to test devices easily.

For local install / CI&CD, use bundletool install-apks CLI just like what you did with adb install.
For manual staging testing by QA, deploy the .aab to PlayStore internal testing channel, AppCenter testing channel, etc.
Comment: No, my question is not about deploying `apks` file. I really need `.apk` file.
Comment: Well...unfortunately no such existing tool to make it from aab to split apk. I also wonder if there is something can provide this feature. @ch271828n


coequalizer of simplicial sets

Question: This is the statement whose first line of proof I am confused. This is on page 10, of Goerss, Jardine's Simplicial Homotopy Theory.

(i) How does one prove the "presentation" of $\partial \Delta^n$?
(ii) How does one obtain the first coequalizer?
In general, I am just confused in how to prove coequalizing diagram for simplicial sets.

Can ignore: I have typed up my attempt for (i). I would be happy to see for a better presentation (hand drawn is great too).
Comment: Remember that $\mathbf S$ is a presheaf category so that colimits are computed pointwise. Also remember that a coequalizer in $\mathsf{Set}$ is easy to compute: the coequalizer of $f,g: A \rightrightarrows B$ is the projection to the quotient $B/{\sim}$ where $\sim$ is generated by $f(a)\sim g(a)$. So the "presentation" is really just about precising the two maps of the fork. (I'll write a detailled answer later if I find the time.)
Comment: Ah, I forgot about this. Yes I 'd be happy to see your write up too.
Answer: Use the cosimplicial identities to check that for $i<j$ the square
$\require{AMScd}$
\begin{CD}
    [n-2]@>\delta_{j-1}>> [n-1]\\
    @VV\delta_i V   @VV \delta_i V\\
    [n-1] @>\delta_j>> [n].
\end{CD}
is a pullback in the simplex category $\bf\Delta$. As Pece points out, pullbacks in $sSet$ are computed levelwise, so since the Yoneda embedding is fully faithful, we get for $i<j$ pullbacks in $sSet$
$\require{AMScd}$
\begin{CD}
    \Delta^{n-2}@>\delta_{j-1}>> \Delta^{n-1}\\
    @VV\delta_i V   @VV \delta_i V\\
    \Delta^{n-1} @>\delta_j>> \Delta^n.
\end{CD}
Now recall that the p-simplices of $\partial \Delta^n$ are those maps $[p]\rightarrow [n]$ in $\bf\Delta$ which factor $[p]\rightarrow [n-1]\xrightarrow{\delta_i}[n]$ for some $i$. Thus there is an epimorphism $\bigsqcup_{0\leq i\leq n}\Delta^{n-1}\rightarrow \partial \Delta^n$ which is the map $\delta_i$ on the $i$-indexed component, and you check by hand using the fact that the previous squares are pullbacks in $sSet$ that
$$\bigsqcup_{0\leq i<j\leq n}\Delta^{n-2}\rightrightarrows\bigsqcup_{0\leq i\leq n}\Delta^{n-1}\rightarrow \partial\Delta^n.$$
Hopefully this fills out the details of what you have worked out in your attempt. Another way to see this is to use the fact that every epimorphism in $sSet$ is the coequaliser of its kernel pair. Use the pullback squares to construct the kernel pair of the epimorphism and you get the result.
The other coequaliser involving the simplicial horn follows in the same manner. Of course the p-simplices of $\Lambda^n_k$ are those maps $[p]\rightarrow [n]$ in $\bf\Delta$ that factor $[p]\rightarrow [n-1]\xrightarrow{\delta_i}[n]$ for some $i\neq k$. Therefore we have an epimorphism  $\bigsqcup_{0\leq i\leq n,i\neq k}\Delta^{n-1}\rightarrow \Lambda^n_k$ which is $\delta_i$ on the $i$-indexed copy. Use the previous pullback square to calculate the kernel pair of these epimorphisms and you are done.
Edit:
Recall that the kernel pair $K(f)$ of a morphism $f:x\rightarrow y$ in a category $\mathcal{C}$ (if it exists) is the pullback of the cospan $x\xrightarrow{f}y\xleftarrow{f}x$. Note that it comes equipped with a pair of projections $\pi_1,\pi_2:K(f)\rightarrow x$. If $f$ is an effective epimorphism then it is the coequaliser in the diagram
$$K(f)\stackrel{\pi_1,\pi_2}{\rightrightarrows} x\xrightarrow{f} y.$$
In $sSet$, or more generally any topos, every epimorphism is effective, and since $sSet$ is complete we can therefore ask for the kernel pair $K(\hat\delta)$ of the epimorphism $\hat\delta=\{\delta_i\}:\bigsqcup_{0\leq i\leq n}\Delta^{n-1}\rightarrow\Delta^n$ to get a coequaliser
$$K(\hat\delta)\stackrel{\pi_1,\pi_2}{\rightrightarrows}\bigsqcup_{0\leq i\leq n}\Delta^{n-1}\xrightarrow{\hat\delta}\Delta^n.$$
But we can calculate $K(\hat\delta)$ directly, levelwise if necessary, as the pullback of
$$\bigsqcup_{0\leq i\leq n}\Delta^{n-1}\xrightarrow{\hat\delta}\Delta^n\xleftarrow{\hat\delta}\bigsqcup_{0\leq j\leq n}\Delta^{n-1}$$
and we have a canonical model for this pullback. In particular a p-simplex in $K(\hat\delta)$ is a pair $(x,y)$ of p-simplices in $\Delta^{n-1}$ which satisfy $\delta_i(x)=\delta_j(x)$ for some $i,j$. This should seem familiar.
Now we have the pair of maps $\bigsqcup_{0\leq i<j\leq n}\Delta^{n-2}\rightarrow \bigsqcup_{0\leq i\leq n}\Delta^{n-1}$ which you describe, and since these are coequalised by $\hat\delta$ we get a comparison map $\bigsqcup_{0\leq i<j\leq n}\Delta^{n-2}\rightarrow K(\hat\delta)$. Using what we know about the interactions of the maps $\delta_i$, that is, our pullback squares, we check directly that this comparison map is one-to-one and onto.
Comment: Hi Tyrone, sorry I still don't understand some parts:   "using the fact that the previous squares are pullback in $sSet$, that (coequalizer equality) "

How do we use the "pullback" part? I see how the maps are induced but I don't see why this is a coequalizer, other than explicitly proving the universal property. It is also unclear to me that if it is easy to check this component wise.
Comment: More elaboration: coequalizer of sets is not easy to write out explicitly... yes we can describe the smallest relation but it is hard to verify(?) I suppose universal property is easier as I wrote out.
Comment: @CL. , I've edited in some details at the bottom of the question. Hopefully you will find it useful.
Comment: Since pullbacks commute with coproducts in $\mathsf{sSet}$, wouldn't this imply that $K(\hat{\delta}) = \coprod_{(i,j) \in [n] \times [n]} \Delta^{n-1} \times_{\Delta^n} \Delta^{n-1}$? This cannot be isomorphic to $\coprod_{0 \leq i < j \leq n} \Delta^{n-2}$. What am I missing?
Comment: @EmilioMinichiello the cospan whose pullback defines $K(\hat\delta)$ is not a coproduct.
Comment: @Tyrone, I think I see my problem, it is the case that both $\coprod d^i$, $\coprod d^j$ are coproducts in the slice category $\mathsf{sSet} / \Delta^n$ and base change preserves these, so each $(d^j)^*(\coprod_i d^i) \cong \coprod_i (d^j)^* d^i$ but i guess the problem is that $(\coprod_j d^j)^*(\coprod_i d^i) \cong \coprod_i (\coprod_j d^j)^* d^i \neq \coprod_{i,j} (d^j)^* d^i$.

coequalizer of simplicial sets


How to write Roman numeral figures for non-chord tones (NCT) and inversions, triads and seventh chords?

Question: What Roman numeral figures distinguish a 2nd inversion dominant triad with a NCT fourth from a root position dominant 7th chord with a NCT fourth?
Related to How writing a dominant 7 sus4 chord in RNA ( Vsus7 chord in the 1st inversion)
Examples, V chord in A major:
2nd inversion dominant triad with a NCT fourth
B E A
Bass B with 7 and 4 above = V7/4
root position dominant seventh chord with a NCT fourth
E A D
Bass E with 7 and 4 above = V7/4
If I don't have an incomplete seventh chord, I have...
E A B D
Bass E with 7, 5, and 4 above = V7/5/4
It might be worth while to extend to examples to a...
second inversion dominant seventh chord with NCT fourth
B E A D
Bass B with 7, 4, and 3 above = V7/4/3

Am I following the correct procedure to get RNA figures?
If so, it seems I need to include all three figures for seventh chords to avoid ambiguity with triads.

EDIT
I'm adding an edit about why I don't accept the only answer posted.
My question is specifically about the ambiguity of the numeric figures and whether the figure will indicate not only a NCT, but also an inversion.
My question isn't about the figures 7-6 or 4-3 to show a resolution. I understand that if the NCT resolves that adding the resolution figures will make clear on the chord or resolution what the bass is for both chords... but what if the NCT doesn't resolve?
Another point of clarification: an 11 figure won't clear this up. An 11 figure would in most cases require the chord third. In my examples the figures 7 and 4 are specifically the NCT displacement of the third.
I dont' know if this will clarify my question but...
With jazz symbols I could write Esus4/B for a 2nd inversion triad (clearly not a seventh chord) with the third displaced as a NCT the minimal tones being B E A, and I could write E7sus4 for a root position dominant seventh chord with the third displaced as a NCT the minimal tones being E A B D and the B sometimes optionally omitted. These symbols seem unambiguous.
In RNA I think I can write the equivalent figures, but to be unambiguous I must use inactive figures which are conventionally omitted the 5 or 3 depending on the inversion as I detailed in my examples.
I'm only looking for confirmation if I'm treating the figures the right way.
If not, I'm looking for an explanation about the chord with the NCT, not an answer that only applies to a specific case of resolution.
Comment: This is a helpful, clarifying edit. According to RNA standard practices, NCT's that don't move anywhere (not UNTs or LNTs, PTs, or even ETs) are simply ignored as they are seen as *non-functional*. As I described in my answer, the point of RNA is to show function. If an NCT doesn't "resolve" then according to RNA it has no function and cannot be counted. Thus the original conceit of your question is a bit of a red herring. It supposes non-functional NCTs have any business being in the analysis to begin with, when in fact they wouldn't be included. This is likely the crux of your confusion.
Comment: "According to RNA...cannot be counted" can you point to some reference? A NCT functions by virtual of its dissonance. I don't see any reason why RNA couldn't be used.
Comment: Why is it so important to you to shoe-horn something into RNA? In music theory, if the system you're using is getting cumbersome then chances are it's not the right system. Theory is a tool to describe music. Sure you can use a screwdriver to hammer a nail, but it's so much easier to use the proper tool. You're essentially asking "am I hammering the nails the right way with this screwdriver"? The confirmation is: no, not the right way. You either omit them completely, relax the RNA to include them, or use a different system. The MAA symbols you used, for example, would be much clearer than RNA
Comment: MAA, what is that?
Comment: MAA = Macro-Analytical Analysis, sometimes colloquially referred to as "pop" or "jazz" symbols
Answer:
What Roman numeral figures distinguish a 2nd inversion dominant triad
  with a suspended fourth from a root position dominant 7th chord with a
  suspended fourth?

It's important not to lose the sense of showing harmonic function.

2nd inversion dominant triad with a suspended fourth
  B E A
Bass B with 7 and 4 above = V7/4

A major = Dominant is "E"
Dominant 2nd Inversion: B E G#
The Roman Numeral for this would be V6/4.
Cool, so where does that handy suspension come in?
Well, remember we need to show function. So the correct way to put the suspension into RNA would be to show where the suspension goes:
V(7-6)/4
Here we show that the "7" above the bass resolves by step to a sixth, thus revealing the "2nd inversion".

root position dominant seventh chord with a suspended fourth

Okay, so still A Major:
Root position dominant-7th chord:
E G# B D = V7
With suspended 4th:
E A B D = V7/(4-3)
Again, we're showing where the suspension is expected to go. If you want to get really technical, the chord should be: V7/5/(4-3) but nobody would write this because it's obnoxious.

second inversion dominant seventh chord with suspended fourth

Still A Major:
B E A D = V(7-6)/4/3
So you're on the right track. Just don't lose sight of function, which is sort of the whole point of RNA (and why the system breaks down when you try to apply it to analyze non-functional harmony).


How do I include a custom JavaScript file in a module?

Question: I want to include a custom JavaScript file in a module using the following code.
function profile2_form_user_register_form_alter(&$form, &$form_state) {
  drupal_add_js('http://localhost/prf2.js', 'external');
}

I then add scripts[] = js/prf2.js in the .info file, but it throws this error.

Warning: file_get_contents(js/prf2.js): failed to open stream: No such file or directory in drupal_build_js_cache()
Comment: You are almost certainly going about this incorrectly since you are hacking the profile2 module rather than adding the javascript from your own custom module.
Comment: drupal_add_js('http://localhost/prf2.js','external'); Is "localhost" really the appropriate domain? Consider what happens when the client tries to load this JavaScript.
Comment: If am I add this inside profile2.module then how to access the js file. Please clarify your above code.
Comment: 1) I suggest we clarify something first. There is probably no need to modify (or hack, as it's often called) the profile2 module, so don't. 2) My code is 4 lines long, even counting the line `);`. If you don't understand it, you need to be more precise about what you need clarified.
Comment: @Letharion Passing the second parameter as a 'type' string is actually fine, it's only if you pass an associated array you need to use `'type' => 'external'`
Comment: @Clive Ah, I see you're right, the value is used to populate the 'type' value if it's just a string. Thanks. I've removed that piece of code.
Answer: This is the right & simple way to include any JS file in Drupal 7.

Create a folder named i.e. js, inside your module folder.
Inside that folder place (modulename).js file.
Note: Drupal JS code has a specific format as follows:
(function ($) {
  $(document).ready(function(){
    alert("Hello world!");  //here we can add our JS code
  });
})(jQuery);

Open (modulename).info file & add:
scripts[] = js/(modulename).js
Clear Cache & Run.
Answer: There is a lot of documentation about how to include a JS file into a custom module or into your theme in general. Here is the official article: https://www.drupal.org/node/304255
There are plenty of examples and you can inspire yourself with it.
PS: Don't hardcode the path of your JS file as you did in your code. Use the drupal_get_path function.
Comment:

.info file => scripts[] = js/prf2.js

Error occured
Comment: May u pls tell me I have to add script[]=js/prf2.js is compulsory..
Comment: If you do the drupal_add_js, you doesn't have to do it in the .info file.
Comment: Depending on your situation, you can choose to add your JS file in your theme, in your module .info file, in a module's hook, in a form...
Comment: My condition is I have a module i.e. profile2 & I have added some JS code to create condition between fields. My JS file is put inside js folder i.e. profile2.js. So in profile2.module I want to include JS. Then which condition is good for me.
Comment: When ever I use drupal_get_path... It shows an error "Fatal error: Class name must be a valid object or a string"
Comment: You cannot override a contrib module code! You should do the process through a custom module that you write yourself. Please read the documentation to see how to create a custom module https://www.drupal.org/developing/modules/7
Answer: Here is two place where you can add JavaScript: In a theme or in a module.
1. Theme
If you want to add JavaScript in theme simply go in your_theme.info file and add your file path for example if your theme directory is:
mytheme\
 \js\my_theme.js
 \my_theme.info

So write down:
scripts[] = js/my_theme.js

Under your my_theme.info
clear cache from admin and that should be work
2. Module
I you want to add js in module then
my_module
my_module\js\my_module.js
my_module.module

In my_module.module call hook:
function my_module_init(){
    drupal_add_js(drupal_get_path('module', 'my_module').'/js/my_module.js');
}

Above code add JavaScript once module enable.
Comment: function profile2_init(){
drupal_add_js(drupal_get_path('module', 'profile2').'/js/profile2.js');
}

-------add this in my profile2.module
Comment: scripts[] = js/profile2.js----- add this in my profile2.info.. Its not working


Part from "Regular polytopes" which I don't understand

Question: This is a paragraph from "Regular polytopes" by Coxeter that I don't understand.

Although it is not always possible to include all the vertices of a polyhedron in a single chain of edges, it certainly is possible to include then all as nodes of a tree (whose $N_0-1$ branches occur among the $N_1$ edges). This merely requires repeated application of the principle that any two vertices may be connected by a chain of edges. In fact, every connected graph has a tress for its "scaffolding" (Geruest), and the connectivity of the graph is defined as the number of its branches that have to be removed to produce a tere, namely $1-N_0+N_1$.

$N_0$ is a number of vertices, $N_1$ is a number of edges and $N_2$ is a number of faces of polyhedron. I don't know a lot about graph theory (I understand basic concepts but this seems to skip a lot of steps for a beginner). Could you explain to me this paragraph using a bit less math-oriented language and go with examples or something?
The paragraph is on 9th page, it goes right after the paragraph that says that not all graphs satisfy that Hamilton's problem about imagining vertices as cities we want to visit and edges the only roads between them. It's all still about three-dimensional polytopes (polyhedra).
I hope you can help me understand this and sorry that this isn't a strict question asking for a certain answer, but more like an open question.
Answer: What he means is that the graph (of the polytope) might not always yield a Hamilton path (which is a single chain of edges), but can always yield a tree (no cycles). This is trivially true of any graph.
You then have to show that a connected tree has $N_0 - 1$ edges only, so from $N_1$ edges, you have to remove $N_1 - N_0 + 1$ edges.


Box-sizing no input button não funciona

Question:
Pessoal, tenho um formulário no qual quando aplico um border-bottom no input button  ele dá um pulo devido ao box-sizing não está funcionando (acredito que seja isso). Nos demais input está funcionando corretamente. Alguém pode me ajudar?
Answer: Uma dica, use box-shadow no lugar do border. Primeiro pq o box-shadow não ocupa luar no box-model e não vai deslocar ou mover seu elemento, depois que a transição do box-shadow costuma ser melhor renderizada e é mais suave do que a transição com bordas. Então fazendo um box-shadow: inset vc coloca a sombra para dentro do botão, dando a impressão que é uma borda.

[type="button"] {
 all:unset;
 background-image: linear-gradient(to bottom, blue 0%, royalblue 100%);
 color: #fff;
 width: 100px;
 height: 50px;
 border-radius: 4px;
 text-align: center;
  cursor:pointer;
 transition: box-shadow 250ms;
}
[type="button"]:hover {
 box-shadow: inset 0 -4px 0 red;
}
<input type="button" value="login">
Comment: Obrigado! Nem conhecia essa propriedade
Comment: @RenanVilela essa propriedade é muito útil depois tire um tempo para estuda-la. Se vc achar que a resposta resolve o problema lembre-se de marca-la como aceita nesse ícone abaixo das setinha ✔, depois se aparecer outra resposta que vc ache mais apropriada vc pode mudar a ✔ para ela

Box-sizing no input button não funciona


Does the run count? Third out, not forced, not by batter-runner

Question: Runners on 2nd and 3rd, two out.  Ground ball to shortstop, following order of events:
1) Runner from third crosses home plate.
2) Runner from second is tagged out by the shortstop for what is judged as third out.
3) SS, forgetting how many outs there are throws to first and the ball arrives, is caught with foot on the bag before runner gets there.
4) Batter-runner crosses first base.
What about in a situation where step 3 didn't happen?
Answer: In the current Official Baseball Rules (pdf), there is only one reference to a "fourth out" that I can find. Page 49, part of Rule 5.09(c) - Making an Out, says:

Appeal plays may require an umpire to recognize an apparent
  "fourth out." If the third out is made during a play in which an appeal
  play is sustained on another runner, the appeal play decision takes
  precedence in determining the out. If there is more than one appeal
  during a play that ends a half-inning, the defense may elect to take
  the out that gives it the advantage.

In the case an appeal is made on a force out (i.e. the batter-runner missed first base) and the appeal is upheld, the appeal takes precedence and the run would not count.
This case is a little more complicated. Given that the batter-runner may stop or slow running because of the tag on the player running from 2nd to 3rd, I would guess that the force out would not apply and the run would count. I am having some trouble finding definitive documentation on that. But, Rule 5.09e - Retiring The Side says:

When three offensive players are legally put out, that team takes the
  field and the opposing team becomes the offensive team.

It seems to me like the third out in your scenario would end the inning immediately and the batter-runner would no longer be required to touch first base. Wikipedia disagrees with me, but there is no citation for the specific scenario.
If step 3 doesn't happen, then the run definitely counts. Third outs only negate a run if they are a force or happen before the runner crosses the plate. See rule 5.08a:

(a) One run shall be scored each time a runner legally advances to
  and touches first, second, third and home base before three men
  are put out to end the inning.
  EXCEPTION: A run is not scored if the runner
  advances to home base during a play in which the third
  out is made (1) by the batter-runner before he touches
  first base; (2) by any runner being forced out; or (3) by
  a preceding runner who is declared out because he
  failed to touch one of the bases.

Since none of the three criteria apply, the run would score.
Comment: Also going back to 20 years or so when I was studying for the NCAA badge... they had an example of what might be one of the most heads up running plays I ever heard about.  Same scenario.  Runner on third scores quickly, Runner on second is about to get tagged out (with apparently a very slow hitter) and he just smacks the glove.  He is out on interference and inning is over - run counts.
Comment: Thanks, @Coach-D. Nice to know my research was well-founded. This question was definitely a tough one.
Comment: Really good answer.  Just FYI this scenario is one of the most included in umpire training pamphlets.  It is given to umpires training for accreditation to help study.  Just know that if you aren't at least the college level umpiring god help you if this happens.
Comment: Thanks for the answers, makes a lot of sense from a procedural sense but sadly not from a fairness of the game sense (but I'd expect this scenario to come up maybe once per decade at the college level or higher).  As a followup question does the run count on the following scenario:  2 out, runner on third (who thinks there's one out).  Fly ball to the outfield, upon first touching by an outfielder he starts running to home.  Batter-runner touches first, then runner from third touches home, then outfielder secures the catch.  (continued in next comment)
Comment: Out is made by the batter-runner but he's already touched first, but the fact he hasn't legally attained it is irrelevant, correct?  So the run would count?  Again, another once in a generation at any level (I'd say little league included) play that I'll probably never see.
Comment: I believe the run would not count. A fly ball is a "force out" (even if juggled) and despite the batter-runner "touching" first base, he has not reached first base safely so the run does not score. See definition of "Catch" on page 141 of the rules. If it touches an offensive player or umpire during the juggling, it's not a catch and the run would score (and the batter-runner would be safe).


Views aggregation?

Question: I have a view that lists users. These users have skills. Two users are listed multiple times; one user three times; twice with "no skill" and once with the skill they have; another one twice, once with "no skill" and once with the skill they have. If I enable aggregation, skills are gone; if I don't, I get duplicate results. I have tried distinct as well, to no avail. Please see the screenshot below.

What can I do to eliminate this issue?
K.
Comment: Just put in a normal filter to filter on skills, and set it to 'Is not equal to' with Value 'No Skill', or something like that, depending on what type of field your skills are.
Comment: @J.Reynolds As you can see in the screenshot above, some users who aren't listed twice not having a skill is indeed valid.
Comment: @J.Reynolds would an export of the view help? http://paste.debian.net/137807/
Comment: Aggregation with "group results" for the name should group all field for that user together.
Comment: @Neograph734 when I aggregate, group results is default and skills are shown multiple times. Please see https://dl.dropboxusercontent.com/u/11918318/Screenshot%20from%202014-12-26%2009%3A12%3A41.png
Answer: If the skills come from taxonomy terms, you can do as follows.
Choose 'group results' for both title and the taxonomy terms. Then in the taxonomy terms dialog it should show a dropdown to group by 'entity id' or 'taxonomy id'. Choose 'entity id'.
No need to check the boxes.
https://www.dropbox.com/s/sooau5vccardovy/Screenshot_2014-12-26-13-06-12_1.jpg?dl=0
(cant embed the image on phone...)
Comment: Worked for me, thanks! I was about to pull out my hair.
Answer: It seems that some profiles were not showing because their "skills" were missing. When I completed a profile in a way that they have a "skill", it also showed up.

Views aggregation?


How to wrap body text around image for drupal 8

Question: How to wrap body text around image for drupal 8. I found tutorial for drupal 7 here https://www.drupal.org/forum/support/post-installation/2008-06-30/how-to-wrap-body-text-around-image, but I still confused to implement this for drupal 8.
I found some css files inside css folder and which one that I have to edit?
Answer: Don't edit css files in a contrib theme, because the changes will be overwritten when updating the theme. Create a subtheme and add a library with your own css file, see https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme
Comment: Any other simple tutorial?, I just want to wrap body text around image