Render sub-paragraph in parent template

Question: I have a paragraph that has a field of type paragraph reference to sub-paragraphs.
Within my template, I need to access these sub-paragraphs and render the entity element. I have a loop that loops through a list of Drupal\paragraphs\Entity\Paragraph elements.
I need to render the paragraph markup.
Is there a function?
I tried item|render and item.view(), but neither of them worked.
Answer: You should be able to render the sub paragraph - without any loop, just like every other field - with
{{ content.field_name }}
If you really need the loop for some special markup you can try something like
{% for key, item in content.field_name if key|first != '#' %}

    {{ item }}

{% endfor %}

Comment: Are you using `{{ content.items }}` or `{{ paragraph.items }}`? The first should provide the render arrays, the latter should give you the objects. If that's not the case, it seems like an error to me. Regarding `entity_view`, I suggest to take a look at at the [Twig tweaks module](https://www.drupal.org/docs/8/modules/twig-tweak/cheat-sheet-8x-2x)
Comment: Thanks Hudri.
Your script does give me the exact list of results as my loop.
A list of Paragraphs.
 {{ item }} is an object of type  Drupal\paragraphs\Entity\Paragraph but this is not rendered. I need to turn them into markups. In D7 i used to use entity_view('paragraphs_item', $entities, 'full'); How to do this in D8?

Is there a way to achieve this in Twig? Or should I create a Twig Function as the Twig context is not able to create markups of entities?
Comment: yeah u are right. Weird... tested it yesterday night and I could not render it. Thanks again
Comment: ok. but how to access the field of the paragraph as markups?

                {% set item_field_tax_1 = item|first.field_tax_1 %}
                {{ item_field_tax_1 }}

Gives me the error "Object of type Drupal\Core\Field\EntityReferenceFieldItemList cannot be printed".
Comment: ok to anybody who will have this issue as well.

Please use this module https://www.drupal.org/project/twig_render_this. It creates a twig extension that allows you to render Field Elements directly without having to use the predefined content element. Pretty much what I wanted to write myself.
Answer: If you want to use a field value in child paragraph within the parent paragraph, you can use this (replace of course field_with_paragraph_childs and field_name_field with the actual fieldnames):
{% for key, item in paragraph.field_with_paragraph_childs if key|first != '#' %}

                {{ item.entity.field_name_field.value }}

{% endfor %}

Render sub-paragraph in parent template


Using pipes and structures with dynamically allocated variables in C

Question: I'm writting a program that needs to pass a matrix from a parent process to its child (that's why I'm using the fork() instruction). I've just read this and this to solve the problem myself, but I still can't understand how to use the read() and write() instructions with the pipe I've created so far. I know these instructions write series of bytes, but I'm not sure about using them with structures or dynamically allocated variables (like a matrix).
Here is the code I used to test (note the comments I put):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

// Structure definition (Matrix)
typedef struct {
    int **mat;
    int rows;
    int cols;
} Matrix;

int main() {
    // Create the pipe
    int file_desc[2];
    if (pipe(file_desc) != 0) exit(1);

    // Create two processes
    if (fork() == 0) {
        /** Instructions for the child process */
        // Read the matrix structure from the pipe
        Matrix *received = NULL;
        read(file_desc[0], received, sizeof *received);
        if (received != NULL) {
            // Print the received matrix
            int i, j;
            printf("The matrix I've just *received* from the parent is:\n");
            for (i = 0; i < received->cols; i++) {
                for (j = 0; j < received->rows; j++) printf("%d\t", received->mat[i][j]);
                printf("\n");
            }
        } else printf("received = NULL :'(\n");
    } else {
        /** Instructions for the parent process */
        /* Create a matrix dinamically.
         * In fact, in the real program I have a function to create a matrix given the
         * rows and columns, and fill it with random values, so it returns a Matrix *
         * (pointer to Matrix), but for testing purposes I've only written this
         * (also useful if I need an array of Matrix elements, for example)
         * */
        Matrix *myMatrix = calloc(1, sizeof *myMatrix);

        // Put the contents into the variable
        myMatrix->rows = 2;
        myMatrix->cols = 2;
        myMatrix->mat = calloc(myMatrix->rows, sizeof *(myMatrix->mat));
        int i, j;
        for (i = 0; i < myMatrix->cols; i++)
            (myMatrix->mat)[i] = calloc(myMatrix->cols, sizeof **(myMatrix->mat));

        // Fill the matrix with some values (testing)
        (myMatrix->mat)[0][0] = 4;
        (myMatrix->mat)[0][1] = 2;
        (myMatrix->mat)[1][0] = 1;
        (myMatrix->mat)[1][1] = 3;

        // Print the matrix
        printf("The matrix I've just filled in the parent is:\n");
        for (i = 0; i < myMatrix->cols; i++) {
            for (j = 0; j < myMatrix->rows; j++) printf("%d\t", myMatrix->mat[i][j]);
            printf("\n");
        }

        // Write the matrix structure to the pipe (here is where I have the problem!)
        write(file_desc[1], myMatrix, sizeof *myMatrix);

        // Wait for the child process to terminate
        wait(0);
        printf("The child process has just finished, the parent process continues.\n");
    }
    return 0;
}

In fact, I tried first with a pointer to an int and it worked. But when I run this program, I receive this output:
The matrix I've just filled in the parent is:
4   2
1   3
received = NULL :'(
The child process has just finished, the parent process continues.

And I don't know why I get the NULL -- I'm almost sure I'm using the write() instruction incorrectly. Any help about this will be appreciated =)
EDIT: I think the matrix should be converted to text, for example, and then pass the string to the child, parse it and convert it to a Matrix structure again. I don't know if this approach is the best. Is there another approach besides this one?
EDIT: I tried the same code with a static variable (changing int **mat; to int mat[2][2]; inside the structure declaration) but the user should change the matrix size.
Comment: I think you need to synchronize the child and parent process. It might be the case when child process is firstly created and read the data before parent writes into it. Also check the return value of read operation.
Answer: This is a serious problem:
Matrix *received = NULL;
read(file_desc[0], received, sizeof *received);

Received is a null pointer.  That read is going to try to write data to NULL, which is an invalid address.  It would be much simpler to write:
Matrix received;
read(file_desc[0], &received, sizeof received);

Comment: No, static variable are irrelevant.  But you need to actually pass the data through the pipe, not just addresses.  Try using arrays instead of pointers in the struct.  You can use a variable length array if necessary, but that will make it harder to read since you'll need a protocol defined for passing the length through.  Get it working first with `struct {int mat[2][2];}`
Comment: I've just done this, the child process can't still receive the matrix from the parent. I think there are other errors in the code.
Comment: Allocating memory in the parent and then passing the address of the memory to the child is doomed to fail!
Comment: I see. So is it better to use static variables in cases like this?
Comment: In fact, I meant with "static variable" the same thing you wrote. Using your advice, it works (in fact, I tried that before asking). Unfortunately, I need a dynamically allocated variable because the user can change the matrix size.
Comment: How about using other shared memory mechanism like mmap? http://man7.org/linux/man-pages/man2/mmap.2.html


Numerical range and essential spectrum

Question: The following question is inspired by the proof of Proposition $\S 40.4$ (the Glimm's Lemma) in A Course in Operator Theory written by John Conway.
Let $H$ be a separable Hilbert space and $\mathcal{A}\subseteq B(H)$ be a unital separable $C^*$-Algebra that contains $\mathcal{K}(H)$. Fix a self-adjoint $A\in\mathcal{A}$, and we use $\pi$ to denote the canonical quotient mapping from $B(H)$ to $B(H)/\mathcal{K}(H)$, and $\sigma_e(A)$ (the essential spectrum) to denote the spectrum of $\pi(A)$. If we suppose $\alpha = \min\sigma_e(A)$ and $\beta = \max\sigma_e(A)$. My questions are below:

Is it true that there exists an orthonormal sequence $\{e_n\}\subseteq H$ such that a subsequence of $\{\langle A e_n, e_n\rangle\}$ converges to $\alpha$ or $\beta$?

Given a sequence of unit vectors $\{h_n\}\subseteq H$ which weakly converges to zero, there is always a subsequence of $\{\langle A h_n, h_n\rangle\}$ that is converging and we use $\{h_n\}-\operatorname{LIM}(A)$ to denote the limit of that subsequence. Once $\{h_n\}$ is given, $\{h_n\}-\operatorname{LIM}$ is a well defined states on $\mathcal{A}$ and we use $\Sigma_1$ to denote the set of states having this form. If we define $\Sigma_1(A) = \{\psi(A): \psi\in\Sigma_1\}$, is $\Sigma_1(A) = [\alpha, \beta]$?

It is shown in this post that whenever $A$ is normal, the numerical range of $A$, $W(A)$ defined as the set $\{\langle Av, v\rangle: \|v\|=1\}$, satisfies that $\overline{W(A)} = \overline{\operatorname{conv}(\sigma(A))}$. For the second questions, if we define:
$$
W_e(A) = \Big\{\{h_n\}-\operatorname{LIM}(A): h_n\overset{w}{\rightarrow}0\text{  and  }\|h_n\|=1 \Big\}
$$
then the ultimate question is that if $\overline{W_e(A)} = \overline{\operatorname{conv}(\sigma_e(A))}$. I am not sure where I need the separability of $\mathcal{A}$ either, and also wonder if $\overline{W_e(A)} = \overline{\operatorname{conv}(\sigma_e(A))}$ is true when $H$ is not separable.
A result that may help with the second question is $\S 7.8$ in the same textbook:

If $\mathfrak{A}$ is a $C^*$-Algebra and $a\in\mathfrak{A}$ is self-adjoint with $\alpha = \min\sigma(a), \beta = \max\sigma(a)$, then $[\alpha, \beta] = \{\phi(a): \phi\text{  is a state on  }\mathfrak{A}\}$
Answer: $\def\e{\varepsilon}$

Yes. One characterization of the essential spectrum is that $E_A(\alpha-\e,\alpha+\e)$ is infinite for any $\e>0$. Then we can choose an orthonormal sequence $\{e_n\}$ with $e_n\in E_A(\alpha-\frac1n,\alpha+\frac1n)$. Since
$$
\big(\alpha-\frac1n\big)E_A(\alpha-\frac1n,\alpha+\frac1n)\leq A\,E_A(\alpha-\frac1n,\alpha+\frac1n)\leq (\alpha+\frac1n)\,E_A(\alpha-\frac1n,\alpha+\frac1n),
$$
we have
\begin{align}
\alpha-\frac1n
&=\langle (\alpha-\frac1n)E_A(\alpha-\frac1n,\alpha+\frac1n)e_n,e_n\rangle\\[0.3cm]
&\leq \langle Ae_n,e_n\rangle\\[0.3cm]
&\leq \langle (\alpha+\frac1n)E_A(\alpha-\frac1n,\alpha+\frac1n)e_n,e_n\rangle\\[0.3cm]
&=\alpha+\frac1n.
\end{align}
Thus $\langle Ae_n,e_n\rangle\to\alpha$. The same can be done for $\beta$ and for any other $\lambda\in\sigma_e(A)$.

You say

Once $\{h_n\}$ is given, $\{h_n\}-\operatorname{LIM}$ is a well defined states on $\mathcal{A}$

As stated, that's not true because the sequence $\{\langle Ah_n,h_n\rangle\}$ can have many accumulation points. For instance, fix an orthonormal basis $\{h_n\}$ and let $A$ be the selfadjoint operator that does $Ae_{2n}=e_{2n}$, $Ae_{2n-1}=2e_{n-1}$. Then both $1$ and $2$ are accumulation points for the sequence $\{\langle Ah_n,h_n\rangle\}$. Tweaking this idea one can get even an interval as the set of accumulation points.
In any case, the answer is yes. By 1) we have that both $\alpha$ and $\beta$ can be obtained in this fashion. Because the numerical range is convex, for each $t\in[\alpha,\beta]$ there exists a state $\phi_t$ on the Calkin algebra such that $\phi(\pi(A))=t$. The state $\phi\circ\pi$ on $B(H)$ is zero on $K(H)$ and hence Glimm's Lemma applies to give us an orthonormal sequence $\{h_n\}$ with $t=\phi_t(\pi(A))=\lim\langle Ah_n,h_n\rangle$.
Comment: Thank you for your answers! In fact, the second question comes from the proof of **Glimm's Lemma** and . The original proof says the following: since we can find a state $\phi_{\alpha}$ such that $\phi[\pi(A)] = \alpha = \inf\sigma_e(A)$, and there exists an ON sequence $\{e_n\}$ such that $\langle\,Ae_n, e_n\,\rangle\rightarrow\alpha$, then $\phi_{\alpha}(\cdot) = \{e_n\}-\operatorname{LIM}(A)$. I also included a screenshot at the end of the question.
Comment: It is clear in your answer to **1)** that $\langle\,A e_n, e_n\,\rangle \rightarrow \alpha$, but can we conclude the sequence of states $\langle\,(\cdot)\,e_n, e_n\,\rangle\rightarrow \phi_{\alpha}$ pointwise? Also, if given $H_0 = \{h_n\}$ weakly converging to zero, then I set $H_1$ to be the subsequence such that $\lim_{H_1}(A_1) = \limsup\langle\,A_1 e_n, e_n\,\rangle$, and then $H_2\subseteq H_1$ such that $\lim_{H_2}(A_2) = \limsup\langle\,A_2, e_n, e_n\,\rangle$, I suppose that is how the original proof make $\{h_n\}-\operatorname{LIM}$ well defined. My definition is incomplete.

Numerical range and essential spectrum


How to remove a link from content using php?

Question: $text = file_get_contents('http://www.example.com/file.php?id=name');
echo preg_replace('#.*?#i', '', $text)

the link contains this content:
text text text.
name

what is the problem at this script?
Comment: it seems that it works.... i don't know what was the problem...
Answer: You can't parse HTML with regular expressions. Use an XML/HTML parser.
Answer: Tempted to flag your question, but there's no option for "Report user for summoning Cthulhu"
I'd recommend reading: http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
RegEx is very poor and not at all intended to parse HTML. That's why there are HTML parsing libraries. Find and use one for PHP. :)
Answer: use ]+>[^<]* (works fine as long as theres just text and no tags inside the a element)
Answer: USE strip_tags this way
$t = 'http://yoururl.com/test1.php';
$t1 = file_get_contents($t);
$text = strip_tags($t1);

it should work getting rid of all the links inside the page you are reading, visit the reference anyway, it may not work for complicated elements http://php.net/manual/en/function.strip-tags.php


Set html and text both to an element on same time with Jquery

Question: hi i how can set text and html both to an existing element. When i click on div text and html both should be set to h1 tag. i tried like this but it is not working. Expected output like this thanks!
NameApple

  sometext

$("#category").onClick(function(){
  $("#brandBtn").html("Name:").text("Apple")
})

Answer: You could change to this: using append instead text
    $("#category").on("click", function(){
      $("#brandBtn").html("Name:").append("Apple")
    });

Comment: thanks it worked , but why does not it works with text ?
Comment: with text this part will be overwrited(Name:)


Countable and uncountable set.

Question:
Which of the following sets of functions are uncountable?

$\{f|f:\Bbb N\to\{1,2\}\}$

$\{f|f:\{1,2\}\to\Bbb N\}$

$\{f|f:\{1,2\}\to\Bbb N, f(1)\le f(2)\}$

$\{f|f:\Bbb N\to\{1,2\}, f(1)\le f(2)\}$

I think 1 and 4 are true. As cardinality of first option is $2^{\aleph_0}=c$ and the cardinality of the second option is $|\Bbb N^2|=\aleph_0$, the third option is a subset of the second option so it is also countable, the fourth option is a subset of the first option but I am not sure about this. Can anyone please explain this?
Comment: **Hint:** Find injections $1\to 4$ and $4\to 1$, and use Cantor-Bernstein.
Answer: It is a subset of the first, which does not show that it is uncountable. To show that it is uncountable you have to show that given any countable list of elements, you can construct an element not on the list. Alternatively, you can reduce the problem to a previous known result, because the condition $f(1) \le f(2)$ only restricts $f(1)$. What if we just fix/ignore $f(1)$? Then how many functions do we have? Remember that these functions are completely determined by their output on the naturals, and can thus be represented by a sequence. With the first element of the sequence fixed, the number of sequences is determined by the number of subsequences from the second onwards.
Comment: if we take f(1)=1 then f(2) can take any value, if we take f(1)=2 then f(2) can take any value except 1, in this way can we say it is same as infinite product of $\Bbb N$'s which is uncountable?
Comment: i think, I'm in wrong way
Comment: Infinite product of what? Each input gives only two choices of output. But the point is that if you fix $f(1) = 1$, then it is equivalent to ignoring what the function does on input $1$. Read my answer carefully, it tells you how to count such functions.
Comment: @Chiranjeev: No problem. By the way, if $f(n) \le f(m)$ for all natural $m,n$, then $f$ must be constant. Now what about the following: How many functions $f \colon \mathbb{N} \to \{1,2\}$ are such that for any natural $m$ there is some natural $n > m$ such that $f(m) \ne f(n)$?
Comment: Ok if we take $m=1,(f(1)=1$ then rest of naturals can be send 2.
if we take $m=2,\{1,2\}\to 1$ and rest of naturals to 2. so it's like partition of naturals in two sets, also for each partition we have 2 maps. so my intuition  says there will be uncountably many functions @user21820
Comment: @Chiranjeev: No that does not answer my question. Your function must satisfy the condition that regardless of what natural $m$ I choose you can choose some natural $n>m$ such that $f(m)≠f(n)$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/25052/discussion-between-chiranjeev-and-user21820).
Comment: @Chiranjeev: Sorry I don't want to use the chat. You should learn how to understand first-order logic, because it is fundamental to everything else. If $f(k) = 2$ for every natural $k > 1$, then I can choose $m = 2$ and you will be unable to choose a natural $n > m$ such that $f(m) \ne f(n)$.

Countable and uncountable set.


Howto secure webservices on GlassFish 2?

Question: We  have some staleless EJBs (EJB3) deployed on a GlassFish 2 server that expose some of their methods as webservices via the @Webmethod annotation.
Now we want to secure these webservice methods so that only authenticated clients can call it. What would be a good way to achieve this?
Comment: When you say authenticated clients, you mean client digital certifications?
Comment: Yes, digital certificates would be optimal.
Comment: Problem is, we cannot secure the webservice port using SSL, since there are other services running on the same port on different urls that should not be secured.
Answer: Like the good reverend said.  Example below uses a file realm for authentication.
<code>@Stateless
@WebService(name = "MyAppServices")
@RolesAllowed({"user"})
public class ItemEJB {
    ...
}
</code>
You will also need sun-ejb-jar.xml e.g.
<code><sun-ejb-jar>
<security-role-mapping>
            <!-- as defined in @RolesAllowed -->
    <role-name>user</role-name>
            <!-- glassfish group created in file realm -->
    <group-name>user</group-name>
</security-role-mapping>
<enterprise-beans>
    <ejb>
        <ejb-name>ItemEJB</ejb-name>
        <webservice-endpoint>
            <!-- equivalent to name attribute of @WebService -->
            <port-component-name>MyAppServices</port-component-name>
            <login-config>
                <auth-method>BASIC</auth-method>
                <realm>file</realm>
            </login-config>
        </webservice-endpoint>
    </ejb>
</enterprise-beans>
</code>

Creation of a group in the file realm in glassfish is trivial (admin console).  you can however create your own custom realm and login module
Answer: You can authorize a list of roles to access a method or an entire bean using security annotations:
E.g.
<code>@Stateless
@RolesAllowed({"user", "employee", "admin"})
public class ItemEJB {
    ...
}
</code>
See the link below for more information:
http://java.sun.com/developer/technicalArticles/J2EE/security_annotation/
Answer:
Now we want to secure these webservice
  methods so that only authenticated
  clients can call it.

I assume that this is not related to ssl. So:
1) The client logs-in giving username and password
2) If username and password are correct (stored in DB) then the user is considered as logged-in and in the reply a unique session token (somehow related to username and password) is generated by the web service and is send back in the reply.
This token is stored along with timestamp info and username and password.
3) Each time a request is send by the client, the token is send back along with the other parameters. If the token is valid then this means that the request comes from an authenticated client.
4) All requests should be expected to have the session token with the rest of parameters.
So an unathenticated client, will have no token to send.


Structs em C podem ter construtores?

Question: Tenho a seguinte estrutura dentro de um programa:
 struct STR00034ST{

     char C_O010XC14B, C_O020XC14B;
     short S_0010XI15C;
     float F_0010XI1D;

     STR00034ST (char _C_O010XC14B, char _C_O020XC14B,  short _S_0010XI15C, float _F_0010XI1D){

        C_O010XC14B=_C_O010XC14B;
        C_O020XC14B=_C_O020XC14B;
        S_0010XI15C=_S_0010XI15C;
        F_0010XI1D=_F_0010XI1D;
    }
};

Porém sempre que compilo retorna o seguinte erro: 'error: expected specifier-qualifier-list before 'STR00034ST''
Andei pesquisando e percebi que só achava exemplos de uso de construtores em struct dentro da linguagem C++ e não em C. Portanto, é impossível usar construtores dentro de uma struct em C?
Answer: Não é possível utilizar construtores em C, portanto você teria que criar uma funcão auxiliar que cria e inicializa structs.
Em C99 existe também uma técninca chamada Compound Literal, que constroi uma estrutura in-place. A sintaxe (em inglês) seria:
( type ) {  initializer-list } ,
por exemplo,
struct foo {int a; char b[2];} structure;.
Comment: Só seu exemplo de inicialização que não inicializa nada. O resto parece-me correto

Structs em C podem ter construtores?


How can I open more than one cmd frames at the saame time and use different codes in them

Question: I am basically hosting 4 node.js projects at the same time and want a batch file to run them all using cmd but I cant open more than one cmd using only one bat file or cant open them all using another bat file so I have to manually make new bat files and edit them everytime I make a new project
cmd.exe
cmd.exe
cmd /k "title hello & color E0"
cmd /k "title hi & color E7"

this is one of my desperete tries, ıt only performs firt line, then the second when I write exit, third line after the next exit and so on. Can u pls help me
Comment: It is batch, the next command runs when the previous is done. So force it to run at the same time. Use `start` (see `start /?`) or do `cmd || cmd2 || cmd3` etc.
Comment: As well as the above advice, I'd invite you to also read the output resulting for opening a Command Prompt window, typing `cmd /?`, and pressing the `[ENTER]` key. Everything you need is explained in the output from those two commands. _If you cannot understand that information you probably shouldn't be using a more complex tool like `node.js`!_
Answer: To give you a better representation of using start in my comment, here is an example:
title This is the original prompt & color A7
start cmd /k "title prompt 1 & color B7"
start cmd /k "title prompt 2 & color C7"
start cmd /k "title prompt 3 & color D7"
start cmd /k "title prompt 4 & color E7"


Prove that numbers divisible by $p$ but not by $p^2$ are quadratic non-residues of $p^n$

Question: Prove that numbers divisible by $p$ but not by $p^2$ are quadratic non-residues of $p^n$
This showed up in Disquisitiones Arithmeticae, article 102, but I fail to see why it must be true.
My attempt so far:
given $a\equiv 0\pmod p$, and $a\not\equiv 0\pmod {p^2}$
then $a = mp$, where m does not contain $p$ in its prime factorization.
Then assume $a$ is a quadratic residue and look for a contradiction.
$a\equiv b^2\pmod {p^n}$
$\frac {a-b^2}{p^n} = I$
$\frac {mp-b^2}{p^n} = I$
How should I proceed from there? Or is there another way to approach this?
Answer: Hint Show that $p|b^2$. Since $p$ is prime and $p|b^2$ you get that...
Answer: $$\implies a\equiv0\pmod p$$
If $x^2\equiv a\pmod p,x^2\equiv0\implies p |x^2\implies p|x\implies p^2|x^2\iff p^2|a$ which contradicts the given proposition
Now if there exists $y,y^2\equiv a\pmod{p^n}$ for integer $n>1$
$y^2\equiv a\pmod p$
Comment: Is it true that $p^2|x^2$ ⟺ $p^2|a$ ?
If $p=3$, $a=3$, and $x^2=9$, then $p^2|x^2$ but $p^2 \not \mid a$, so that is a counter example.


To prove that the Cantor function maps the end points of the intervals removed to a same point

Question: For the function f in 1.6D i.e. $$x=0.b_1b_2....(3)$$ then
$$f(x) = y= 0.a_1a_2.....(2)$$ where $a_i=b_i/2$
Here (2),(3) represents the binary and ternary expansions of $x$ respectively.
Show that if $(a,b)$ is any one of the open intervals removed in the construction $K$, show that $f(a)=f(b)$.
Hint: show that a and b can be written $a=0.a_1a_2.....a_n1$, $b=0.a_1a_2.....a_n2$, where each $a_i$ is 0 or 2. Then rewrite the expansion for a using only 0 and 2.
I'm able to prove this for the first interval that is removed $(1/3,2/3)$ but for general case i don't totally get it. How can i able to express $a$ and $b$ in the form given in the hint? I'm lost!! Please help me understand decimal expansion.
Comment: using $b_1,b_2, \ldots$ and $a_1,a_2, \ldots$ for the ternary and binary digits of $x$ and $f(x)$ and then $(a,b)$ for the removed interval may be confusing.
Answer: Essentially at each step you are removing the interval between the ternary numbers

$0.b_1b_2\ldots b_n02222\ldots_3$
$0.b_1b_2\ldots b_n20000\ldots_3$

with each $b_i \in \{0,2\}$.  The first could also be written as $0.b_1b_2\ldots b_n10000\ldots_3$ and the second as $0.b_1b_2\ldots b_n12222\ldots_3$ but we need to avoid the digit $1$ if we want to apply the function by dividing by $2$.
Applying the function $f$ to these two end points would give

$0.a_1a_2\ldots a_n01111\ldots_2$
$0.a_1a_2\ldots a_n10000\ldots_2$

and these are the same value in binary.
Consider the interval $\left(\frac{7}{27}, \frac{8}{27}\right)$ which you will remove.  You can write $\frac{7}{27}$ in ternary as $0.021_3$ i.e. $0.0210000\ldots_3$ but in this case we want to write it as $0.0202222\ldots_3$  so we can divide each digit by $2$ to get $f\left(\frac{7}{27}\right)=0.0101111\ldots_2 = \frac{3}{8}$.   Meanwhile $\frac{8}{27}$ is $0.0220000\ldots_3$ so $f\left(\frac{8}{27}\right)=0.0110000\ldots_2 = \frac{3}{8}$ too.
Comment: how are u saying that the intervals.removed are between those two numbers that you've mentioned? And i don't get the hint given in the book what about it?? There is a 1 in the ternary expansion of a what should i do about it?
Comment: @LakshmiPriya Yes: each removed interval is between a pair of numbers of that ternary form, and every pair of numbers of that ternary form has the interval between them removed.
Comment: @LakshmiPriya If $a$ is the endpoint of a removed interval and has a ternary digit $1$, then you will be able to rewrite $a$ so it does not have a ternary digit $1$.  I have added an example to my answer
Comment: I understand it now. We should rewrite the endpoint to the desired form to apply f. Thanks for the help


Show that $\{ (1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots\}$ is not a basis of $\Bbb R^N$

Question:
Show that $\beta = \{ (1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots\}$ is not a basis for $\Bbb R^N$

We know that for $\beta$ to be a basis we need $(1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots$ to be both linearly independent and spanning $\Bbb R^N$. The first condition clearly holds as the only way we get $\sum_i \alpha_i v_i = 0$ is for $\alpha_i = 0$.
However, why doesn't $\Bbb R^N = span((1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots)$ hold? Is it because the span of an infinite vector space is ill-defined? Imagine that $N$ is a finite number. Then I guess that $\Bbb R^N = span((1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots)$ would not hold either so I suspect that the reason I presented is not the right one.
Comment: Do you mean $N$ as in the natural numbers? This is usually denoted as $\mathbb{N}$ or $\mathbf{N}$. Also, the span of any subset of a vector space *is* well-defined.
Comment: The function $f:\mathbb{N}\rightarrow\mathbb{R}$ given by $f(n)=1$ for all $n\in\mathbb{N}$ can't be represented by a finite liner combination of the functions $\mathbf{e}_j(n)=\mathbb{1}_{\{j\}}(n)$.
Comment: Does this answer your question? [What is the difference between a Hamel basis and a Schauder basis?](https://math.stackexchange.com/questions/630142/what-is-the-difference-between-a-hamel-basis-and-a-schauder-basis)
Answer: Do you mean $\mathbb R^{\mathbb N}$? In any case it depends how you define "basis" and "span". If you mean a Hamel (or algebraic) basis, then by definition this requires that any element can be written as a finite linear combination of the basis vectors. In the context of Hamel basis, $\text{span}(S)$ is always $\text{span}_\text{fin}(S)$, the set of finite linear combinations.
Then $\mathbb R^{\mathbb N} \neq \text{span}_\text{fin}(\{ e_i \mid i=1\ldots n\})$ is  quite obvious, since for example $(1,1,1\ldots)$ cannot be expressed a finite linear combination of $(1, 0, \dots), (0, 1, 0,\dots), (0, 0, 1, 0,\dots), \dots$
In fact, no person on this earth can show you an explicit example of how a Hamel Basis of $\mathbb R^{\mathbb N}$ looks like, despite the fact that the existence can be proven via the Axiom of Choice. For this reason, one needs a more sensible notion of basis for infinite dimensional spaces: Schauder basis.


object value pairs return undefined except for _id when passed to pug view from a recent mongoose query

Question: I've come across an issue where I can only retrieve the _id property from the object I passed to my pug view. Trying to access word.name returns undefined.
Node.JS route:
const router = require("express").Router();
const authCheck = require("../modules/auth-check");
const errorlog = require("../modules/logs");

// Import DB Models
const Dictionary = require("../models/dictionary");
const Words = require("../models/words");

// Dictionary route for receiving get requests.
router.get("/", authCheck, (req, res) => {
  // Retrieve user words from index and
  Words.find({userid:req.user.id}).sort({createdAt:-1}).exec( (err, words) =>{
    let wordArray = [];
    words.forEach((word)=>{
      wordArray.push(word.wordid);
    });
    Dictionary.find({ _id: {$in: wordArray} }).exec( (err, dictionary)=>{
      if (err){
        console.error(err.message);
        errorlog.write(`${err} OCCURRED: ${Date()} \n`);
      } else {
        // Message contains the query message if pressent. (e.g. /bookmark?message=Bookmark Added)
        let message = req.query.message;
        res.render("dictionary", {words:dictionary, message:message});
      }
    });
  });
});

Pug View Snippet:
// Database Bookmarks output
#output
  each word, index in words
    .content
      .card
        .card-image
          img(src="/img/book.jpg")
          .card-delete(data-id=word._id)
            svg(xmlns='http://www.w3.org/2000/svg', width='24', viewbox='0 0 24 24')
              path(d='M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z')
          span.card-title= word.name
        .card-content
          p= word.desc
      br

Log of object right before sending it to pug view:
{ _id: 5ae055b8e96bb31f8a74affb,
  name: 'corollary',
  desc: '1. That which is given beyond what is actually due, as a garland of flowers in addition to wages; surplus; something added or superfluous. [Obs.] Now come, my Ariel; bring a corollary, Rather than want a spirit. Shak. 2. Something which follows from the demonstration of a proposition; an additional inference or deduction from a demonstrated proposition; a consequence.' }

I suspected it may be to do with the format, but have been stumped. I tried let JSONdictionary = JSON.parse(dictionary) and parse that to the view but recieved errors.
Rendered view(Retrieving ID but nothing else): https://screenshots.firefox.com/yK4Fs1gIQGVN3s3J/null
Update: Result of console.log({words:dictionary, message:message}); :
{ words:
   [ { _id: 5ae055b8e96bb31f8a74affb,
       name: 'corollary',
       desc: '1. That which is given beyond what is actually due, as a garland of flowers in addition to wages; surplus; something added or superfluous. [Obs.] Now come, my Ariel; bring a corollary, Rather than want a spirit. Shak. 2. Something which follows from the demonstration of a proposition; an additional inference or deduction from a demonstrated proposition; a consequence.' },
     { _id: 5ae055b9e96bb31f8a753f22,
       name: 'tree',
       desc: '1. (Bot.)  Any perennial woody plant of considerable size (usually over twenty feet high) and growing with a single trunk. Note: The kind of tree referred to, in any particular case, is often indicated by a modifying word; as forest tree, fruit tree, palm tree, apple tree, pear tree, etc. 2. Something constructed in the form of, or considered as resembling, a tree, consisting of a stem, or stock, and branches; as, a genealogical tree. 3. A piece of timber, or something commonly made of timber; -- used in composition, as in axletree, boottree, chesstree, crosstree, whiffletree, and the like. 4. A cross or gallows; as Tyburn tree. [Jesus] whom they slew and hanged on a tree. Acts x. 39. 5. Wood; timber. [Obs.] Chaucer. In a great house ben not only vessels of gold and of silver but also of tree and of earth. Wyclif (2 Tim. ii. 20). 6. (Chem.)  A mass of crystals, aggregated in arborescent forms, obtained by precipitation of a metal from solution. See Lead tree, under Lead. Tree bear (Zoöl.), the raccoon. [Local, U.S.] -- Tree beetle (Zoöl.) any one of numerous species of beetles which feed on the leaves of trees and shrubs, as the May beetles, the rose beetle, the rose chafer, and the goldsmith beetle. -- Tree bug (Zoöl.), any one of numerous species of hemipterous insects which live upon, and suck the sap of, trees and shrubs. They belong to Arma, Pentatoma, Rhaphigaster, and allied genera. -- Tree cat (Zool.), the common paradoxure (Paradoxurus musang). -- Tree clover (Bot.), a tall kind of melilot (Melilotus alba). See Melilot. -- Tree crab (Zoöl.), the purse crab. See under Purse. -- Tree creeper (Zoöl.), any one of numerous species of arboreal creepers belonging to Certhia, Climacteris, and allied genera. See Creeper, 3. -- Tree cricket (Zoöl.), a nearly white arboreal American cricket (Ecanthus nivoeus) which is noted for its loud stridulation; -- called also white cricket. -- Tree crow (Zoöl.), any one of several species of Old World crows belonging to Crypsirhina and allied genera, intermediate between the true crows and the jays. The tail is long, and the bill is curved and without a tooth. -- Tree dove (Zoöl.) any one of several species of East Indian and Asiatic doves belonging to Macropygia and allied genera. They have long and broad tails, are chiefly arboreal in their habits, and feed mainly on fruit. -- Tree duck (Zoöl.), any one of several species of ducks belonging to Dendrocygna and allied genera. These ducks have a long and slender neck and a long hind toe. They are arboreal in their habits, and are found in the tropical parts of America, Africa, Asia, and Australia. -- Tree fern (Bot.), an arborescent fern having a straight trunk, sometimes twenty or twenty-five feet high, or even higher, and bearing a cluster of fronds at the top. Most of the existing species are tropical. -- Tree fish (Zoöl.), a California market fish (Sebastichthys serriceps). -- Tree frog. (Zoöl.) (a) Same as Tree toad. (b) Any one of numerous species of Old World frogs belonging to Chiromantis, Rhacophorus, and allied genera of the family Ranidæ. Their toes are furnished with suckers for adhesion. The flying frog (see under Flying) is an example. -- Tree goose (Zoöl.), the bernicle goose. -- Tree hopper (Zoöl.), any one of numerous species of small leaping hemipterous insects which live chiefly on the branches and twigs of trees, and injure them by sucking the sap. Many of them are very odd in shape, the prothorax being often prolonged upward or forward in the form of a spine or crest. -- Tree jobber (Zoöl.), a woodpecker. [Obs.] -- Tree kangaroo. (Zoöl.) See Kangaroo. -- Tree lark (Zoöl.), the tree pipit. [Prov. Eng.] -- Tree lizard (Zoöl.), any one of a group of Old World arboreal lizards (Dendrosauria) comprising the chameleons. -- Tree lobster. (Zoöl.) Same as Tree crab, above. -- Tree louse (Zoöl.), any aphid; a plant louse. -- Tree moss. (Bot.) (a) Any moss or lichen growing on trees. (b) Any species of moss in the form of a miniature tree. -- Tree mouse (Zoöl.), any one of several species of African mice of the subfamily Dendromyinæ. They have long claws and habitually live in trees. -- Tree nymph, a wood nymph. See Dryad. -- Tree of a saddle, a saddle frame. -- Tree of heaven (Bot.), an ornamental tree (Ailantus glandulosus) having long, handsome pinnate leaves, and greenish flowers of a disagreeable odor. -- Tree of life (Bot.), a tree of the genus Thuja; arbor vitæ. -- Tree onion (Bot.), a species of garlic (Allium proliferum) which produces bulbs in place of flowers, or among its flowers. -- Tree oyster (Zoöl.), a small American oyster (Ostrea folium) which adheres to the roots of the mangrove tree; -- called also raccoon oyster. -- Tree pie (Zoöl.), any species of Asiatic birds of the genus Dendrocitta. The tree pies are allied to the magpie. -- Tree pigeon (Zoöl.), any one of numerous species of longwinged arboreal pigeons native of Asia, Africa, and Australia, and belonging to Megaloprepia, Carpophaga, and allied genera. -- Tree pipit. (Zoöl.) See under Pipit. -- Tree porcupine (Zoöl.), any one of several species of Central and South American arboreal porcupines belonging to the genera Chætomys and Sphingurus. They have an elongated and somewhat prehensile tail, only four toes on the hind feet, and a body covered with short spines mixed with bristles. One South American species (S. villosus) is called also couiy; another (S. prehensilis) is called also coendou. -- Tree rat (Zoöl.), any one of several species of large ratlike West Indian rodents belonging to the genera Capromys and Plagiodon. They are allied to the porcupines. -- Tree serpent (Zoöl.), a tree snake. -- Tree shrike (Zoöl.), a bush shrike. -- Tree snake (Zoöl.), any one of numerous species of snakes of the genus Dendrophis. They live chiefly among the branches of trees, and are not venomous. -- Tree sorrel (Bot.), a kind of sorrel (Rumex Lunaria) which attains the stature of a small tree, and bears greenish flowers. It is found in the Canary Islands and Teneriffe. -- Tree sparrow (Zoöl.) any one of several species of small arboreal sparrows, especially the American tree sparrow (Spizella monticola), and the common European species (Passer montanus). -- Tree swallow (Zoöl.), any one of several species of swallows of the genus Hylochelidon which lay their eggs in holes in dead trees. They inhabit Australia and adjacent regions. Called also martin in Australia. -- Tree swift (Zoöl.), any one of several species of swifts of the genus Dendrochelidon which inhabit the East Indies and Southern Asia. -- Tree tiger (Zoöl.), a leopard. -- Tree toad (Zoöl.), any one of numerous species of amphibians belonging to Hyla and allied genera of the family Hylidæ. They are related to the common frogs and toads, but have the tips of the toes expanded into suckers by means of which they cling to the bark and leaves of trees. Only one species (Hyla arborea) is found in Europe, but numerous species occur in America and Australia. The common tree toad of the Northern United States (H. versicolor) is noted for the facility with which it changes its colors. Called also tree frog. See also Piping frog, under Piping, and Cricket frog, under Cricket. -- Tree warbler (Zoöl.), any one of several species of arboreal warblers belonging to Phylloscopus and allied genera. -- Tree wool (Bot.), a fine fiber obtained from the leaves of pine trees.\n\n1. To drive to a tree; to cause to ascend a tree; as, a dog trees a squirrel. J. Burroughs. 2. To place upon a tree; to fit with a tree; to stretch upon a tree; as, to tree a boot. See Tree, n., 3.' } ],
  message: undefined }

Comment: Could you please log the entire object you are passing to the view? I mean, console.log({words:dictionary, message:message})
Comment: Hi, I've added a log of both dictionary and message. The message returns undefined as there's no query passed to it from the URL however, it would return the message if present.
Answer: I found the root of the issue and must thank Vivasaayi for taking the time to help. I had cloned the words model and named it dictionary changing the tank but had neglected to update the schema. I can now access the object with no issues. Thanks again.
Answer: I don't have any problems with your View. In fact, with your input object, I am able to render the contents without issues.
Full Code:
router.get("/renderList", function (req, res) {
  res.render("list", {
    words:
      [{
        _id: "5ae055b8e96bb31f8a74affb",
        name: 'corollary',
        desc: '1. That which is given beyond what is actually due, as a garland of flowers in addition to wages; surplus; something added or superfluous. [Obs.] Now come, my Ariel; bring a corollary, Rather than want a spirit. Shak. 2. Something which follows from the demonstration of a proposition; an additional inference or deduction from a demonstrated proposition; a consequence.'
      },
      {
        _id: "5ae055b9e96bb31f8a753f22",
        name: 'tree',
        desc: '1. (Bot.)  Any perennial woody plant of ...'
      }],
    message: undefined
  });
});

Could you please get the object details before passing it to the template.
let message = req.query.message;
console.log({words:dictionary, message:message})
res.render("dictionary", {words:dictionary, message:message});

Comment: Dang, I can only access `words._id` and `words` which displays the whole object in my view. Thanks for the help, at least I know it's to do with the back end.
Comment: Hi, sorry wasn't too clear when you asked for a console log but provided a log of `console.log({words:dictionary, message:message});`. Thanks.
Comment: I tested again and it worked with your object. Seems something else is the problem.
Comment: BTW, If you do any changes to your template, is it reflecting the UI? Is there any caching issue, so its still referring to older version of your PUG template?
Comment: Not sure if this is relevant but if I console log `words` in a script tag inside my view I get undefined. However, if I do `console.log(!{JSON.stringify(words)});` it logs my object. Template changes update, I've changed several elements and cleared my cache.


O meu código está aparecendo esse erro. [object HTMLInputElement] NaN [object NodeList]

Question: Criei o seguinte código, porém não estou conseguindo exibir as informações da forma que gostaria.
Queria exibir algo como
Produto: Nome do produto Valor: 0 Origem: Origem do Produto

Mas está aparecendo [object HTMLInputElement] NaN [object NodeList], alguém poderia me ajudar?

function verificar(){
        var nome = window.document.getElementById('nome')
        var valor = Number(window.document.getElementById('valor'))
        var origem = window.document.getElementsByName('radp')
        var res = window.document.getElementById('res')

        res.innerHTML += `Produto: ${nome}`
        res.innerHTML += `Valor: ${valor}`
        res.innerHTML += `Origem: ${origem}`

    }

Nome do Produto: <input type="text" name="nome" id="nome">

Valor do Produto: <input type="number" name="valor" id="valor">

Origem do Produto:
                <input type="radio" name="radp" id="importado" checked>
                Importado
                <input type="radio" name="radp" id="nacional">
                Nacional

                <input type="button" value="Verificar" onclick="verificar()">

           Preencha os Dados para receber as informações.

Answer: Falta pegar os .value dos elementos. E no caso dos radiobuttons você deve colocar um value em cada um, tipo: value="Importado" e value="Nacional" respectivamente.
E para pegar o valor do radio checado mais facilmente, você pode usar...
var origem = window.document.querySelector('[name="radp"]:checked').value

...em vez de usar window.document.getElementsByName.
No caso de inserir o resultado no HTML, você pode usar o template string desta forma:
res.innerHTML = `Produto: ${nome}
Valor: ${valor}
Origem: ${origem}`

Isso irá gerar um espaço entre cada item.
Veja:

function verificar(){
    var nome = window.document.getElementById('nome').value
    var valor = Number(window.document.getElementById('valor').value)
    var origem = window.document.querySelector('[name="radp"]:checked').value
    var res = window.document.getElementById('res')

    res.innerHTML = `Produto: ${nome}
    Valor: ${valor}
    Origem: ${origem}`

}

Nome do Produto: <input type="text" name="nome" id="nome">

Valor do Produto: <input type="number" name="valor" id="valor">

Origem do Produto:
         <input type="radio" name="radp" id="importado" value="Importado" checked>
         Importado
         <input type="radio" name="radp" id="nacional" value="Nacional">
         Nacional

         <input type="button" value="Verificar" onclick="verificar()">

    Preencha os Dados para receber as informações.

Comment: Iria responder exatamente isso, mas você foi mais rápido no gatilho


Bourne shell scripting reading file

Question: This simple program supposed to read the file lines, but instead it outputs "cat" every time. What is the problem?
#!/bin/sh
while read line
do
  echo $line
done <file

Edit:
file is supposed to be the users input file when calling the program from the terminal. Like:
./programname file

Comment: What do you means it "outputs cat"? As it it prints the word "cat" or it just shows all the liens?
Comment: @kamillaKan What is the content of `file`? Update the question with the same
Comment: @Zephyr Pellerin it just prints the word cat
Comment: @sjsam this is suppose to be the users input file when calling the program from the terminal. Like: ./programname file
Answer:
this is suppose to be the users input file when calling the program
  from the terminal. Like: ./programname file

In this case you should be doing
#!/bin/sh
if [ -f "$1" ] # checking if file exist
then
 while read line
 do
   echo "$line"
 done <"$1" # double quotes important to prevent word splitting
else
  echo "Sorry file $1 doesn't exist"
fi

Here $1 represents the first parameter that you pass to the script.
Interesting reads:

What is [ word splitting ] ?
Shell script [ parameters ]
Comment: Sometimes you never know. Those with the integrity will backup their downvote with a comment, those that lack integrity won't. The community can tell the difference between the two quite easily. It's as simple as that. Don't sweat it.
Comment: @DavidC.Rankin :  `Those with the integrity will backup..` Agree with you 100%. :-)
Comment: Your code runs fine for me and seems as close to an answer as the OP is going to get unless he provides more info.  So: +1.
Comment: @John1024 : Thanks pal. I'm more concerned about the downvote here. Unless the downvoters provide me some information, they are depriving me of a great learning opportunity. I am  taking this to International Court of Justice, ie the meta ;)

Bourne shell scripting reading file


Run Out without bails

Question:
A batsman is Run out if at any time while the ball is in play no
  part of his bat or person is grounded behind the popping crease and
  his wicket(bails) is fairly put down by the opposing side.
                  - Wikipedia

Consider the situation, if a batsman was bowled on a no-ball and the bails were down the stumps then the batsmen are running for a run, at this time, how the fielders will try to run out the batsmen?
Consider this situation,
Batsmen are running between the wickets after hitting the ball inside the ground, the ball was thrown to the fielder/WK, he(WK) then hit the stumps with the ball, all the three stumps were pulled off the ground, but the batsman got reached and the ball slipped from his hand and gone for overthrows, now the batsmen started running between the wickets, now how the fielders will try to run out the batsmen?
Answer: I think it will be useful

If the bails have already been removed, a fielder can remove a remaining stump by pulling it out or hit out the stump(ensure that the stump is fully out of ground) from the ground with the ball in their hands. A fielder can also "remake" the stumps and remove a stump/bail to effect a runout.

from the link here and here
Answer: No if the bails are already off the stumps then the fielder can pull the stump out from the ground and batsmen will be given out as a run out.
Adding to the answer by Ashutosh Mishra
Bangladesh Wicket Keeper Mushfiqur Rahim had used this technique in the match against England in World Cup 2011 to Out England Matt Prior.(though it was Stump Out)
You can watch the image here on
http://www.espncricinfo.com/icc_cricket_worldcup2011/content/image/505600.html
And video of the wicket in HighLights here
Hope it helps.

Run Out without bails


I'm trying to learn how to prove by induction

Question: Please, I need some help to prove this
$$1+\sum_{i=1}^n 5^i = \frac{5^{n+1}-1}{4}$$
I got this but I'm not sure how to proceed
Base n=1
$$=\frac{(5^2)-1}{4}$$
$$=\frac{25-1}{4}$$
$$=\frac{24}{4}$$
$$={6}$$
It works for n=1
Induction hypothesis
Let n=k
$$1+5+25+125+...+k=\frac{5^{k+1}-1}{4}$$
Induction step
Let n=k+1
Prove $$1+5+25+125+...+k+(k+1)=\frac{5^{k+2}-1}{4}$$
By induction hypothesis
$$1+5+25+125+...+k=\frac{5^{k+1}-1}{4}$$
And I tried this way using laws of exponents
$$1+5+25+125+...+k+(k+1)=\frac{5^{k+1}-1}{4}+(k+1)$$
$$=\frac{5^{k+1}-1}{4}+\frac{4(k+1)}{4}$$
$$=\frac{5^k*5+4k+3}{4}$$
I think that I'm doing it wrong but  would be so grateful if you could help me
EDIT: I just realized how bad my summation was, but now I understand the proof, ty all
Comment: And the last term is not $k$. It should be something like $5^k$.
Answer: It seems to me, you interpret the summation is wrong.
But, you have correctly confirmed that the formula is correct for $n=1.$
You can continue from where you left off.
For $n=k$, you get
$$1+5+25+\cdots+5^k=\frac{5^{k+1}-1}{4}$$
Then for $n=k+1$, you get
$$\begin{align}1+5+25+\cdots+5^k+5^{k+1}
&=\frac{5^{k+1}-1}{4}+5^{k+1}\\
&=\frac{4\times 5^{k+1}+5^{k+1}-1}{4}\\
&=\frac{5\times 5^{k+1}-1}{4}\\
&=\frac{5^{k+2}-1}{4}\\
&=\frac{5^{(k+1)+1}-1}{4}.\end{align}$$
This means, if the statement is correct for  $n=k$, then it is also correct for $n=k+1$.
Then by induction, you are done.
Answer: Let $k\in\Bbb N$ and assume that
$$
1+\sum_{i=1}^k5^i=\frac{5^{k+1}-1}4.
$$
Then
\begin{align}
1+\sum_{i=1}^{k+1}5^i&=\left(1+\sum_{i=1}^k5^i\right)+5^{k+1}\\
&=\frac{5^{k+1}-1}4+5^{k+1}\\
&=\frac{5^{k+1}-1+4\times5^{k+1}}4\\
&=\frac{5\times5^{k+1}-1}4\\&=\frac{5^{k+2}-1}4.
\end{align}
Comment: @JoséCarlosSantos Considering the level of the question asked, it might help to explain to the asker how induction actually works instead of just showing the calculations.
Comment: I replaced $n$ with $k$ so that your notation is consistent with that of Ysalva. I hope you don't mind.
Comment: @Joe Not at all. Thank you.
Answer: Other answers are focused on the inductive step (which is almost always the harder part). But I'm going to assert that your basis step also needs correction. You write (shown in one line for brevity):
$$=\frac{(5^2)-1}{4} =\frac{25-1}{4} =\frac{24}{4} ={6}$$
The following observations are things I commonly need to point out to my students:

What's on the left-hand side of that initial equal sign? You cannot start a statement with a relation symbol. You wouldn't write a statement "$= 7$" ("is equal to 7"); that's a sentence fragment, doesn't communicate any information, and needs to be fixed.
Related: The formula in the theorem has two sides! You've shown (once the preceding gets fixed) that when $n = 1$, the right-hand side is equal to $6$. But is that the same as the left-hand side? Are they actually equal? That remains to be verified.

Personally, when proving summation formulas, I find it clearest to write chained relations for the left-hand and right-hand sides separately, then confirm they are the same value. (And of course on the blackboard many abbreviate these as LHS and RHS.) In this case you should be able to write something like:
When $n = 1$:

The left-hand side of the formula is $1+\sum_{i=1}^1 5^i = ... = 6$.
The right-hand side of the formula is $\frac{(5^{1+1})-1}{4} = ... = 6$.
So the equality is true when $n = 1$.


How to view a site as IE would see it, without IE?

Question: So my issue lies within the web design realm. As much as I hate IE, I want to make sure my site is showing correctly for users who are unfortunate enough to have it.
The problem is, I run OS X, so the last version available to me is 5, which barely even starts on my machine.
Are there any worthwhile plug ins or methods so that I can design for IE without having to locate a PC?
Comment: Do you also care if your site *works*, or only how it *looks?*
Comment: I presume he can tell if his site works using other browsers. What happens on the server side should be the same regardless of which client you are using.
Comment: Well, I'd certainly like it to work, but as Jay said, the server side code should work regardless. Ideally, the solution would have the ability for me to interact with it.
Answer: Get Virtualbox and a CD/ISO of Windows and run it. Or use sites such as http://browsershots.org/.
Comment: I'll check out the site, as I don't like the idea of having to boot up a Virtual PC just to run IE.

EDIT: My gosh, BrowserShots is telling me I'll be waiting almost for an hour. I guess VPC is the way to go? Any other methods like plugins or addons?
Comment: +1 for the virtualization suggestion - It's much easier to make small changes and debug your site without having to wait for BrowserShots.
Comment: +1 Even though I hate it the best soultion I know of is to run windows in a VM. Actually it might be worth running multiple versions of window so you can test all their crappy browsers. Browsershot is neat, but its not very practical for testing.
Answer: Use http://browsershots.org/
Answer: I find Adobe BrowserLab really help full, the disadvantage is that you need a user name and password (but it's free) and has most of the internet explorers.
https://browserlab.adobe.com/
Comment: This is exactly the kind of thing I was envisioning when I asked. And I already have an Adobe Account, so there's no hassle. Thanks!
Answer: http://browsershots.org/
Comment: Oh wow....I thought you meant like wait a few minutes...it's showing a wait time of 50 minutes, you really weren't kidding!
Answer: Sad to say, but the most practical solution may be to buy a cheap computer and install Windows on it just for testing. At one time I was doing development on Windows XP but also had a Windows 95 box, a Windows 98 box, and a Linux box, to test for compatibility. I don't know how rich you are or how much office space you have available, but having a real box of the given platform is the most reliable way to test. Setting up a multi-boot would presumably be just as good when that's do-able.
Answer: I use various Parallels instances on the Mac, with different versions of Internet Explorer running inside Windows XP.
Just get yourself Parallels Desktop (or VMware or something similar), install Windows XP and upgrade to SP3 and get all the other Windows updates. However, exclude the Internet Explorer 8 update.
When your VM is up-to-date (except for IE8), then duplicate the VM, once for IE7 and once for IE8. Install the respective IE versions in those VMs.
If you want to test on Windows Vista and Windows 7 as well (you probably should), apply the same tricks, running multiple VMs.
Note that with 2 GB of RAM, you can probably run no more than 2 VMs at a time. The more RAM, the more VMs you can run in parallel.


Rails testing with fog/webmock

Question: I am using the fog gem to send carrierwave uploads to an AWS S3 bucket. That seems to be working fine, but when I try to run my cucumber tests I get:
You are using Excon 0.6.6. WebMock supports version >= 0.9.6

I have moved fog out of the test group in the gemfile (it's only in development and production). I've looked around for other people have thing problem, but I haven't been able to find anything.
My goal really would be to not use fog at all in the test suite, but just use the local file system.
Answer: It turns out that I was using an old version of fog. I had:
gem 'fog'

In my gemfile when I needed to have:
gem "fog", "~> 1.12.1"

That fixed this problem.
Answer: Yep, I was about to chime in and let you know as much. I think a bundle update fog would also do the trick (without needing to lock to anything in particular or change the gemfile). Glad you were able to get yourself back on track so easily though.

Rails testing with fog/webmock


Erro no autocomplete de um input

Question: Olá, estou tentando fazer um autocomplete no campo valor unitário de acordo com o nome do produto escolhido no select, options do select preenchidos de acordo com os produtos do banco de dados

A lógica que desenvolvi foi executar uma query no PHP que seleciona descricao e preco_venda e preenche a tag  sendo value = preco_venda e conteúdo da option recebendo descricao.
Em seguida usei o DOM do javascript para pegar o value da opção escolhida no evento "onblur" e uma variável PHP recebe esse conteúdo.
Com a variável PHP recebendo o value, queria preencher esse valor no campo unitário
 Produto:

        <select name="nomeproduto" onblur="valorSelect()">
            <option value=""></option>

            <?php
                $sql = "select descricao, preco_venda from produtos";
                $result = $conn->query($sql);

                while($rows = $result->fetch_assoc()) {
            ?>
                    <option value="<?php echo $rows['preco_venda']; ?>">
                        <?php echo $rows['descricao']; ?>
                    </option>

          <?php } ?>

        </select>

        <?php

        $valor =
            "";
        ?>

        Valor unitário:

        <input type="number" name="valorunitario" value="<?php echo $valor; ?>">

Mas ocorre esses erros:

Quem puder ajudar a corrigir esses erros estarei muito grato
Answer: Vamos lá, você está tentando passar a variável $valor para o value de um input. Esse é o primeiro erro, pois a variável não vai ser o valor da execução dessa função, e sim a string que foi declarada dentro dela. Desse modo, o javascript não reconhece que existe uma função chamada valorSelect(), que é o erro apontado no seu console.
Vale lembrar também, que não é possível pegar um valor de dentro de um bloco javascript, enquanto o seu documento é carregado pelo browser.
O que você deve fazer é criar essa função fora do php, diretamente no HTML, como no exemplo a seguir.

    var select = document.querySelector('select');
    var input = document.querySelector('input');

    select.onchange = function(e) {
        var value = e.target.value;
        input.value = value;
    }
<select>
    <option value="">Escolher</input>
    <option value="12.000">Pc gamer</option>
    <option value="7.000">Notebook</option>
    <option value="500">Cadeira gamer</option>
</select>

<input />

Uma observação, é que você não vai conseguir obter o produto que a pessoa escolheu dessa forma, e só o valor dele.
Espero ter ajudado!!
Comment: Obrigado, consegui resolver o problema, mas vou testar sua lógica

Como resolvi:

function valorSelect() {
                        let valor = event.target;
                        valor = parseFloat(valor.value)

                        let exibir = document.getElementById('preco')
                        exibir.value = "";
                    }
Comment: Show! Tenta bolar uma lógica pra deixar esse javascript em um arquivo externo, para melhores performances, já que ele entrará no cache do navegador.

Erro no autocomplete de um input


Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found

Question: My view :
def display(request):
    feed = SoukFeedMaster.objects.filter(person = request.user)
    return render(request, 'soukfeed/display.html', {'feed' : feed ,})

My Template :
{% extends "base.html" %}

    {% block content %}
    {% for x in feed %}
        {% load url from future %}
          {{x.content.content}}

    {% endfor %}

    {% endblock %}

Traceback  :
Environment:

Request Method: GET
Request URL: http://localhost:8000/soukfeed/

Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.comments',
 'ec.kiosk',
 'ec.chakra',
 'ec.ajax',
 'ec.broadcast',
 'ec.connect',
 'ec.seek_solutions',
 'ec.feed',
 'ec.ec_model',
 'ec.info',
 'ec.souk_info',
 'ec.ec_central',
 'ec.domains',
 'ec.souk',
 'ec.souk_feed',
 'ec.meta',
 'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Template error:
In template /volumes/disk2/workspace/templates/ec/soukfeed/display.html, error at line 1
   Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.
   1 : {% extends "base.html" %}

    {% block content %}
     {% for x in feed %}
        {% load url from future %}
          {{ x.content.content }}

    {% endfor %}

    {% endblock %}

Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Volumes/Disk2/workspace/ec/ec/souk_feed/views.py" in display
  18.         return render(request, 'soukfeed/display.html', {'feed' : feed ,})
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
  44.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  123.             return self._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  450.                         raise e

Exception Type: TemplateSyntaxError at /soukfeed/
Exception Value: Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.

Comment: edit your post to include your urls.py and your model for SoukFeedMaster
Answer: Just had the same problem with my app. The following solved it for me:
Because you're using the {% url %} tag to generate the link to the view, you need to add the URLs for the application to your project's root URLConf module (via include() calls). If you use the {% url %} tag with a URL name that you haven't yet set up in your project, it won't be able to find the correct URL and will simply return an empty string instead of a URL.
So basically the problem is that the url you're looking up must be in the urls.py of your project, otherwise Django can't find and trace it.
Answer: It is really not enought information. But the problem is here:
{% url x.content.url_internal_django_link  x.content.id  %}

May be you need that:
{% extends "base.html" %}

{% block content %}
{% for x in feed %}
      {{x.content.content}}

{% endfor %}

{% endblock %}

But I am not sure - it depends from you model code and your general logic
Answer:
Exception Value: Caught NoReverseMatch
  while rendering: Reverse for '' with
  arguments '(1,)' and keyword arguments
  '{}' not found.

it looks like your x.content.url_internal_django_link is returning an empty string.
Check your db or change your {% url %} tags temporarily to:
{{ x.content.url_internal_django_link }}

to see what is stored and why you are getting empty strings from the db.
Answer: I have got the same exception output saying that not able to '(93L,)' and the keyword argument is not found.
Check the urls.py,where you can see that the url is not provided there.So provide the url then youre not going to this error.
Answer: Another possibility is that the regex string of URL is not matched with your request.user.username


run command on multiple threads

Question: I am running a command (pngquant to be precise: https://github.com/pornel/pngquant) in a terminal window. I noticed, that if I open 4 terminal windows, and run pngquant command in each of them, I get 4x speed increase, effectively compression 4 times as many images in the same time as before.
So I used this approach and assigned each pngqunat process a portion of images I want to compress, effectively creating multiple processes on multiple threads
Can you run command on multiple threads without doing this tricks that I did? I would like to just say "run pngquant compression on all this images and use all threads avalable."
Answer: This is only possible if the developer of the tool developed it with multithreading capabilities, which appears to not be the case for your tool.
However, in many cases you can use something like GNU Parallel to overcome this limitation and it will automate this for you.
Comment: _multicore support (via OpenMP) and Intel SSE optimizations_ https://github.com/pornel/pngquant
Answer: In your case it should be simple to use GNU xargs. Here an example using 4 threads (-P4)
<code>find . -name "*.png*" -not -name "*8.png" -print0 | xargs -0 -n1 -P4 pngquant 64
</code>

run command on multiple threads


Are any of these metrics equivalent?

Question: I have the space of continuous functions from $[0,1]$, $C([0,1]),$ with 3 different metrics, $d_1, d_2$ and $d_{\infty}$. Where $d_1(f,g)=\int_{0}^1|f(t)-g(t)|dt$, $d_2(f,g)=(\int_{0}^1|f(t)-g(t)|^{2})^{0.5}dt$ and $d_{\infty}=sup_{t\in[0,1]}(|f(t)-g(t)|)$ I am asked to show if anyof them are equivalent, I know the meaning of this but have no clue where to start, any help will be appreciated!
Comment: To show a pair aren't equivalent, you in effect need to find a bounded sequence of functions in one of the metrics, which is unbounded in the other.
Comment: Are you sure the exponent $\frac 12$ is inside the integral for $d_2$? Otherwise $d_1 = d_2$.
Comment: The exponent isnt inside the integral. And so I need to find a sequence $f_n$ s.t. $d_i(f,0)$ is bounded and $d_j(f,0)$ isnt?
Comment: You'll need the definition of "equivalent" that is in the mind of the person asking the question. Can you add that to the question?
Answer: Some hints:
Easy inequalities to prove are the following:
$$
d_2(f,g) \leq d_\infty d(f,g) \\
d_1(f,g) \leq d_\infty d(f,g) \\
d_1(f,g) \leq d_2(f,g).
$$
To prove the last one you'll need the Hölder's inequality. As a last hint, none of the metrics are actually equivalent. So you should be able to find sequence of functions that are convergent in $d_i$, but not in $d_\infty$ for $i=1,2$ and a sequence of functions that is convergent in $d_1$ but not in $d_2$. These aren't too hard to find, consider for example a sequence with $f_n(0)=1$ for all $n$ but for which the integral converges to zero.

Are any of these metrics equivalent?


Export news items (including pictures etc.) from Drupal to SQL

Question: I would like to export newsitems from Drupal including images to import them into a whole different database.
Is there any module or whats the best way to create an export from Drupal to a SQL, CSV file?
Comment: Are you migrating from Drupal to another system? or you want migrate your Drupal to another database?
Comment: From Drupal to another database. So I would like to export only news items and images belonging to those news items.
Answer: Try Node Export.

This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.
Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.
You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.

Node export formats
The format to export with is configurable, and the Node export package comes with the following formats:

JSON - JavaScript Object Notation code which is known for being
  security friendly. (Drupal 7 only)
Drupal var export - A Drupalized PHP array which is similar to
  var_export(). (Drupal 7 only)
Node code - A customized PHP array which is similar to var_export().
  (Drupal 6 only) CSV - RFC4180 compliant CSV code. Ideal for viewing in
  Windows software, and editing data as spreadsheets.
Serialize - Very robust, though not human readable, representation
  through Serialization using the PHP serialize function.
XML - XML 1.0 representation which is good for machine-readability and
  human-readability.
Comment: Hi, I'd like to export the data for use in an other system, our own CMS. So I'd like to have all elements of the news items to be exported to preferrably SQL
Comment: @tvgemertI don't get how is sql going to help you. Are you planning to have the same table structure, IS so then just go to phpMyAdmin and do an export. CSV is the best option according to me and you will have to write a custom script to do the import into the custom tables which you will create in your own cms.


How to efficiently pre-filter rows in conjunction with a join?

Question: I need to calculate timestamps between filtered rows in a table.
I am using a join based on a helpful answer from another question:
StackOverflow: difference between timestamps in two consecutive rows in single table
My problem is that my table has mixed data from multiple different objects and I expect that I need to first filter on "object_id=blah" before performing the join, because if I don't pre-filter then the join will difference the timestamps from unrelated object_id's (because it's just looking consecutively, row by row).
I need the join to do the timestamp differences based on the previous occurrence of object_id=blah, not merely the immediately preceeding row.
Looking for how to solve this query most efficiently.
Thanks in advance!  =D
I've already tried adding a WHERE object_id=blah after the JOIN, and I got the right number of rows, but the timestamp diffs were still just based on the prior row in each timestamp difference.
I was really hoping the WHERE would apply to the source table before the JOIN occurred, but clearly that isn't how this works.  :-(
SELECT
   t1.scanid, t1.event_id, t1.objectect_id, t1.object_timestamp, t1.object_counter,
   TIMEDIFF(t1.object_timestamp, t2.object_timestamp) AS diff
FROM event_data AS t1
LEFT JOIN event_data AS t2 ON ( t2.scanid = t1.scanid - 1);

--+---------------+--------------+------+-----+----------------------+----------------+
--| Field         | Type         | Null | Key | Default              | Extra          |
--+---------------+--------------+------+-----+----------------------+----------------+
--| scanid        | int(11)      | NO   | PRI | NULL                 | auto_increment |
--| event_id      | int(12)      | NO   |     | NULL                 |                |
--| objectect_id  | int(11)      | NO   |     | NULL                 |                |
--| obj_timestamp | timestamp(3) | NO   |     | CURRENT_TIMESTAMP(3) |                |
--| obj_counter   | int(11)      | YES  |     | -1                   |                |
--+---------------+--------------+------+-----+----------------------+----------------+

And with the WHERE object_id=2:
SELECT
   t1.scanid, t1.event_id, t1.objectect_id, t1.object_timestamp, t1.object_counter,
   TIMEDIFF(t1.object_timestamp, t2.object_timestamp) AS diff
FROM event_data AS t1
LEFT JOIN event_data AS t2 ON ( t2.scanid = t1.scanid - 1)
WHERE t1.object_id = 2;

Here is the original object data:
+--------+----------+------------+-------------------------+-------------+
| scanid | event_id | object_id  | obj_timestamp           | obj_counter |
+--------+----------+------------+-------------------------+-------------+
|      1 |        1 |          2 | 2019-02-17 13:11:02.425 |           0 |
|      2 |        1 |          0 | 2019-02-17 13:11:08.227 |           0 |
|      3 |        1 |          0 | 2019-02-17 13:11:12.303 |           1 |
|      4 |        1 |          0 | 2019-02-17 13:11:31.383 |           2 |
|      5 |        1 |          0 | 2019-02-17 13:11:32.417 |           3 |
|      6 |        1 |          0 | 2019-02-17 13:11:33.451 |           4 |
|      7 |        1 |          0 | 2019-02-17 13:11:34.839 |           5 |
|      8 |        1 |          0 | 2019-02-17 13:11:35.868 |           6 |
|      9 |        1 |          0 | 2019-02-17 13:12:05.143 |           7 |
|     10 |        1 |          0 | 2019-02-17 13:13:08.733 |           8 |
|     11 |        1 |          0 | 2019-02-17 13:13:11.169 |           9 |
|     12 |        1 |          0 | 2019-02-17 13:13:22.239 |          10 |
|     13 |        1 |          0 | 2019-02-17 13:13:24.256 |          11 |
|     14 |        1 |          0 | 2019-02-17 13:13:26.875 |          12 |
|     15 |        1 |          0 | 2019-02-17 13:13:27.910 |          13 |
|     16 |        1 |          2 | 2019-02-17 13:16:24.326 |           1 |
|     17 |        1 |          2 | 2019-02-17 13:16:25.362 |           2 |
|     18 |        1 |          2 | 2019-02-17 13:19:48.318 |           3 |
|     19 |        1 |          2 | 2019-02-17 13:25:01.604 |           4 |
|     20 |        1 |          2 | 2019-02-17 13:30:17.024 |           5 |
|     21 |        1 |          0 | 2019-02-17 13:39:19.664 |          14 |
|     22 |        1 |          0 | 2019-02-17 13:39:20.696 |          15 |
|     23 |        1 |          2 | 2019-02-17 13:41:12.324 |           6 |
|     24 |        1 |          2 | 2019-02-17 13:41:13.349 |           7 |
|     25 |        1 |          0 | 2019-02-17 13:41:14.381 |          16 |
|     26 |        1 |          0 | 2019-02-17 13:41:17.436 |          17 |
|     27 |        1 |          2 | 2019-02-17 13:41:18.467 |           8 |
|     28 |        1 |          0 | 2019-02-17 13:41:20.503 |          18 |
|     29 |        1 |          0 | 2019-02-17 13:41:21.535 |          19 |
|     30 |        1 |          0 | 2019-02-17 13:41:22.563 |          20 |
|     31 |        1 |          2 | 2019-02-17 13:41:23.591 |           9 |
|     32 |        1 |          2 | 2019-02-17 13:41:24.619 |          10 |
+--------+----------+------------+-------------------------+-------------+
32 rows in set (0.00 sec)

Actual Output (without the WHERE):
+--------+----------+------------+-------------------------+-------------+--------------+
| scanid | event_id | object_id  | obj_timestamp           | obj_counter | diff         |
+--------+----------+------------+-------------------------+-------------+--------------+
|      1 |        1 |          2 | 2019-02-17 13:11:02.425 |           0 | NULL         |
|      2 |        1 |          0 | 2019-02-17 13:11:08.227 |           0 | 00:00:05.802 |
|      3 |        1 |          0 | 2019-02-17 13:11:12.303 |           1 | 00:00:04.076 |
|      4 |        1 |          0 | 2019-02-17 13:11:31.383 |           2 | 00:00:19.080 |
|      5 |        1 |          0 | 2019-02-17 13:11:32.417 |           3 | 00:00:01.034 |
|      6 |        1 |          0 | 2019-02-17 13:11:33.451 |           4 | 00:00:01.034 |
|      7 |        1 |          0 | 2019-02-17 13:11:34.839 |           5 | 00:00:01.388 |
|      8 |        1 |          0 | 2019-02-17 13:11:35.868 |           6 | 00:00:01.029 |
|      9 |        1 |          0 | 2019-02-17 13:12:05.143 |           7 | 00:00:29.275 |
|     10 |        1 |          0 | 2019-02-17 13:13:08.733 |           8 | 00:01:03.590 |
|     11 |        1 |          0 | 2019-02-17 13:13:11.169 |           9 | 00:00:02.436 |
|     12 |        1 |          0 | 2019-02-17 13:13:22.239 |          10 | 00:00:11.070 |
|     13 |        1 |          0 | 2019-02-17 13:13:24.256 |          11 | 00:00:02.017 |
|     14 |        1 |          0 | 2019-02-17 13:13:26.875 |          12 | 00:00:02.619 |
|     15 |        1 |          0 | 2019-02-17 13:13:27.910 |          13 | 00:00:01.035 |
|     16 |        1 |          2 | 2019-02-17 13:16:24.326 |           1 | 00:02:56.416 |
|     17 |        1 |          2 | 2019-02-17 13:16:25.362 |           2 | 00:00:01.036 |
|     18 |        1 |          2 | 2019-02-17 13:19:48.318 |           3 | 00:03:22.956 |
|     19 |        1 |          2 | 2019-02-17 13:25:01.604 |           4 | 00:05:13.286 |
|     20 |        1 |          2 | 2019-02-17 13:30:17.024 |           5 | 00:05:15.420 |
|     21 |        1 |          0 | 2019-02-17 13:39:19.664 |          14 | 00:09:02.640 |
|     22 |        1 |          0 | 2019-02-17 13:39:20.696 |          15 | 00:00:01.032 |
|     23 |        1 |          2 | 2019-02-17 13:41:12.324 |           6 | 00:01:51.628 |
|     24 |        1 |          2 | 2019-02-17 13:41:13.349 |           7 | 00:00:01.025 |
|     25 |        1 |          0 | 2019-02-17 13:41:14.381 |          16 | 00:00:01.032 |
|     26 |        1 |          0 | 2019-02-17 13:41:17.436 |          17 | 00:00:03.055 |
|     27 |        1 |          2 | 2019-02-17 13:41:18.467 |           8 | 00:00:01.031 |
|     28 |        1 |          0 | 2019-02-17 13:41:20.503 |          18 | 00:00:02.036 |
|     29 |        1 |          0 | 2019-02-17 13:41:21.535 |          19 | 00:00:01.032 |
|     30 |        1 |          0 | 2019-02-17 13:41:22.563 |          20 | 00:00:01.028 |
|     31 |        1 |          2 | 2019-02-17 13:41:23.591 |           9 | 00:00:01.028 |
|     32 |        1 |          2 | 2019-02-17 13:41:24.619 |          10 | 00:00:01.028 |
+--------+----------+------------+-------------------------+-------------+--------------+
32 rows in set (0.01 sec)

And with the WHERE object_id=2:
+--------+----------+------------+-------------------------+-------------+--------------+
| scanid | event_id | object_id  | obj_timestamp           | obj_counter | diff         |
+--------+----------+------------+-------------------------+-------------+--------------+
|      1 |        1 |          2 | 2019-02-17 13:11:02.425 |           0 | NULL         |
|     16 |        1 |          2 | 2019-02-17 13:16:24.326 |           1 | 00:02:56.416 |
|     17 |        1 |          2 | 2019-02-17 13:16:25.362 |           2 | 00:00:01.036 |
|     18 |        1 |          2 | 2019-02-17 13:19:48.318 |           3 | 00:03:22.956 |
|     19 |        1 |          2 | 2019-02-17 13:25:01.604 |           4 | 00:05:13.286 |
|     20 |        1 |          2 | 2019-02-17 13:30:17.024 |           5 | 00:05:15.420 |
|     23 |        1 |          2 | 2019-02-17 13:41:12.324 |           6 | 00:01:51.628 |
|     24 |        1 |          2 | 2019-02-17 13:41:13.349 |           7 | 00:00:01.025 |
|     27 |        1 |          2 | 2019-02-17 13:41:18.467 |           8 | 00:00:01.031 |
|     31 |        1 |          2 | 2019-02-17 13:41:23.591 |           9 | 00:00:01.028 |
|     32 |        1 |          2 | 2019-02-17 13:41:24.619 |          10 | 00:00:01.028 |
+--------+----------+------------+-------------------------+-------------+--------------+
11 rows in set (0.00 sec)

Answer: From looking at your data, it seems the appropriate JOIN condition for your table is actually t2.obj_counter = t1.obj_counter - 1 AND t2.object_id = t1.object_id; this will ensure that only timestamps related to a given object are compared with each other. So your query becomes (based on your sample data):
SELECT
   t1.scanid, t1.event_id, t1.object_id, t1.obj_timestamp, t1.obj_counter,
   TIMEDIFF(t1.obj_timestamp, t2.obj_timestamp) AS diff
FROM event_data AS t1
LEFT JOIN event_data AS t2 ON t2.obj_counter = t1.obj_counter - 1 AND t2.object_id = t1.object_id
WHERE t1.object_id = 2
ORDER BY t1.obj_counter

Output:
scanid  event_id    object_id   obj_timestamp       obj_counter diff
1       1           2           2019-02-17 13:11:02 0           null
16      1           2           2019-02-17 13:16:24 1           00:05:22
17      1           2           2019-02-17 13:16:25 2           00:00:01
18      1           2           2019-02-17 13:19:48 3           00:03:23
19      1           2           2019-02-17 13:25:02 4           00:05:14
20      1           2           2019-02-17 13:30:17 5           00:05:15
23      1           2           2019-02-17 13:41:12 6           00:10:55
24      1           2           2019-02-17 13:41:13 7           00:00:01
27      1           2           2019-02-17 13:41:18 8           00:00:05
31      1           2           2019-02-17 13:41:24 9           00:00:06
32      1           2           2019-02-17 13:41:25 10          00:00:01

Demo on dbfiddle
Comment: @LeonShaner unless you turn this SELECT into a subquery, you can't use an alias in the same SELECT so you would have to repeat the `TIMEDIFF`
Comment: @LeonShaner that's the way you have to do it unless you write a subquery e.g. `SELECT scanid, event_id, object_id, obj_timestamp, obj_counter, diff, diff /2 AS hdiff FROM (SELECT t1.scanid, t1.event_id, t1.object_id, t1.obj_timestamp, t1.obj_counter, TIMEDIFF(t1.obj_timestamp, t2.obj_timestamp) AS diff FROM event_data AS t1 LEFT JOIN event_data AS t2 ON t2.obj_counter = t1.obj_counter - 1 AND t2.object_id = t1.object_id WHERE t1.object_id = 2 ORDER BY t1.obj_counter) AS diffs`
Comment: Thanks so much, @Nick!  Your solution is great! =D
Comment: quick follow-up, since all the context is already here.  =D  What if I want to store the TIMEDIFF result into a local var in addition to storing AS diff so I can use the the local var in a computation for another column in the join?   I couldn't work out the syntax.  I can just repeat the TIMEDIFF instead of referencing a local var, but that seems inefficient.  I'll post my inefficient code in the next comment.
Comment: Not the exact math I'll be doing, but should illustrate why I want a local variable to store diff (in addition to passing it to the join AS diff):

    SELECT
       t1.scanid, t1.event_id, t1.object_id, t1.obj_timestamp, t1.obj_counter,
       TIMEDIFF(t1.obj_timestamp, t2.obj_timestamp) AS diff,
       TIMEDIFF(t1.obj_timestamp, t2.obj_timestamp) / 2 AS hdiff
    FROM event_data AS t1
    LEFT JOIN event_data AS t2 ON t2.obj_counter = t1.obj_counter - 1 AND t2.object_id = t1.object_id
    WHERE t1.object_id = 2
    ORDER BY t1.obj_counter
Comment: Thanks again, @Nick.  I'll sleep on it and see if I can figure out how to do the sub-query.  This is my first join, soo..  Steep learning curve at the moment.  :S  Cheers! =D
Comment: ! Awesome!  Wow, I've learned so much here.  Thanks again.  Cheers! =D
Comment: Hey, @Nick, if you think to copy your last comment as an answer, I'll mark it as the best solution.  It's ultimately what I meant by meant by "pre-filter" a la select what I want up front and manipulate it before I pass it to the join.  You ROCK! =D


How to call function from PHP file (or another module) in JS file from my custom module?

Question: After this question, I try to write custom module to add support Views Infinite Scroll to Background Images module. Here is my code:
my_module.module
/**
 * @file
 * Module file for Background Image for Views Infinite Scroll.
 */

/**
 * Implements hook_page_build().
 */

function my_module_page_build() {
  // Settings.
  drupal_add_js(array(
    'viewClass' => '.view-content',
    'nodeClass' => '.node-content',
  ), 'setting');
  // Add JS to page.
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
}

/**
 * My function.
 */

function my_module_function() {
   // Code here
}

And ./js/my_module.js
/**
 * @file
 * This is main script of Background Image for Views Infinite Scroll.
 */

(function($, Drupal) {

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      $(Drupal.settings.viewClass).on('DOMNodeInserted', function() {
        // Code here
      });
    }
  }

})(jQuery, Drupal);

How call function my_module_function() in my JS file?
Answer: You can add a menu callback in your module, that will be used by JS to send-receive values from PHP.
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my-module/my-function'] = array(
    'title' => 'Ajax callback for my function.',
    'page callback' => 'my_module_function',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_function() {
  // Remember you have to print your results if you want to
  // send any values back to JS.
  print 'Hi, there!';
  drupal_exit();
}

Now in your JS code, you make an Ajax call and, optionally, get values back from PHP (if desired).
$.ajax({
  url: Drupal.settings.basePath + "?q=my-module/my-function",
  done: function(data) {
    // If my_module_function returns any value, it will come in the data variable.
    alert(data);
  }
});

Comment: Ok, If ``my_module_function`` don't returns any value? I mean, I'm try to alter original function from Background Images module — http://cgit.drupalcode.org/bg_image/tree/bg_image.module#n289
Comment: What function are you trying to run from JS?
Comment: I try to refresh function in ``bg_image`` module (http://cgit.drupalcode.org/bg_image/tree/bg_image.module) that place styles with background images for each node (in row) to ``head`` document when Views Infinite Scroll loaded new row content with background image.


Definir domínio para container docker-compose

Question: Estou começando a usar docker-compose e gostaria de saber como configuro um domínio para o meu container apache via docker-compose.yml? Atualmente para acessar o meu container eu digito localhost:3000.
cms:
  environment:
    O2_MYSQL_HOST: mysql
  TZ: "America/Sao_Paulo"
  image: o2multi/apache-php7
  restart: always
  ports:
    - "3000:80"
  volumes:
    - ./src:/var/www/html/
    - ./devops/docker/webserver/custom.ini:/etc/php/7.1/apache2/conf.d/666-custom.ini
    - ./devops/docker/webserver/o2.conf:/etc/apache2/sites-enabled/001-o2.conf
  links:
    - mysql

Comment: Fala amigo, quando você diz dominio você está dizendo que tem um dominio ".com, .com.br" comprado e gostaria de apontar para seu container ?
Comment: Não, eu apenas quero poder acessar o meu container via um domínio não comprado. Ex: docker.qqrcoisa.com
Answer: Se você quer acessar por um domínio somente na sua máquina, uma forma simples é mudar a porta de 3000 para 80 no seu container e alterar o arquivos hosts adicionando o "domínio" que quer usar.
127.0.0.1     meu.dominio.com

Cadas SO mantém o mesmo em locais diferentes.

Windows: C:/Windows/system32/drivers/etc/hosts
Linux: /etc/hosts
Answer: Você pode fazer o apontamento de um container docker para um dominio específico usando Proxy Reverso.
Primeiro, você vai precisar criar um novo arquivo .conf em \etc\apache2\sites-avaiable algo tipo isso:
meusite.com.br.conf:
<VirtualHost *:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName meusite.com.br
  ProxyPass / http://<IP_DO_SERVIDOR>:3000/
  ProxyPassReverse / http://<IP_DO_SERVIDOR>:3000/
</VirtualHost>

e depois habilitar e reiniciar o apache
$ a2ensite meusite.com.br.conf
$ service apache2 reload

Basicamente o que vai acontecer aqui é que toda requisição feita para esse dominio meusite.com.br vai ser direcionada para a porta 3000 especificada na configuração do VirtualHost.
Lembra que que se estiver usando o docker-compose de colocar a diretiva restart: always para que o container seja recarregado toda vez que a máquina for bootada.
Comment: O que preciso fazer para que a url seja: meusite.com.br/webapps?


App made with android studio exceeds phone width

Question: I have made an app for my blog. Blog looks fine while using a browser but with app it exceeds screen width.
This is my blog
This is what i see from my browser (opera, yandex etc)
And the result using the app
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/swipe_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="WebViewLayout" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

And the main activity xml
Comment: Looks like your blog doesn't have a mobile/small screen layout. The WebView is just showing what the HTML and CSS code of your blog tell it. Also you can't compare a wide desktop view with a mobile view. You can simulate a mobile view on your desktop and thus adapt your blog https://dev.opera.com/articles/opera-mobile-emulator/
Comment: I am comparing mobile browsers not desktop
Answer: The solution was to add these two lines in my java file.
Thanks  to this answer

webView.getSettings().setUseWideViewPort(true);
webView.setInitialScale(1);


Prove that $\sum_{cyc}\frac{1}{x^2 + 1} \ge \frac{2}{3}\bigl(\sum_{cyc}\frac{x}{\sqrt{x^2 + 1}}\bigr)^3$ where $x, y, z > 0$ and $xy + yz + zx = 1$.

Question:
$x$, $y$ and $z$ are positives such that $xy + yz + zx = 1$. Prove that $$\large \frac{1}{x^2 + 1} + \frac{1}{y^2 + 1} + \frac{1}{z^2 + 1} \ge \frac{2}{3}\left(\frac{x}{\sqrt{x^2 + 1}} + \frac{y}{\sqrt{y^2 + 1}} + \frac{z}{\sqrt{z^2 + 1}}\right)^3$$

We have that $$\frac{x}{\sqrt{x^2 + 1}} = \frac{x}{\sqrt{x^2 + xy + yz + zx}} = \frac{x}{\sqrt{(x + y)(z + x)}} \le \frac{x}{x + \sqrt{yz}} = 1 - \frac{\sqrt{yz}}{x + \sqrt{yz}}$$
$$ \implies \sum_{cyc}\frac{x}{\sqrt{x^2 + 1}} \le 3 - \sum_{cyc}\frac{\sqrt{yz}}{x + \sqrt{yz}} = 3 - \sqrt{xyz}\sum_{cyc}\frac{1}{x\sqrt x + \sqrt{xyz}} \le 3\left(1 - \frac{3\sqrt{xyz}}{x\sqrt x + y\sqrt y + z\sqrt z + 3\sqrt{xyz}}\right) = \frac{3(x\sqrt x + y\sqrt y + z\sqrt z)}{x\sqrt x + y\sqrt y + z\sqrt z + 3\sqrt{xyz}}$$
Furthermore, $$\frac{1}{x^2 + 1} = \frac{1}{x^2 + xy + yz + zx} = \frac{1}{(x + y)(z + x)} \ge \frac{4}{(z + 2x + y)^2}$$
$$\ge \frac{8}{4x^2 + (y + z)^2} = \frac{2}{x^2}\left[1 - \frac{(y + z)^2}{4x^2 + (y + z)^2}\right] = \frac{2}{x^2}\left[1 - \frac{(y + z)^2}{4(x^2 + yz)}\right]$$
$$\implies \sum_{cyc}\frac{1}{x^2 + 1} \ge \sum_{cyc}\frac{2}{x^2}\left[1 - \frac{(y + z)^2}{4(x^2 + yz)}\right]$$
$$\ge \frac{18}{x^2 + y^2 + z^2} - \frac{1}{2}\sum_{cyc}x^2\left[\frac{1}{y^2(y^2 + zx)} + \frac{1}{z^2(z^2 + xy)}\right]$$
And I'm stuck.
Answer: We need to prove that:
$$\sum_{cyc}\frac{1}{x^2+1}\geq\frac{2}{3}\left(\sum_{cyc}\frac{x}{\sqrt{x^2+1}}\right)^3$$ or
$$\sum_{cyc}xy\sum_{cyc}\frac{1}{(x+y)(x+z)}\geq\frac{2}{3}\left(\sum_{cyc}\frac{x}{\sqrt{(x+y)(x+z)}}\right)^3.$$
Now, by C-S
$$\sum_{cyc}xy\sum_{cyc}\frac{1}{(x+y)(x+z)}=\frac{\sum\limits_{cyc}x(y+z)\sum\limits_{cyc}x}{\prod\limits_{cyc}(x+y)}\geq$$
$$\geq\frac{\left(\sum\limits_{cyc}x\sqrt{y+z}\right)^2}{\prod\limits_{cyc}(x+y)}=\left(\sum_{cyc}\frac{x}{\sqrt{(x+y)(x+z)}}\right)^2.$$
Id est, it's enough to prove that
$$\sum_{cyc}\frac{x}{\sqrt{(x+y)(x+z)}}\leq\frac{3}{2},$$
which is true by AM-GM:
$$\sum_{cyc}\frac{x}{\sqrt{(x+y)(x+z)}}=\sum_{cyc}\left(\sqrt{\frac{x}{x+y}}\cdot\sqrt{\frac{x}{x+z}}\right)\leq$$
$$\leq\frac{1}{2}\sum_{cyc}\left(\frac{x}{x+y}+\frac{x}{x+z}\right)=\frac{1}{2}\sum_{cyc}\left(\frac{x}{x+y}+\frac{y}{y+x}\right)=\frac{3}{2}.$$
Done!
Comment: Thanks for that. I mistyped the problem.


How light is a ping?

Question: Hopefully this question isn't too dumb.  I'm wondering how expensive (system resource, and bandwidth wise) a ping is.  If I have a small embedded linux device that has very limited ram, cpu, and bandwidth would it be bad to start a ping command and have it continue running for days?
I'm trying to figure out how to minimize the impact.  Looking at the options for ping it looks like I can specify the size.  Should I do that to make it smaller?  Is there anything else I can do to make it smaller?  I need it to run but I don't want it to have any negative impact on ram, cpu, or bandwidth (performance in any way).
In my testing I haven't observed any difference in ram or cpu with it running.  I haven't tested network speed very thoroughly but I haven't noticed anything there either.  Thoughts?
Comment: `ping command and have it continue running for days?` - Adjust the interval.  Do you really need a response every second?  Will every 15, or 60 seconds be adequate?   What are you trying to test with constant ping?  Would something like smokeping set to every 5 minutes give you better information?  It sends a burst of 20 packets and graphs the delay of each reply.
Comment: That's a good idea.  I might be able to have it only ping every 5 seconds or so.  In this case smokeping would not help. Most of the time I'm expecting to not receive a response from the ping.  In the event that I do I will be running a script.
Comment: Are you trying to monitor network stability or performance? Instead of just a ping, try `mtr` and adjust the interval of its pings (also has the option to choose UDP datagrams or ICMP packets): http://www.bitwizard.nl/mtr/
Comment: Actually, I'm not using it to monitor either.  I'm using it to trigger an action on the embedded device.  Essentially, I have a bunch of embedded devices that will be pinging a server.  I will use iptable rules on the server to respond to the ping requests or not.  If a the device receives a response it will run a script.  If the ping timesout it will not run the script.  So, the point is to provide a way of triggering a script on the device in close to real time in a way that is managed from the server.
Answer: The cost difference between processing a ping hardly varies at all across byte sizes.  The bulk of the cost of responding to one is in the routing table lookup when the reply is sent, and in the various socket logic (which varies based on OS) used to listen for and recieve a packet.  This is also negligible in virtually all cases.
The reason for the adjustable size of ICMP echo (ping) packets is so that you can determine network characteristics based on packet size (eg. to find the MTU).
Because most of the cost is in the protocol stack in the kernel, and the NIC operation and network drivers, there is probably plenty a developer or hardware designer could do to make it (and network operation in general) more efficient, but in the general case as a system administrator these present a fixed and negligible load.
Tangentially, many people like to throttle ICMP requests at firewalls to prevent a ping-based DoS attack (which is one of the least effective DoS attacks available).

How light is a ping?