New twist on a Putnam problem

Question: A recent Putnam problem:

Let $f$ be a real-valued function on the plane such that for every square $ABCD$ in the plane, $f(A)+f(B)+f(C)+f(D)=0$. Does it follow that $f$ is identically zero?

The answer is yes. Without loss of generality consider only the origin. We have
$$f(1,1)+f(-1,1)+f(1,-1)+f(-1,-1)\tag{a}$$
$$f(0,0)+f(0,1)+f(1,0)+f(1,1)\tag{b}$$
$$f(0,0)+f(0,1)+f(-1,0)+f(-1,1)\tag{c}$$
$$f(0,0)+f(0,-1)+f(1,0)+f(1,-1)\tag{d}$$
$$f(0,0)+f(0,-1)+f(-1,0)+f(-1,-1)\tag{e}$$
$$f(1,0)+f(-1,0)+f(0,-1)+f(0,1)\tag{f}$$
are all zero. Then $f(0,0)=[\rm(b)+(c)+(d)+(e)-(a)-2(f)]/4=0$. A similar argument works when we replace the condition in the problem with triangles $\triangle ABC$. I have pictured both ideas as so-called "proof without words" below:

What happens when we replace the codomain of $f$ with an abelian group of exponent dividing $4$ or $6$ respectively? Do there then exist non-constant maps with these properties?
Comment: The solution (to the Putnam problem) at math.hawaii.edu/home/pdf/putnam/Putnam_2009.pdf says "Problem 1 of the 1996 Romanian IMO team selection exam asks the same question with squares replaced by regular polygons of any (fixed) number of vertices."
Comment: Aside from constant maps?
Comment: @ShaunAult Erm, right.
Answer: The case of the abelian group $Z_2$ came up before on this forum.
Is there a non-constant function $f:\mathbb{R}^2 \to \mathbb{Z}/2\mathbb{Z}$ that sums to 0 on corners of squares?
I gave an answer to that, which after some simplification, and using some of the sets of the OP, goes as follows: Let $f$ be the function from the plane into $Z_2$, and use the relations:
[a] $f(0,0)+f(1,0)+f(1,1)+f(0,1)=0,$
[b] $f(0,0)+f(-1,0)+f(-1,-1)+f(0,-1)=0,$
[c] $f(1,0)+f(0,1)+f(-1,0)+f(0,-1)=0.$
Adding these in $Z_2$, everything cancels exept $f(1,1)+f(-1,-1).$ This means (since we're in $Z_2$) that the values of $f$ at diagonally opposite points of any square are the same, from which by rescaling the square and moving it, we can see the map $f$ is constant.
EDIT: Extension to the case of the group $Z_4$. Suppose $f$ maps the plane to $Z_4$ and the sum of $f$ on corners of every square is $0$. By reducing mod 2 and using the above result that maps into $Z_2$ with this corner-sum property are constant, we can deduce that in the case of this map $f$ to $Z_4$ there are only two possible cases left: The "1,3" case, in which the value of $f$ at each point is in $\{1,3\}$ and the "2,4" case in which the value of $f$ at each point is in $\{2,4\}$.
Now in either of these cases, the values at the vertices of any square are either all the same or else there are two of each value. For example in the 1,3 case we cannot have three 1's and one 3 at the corners of any square, since $1+1+1+3=2 \mod 4.$ The same happens with three 3's and one 1, or with three 2's and a 4, or with three 4's and a 2.
To simplify the rest we'll use the symbols $a,b$ to mean the two distinct elements in either the 1,3 case or the 2,4 case. So by what has been said, every square must have its corners labelled either all $a$, or all $b$, or else two $a$ and two $b$ on the corners.
Our claim now is that there is no way to label the nine points of the "double square" in this way, in such a way that the diagonally opposite corners of the "big square" end up with different labels from $a,b$. By the "double square" we mean the collection of nine points $(x,y)$ with each of $x,y$ taken from the set $\{-1,0,1\}$ (as described in the OP and in the above proof). There are then in an obvious way a "big square", four "small squares" we can call lower right, lower left, etc., and a "diamond" (also a square) formed by the midpoints of the sides of the big square.
Now suppose it is possible to put different values at diagonally opposite points of the big square. Without loss, assume the lower right is given the value $a$ and the upper left the value $b$. Then the other two points of the big square are also $a,b$ (not both $a$ or both $b$); again without loss suppose the lower left of the big square is $a$ while the upper right of the big square is $b$.
Now the center of the square must be labelled either $a$ or $b$, and we may suppose it is labelled $a$ (if it were $b$ we could rotate the square 180 degrees and interchange the letters $a,b$).
Now there are two possiblilties for the midpoint of the right side of the big square.
case 1: we put the value $a$ at this right side midpoint. Then we already have three $a$ labels on the lower right square, so are forced to place another $a$ at the fourth point of this square, i.e. at the midpoint of the bottom side of the big square. Then easily the bottom left square ends up labelled all with $a$. Now looking at the top two smaller squares, each now has three of its vertices chosen, with two $a$ and one $b$ for the choices so far. This means that the midpoint of the top side of the large square must be given the value $b$, and finally our contradiction, since now the diamond square has three points labelled $a$ and one point (top of diamond) labelled $b$. As noted there cannot be three $a$ and one $b$ at the corners of any square.
case 2: we put the value $b$ at the right side midpoint. This time we are forced to place a $b$ at the midpoint of the bottom side of the big square, then another $b$ at the midpoint of the left side of the big square, and now the two smaller upper squares require there to be an $a$ at the midpoint of the top side of the large square. Again we reach a contradiction, this time because the diamond square is now labelled with three $b$ and one $a$ corner.
To complete the argument for the group $Z_4$: From what we've shown, every square must have the same value mod 4 at any two of its diametrically opposite vertices. Then by expanding and moving such squares we can position one with its opposite corners at any two points $P,Q$ in the plane, making the map constant in $Z_4$.
The question regarding other abelian groups of exponent dividing 4 may be approachable in this way; if so I don't see it yet.
ADDED: Thanks to Gerry Myerson for pointing out that Mercio's solution to the $Z_2$ problem shows how to extend to any finite abelian group $G$. A good answer to look at for anyone interested! (same reference, "Is there a nonconstant...")
Comment: mercio's solution to that earlier appearance of the problem claimed to work for maps into an arbitrary finite abelian group. What say you?
Comment: Gerry: Mercio's solution looks right to me, and makes the above $Z_4$ solution unnecessary. It also saves me work, since I was just going at $Z_8, Z_{16}$, etc. and thinking about direct products etc. in an attempt to generalize! +1 on comment.
Answer: As noted in several other answers, the purely discrete version of the problem (with ${\mathbb Z}^2$ in place of ${\mathbb R}^2$) has a few solutions, and the possibility of rescaling in $\mathbb R$ forces any solution in this case. Here is some more information on the discrete problem.
By considering first smaller families of squares or triangles, one can avoid the torsion problem and obtain nice characterizations of the solutions. Then, a final small adjustment is needed to obtain a full charcaterization to the solution of the initial problem.
 Theorem  Let $G$ be an arbitrary abelian group, and let $V$ be the module of all maps$f: {\mathbb Z}^2 \to G$ whose sums are zero on all the squares of the form $(x,y)+[0,1]^2$ and $\lbrace (x,y), (x+1,y+1), (x,y+2), (x-1,y+1)\rbrace$. Then the ${\mathbb Z}$-linear map
$$
\phi : V \to G^4,\ \  f \mapsto (f(1,1),f(0,0),f(1,0),f(2,0))
$$
is an isomorphism. Indeed, for $(a,b,c,d)\in G^4$ the unique $f$ such that $\phi(f)=(a,b,c,d)$, is given by the following rule : for integers $x,y,i,j$,
$$
f(x,y)=
\begin{cases}
-ya & -(i+j-1) b&  &+(i-j)d & \text{if }\  x=2i,& y=2j  \\
-ya & +(i-j-1) b& -c& -(i+j)d & \text{if}\ x=2i,& y=2j+1\\
ya & -(i-j)b& c & +(i+j)d & \text{if}\  x=2i+1,& y=2j \\
ya & +(i+j)b& & -(i-j)d & \text{if}\  x=2i+1,& y=2j+1
 \\
\end{cases}\tag{*}
$$
 Corollary  Let $G$ be an arbitrary abelian group, and let $f: {\mathbb Z}^2 \to G$ be a map. Then the sum of $f$ is zero over all the rectangles of ${\mathbb Z}^2$ iff $f$ satisfies (*) above for some four tuple $(a,b,c,d)$ with
$4a=4b=4c=4d=0$ in $G$.
 Proof of the theorem  :

New twist on a Putnam problem


Como inserir um contador de tentativas dentro de uma exceção (except ValueError) do Python 3

Question: Olá. Eu sou iniciante em programação e venho tentando desenvolver por conta própria programas que aprendi em exercícios de livros de programação. Eu fiz minha versão do clássico "Guess the number", onde o usuário tem (n) tentativas para acertar um número gerado aleatoriamente pelo programa. Meu problema está no contador de tentativas. O contador que coloquei (5x) só abrange no caso de usuário acertar digitando somente números, ou errar as 5 tentativas. Porém, há um validador de entrada. Se o usuário digitar uma letra, o validador entra em um loop e só sai se ele digitar um número, e dentro desse loop eu não consegui inserir um contador. Minha pergunta é: Como eu posso contar os caracteres inválidos como número de tentativas?
Variáveis usadas:
x = contador de tentativas
t = número de tentativas final
n = número digitado pelo usuário
r = número aleatório gerado pelo módulo random

Código do programa:
    #!/usr/bin/python3
    #coding=utf-8
    #Filename=num.py

    # Importa os módulos necessários
    import random
    import time

    # Define uma linha vazia
    def vazio():
        print()

    # Define uma linha pontilhada
    def linhas():
        print('----------------------------------------------')

    # Define três pontinhos
    def pontinhos():
        print('.')
        time.sleep(0.3)
        print('.')
        time.sleep(0.3)
        print('.')
        time.sleep(0.3)

    # Define o título
    def title():
        print('##############################################')
        time.sleep(0.5)
        print('#################### NUM #####################')
        time.sleep(0.5)
        print('##############################################')
        time.sleep(1.5)
        pontinhos()

    # Define a introdução
    def intro():
        nome = input('\nQual é o seu nome? ')
        vazio()
        linhas()
        time.sleep(1)
        print('\nOlá %s!\n' % nome)
        linhas()
        time.sleep(1)
        print('\nEu estou pensando em um número...\n')
        linhas()
        time.sleep(1)
        print('\nEntre 1 e 100...\n')
        linhas()
        time.sleep(1)
        print('\nAdivinhe qual...\n')
        linhas()
        time.sleep(2)

    # Define o main loop
    def main():
    """ Adivinhe o número aleatório de 1 a 100  com no máximo 5 tentativas """

        title()
        intro()
        x = 0
        n = 0
        t = 0
        r = random.randint(1,100)
        while True:
            # Se errar ou acertar...tente novamente ou saia do jogo...
            if x == 5 or n == r:
                # Se errar
                if x == 5 and n != r:
                    print('\n5 tentativas não foram suficientes! :(\n')
                    linhas()
                # Errando ou acertando...
                x = 0
                t = 0
                r = random.randint(1,100)
                s = input('\n[S] para sair: ')
                linhas()
                vazio()
                if s == 'S' or s == 's':
                    pontinhos()
                    print('Agradeço por jogar NUM!')
                    break
                else:
                    title()
            # Verifica se números são digitados ao invés de letras...
            while True:
                try:
                    n = int(input('\nDigite um valor: '))
                    vazio()
                    pontinhos()
                    linhas()
                    break
                except ValueError:  # Se digitar letra ao invés de n....
                    linhas()
                    print('\nIsso não é um número!\n')
                    linhas()
            # Se acertar
            if n == r:
                print('\nVocê acertou em %d tentativas! :)\n' % t)
                linhas()
                time.sleep(1)
            # Se o número digitado for menor que a resposta...
            elif n > r:
                print('\nO número é menor que isso!\n')
                linhas()
                time.sleep(1)
            # Se o número digitado for maior que a resposta...
            elif n < r:
                print('\nO número é maior que isso!\n')
                linhas()
                time.sleep(1)
            x = x + 1
            t = t + 1

    # Chama o main loop
    main()

Answer: Olá, parabéns pela iniciativa na programação. A sua versão do código está bem organizada e comentada. Isso é uma boa prática de programação.
Como você está iniciando e está criando sua própria versão do problema, alterei o seu código minimamente. Com o tempo você vai ver aonde pode melhor e otimizar seus programas.
Para que os inputs errados do usuário contem como tentativas, adicionei a variável maxTentativas que vai se tornar verdadeira ao atingir o máximo de tentativas permitidas e irá impedir que o código entre na parte de testar o número depois do while. Removi sua variável x e deixei somente a t, pois assim não há mais a necessidade da primeira.
A variável é inicializada antes do primeiro while:
n = 0
t = 0
maxTentativas = False
r = random.randint(1,100)

E também quando entra em nova iteração o jogo. Aqui a sua variável x foi substituída por t.
if t >= 5 or n == r:
    # Se errar
    if t >= 5 and n != r:
        print('\n5 tentativas não foram suficientes! :(\n')
        linhas()
# Errando ou acertando...
t = 0
maxTentativas = False
r = random.randint(1,100)
s = input('\n[S] para sair: ')

O seu contador de tentativas é adicionado no except e, logo após incrementá-lo, há um teste para ver se atingiu o máximo de tentativas. Caso verdadeiro ele atualiza a variável maxTentativas sai do while. Depois, se o jogador atingiu o máximo de tentativas, não há a necessidade de testar se ele acertou o número ou não. Assim, o if após o while impede que esses testes sejam realizados.
# Verifica se números são digitados ao invés de letras...
while True:
    try:
        n = int(input('\nDigite um valor: '))
        vazio()
        pontinhos()
        linhas()
        break
    except ValueError:  # Se digitar letra ao invés de n....
        linhas()
        print('\nIsso não é um número!\n')
        linhas()
        t = t + 1
        if t >= 5:
            maxTentativas = True
            break

if not maxTentativas:
    # Se acertar
    if n == r:
        print('\nVocê acertou em %d tentativas! :)\n' % t)
        linhas()
        time.sleep(1)
    # Se o número digitado for menor que a resposta...
    elif n > r:
        print('\nO número é menor que isso!\n')
        linhas()
        time.sleep(1)
    # Se o número digitado for maior que a resposta...
    elif n < r:
        print('\nO número é maior que isso!\n')
        linhas()
        time.sleep(1)
    t = t + 1


Angular2 Exception: TypeError el.createShadowRoot is not a function (Safari/Edge)

Question: I have an angular2 app that works great in Chrome and Firefox, but in Safari I get this error:

TypeError el.createShadowRoot is not a function

And similarly in Edge:

Object doesn't support property or method 'createShadowRoot'
  at BrowserDomAdapter.prototype.createShadowRoot (http://localhost:5000/lib/angular2/bundles/angular2.dev.js:22893:7)

More from Edge:

Is there some shim or polymer I am missing?
Comment: could you try [this link](https://docs.webplatform.org/wiki/concepts/experimental_features) for updating experimental flag in safari
Comment: According to MDN [Element.createShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/Element/createShadowRoot) is not supported in either IE nor Safari. Besides that it has been deprecated.
Comment: @EricMartinez thanks for the reference.  How do I tell Angular2 not to use createShadowRoot?
Answer: createShadowRoot() should only be called if you use ViewEncapsulation.Native.
Either use ViewEncapsulation.Emulated or ensure polyfills are loaded (I can't guide you how, because I don't use the TS toolchain, only Dart)
Comment: Many thanks!  Turns out I was using snippets in VS Code and inadvertently was using ViewEncapsulation.Native
Comment: excellent answer, is it documented in the angular docs somewhere? or which polyfill(s) we should use for it?
Comment: I lost track of the web components support status in various browsers. Last year the web_components polyfill with full shadow DOM (not shady DOM) was required except for Chrome. https://angular.io/docs/ts/latest/guide/browser-support.html doesn't mention it. I think native is officially only supported for browsers with native support, which makes some sense because Angular has his own emulation which is much faster. The disadvantage is that it doesn't allow to choose between native and emulated depending on browser support.
Comment: I already added the polyfill and still facing same issue, please see this https://stackblitz.com/edit/angular-webcomponent-polyfill
Comment: See my previous comment. ShadowDom changed substantially. I don't think you still neec polyfills, but you need recent docs about how to create custom elements.
Answer: I faced the same issue recently, got this error on Firefox
el.createShadowRoot is not a function
From the documentation, I learned that createShawdowRoot is deprecated, replaced by attachShadow()
https://developer.mozilla.org/en-US/docs/Web/API/Element/createShadowRoot
Looking at the encapsulation of all the components in my Angular project, one component stood out and was using the ViewEncapsulation.Native , which was also deprecated so I replaced it by ViewEncapsulation.ShadowDom as recommended, check
https://angular.io/api/core/Component#encapsulation
and that cured it for me.
So I suppose that the Native encapsulation compiles to createShawdowRoot no longer supported by Firefox.
Comment: Thank you this was also the issue in my application.
Answer: if you are facing this issue in simple HTML file then below line of code can be helpful
element.attachShadow({mode: 'open'})


Jump out in Tkinter loop

Question: I am working on a Tkinter doesn't jump out problem.
There is what I am running:
from Tkinter import *
import ttk

def plus(*args):
    value = float(a.get())
    value1 = float(b.get())
    result.set(value + value1)
    print "the result is " + str(result.get())

root = Tk()
root.title("Plus them")

mainframe = ttk.Frame(root, padding="10 10 10 10")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

a = StringVar()
b = StringVar()
result = StringVar()

feet_entry = ttk.Entry(mainframe, width=5, textvariable=a)
feet_entry.grid(column=2, row=1, sticky=(W, E))

feet_entry1 = ttk.Entry(mainframe, width=5, textvariable=b)
feet_entry1.grid(column=5, row=1, sticky=(W, E))

ttk.Label(mainframe, text="the result is").grid(column=3, row=2, sticky=W)
ttk.Label(mainframe, textvariable = result).grid(column=5, row=2, sticky=(W, E))

ttk.Button(mainframe, text="Plus", command=plus).grid(column=3, row=3, sticky=W)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)
    feet_entry.focus()
    root.bind('<Return>', plus)
    root.mainloop()

When it runs, it seems fine. But it doesn't "jump out" no matter how many times I click the "Plus", until I input new values for calculation and it still waiting for new entry.
How can I adjust to have it calculate only for once? Thanks.
Comment: Dont understand what you want to achieve. What is the purpose of this for loop `for child in mainframe.winfo_children()`?
Answer: To make your window execute only once and have plus button closing the window do as follow:
from Tkinter import *
import ttk

def plus(*args):
    value = float(a.get())
    value1 = float(b.get())
    result.set(value + value1)
    print "the result is " + str(result.get())
    root.destroy()             ####### look here !!!#######

root = Tk()

root.title("Plus them")

mainframe = ttk.Frame(root, padding="10 10 10 10")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

a = StringVar()
b = StringVar()
result = StringVar()

feet_entry = ttk.Entry(mainframe, width=5, textvariable=a)
feet_entry.grid(column=2, row=1, sticky=(W, E))

feet_entry1 = ttk.Entry(mainframe, width=5, textvariable=b)
feet_entry1.grid(column=5, row=1, sticky=(W, E))

ttk.Label(mainframe, text="the result is").grid(column=3, row=2, sticky=W)
ttk.Label(mainframe, textvariable = result).grid(column=5, row=2, sticky=(W, E))

ttk.Button(mainframe, text="Plus", command=plus).grid(column=3, row=3, sticky=W)

# for child in mainframe.winfo_children():
#     child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', plus)

root.mainloop()

So here, in your plus callbeck you need to call root.destroy(). Also this loop for child in mainframe.winfo_children() does not make sense in my option, and its not needed. So I removed it in the example.
Comment: marvelous! thanks. and what if I want to keep the GUI running/open after execute the script, instead of closing it once run? I mean I can use the same small window for different calculations and no need to open it each time. is it possible?
Comment: You cant. `root.mainloop()` is an infinite loop. And until you close it, nothing past the `root.mainloop()` is going to be executed. However, if you want to keep your window open, and calculate many sums, just comment out `root.destroy()` in the plus callback.
Comment: thanks again. by the way, I dream to make a small program so likely I need to package above to an .exe file? Could you please point me the direction as well? many thanks.
Comment: Cant help with exe unfortunately. I work on Linux, and no exe files there. Have not much experience with python on windows :-(

Jump out in Tkinter loop


Get an email notification when my cron fails with non zero exit code - Crontab

Question: I have scheduled a script take_backup.sh in crontab like so
00 19 * * * bash /home/test/take_backup.sh > /home/test/backup.log 2>&1 || mail -s "Backup failed, check attached logs" email@example.com < /home/test/backup.log

The requirement is to only send an email notification with the logs attached when the cron fails with a non zero exit code. I have set up logs and exit codes in the script to provide more details in backup.log. However, when this cron fails, I do not receive any notification.
Where am I going wrong?
Answer: if the "mail" part succeeds then the cron job has succeeded (and thus the code is zero)
 00 19 * * * bash /home/test/take_backup.sh > /home/test/backup.log 2>&1 || ( mail -s "Backup failed, check attached logs" firstname.lastname@example.com < /home/test/backup.log && false )

Comment: I require the notification when the cron fails though, how do I change the command for that?


Texture of Beethoven's Symphony Number 8 movement 1

Question: I have been struggling to come up with a conclusion if the first movement of Beethoven's Symphony No. 8 has a polyphonic texture. But I cannot find a valid reason. Does anyone have any solid ideas of what type of texture it has and why?
Comment: It would be helpful to know where your uncertainty lay. That is, what in the score suggested to you homophony, and what suggested polyphony? Or, better, it sounds like you were trying to support a thesis that the movement is polyphonic. It might help to know more about the origin of that thesis.
Answer: Differentiating polyphony and homophony in general
The core idea behind polyphony is the presence of two or more melodies that are independent of each other but which correspond in harmonically pleasing ways.
Homophony, by contrast, has parts that tend to move in sync with each other.
One can think of polyphony as being composed "horizontally" (that is, primarily melodically); whereas, homophony emphasizes the "vertical" (this is, primarily chordal). Any (part of a) piece could have elements of both, so one has to decide which plays the predominant role in developing the overall sound.
Is Beethoven Symphony #8, Movement 1 polyphonic or homophonic?
I find little question that it is homophonic, seeing little to no evidence of polyphony. Looking through the score, the parts tend to move in lock step, and I don't see anything that looks like two or more independent melodic parts.


Designated initializers for variable arguments

Question: I'm writing a text-based Minecraft bot, mainly to (try to) annoy some players/admins and check out the internals of the Minecraft protocol.
Anyway, I'm still in the design phase and writing functions for sending and receiving packets. The declarations look like this right now:
int send_packet(int sock, con_state_t state, send_packet_t ptype, ...);
int recv_packet(int sock, con_state_t state, recv_packet_t ptype, ...);

(I'm planning on adding typedefs for error and socket types, both ints.)
So far, so good. I know variable arguments are type-unsafe but enable me to write better code as opposed to structs. I can write code such as this (the send_packet function):
/* BTW: I had to decide between structs passed as void* to imitate
 * inheritance and variable-length arguments.
 * Both are equally type-unsafe but variable-length arguments offer the
 * significant advantage of portably iterating over them. Therefore, I can
 * implement a packet-independent packet sending function without remarkable
 * struggle or packet-specific functions, which would be QUITE a hassle.
 * A drawback is that for every argument from the variable-length arguments,
 * data has to be pushed on the stack, so the stack frame grows linearly
 * to the argument count. Not so with a struct; only the address of it had to
 * be passed.
 * (Is variable-length argument the right term at all? I deduced it from
 * variable-length array...)
 */
int send_packet(int sock, send_packet_t ptype, ...) {
    va_list fields;
    uint8_t data[0];    /* TODO: replace 0 by something like PACK_MAX_LEN
                                          * or so! */

    /* TODO: as mentioned above, data should actually have the size of
     * PACK_MAX_LEN. because this might be very big, you could use some
     * dynamic memory allocation mechanism! same goes for string_t, chat_t,
     * and all similar data types. */

    uint8_t* data_it = data;

    /* TODO: ADD PREPENDING OF PACKET ID AND PACKET LENGTH HERE! */
    /* TODO: this function isn't finished. add some code, man! resuming the
     * above comment. */

    /* TODO: add support for legacy server list ping! (packet id = 0xfe) */

    /* TODO: for more complex data types: add code to convert from
     * simple data types to these complex ones like fix_varint_t to
     * varint_t! */

    va_start(fields, ptype);
    for (size_t i = 0; i < sp_structs[ptype].len; ++i) {
        /* Jeez, I hope my code is understandable... */
        switch (sp_structs[ptype].fields[i]) {
        case map_boolean:
            cpy_data_sp(boolean_t);
            break;
        case map_byte:
            cpy_data_sp(byte_t);
            break;
        case map_ubyte:
            cpy_data_sp(ubyte_t);
            break;
        case map_short:
            cpy_data_sp(short_t);
            break;
        case map_ushort:
            cpy_data_sp(ushort_t);
            break;
        case map_int:
            cpy_data_sp(int_t);
            break;
        case map_long:
            cpy_data_sp(long_t);
            break;
        case map_chat:
            cpy_data_sp(chat_t);
            break;
        case map_string:
            cpy_data_sp(string_t);
            break;
        case map_varint:
            /* TODO: maybe write a macro to generalize wr_varint
             * and wr_varlong. */

            fix_varint_t fix = va_arg(fields, fix_varint_t);
            data_it += wr_varint(data_it, fix);
            break;
        case map_varlong:
            fix_varlong_t fix = va_arg(fields, fix_varlong_t);
            data_it += wr_varlong(data_it, fix);
            break;
        /*case map_chunk:
            cpy_data_sp(chunk_t);
            break;*/
        }
    }

/*
    if (sock_send(sock, data, packet_len) == -1) {
        return -1;
    }
*/
    va_end(packet);

    return 0;
}

I just want to show you that, so you get why variable arguments are better here.
With structs, the function prototype would look as follows:
 int send_packet(int sock, con_state_t state, send_packet_t ptype, void* pack);

pack points to the struct here. Now we could deduce the packet type with ptype but we cannot iterate conveniently over the fields as mentioned in the first comment in the above code.
Everyone using that function has to know the exact order of the arguments or undefined behavior might occur. structs are nice here because of designated initializers, which enable order-independent member initialization.
Can you think of some way to emulate that for variable arguments?
Maybe some va_list magic? It should be strictly-conforming, though.
Note: using C++ already came to my mind, which would solve all my problems, but I want to do this in nice, standard C99 with some C11.
Answer: You could use key/value-pairs instead of positioned values:
 int func(int argc, ...) {

 }

and call it like
func(3,
         P_NAME,    "John",
         P_SURNAME, "Myers",
         P_AGE,     10
    );

or use a 0-value as terminator to avoid argc.
Comment: Nice idea! Only drawback is that the number of arguments passed is doubled and thus more data has to be passed. Do you have any code where this is actively used?
Comment: No, I haven't used this yet. The stack size needed for the parameters will be about double size, this is correct. But if you do not recurse with such functions (or code for platforms with very restricted resources), this is probably not noticable in practice.


Pass variables through AJAX callback and update MySQL database

Question: I have a form where the users submit a text. Here is the code:
$form['reason'] = array(
            '#type' => 'textfield',
            '#title' => '',
            '#size' => '200',
            '#attributes' =>array('placeholder' => t('*Reason')),
            '#prefix' => '
'
          );

    $form['newsletter_unsubscribe_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#attributes'=> array(
            'class' => ['btn', 'btn-primary']
        ),
        '#ajax' => array(
            'callback' => 'newsletter_unsubscribe_quiz_submit_driven_callback_share',
            'method' => 'replace',
            'effect' => 'fade',
        ),
        '#prefix' => '
',
        '#suffix' => '

');

    return $form;

I managed to get the input of the user on a variable using $_values = $form_state['values'];
Also, I have some other variables to read from the current path and get some values.
    $_path = $_SERVER['HTTP_HOST'] . request_uri();

    preg_match('~id=(.*?)&~', $_path, $id);

    $first = $id[1];
    $second = substr($_path, -5);

where the first is the user id and the second is another variable that is unique per user.
My only problem is that I can't pass the $first and $second variables through the callback, and have them along with $reason $_reason = filter_xss($_values['reason']);
So, in my callback I want to be able to get the variables $first,$second with the $reason I already have. Now I have the $_path variables above my form, in the same function.
Then I want to perform an update query on MySQL, something like
UPDATE users SET reason=$reason
WHERE first=$first AND second=$second

where the column users has only the columns first,second and reason . Is this possible? Thanks in advance!
EDIT
I actually managed to do the first part and get the variables. I created two form inputs and I give them default values, the two variables I want to get, and I will hide them afterwards.
I still haven't figured out how to update MySQL though, so all answers are welcome!
Answer: I actually managed to do it! For anyone that may have a similar problem this is what I did.
First of all, I took the url parameters using parse_url and did the following
$parts =  parse_url($_path);
parse_str($parts['query'], $query);
$first = $query['first'];
$second = $query['second'];

,then put those variables as form default values, that I will hide using css:
$form['user_id'] = array (
         '#type' => 'textfield',
         '#title' => t('User id'),
         '#description' => t('user id'),
         '#default_value' => $first,
);

Then, on my callback function I take those variables, for example:
$_first = filter_xss($_values['first']);

and then I used db_update:
$num_updated = db_update('unsubscribed_users')
    ->fields(array(
        'reason' => $_reason,
      ))
    ->condition('first', $_first , '=')
    ->condition('second', $_second , '=')
    ->execute();


Question about discrete topology of $\mathbb{R}$

Question: If we let $\tau$ be a topology of the $\mathbb{R}$ s.t $\tau = \mathbb{P}(\mathbb{R})$, surely $\{1\} \in \tau$ and that is an open set if we define such to be an element of a topology. I'm not understanding how this is consistent with other definitions of open set such as

A set $U \subset  R$ is called open, if for each $x \in U$ there exists an $\epsilon > 0$ such that the interval $(x - \epsilon, x +  \epsilon)$ is contained in $U$.

In this case, there is no $\epsilon > 0$ s.t $(1 - \epsilon, 1 + \epsilon) \in [1]$, so how can it be an open set? Does $\{1\} \neq [1]$? If it does, how is $[1]$ an open set if it's closed off by brackets?
Answer: Not all spaces are metric,  and thus have open sets characterized by epsilon balls. For instance the trivial topology:   $\{\emptyset,X\}$.
However discrete spaces are.
The discrete metric is $$d(x,y)=\begin {cases}1,\,x\ne y\\0,\,x=y\end {cases}$$.
Thus each point is open,  as $x=B(x,1)$, say.
Comment: The interval $(x-1,x+1)$ is NOT the same as the unit ball in the discrete metric.  The interval depends on the ordering, NOT on the metric.  The ball, on the other hand, very much does depend on the metric. Intervals only make sense when you have an ordered set, in which case $(x-1,x+1)=\{z\mid x-1<z<x+1\}$ which is very much NOT {x}.  You've confused one circumstance where the objects coincide with a circumstance where they do not.
Comment: @MSIS Yes.  Any time you put a metric on $\mathbb R$ that is not the standard metric, you get that there is an $x, r$ such that $B(x,r)\neq (x-r,x+r)$.  The two notions of balls and symmetric intervals like this ONLY coincide for the standard metric.
Comment: Hmm.  I see.  @Aaron. Thanks for the touch up.
Comment: @Aaron: Can you think of a case where the two don't coincide?
Comment: Thanks, Aaron. Is the order topology on the Real line equivalent to that generated by the standard metric d(x,y)=|x-y|?  I guess any relationship breaks down for higher dimensions,  as there's no " obvious" ordering in $\mathbb R^2$ or higher?
Answer: The second definition is for the standard topology of $\mathbb R$, not the discrete topology.  In the standard topology, the intervals form a "basis" for the topology.  If you have a basis $\mathcal B$, then a set $U$ is open if for every $x\in U$ we can find $V\in B$ such that $x\in V\subset U$.
In the discrete topology, one can take the set of all singletons to be a basis.  Then if $x\in U$, we can take $x\in \{x\}\subset U$.  Singletons are replacing intervals.
But again, this is two separate topologies, so the fact that they yield different open sets is what you would expect (unless the two topologies unexpectedly coincided, which they do not here).


Build VueJS storage plugin

Question: I need to create a plugin that would watch data of the component, and synchronize it with a kind of storage, such as localStorage - it does not matter.
When mounted orcreated this component will retrieve the storage values, and write them in data
Ultimately, I want the data from the interface did not disappear after reloading the page.
vuex-persist and like this plugins  working with data from Vuex, when I want to work with these components.
I began to create a plugin:
export default {
  install(Vue, options) {
    Vue.mixin({
      computed: {
        watchedComponents() {
          return this._data // Is there some other way to obtain the component data ???
        }
      },
      watch: {
        watchedComponents: {
          deep: true, // For watching nestead changes
          handler() {
            // At this point I start receive recursion errors.
          }
        }
      }
    })
  }
}

Share your vision solutions.
I would be grateful to any attention and assistance.
Comment: This question is not well suited for this plattform. Please try to ask specific questions  that allow for a concrete answer rather than asking for such broad implementation examples. Try to work as far as you can get - then ask when you are stuck.
Answer: You will love that this already exists.
Independed of whether you want to use it or build your own plugin, you can learn a lot from vuex-persis.

Build VueJS storage plugin


Dropping of connections with tcp_tw_recycle

Question: summary of the problem
we are having a setup wherein a lot(800 to 2400 per second) of incoming connections to a linux box and we have a NAT device between the client and server.
so there are so many TIME_WAIT sockets left in the system.
To overcome that we had set tcp_tw_recycle to 1, but that led to drop of in comming connections.
after browsing through the net we did find the references for why the dropping of frames with tcp_tw_recycle and NAT device happens.
resolution tried
we then tried by setting tcp_tw_reuse to 1 it worked fine without any issues with the same setup and configuration.
But the documentation says that tcp_tw_recycle and tcp_tw_reuse should not be used when the    Connections that go through TCP state aware nodes, such as firewalls, NAT devices or load balancers may see dropped frames. The more connections there are, the more likely you will see this issue.
Queries

can tcp_tw_reuse be used in this type of scenarios?
if not, which part of the linux code is preventing tcp_tw_reuse being used for such scenario?
generally what is the difference between tcp_tw_recycle and tcp_tw_reuse?
Answer: By default, when both tcp_tw_reuse and tcp_tw_recycle are disabled, the kernel will make sure that sockets in TIME_WAIT state will remain in that state long enough -- long enough to be sure that packets belonging to future connections will not be mistaken for late packets of the old connection.
When you enable tcp_tw_reuse, sockets in TIME_WAIT state can be used before they expire, and the kernel will try to make sure that there is no collision regarding TCP sequence numbers. If you enable tcp_timestamps (a.k.a. PAWS, for Protection Against Wrapped Sequence Numbers), it will make sure that those collisions cannot happen. However, you need TCP timestamps to be enabled on both ends (at least, that's my understanding). See the definition of tcp_twsk_unique for the gory details.
When you enable tcp_tw_recycle, the kernel becomes much more aggressive, and will make assumptions on the timestamps used by remote hosts. It will track the last timestamp used by each remote host having a connection in TIME_WAIT state), and allow to re-use a socket if the timestamp has correctly increased. However, if the timestamp used by the host changes (i.e. warps back in time), the SYN packet will be silently dropped, and the connection won't establish (you will see an error similar to "connect timeout"). If you want to dive into kernel code, the definition of tcp_timewait_state_process might be a good starting point.
Now, timestamps should never go back in time; unless:

the host is rebooted (but then, by the time it comes back up, TIME_WAIT socket will probably have expired, so it will be a non issue);
the IP address is quickly reused by something else (TIME_WAIT connections will stay a bit, but other connections will probably be struck by TCP RST and that will free up some space);
network address translation (or a smarty-pants firewall) is involved in the middle of the connection.

In the latter case, you can have multiple hosts behind the same IP address, and therefore, different sequences of timestamps (or, said timestamps are randomized at each connection by the firewall). In that case, some hosts will be randomly unable to connect, because they are mapped to a port for which the TIME_WAIT bucket of the server has a newer timestamp. That's why the docs tell you that "NAT devices or load balancers may start drop frames because of the setting".
Some people recommend to leave tcp_tw_recycle alone, but enable tcp_tw_reuse and lower tcp_fin_timeout. I concur :-)
Comment: tcp_tw_recycle has been removed as of Linux 4.12.  This is because Linux now randomizes timestamps per connection and they do not monotonically increase.  If you're using Linux 4.12 with machines using tcp_tw_recycle and TCP timestamps are turned on you will see dropped connections.  You can of course disable it like so `echo 0 > /proc/sys/net/ipv4/tcp_timestamps` (temporarily, use sysctl.conf for permanent changes).  Details on 4.12 removing tcp_tw_recycle: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=4396e46187ca5070219b81773c4e65088dac50cc
Comment: Link at bottom broken
Comment: Great thanks. I encountered exactly this case --hosts behind NAT will randomly unable to connect, and disabling net.ipv4.timestamps just got everything fine(tcp_tw_recycle and tcp_tw_reuse are both enabled on both machine).
Comment: I believe, it should be `tcp_fin_timeout` and not `tcp_timewait_len`. But perhaps it changed in the kernel versions?


Formatar data vindo de variável com php

Question: Possuo a variável abaixo e quero formatar para o padrão brasileiro (20/01/2015) usando PHP.
$data = Sun Jan 10 00:00:00 CST 2016

Comment: Acho que [esta pergunta](http://pt.stackoverflow.com/questions/29694/converter-uma-data-para-o-nome-do-dia-da-semana) pode te ajudar... Em tem [esta outra](http://pt.stackoverflow.com/questions/48309/exibir-data-e-hora-em-php?rq=1) também.
Comment: `Sun Jan 10 00:00:00 CST 2016` é a saída da variável. Daí precisa ver como está declarada. No caso acho que tá usando [Datetime](http://php.net/manual/en/class.datetime.php). Pra exibir por exemplo a data do dia de hoje no formato que vc quer usando date, é fazer simplesmente `$data = date("d-m-Y");`
Comment: Na verdade ela sai como um array:
[x-inquiry-arrival] => Sun Jan 10 00:00:00 CST 2016
Comment: Posta a declaração da variável...
Comment: O php esta lendo essa variavel como um texto e não como data, como transformo isso em data, dai depois eu faço a formatação.
Answer: Converta essa data por para timestamp com strtotime() e depois pegue no formato desejado com date()
echo date('d/m/Y', strtotime('Sun Jan 10 00:00:00 CST 2016'));

Exemplo - 3v4l

Formatar data vindo de variável com php


How to use Prism plugins with Docusaurus v2?

Question: I would like to use diff-highlighting on my documentation – which requires installing a plugin
It is apparently not installed by default, but there is no documentation on how to add plugins (only languages, which doesn't work for plugins)
How can I install prisms plugins in Docusaurus v2?
Comment: Do you have the plugin you would like to install, or is that part of the question?
Comment: The closest would be to use the `swizzle` feature of Docusaurus to extract the theme/Highlight component and modify the code using prism-react-renderer. But I wasn't successful with that
Comment: The plugin is linked in the question: https://prismjs.com/plugins/diff-highlight/
Comment: for some reason I am unable to open the link from my mobile. Is there a packaged `json` for prism?
Comment: Is [this](https://github.com/ngx-prism/core#installation) what you need?
Comment: I am using docusaurus, a React app. The answer has to be compatible with prism-React-renderer and docusaurus
Comment: Did you not install docusauras using `npm`? it is essentially a `npm` component.
Comment: Yes, I am not sure what your argument is though.
Comment: my argument is. if you install prismjs via `npm` you can add the plugin to your docusaurus configuration.
Comment: prismjs is already installed via npm when using docusaurus, as a peer dependency.
Comment: So then just configure your docusarus config to include prism to it.. will see if I can find a link quick.
Comment: [this](https://v2.docusaurus.io/docs/using-plugins/) should help?
Comment: Prism is already included. That's not the problem. It's about how to make Docusaurus use Prism plugins. As for the link you gave, this is a different kind of plugins – it is docusaurus plugins not prism plugins
Comment: This seems to still be accurate in 2023
Answer: It works out of the box
```
diff
+ hey
- ho

hello
```

Comment: This question is not about `diff` but rather a variant that has both the diff highlight and the syntax highlight of your programing language. So for Dart, it would be `diff-dart`
Answer: The only supported way seems to be using swizzle on prism-include-languages, which is a pretty elegant solution.
This process is documented by Docusaurus.
Here is the relevant feature request.


Using an if else statement for two functions

Question: I'd really appreciate some help with this code.  I have two separate functions that both check a table in my database for data against an ID that is fetched from the page's URL.  On displaying the information, I want to use an IF ELSE statement to check if there are results from either of those functions, and if there are no results, post nothing, and if there are results, post the results.  At the moment I have this code:
    <?php
    if (getArtistsBySongId($id) == NULL AND getGroupsBySongId($id) == NULL) {

    } else {
        include 'songs/getsongcredits.php';
    }
    ?>

While the code works in displaying my data, it seems to be ignoring my IF statement, and just posting what's in the include.  Would someone be able to let me know the correct way to do this if else statement?
Thanks, Mitch
Answer: You should deny the if statement, don't use a redundant if/else.
if ((getArtistsBySongId($id) != NULL) OR (getGroupsBySongId($id) != NULL)) {
     include 'songs/getsongcredits.php';
}

Answer: You need proper enclosures:
<?php
if ( ( getArtistsBySongId( $id ) == NULL ) AND ( getGroupsBySongId( $id ) == NULL ) ) {
  // do something
} else {
    include 'songs/getsongcredits.php';
}
?>


Finiteness of the penalty of the thin-plate spline

Question: The original problem:
$$\min_{f}\sum_{i=1}^{N}\{y_i-f(x_i)\}^2 + \lambda J(f)$$
I write again the penalty of a thin-plate spline on $\mathrm{R}^2$:
$$J(f) = \int\int_{\mathrm{R^2}}\left[f_{x_1 x_1}''(x)^2 + 2f_{x_1 x_2}''(x)^2 + f_{x_2 x_2}''(x)^2\right]dx_1 dx_2$$
, and the form of solution:
$$f(x) = \beta_0 + \beta_1^T x + \sum_{j=1}^{N}\alpha_j h_j(x)$$
with $h_j$ are radial basis functions, $h_j(x)=||x-x_j||^2 \log||x - x_j||$.
I did read some documents talk about the thin-plate spline, they always attach the finite conditions of $J(f)$, that is: $\sum_j \alpha_j =0$ and $\sum_j \alpha_j x_j = 0$, but none of them show how derive these conditions. I spent about three hours to clarify them but not success :(.
Answer: After spending a lot of time, I finally found the solution of the problem. It's really simple than my imagine. On basically, it's a extension of linear constraints of the natural cubic spline and for any cubic splines $g$ then $\int_{-\infty}^{+\infty}g(x)''dx$ is infinite unless $g$ is a natural cubic spline.
Now, we fix $x_2$ and then using the natural cubic spline on $x_1$ we obtain the coefficient vector $\theta_1$. Because the solutions of natural cubic spline and the thin-plate spline are both unique. Thus, we can present $\alpha = A\theta_1$ with $A$ is a non-singular matrix. Applying linear constraints of the natural cubic spline on $\theta_1$ we can derive linear constraints of the thin-plate spline on $x_1$. Doing the same thing for $x_2$ we can derive the overall conditions of the thin-plate spline.


Type determination when indexing on non-array pointers & reading beyond the last element

Question: int main()
{
    auto foo = new int;
}

I understand that foo will be of type int*.
Since foo is a pointer you can index it with [].
Therefore foo[0] will be the same as *foo and be of type int.
What I'm having trouble with understanding is why foo[1] would be an int.
I know c++ doesn't care that you go 'out of bounds' and undefined behavior is expected, but why would foo[1] also be of type int?
Does it just takes the next 4 bytes and assumes it is an int because foo is an int*?
Comment: `foo` can be seen as a pointer to the first element of a one-element array. It's similar to e.g. `int array[1]; int* foo = &array[0];`. However, C++ doesn't have any kinds of bounds checking for array or pointers. Therefore you can easily access elements out of bounds, like `foo[1]`. This will lead to *undefined behavior*. But even when going out of bounds, the "base type" will still be the same, as each element in the "array" is the same type.
Comment: If `foo` is declared as a pointer type (e.g. `int*`), then the expression `foo[x]` is interpreted as `*(foo + x)`. It doesn't matter what value of `x` is. `foo + x` may point to a valid memory location, or it may not. It's up to you, to not use invalid values of `x`. Interestingly, this makes expressions, such as `x[foo]` work, due to them being interpreted as `*(x + foo)`, which is exactly the same as `*(foo + x)`.
Comment: "foo will be of type int*." Note that this means `foo` might point at one `int`, or many `int` in an array, or no `int` at all. They're all the same type. This is important for understanding `foo[1]`
Answer: In this expression
foo[1]

there is used the pointer arithmetic. This expression is evaluated like
*( foo + 1 )

The sub-expression foo + 1 has the type int * . So formally the full expression has the type int. That is the memory pointed to by the sub-expression foo + 1 is interpreted as storing an object of the type int.
Answer:
Does it just takes the next 4 bytes and assumes it is an int because foo is an int*?

I would say that's an easy way to look at it.
Fundamentally C++'s type system is fixed at compile-time. Putting aside things like virtual functions or dynamic_cast, C++ doesn't verify or second-guess what type it's told to treat memory as. When you get down to basic types like int, they don't carry any meta-information from which one could determine whether a certain 4 bytes in memory are an int or a float or char[4] or something else.
So, for example, the memory pointed to by an is int* is treated as an int. Under the hood in the instructions that make up a compiled program, this is a very simple and efficient way for things to work.
This also leads to the all the advice to be cautious about casting from one type to another, and generally avoid it if possible. Because with casting you can force memory to be treated as a different type than it normally would be - essentially telling the compiler "do what I say because I know better than you". If you know what you're doing, this can be used for clever tricks. But if you're mistaken, then nothing is going to save you from shooting yourself in the foot.


Salvar um array vindo do formulario no banco de dados

Question: Já tentei de varias formas salvar os dados que vem no formulário no banco de dados mas não esta dando certo, quando utilizava o PHP5 funcionava mas agora convertendo para PHP7 parou de funcionar, alguém pode me ajudar.
O formulario de Cadastro:
<?php
if (!isset($seguranca)) {
    exit;
}
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

$result_paciente = "SELECT * FROM pacientes WHERE id = '$id'";
$resultado_paciente = mysqli_query($conn , $result_paciente);

?>

Receituario

   <?php while($row_paciente = mysqli_fetch_assoc($resultado_paciente)){?>

            Paciente
              <?php echo $row_paciente["nome_paciente"]; ?>

            Profissional
           <?php echo $_SESSION['nome'];?>
            <?php } ?>

     <form action="<?php echo pg; ?>/processa/proc_cad_receitas" method="POST" class="form-horizontal">

          Medicamento
          Qtd Comprar
          Qtd Tomar
          Intervalo
          Nº Dias
          <input type="button"  class="btn btn-primary add" value="+">

               <select type="text" name="med[]" class="form-control med"> <option value=""></option>
              <?php
                $result_medicamento = "SELECT M.medicacao_id, M.comercial, V.nome_via, A.nome_apre
                                              FROM tbl_drugs_medicacao AS M
                                              INNER JOIN tbl_drugs_vias_cadastradas AS V
                                              ON M.via_id = V.id_via
                                              INNER JOIN tbl_drugs_apresentacao AS A
                                              ON M.apresentacao_id = A.id_apre
                                              ORDER BY comercial";
                $resultado_medicamento = mysqli_query($conn, $result_medicamento);
                while($row_medicamento = mysqli_fetch_assoc($resultado_medicamento) ) {
                  echo '<option value="'.$row_medicamento['medicacao_id'].'">'.$row_medicamento['comercial'].'-|-'.$row_medicamento['nome_via'].'-|-'.$row_medicamento['nome_apre'].'</option>';
                  }
              ?>
              </select>
               <input type="text" name="compra[]" class="form-control compra">
               <input type="text" name="tomar[]" class="form-control tomar">
               <select type="text" name="inter[]" class="form-control inter"><option value=""></option>
                <?php
                  $result_intervalo = "SELECT * FROM tbl_drugs_intervalo";
                  $resultado_intervalo = mysqli_query($conn, $result_intervalo);
                  while($row_intervalo = mysqli_fetch_assoc($resultado_intervalo) ) {
                    echo '<option value="'.$row_intervalo['id_inter'].'">'.$row_intervalo['nome_inter'].'</option>';
                  }
                ?>
              </select>
               <select type="text" name="day[]" class="form-control day"><option value=""></option>
                <?php
                $result_dia = "SELECT * FROM tbl_drugs_dias";
                $resultado_dia = mysqli_query($conn, $result_dia);
                while($row_dia = mysqli_fetch_assoc($resultado_dia)){
                  echo '<option value="'.$row_dia['id_dias'].'">'.$row_dia['nome_dias'].'</option>';
                  }
                ?>
              </select>
               <input type="button"  class="btn btn-danger remove" value="Remover">

            <input type="submit" class="btn btn-success" name="Sendreceitas" value="Salvar">

  </form>

Formulario Antigo do PHP 5

<?php
  session_start();

  $id_prof = $_SESSION['usuarioId'];
  include_once("../../../../conexao/conexao.php");
?>

<?php
    $id = $_SESSION['paciente_receita'];
    $result_paciente = "SELECT * FROM tbl_pacientes WHERE id = '$id'";
    $resultado_paciente = mysqli_query($conn , $result_paciente);
    $id_receita = $_SESSION['receitas_emitir'];
 ?>

<?php

        if(isset($_POST['order']))
          {
            if($id > 0)
              {
                for($i=0;$i<count($_POST['med']);$i++)
                  {
        $med      = mysqli_real_escape_string($conn, $_POST['med'][$i]);
        $compra   = mysqli_real_escape_string($conn, $_POST['compra'][$i]);
        $toma     = mysqli_real_escape_string($conn, $_POST['tomar'][$i]);
        $inter    = mysqli_real_escape_string($conn, $_POST['inter'][$i]);
        $dias     = mysqli_real_escape_string($conn, $_POST['day'][$i]);

$result_itens = "INSERT INTO tbl_pacientes_receitas_itens(presc_id, med_id, compra, toma, inter_id, dias_id, criado) VALUES ('$id_receita', '$med', '$compra', '$toma', '$inter', $dias, NOW())";
  $resultado_itens = mysqli_query($conn, $result_itens);

                  }
              }
          }
?>

<!DOCTYPE html>

        <meta charset="utf-8">

        <?php
            if(mysqli_affected_rows($conn) != 0){
                header('location: http://localhost/clinica/adm/adm.php?link=41&id='.$id);
                    }
                        unset($_SESSION["receitas_emitir"]);
        ?>

<?php $conn->close(); ?>

Tentei usar esse código mas não da certo de jeito nenhum, fala que não posso acessar o POST diretamente.
Nem receber os dados estou conseguindo.
<?php

if (!isset($seguranca)) {
    exit;
}
$id = $_SESSION['id_pac'];

$prontuario_id = $_SESSION['prontuario'];

$result_paciente = "SELECT * FROM pacientes WHERE id = '$id'";
$resultado_paciente = mysqli_query($conn, $result_paciente);
$row_paciente = mysqli_fetch_assoc($resultado_paciente);

$receita = filter_input_array(INPUT_POST, FILTER_DEFAULT);

echo $receita['med'];
echo $receita['compra'];
echo $receita['tomar'];
echo $receita['inter'];
echo $receita['day'];
?>

Answer: faz tempo que não programo em php mas uma ideia seria fazer um FOR para cada request e salvar dentro do array, e da mesma forma pode usar para exibir.
ex:
 <?php
    $results = array
      (
      array("Marcos","ritalina","18","2"),
      array("Julia","ibuprofeno","30","1"),
      array("Marcelo","alprazolam ","06","4"),
      array("Antonia","clonazepam ","02","2"),
      );

    for ($i = 0; $i < 4; $i++) {
        $j = 0;
        print_r('Paciente: '.$results[$i][$j].'. medicamento: '.$results[$i][$j+=1].'. dose(mg): '.$results[$i][$j+=1].'. vezes ao dia: '.$results[$i][$j+=1].'.' );
        echo '
';
    }
?>

Comment: Nao da certo,
Porque tem um raio de um filtro contra mysqli injection que nao deixa vir.
Comment: Não tô entendendo o que você deseja, um.modo de burlar o sistema ou apenas fazer um request?
Comment: Caro Colega,
Estou tentando pegar os dados enviados pelo formulario e salvar no banco de dados.
O formulario add as linhas de acordo com a quantidade de medicamento a pedir via javascript, ate ai tudo bem.
Quando faço um arquivo para enviar para o banco de dados ele nao envia.
Se uso o codigo direto para pegar o conteudo do array ele diz que nao posso acessar diretamente os dados do array, que preciso de um filtro.
Nao estou conseguindo filtrar os dados no array no php 7 .


Can someone explain this output?

Question: I was going through some program when i came across this.
#include<stdio.h>
void main()
{
char z;
do
{
    printf("1st line\n");
    printf("2nd line\n");
            scanf("%c",&z);

    switch(z)
    {
        case 'a':printf("this is case a\n");
            break;
        case 'b':printf("this is case b\n");
            break;
        case 'c':printf("Exit\n");
            return;
            break;
        default:
            printf("this is default\n");
            break;
    }
}while(1);

}
1st time i give an input, the output is proper. But after the first input is given and the loop starts for the second time, scanf statement isn't executed at all. The printf statements get executed though and also the default case.

1st line
  2nd line
  b
  this is case b
  1st line
  2nd line
  this is default
  1st line
  2nd line
Answer: When you entered b for the first scanf call, you also hit enter. When scanf("%c", &z) processed this input, it left the newline character in the input stream.
The second set of output is due to the scanf reading the newline character that followed b. Since \n is neither a, nor b, nor c, it hits the default case.
You can fix the behavior to be more like what you expect by modifying your scanf string:
scanf(" %c", &z);

Note the space character before the %c. This will cause scanf to skip whitespace characters (including the newline) before processing the input.
Answer:
int main().
No undefined behavior here. It's just that scanf() doesn't work how you think it does. %c consumes a character. A character. One. And it doesn't consume the newline that's left in the buffer of stdin after you hit Enter. (So "the second scanf isn't executed" is not true - it's executed and it processes whatever is left for it.) Now, the newline character isn't either one of a, b or c, so the switch statement continues execution at the default: label.

If you want to read a character from the standard input, a reliable way is:
char buf[LINE_MAX];
fgets(buf, sizeof buf, stdin);
switch (buf[0]) {
    // etc.
}

alternative:
int c = fgetc(stdin);
while (fgetc(stdin) == '\n')
    ;

Don't use scanf(). (At least not until you understand what it does.) It's evil.
Comment: +1, I agree that `scanf()` should generally be avoided.
Comment: @H2CO3, I tested this sample with Eclipse and gcc, and it behaves as the OP expected. Does this mean that eclipse doesn't put the `\n` in the stream? I also thought that the return key would be the problem, so I was surprised that it works.
Comment: When running it on the console, it is as you described, so it seems that Eclipse is indeed swallowing the `\n` itself.
Comment: @Devolus I think in this case it does. (Thanks for giving me another reason to hate IDEs, I collect those!)
Answer: No big problem, you just ignore to handle the '\n' input after each character, you may do it this way:
scanf("%c\n",&z);

So that you can avoid handling '\n'.

Can someone explain this output?


Simple argument for $\frac{(x+y)^2}{x^2+xy+y^2}\le 4/3$

Question: I would like to show that $\forall x,y\in\mathbb R^+:\frac{(x+y)^2}{x^2+xy+y^2}\le 4/3$.
The inequality is indeed true as the maximum of $\frac{(x+y)^2}{x^2+xy+y^2}$ is reached for $x=y$ and its value is $4/3$.
Except for the standard way of computing partial derivatives and finding the maximum, is there a simple argument that imply this inequality (perhaps using symmetry somehow?).
Thanks !
Answer: $$\frac{(x+y)^2}{x^2+xy+y^2} = 1 + \frac{xy}{x^2+xy+y^2}$$
$$xy \le \frac{(x^2 + y^2)}{2} $$
$$\therefore \frac{3xy}{2} \le \frac{(x^2 + y^2 + xy)}{2}$$
$$\therefore \frac{xy}{x^2+xy+y^2} \le \frac 13$$
$$\therefore \frac{(x+y)^2}{x^2+xy+y^2} \le \frac 43 $$
Answer: We have $$\frac{(x+y)^2}{x^2+xy+y^2} = \frac{(x+y)^2}{\frac{3}{4}(x+y)^2 + \frac{1}{4}(x-y)^2}\leq \frac{(x+y)^2}{\frac{3}{4}(x+y)^2}=\frac{4}{3}$$
The inequality holds since squares are non-negative.
Comment: There is a small typo. $\frac{(x+y)^2}{\frac{4}{3}(x+y)^2}$ must be $\frac{(x+y)^2}{\frac{3}{4}(x+y)^2}.$
Comment: Should be fixed now, thanks!
Answer: The reciprocal is
$$\frac{x^2+xy+y^2}{(x+y)^2}=1-\frac{xy}{(x+y)^2} $$
and by the AMGM inequality, $\sqrt{xy}\le \frac{x+y}2$ with equality iff $x=y$, hence $\frac{xy}{(x+y)^2}\le \frac14$ with equality iff $x=y$ and from this  $\frac{x^2+xy+y^2}{(x+y)^2}\ge \frac 34$ and finally $\frac{(x+y)^2}{x^2+xy+y^2}\le \frac 43$
Answer: $$\frac{(x+y)^2}{x^2+xy+y^2}=1+\frac{xy}{x^2+xy+y^2}\le 1+\frac{1}{3}$$
$$\iff 3xy\le x^2+xy+y^2\iff (x-y)^2\ge 0,$$
which is true, with equality iff $x=y$.
Note we could multiply by $x^2+xy+y^2$ without flipping ineq sign because it equals $\left(x+\frac{1}{2}y\right)^2+\frac{3}{4}y^2>0$
Answer: Since $x^2+xy+y^2=\left(x+\frac y2\right)^2+\frac{3y^2}{4}\gt 0$, one has$$\begin{align}\frac{(x+y)^2}{x^2+xy+y^2}\le\frac 43&\iff (x+y)^2\le\frac{4}{3}(x^2+xy+y^2)\\&\iff \frac 13x^2-\frac 23xy+\frac 13y^2\ge0\\&\iff \frac 13(x-y)^2\ge 0\end{align}$$
This is true.


What is true about the fraction of ketchup in the ketchup bottle compared to the fraction of mustard in the mustard bottle?

Question:
Suppose we have a bottle with $1$L of ketchup and another bottle with 1L of mustard. We take $1$Tbsp of ketchup from the ketchup bottle and put it in the mustard bottle and then mix it (but it might not be mixed very well). Then, I take $1$Tbsp of the mixture back into the ketchup bottle. What is true about the fraction of ketchup in the ketchup bottle compared to the fraction of mustard in the mustard bottle?

I am really not sure what to do here. The problem seems so simple but I don't even know how to start.
Comment: Maybe that the fraction of ketchup in the ketchup bottle is greater compared to the fraction of mustard in the mustard bottle? This question is rather ambiguous...
Comment: What do you mean by "What is true"? I'm confused about what you're asking.
Comment: They're equal. Prove this.
Answer: Give names to the quantities involved. After you are finished mixing, the ketchup bottle contains a large quantity $K$ of ketchup and a small quantity $m$ of mustard, and the mustard bottle contains a large quantity $M$ of mustard and a small quantity $k$ of ketchup. What can you say about the four sums $K+m$, $M+k$, $K+k$, and $M+m$? What does this imply about the four quantities $K,k,M,m$?


bijection between graphs

Question: let $G(E,V)$ be a graph. I'm trying to find a bijection between the two following sets:
Set A - simple, undirected graphs with $n$ vertices which does not have vertices with a rank of $0$.
Set B - simple, undirected graphs that does not have vertex with a rank of $n−1$.
Both of the sets are finite.
Prove with a bijection that $|A| = |B|$.
Comment: What is the "rank" of a vertex? Do you mean the degree?
Answer: If $K(V)$ denotes the complete graph on vertex set $V$, then a suitable bijection is $G(E,V)\mapsto K(V)-G(E,V)$ (works in both directions).

bijection between graphs


Spring @RequestParam Date Formatting

Question: How do you format the incoming @RequestParam using annotations?  The form is sending the date in MM/DD/YYYY format and the controller is not picking it up as a valid Date.
@RequestMapping(params="/updateDate")
public @ResponseBody String updateDate(HttpServletRequest request
        , @RequestParam Integer productId
        , @RequestParam Date dateReceived) {
    // Code here...
}

Answer: Use the Spring annotation DateTimeFormat
@RequestMapping(params="/updateDate")
public @ResponseBody String updateDate(HttpServletRequest request
        , @RequestParam Integer productId
        , @RequestParam @DateTimeFormat(pattern="MM/dd/yyyy") Date dateReceived) {
    // Code here...
}

Spring @RequestParam Date Formatting


Draw a rounded rectangle using a single glDrawElement( triangle_strip...) call in OpenGL ES

Question: I want to draw a rounded rectangle in Opengl es, with a single glDraw call.
I have also tried it. and shared it in the answer.
Hope it will be helpful.
Answer: I have tried to draw a rounded rectangle in opengl es with single glDraw call.
Below is the code snippet:
<code>// -0.3f,   -0.2f,  0.0f,   // 0
//  0.3f,  -0.2f,  0.0f,    // 1
// -0.3f,   0.2f,  0.0f,    // 2
//  0.3f,    0.2f,  0.0f,   // 3
//  0.6f,   0.2f,  0.0f,    // 4
//  0.6f,   -0.2f,  0.0f,   // 5
//  0.6f,  -0.5f,  0.0f,    // 6
//  0.3f,  -0.5f,  0.0f,    // 7
// -0.3f,   -0.5f,  0.0f,   // 8
// -0.6f,  -0.5f,  0.0f,    // 9
// -0.6f,  -0.2f,  0.0f,    // 10
// -0.6f,   0.2f,  0.0f,    // 11
// -0.6f,    0.5f,  0.0f,   // 12
// -0.3f,   0.5f,  0.0f,    // 13
//  0.3f,    0.5f,  0.0f,   // 14
//  0.6f,   0.5f,  0.0f // 15
//
//            8_______________________7
//            /|                      |\
//          9/ |                      | \6
//        10/  |                      |  \5
//         /___|______________________|___\
//       1 |   |2                    3|   |4
//         |   |                      |   |
//         |   |                      |   |
//      12 |___|______________________|___|19
//         \   |0                    1|   /
//        13\  |                      |  /18
//         14\ |                      | /17
//            \|______________________|/
//            15                      16
//

static GLfloat vertRndRect[N];
// first store the vertices 0,1,2,3,4 in vertRndRect array
// then calculate the value for vertices 5 and 6 using the below code
for (i = 30; i < 90; i = i + 30)  // change this line to create more vertices but 'indices' array will change
{
float X_cen = vert1[9];
float Y_cen = vert1[10];
    vertRndRect[iVertCnt++]  = X_cen + (cos(degreesToRadians(i)) * rad);
    vertRndRect[iVertCnt++]  = Y_cen + (sin(degreesToRadians(i)) * rad);
vertRndRect[iVertCnt++]  = 0.0f; // Z
}
// Then store  vertices 7 and 8 to vertRndRect array
// then calculate the value for vertices 9 and 10 using the below code
for (i =  120; i < 180; i = i + 30)
{
float X_cen = vert1[6];
float Y_cen = vert1[7];
    vertRndRect[iVertCnt++]  = X_cen + (cos(degreesToRadians(i)) * rad);
    vertRndRect[iVertCnt++]  = Y_cen + (sin(degreesToRadians(i)) * rad);
vertRndRect[iVertCnt++]  = 0.0f; // Z
}

// Then store  vertices 11 and 12 to vertRndRect array
// then calculate the value for vertices 13 and 14 using the below code
for (i = 210; i < 270;  i = i + 30)
{
float X_cen = vert1[0];
float Y_cen = vert1[1];
    vertRndRect[iVertCnt++]  = X_cen + (cos(degreesToRadians(i)) * rad);
    vertRndRect[iVertCnt++]  = Y_cen + (sin(degreesToRadians(i)) * rad);
vertRndRect[iVertCnt++]  = 0.0f; // Z
}

// Then store  vertices 15 and 16 to vertRndRect array
// then calculate the value for vertices 13 and 14 using the below code
for (i = 300; i < 360;  i = i + 30)
{
float X_cen = vert1[3];
float Y_cen = vert1[4];
    vertRndRect[iVertCnt++]  = X_cen + (cos(degreesToRadians(i)) * rad);
    vertRndRect[iVertCnt++]  = Y_cen + (sin(degreesToRadians(i)) * rad);
vertRndRect[iVertCnt++]  = 0.0f; // Z
}
// Then store  vertices 19
//////////////////////////
GLushort indices[] = {  0, 1, 2, 3, 3, 4,
                            5, 5, 3, 6, 7, 7,
                            3, 8, 2, 9, 10, 10,
                            2, 11, 0, 12, 13, 13,
                            0, 14, 15, 15, 0, 16,
                            1, 17, 18, 18, 1, 19, 3, 4
                         };
//////////////////////////
glDrawElements(GL_TRIANGLE_STRIP, 38, GL_UNSIGNED_SHORT,indices); // 38 is size of 'indices' array
</code>
Here, I calculated only 2 vertices for each rounded corner.
But can increase it to get more smoothness.
But corresponding changes has to be done in 'indices' array
Lot of optimizations can be done in this code.
Answer: I modified the code to get the  inputs ( TopLeft Corner Position, width and height) and dynamically generating 10 vertices for each rounded corners and its texture coordinates.
<code>     // Vertices and Texture Coordinates Generation.
    Input: Width and Height, Sx, Sy,Sz (Top Left Vertex Position)
    // To get smooth rounded rectangle, 10 vertices are generated for each rounded corner

    float Sx = 0.0;
    float Sy = 0.0;
    float verCz = Sz = 0.0;

    float rad;

    if (fWidth > fHeight)
    {
        rad = 0.3f * (fHeight/fWidth);
    }
    else
    {
        rad = 0.3f * (fWidth/fHeight);
    }

    float invWidth    = 1.0/fWidth ;
    float invHeight   = 1.0/fHeight;
    float radbywidth  = rad * invWidth;
    float radbyheight = rad * invHeight;

    float texCx   = (Sx + fWidth - rad) * invWidth;
    float texCy   = (Sy - rad)          * invHeight;

    //0 to 9 vertices
    for (i = 0; i <= 90; i = i + 10)
    {
        vertices[iVertCnt++]  = (Sx + fWidth - rad) + (cos(degreesToRadians(i)) * rad); //centre point-X + r*cos
        vertices[iVertCnt++]  = (Sy - rad)          + (sin(degreesToRadians(i)) * rad); //centre point-Y + r*sin
        vertices[iVertCnt++]  = verCz;

        texcoord_RndRect [tex++]  = texCx + (cos(degreesToRadians(i)) * radbywidth);
        texcoord_RndRect [tex++]  = texCy + (sin(degreesToRadians(i)) * radbyheight);
    }

    GLfloat vert1[] =
    {
        (Sx + rad),   Sy       , 0.0f,  // 10
        (Sx + rad),   (Sy -rad), 0.0f,  // 11
    };

    for (i = 0; i < 6; i = i+3)
    {
        vertices[iVertCnt++]        =  vert1[i];
        vertices[iVertCnt++]        =  vert1[i+1];
        vertices[iVertCnt++]        =  vert1[i+2];
        texcoord_RndRect [tex++]    =  vert1[i]   * invWidth;
        texcoord_RndRect [tex++]    =  vert1[i+1] * invHeight;
    }

    texCx   =  (Sx + rad) * invWidth;
    texCy   =  (Sy - rad) * invHeight;
    ////12 to 21 vertices
    for (i = 90; i <= 180; i = i + 10)
    {
        vertices[iVertCnt++]  = (Sx + rad) + (cos(degreesToRadians(i)) * rad); //centre point-X + r*cos
        vertices[iVertCnt++]  = (Sy - rad) + (sin(degreesToRadians(i)) * rad); //centre point-Y + r*sin
        vertices[iVertCnt++]  = verCz;

        texcoord_RndRect [tex++]  = texCx +(cos(degreesToRadians(i)) * radbywidth);  // texture will be from 0 to 1 only
        texcoord_RndRect [tex++]  = texCy +(sin(degreesToRadians(i)) * radbyheight);
    }

    GLfloat vert2[] =
    {
        (Sx)        , (Sy - fHeight + rad),  0.0f,  // 22
        (Sx + rad ),  (Sy - fHeight + rad),  0.0f,  // 23
    };

    for (i = 0; i < 6; i = i+3)
    {
        vertices[iVertCnt++]        =  vert2[i];
        vertices[iVertCnt++]        =  vert2[i+1];
        vertices[iVertCnt++]        =  vert2[i+2];
        texcoord_RndRect [tex++]    =  vert2[i]   * invWidth;
        texcoord_RndRect [tex++]    =  vert2[i+1] * invHeight;
    }

    texCx   = (Sx + rad )          * invWidth;
    texCy   = (Sy - fHeight + rad)  * invHeight;
    ////24 to 33 vertices
    for (i = 180; i <= 270; i = i + 10)
    {
        vertices[iVertCnt++]  = (Sx + rad )         + (cos(degreesToRadians(i)) * rad); //centre point-X + r*cos
        vertices[iVertCnt++]  = (Sy - fHeight + rad) + (sin(degreesToRadians(i)) * rad); //centre point-Y + r*sin
        vertices[iVertCnt++]  = verCz;

        texcoord_RndRect [tex++]  = texCx +(cos(degreesToRadians(i)) * radbywidth);
        texcoord_RndRect [tex++]  = texCy +(sin(degreesToRadians(i)) * radbyheight);
    }

    GLfloat vert3[] =
    {
        (Sx + fWidth - rad),   (Sy - fHeight)       ,  0.0f,    // 34
        (Sx + fWidth - rad),   (Sy - fHeight + rad) ,  0.0f,    // 35
    };

    for (i = 0; i < 6; i = i+3)
    {
        vertices[iVertCnt++]        =  vert3[i];
        vertices[iVertCnt++]        =  vert3[i+1];
        vertices[iVertCnt++]        =  vert3[i+2];
        texcoord_RndRect [tex++]    =  vert3[i]   * invWidth;
        texcoord_RndRect [tex++]    =  vert3[i+1] * invHeight;
    }

    //36th vertices
    vertices[iVertCnt++]  = (Sx + fWidth - rad);
    vertices[iVertCnt++]  = (Sy - fHeight + rad);
    vertices[iVertCnt++]  = 0.0f;

    texcoord_RndRect [tex++]  = (Sx + fWidth - rad) * invWidth;  // 11
    texcoord_RndRect [tex++]  = (Sy - fHeight + rad)* invHeight;

    texCx   = (Sx + fWidth - rad) * invWidth;
    texCy   = (Sy - fHeight + rad) *invHeight ;

    ////37 to 46 to  vertices
    for (i = 270; i <= 360; i = i + 10)
    {
        vertices[iVertCnt++]  = (Sx + fWidth - rad)  + (cos(degreesToRadians(i)) * rad); //centre point-X + r*cos
        vertices[iVertCnt++]  = (Sy - fHeight + rad) + (sin(degreesToRadians(i)) * rad); //centre point-Y + r*sin
        vertices[iVertCnt++]  = 0.0f;

        texcoord_RndRect [tex++]  = texCx +(cos(degreesToRadians(i))  * radbywidth);
        texcoord_RndRect [tex++]  = texCy +(sin(degreesToRadians(i))  * radbyheight);
    }

    GLfloat vert4[] =
    {
        (Sx + fWidth )      ,    (Sy - rad),  0.0f, // 47
        (Sx + fWidth - rad) ,    (Sy -rad ),  0.0f, // 48

    };

    for (i = 0; i < 6; i = i+3)
    {
        vertices[iVertCnt++]        =  vert4[i];
        vertices[iVertCnt++]        =  vert4[i+1];
        vertices[iVertCnt++]        =  vert4[i+2];
        texcoord_RndRect [tex++]    =  vert4[i]   * invWidth;
        texcoord_RndRect [tex++]    =  vert4[i+1] * invHeight;
    }

            // Display
    ///////////////////////////////////////
    GLushort indices_topright[] =
    {
        0,1,2,3,4,5,6,7,8,9,10,11
    };

    GLushort indices_topleft[] =
    {
        12,13,14,15,16,17,18,19,20,21,22,23
    };

    GLushort indices_bottomleft[] =
    {
        24,25,26,27,28,29,30,31,32,33,34,35
    };

    GLushort indices_bottomright[] =
    {
        36,37,38,39,40,41,42,43,44,45,46,47,48,11,23
    };
    glDrawElements(GL_TRIANGLE_FAN, (sizeof(indices_topright)/sizeof(indices_topright[0])), GL_UNSIGNED_SHORT, indices_topright);
    glDrawElements(GL_TRIANGLE_FAN, (sizeof(indices_topleft)/sizeof(indices_topleft[0])), GL_UNSIGNED_SHORT, indices_topleft);
    glDrawElements(GL_TRIANGLE_FAN, (sizeof(indices_bottomleft)/sizeof(indices_bottomleft[0])), GL_UNSIGNED_SHORT, indices_bottomleft);
    glDrawElements(GL_TRIANGLE_FAN, (sizeof(indices_bottomright)/sizeof(indices_bottomright[0])), GL_UNSIGNED_SHORT, indices_bottomright);
    ////////////////////////
</code>
This code works for me.


Clustered vertical lines in the plot(model, residuals)

Question: I am stuck in the diagnostics of my model, and I am looking for advice on what to do.
My data frame goes like this
 $ ID      : Factor w/ 15 levels "Buzinza","Kabukojo",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Period  : Factor w/ 3 levels "After","Before",..: 1 3 1 1 2 1 1 2 3 1 ...
 $ Class   : Factor w/ 3 levels "Adult female",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ no.trans: num  4 5 6 4 15 4 17 22 2 23 ...

Nbinom had a better AIC than Poisson (which was overdispersed)
model_nb <- glmmTMB(no.trans ~ Period * Class + (1 | ID),
                    family = nbinom2(),
                    data = periods)

Normality and overdispersion were ok.
Vif was not sensible so I calculated the variance of predictor variables and the matrix seemed ok.
But  plot(fitted(model_nb), resid) showed vertical clustered lines.

Dharma accused the presence of 12 outliers in 3465 observations for the non-transformed data and 6 outliers for the sqr transformed data.
I tried also lme4 package.
I have only those variables so I cannot complicate the model further. And it is already quite simple.
Not sure what to do next, any advice would be very welcomed!
Cheers,
Comment: You have only factors as predictors, so there is only a limited number of values that your model can predict, hence vertical lines
Comment: Looks fine to me, what is the problem?
Comment: @mkt good point
Comment: Shouldn't be showing a random scattering of points instead of the vertical patterns? This is my first time working with count data. Is this normal for this type of data?
Comment: Thank you!! I really appreciate it!
Comment: @rep_ho Why not add that as an answer?
Answer: In this case vertical lines are expected. You have only factors as predictors, so there is only a limited number of values that your model will produce as predictions; hence the small set of vertical lines on your plot.


Prove $\lfloor{(p+1+a)/b}\rfloor<1+\lfloor{(1+a+b)/p}\rfloor$ is true, $a$ odd, $p$ prime, $a=\lfloor{p/3}\rfloor$ & $b=\lceil{(2/3)p}\rceil$

Question: Here $p$ is prime $\ge 5$.  I have tested this numerically and it holds for the range tested.
A possible simplification is let $c = \lfloor{(4/3)p + 1}\rfloor$ then when $a$ is odd then $c$ is odd and we can write $\lfloor{c/b}\rfloor < \lfloor{(c+b)/p}\rfloor$.  Perhaps this will simplify the analysis.
Answer: Primality has nothing to do with it.

Replace $p$ by $x$, where $x$ is an integer, $x >1$.

Claim: $\text{RHS} - \text{LHS} = 1$ if and only if $x \equiv 2 \pmod 3$, and equals $0$ otherwise.

To prove it, write $x = 6k + r$, where $k,r$ are nonnegative integers and $0 \le r < 6$.

Then consider cases based on the value of $r$. For each $r$, compute the $\text{RHS}$ and $\text{LHS}$ exactly in terms of $k$ (for each fixed value of $r$, the floors and ceilings can be simplified), and observe that the claim stated above holds.

For the case where $x$ is prime, it follows that $\text{RHS} - \text{LHS} = 1$ if and only if $x = 2$ or $x = 5 \pmod 6$, which is consistent with what you found experimentally.


File Server - Storage configuration: RAID vs LVM vs ZFS something else...?

Question: We are a small company that does video editing, among other things, and need a place to keep backup copies of large media files and make it easy to share them.
I've got a box set up with Ubuntu Server and 4 x 500 GB drives.  They're currently set up with Samba as four shared folders that Mac/Windows workstations can see fine, but I want a better solution.  There are two major reasons for this:

500 GB is not really big enough (some projects are larger)
It is cumbersome to manage the current setup, because individual hard drives have different amounts of free space and duplicated data (for backup).  It is confusing now and that will only get worse once there are multiple servers. ("the project is on sever2 in share4" etc)

So, I need a way to combine hard drives in such a way as to avoid complete data loss with the failure of a single drive, and so users see only a single share on each server.  I've done linux software RAID5 and had a bad experience with it, but would try it again.  LVM looks ok but it seems like no one uses it.  ZFS seems interesting but it is relatively "new".
What is the most efficient and least risky way to to combine the hdd's that is convenient for my users?

Edit: The Goal here is basically to create servers that contain an arbitrary number of hard drives but limit complexity from an end-user perspective. (i.e. they see one "folder" per server)  Backing up data is not an issue here, but how each solution responds to hardware failure is a serious concern.  That is why I lump RAID, LVM, ZFS, and who-knows-what together.
My prior experience with RAID5 was also on an Ubuntu Server box and there was a tricky and unlikely set of circumstances that led to complete data loss.  I could avoid that again but was left with a feeling that I was adding an unnecessary additional point of failure to the system.
I haven't used RAID10 but we are on commodity hardware and the most data drives per box is pretty much fixed at 6.  We've got a lot of 500 GB drives and 1.5 TB is pretty small.  (Still an option for at least one server, however)
I have no experience with LVM and have read conflicting reports on how it handles drive failure.  If a (non-striped) LVM setup could handle a single drive failing and only loose whichever files had a portion stored on that drive (and stored most files on a single drive only) we could even live with that.
But as long as I have to learn something totally new, I may as well go all the way to ZFS.  Unlike LVM, though, I would also have to change my operating system (?) so that increases the distance between where I am and where I want to be.  I used a version of solaris at uni and wouldn't mind it terribly, though.
On the other end on the IT spectrum, I think I may also explore FreeNAS and/or Openfiler, but that doesn't really solve the how-to-combine-drives issue.
Comment: Another note regarding LVM. . . stop thinking about it in terms of redundancy and disk failure.  LVM should never know about disk failures, because it should be handled at a lower level (RAID).  LVM gives you the ability to manage and partition your disks in a cleaner and more flexible way, but it doesn't add redundancy and it handles a disk failure the same way a non LVM partition does (it blows up).
Comment: ZFS is really only considered a stable production ready option on Solaris/OpenSolaris (although a few people would argue even with it's readiness there).
Answer: LVM is actually quite heavily used.  Basically, LVM sits above the hardware (driver) layer.  It doesn't add any redundancy or increased reliability (it relies on the underlying storage system to handle reliability).  Instead, it provides a lot of added flexibility and additional features.  LVM should never see a disk disappear or fail, because the disk failure should be handled by RAID (be it software or hardware).  If you lose a disk and can't continue operating (rebuild the RAID, etc), then you should be going to backups.  Trying to recover data from an incomplete array should never be needed (if it is, you need to reevaluate your entire design).
Among the things you get with LVM are the ability to easily grow and shrink partitions/filesystems, the ability to dynamically allocate new partitions, the ability to snapshot existing partitions, and mount the snapshots as read only or writable partitions.  Snapshots can be incredibly useful, particularly for things like backups.
Personally, I use LVM for every partition (except /boot) on every box I build, and I've been doing so for the past 4 years.  Dealing with non-LVM'ed boxes is a huge pain when you want to add or modify your disk layout.  If you're using Linux, you definitely want use LVM.  [Note: This above stuff on LVM has been updated to better explain what it is and how it fits into the storage equation.]
As for RAID, I don't do servers without raid.  With disk prices as cheap as they are, I'd go with RAID1 or RAID10.  Faster, simpler, and much more robust.
Honestly though, unless you're wedded to Ubuntu (which I would normally recommend), or if the box is performing other tasks, you might want to look into OpenFiler.  It turns your box into a storage appliance with a web interface and will handle all of the RAID/LVM/etc for you, and allow you to export the storage as SMB, NFS, iSCSI, etc.  Slick little setup.
Comment: I second the OpenFiler suggestion. It seems one can never keep up with the amount of needed disk space, and separating the Server from the Data can make the end-user experience and the management so much easier and better. There is a reason why Netapp has been so successfull. I would suggest following that model.
Comment: I had looked briefly into freeNAS.. any reason to choose OpenFiler instead?
Comment: I've been using FreeNAS for SMB and iSCSI target and it's been brilliant, never missed a beat. On the other hand, I haven't evaluated OpenFiler, so I've no idea how it compares
Comment: When I first started playing with them a couple of years ago, OpenFiler looked more stable, more featureful, had better driver support, and was under more active development.  I decided to give it a shot, and it worked out really well for me.  I honestly haven't looked at FreeNAS since.  It may be that FreeNAS has caught up to OpenFiler, but I don't know.
Answer: ZFS is really reliable and it sure does make your storage management hell of a lot easier.
As a bonus: smb is integrated with ZFS in OpenSolaris and it handles Raid very well.
Wait a few days, download the by then released 2009.6 version and give it a go on a test machine. I am sure you will love ZFS.
And about your comment ZFS being new: not very new anymore!
Comment: ZFS support on other operating systems is severely lacking functionality. And really, OpenSolaris is a really nice operating system, but please use the real OpenSolaris.

zfs set sharesmb=on backup/share1

really nice integration.
Comment: If you need ZFS, you need it on OpenSolaris. Implementations on linux are done via userspace and as a result are subject to performance overhead and conflicting cache policies.
Comment: "New" meant mostly to me, and just that I haven't been hearing about it and playing with it for years etc.  But so, I need to be running OpenSolaris to use ZFS?
Comment: I have heard that there is some support on other unixes, for ZFS.
Answer: The central question is: "How important is this data?"
If the answer is "I can recreate it easily" you want RAID5, possibly with LVM on top of it for simplicity of management.
If the answer is "I can recreate it but it would take a while and people would complain" you want RAID 6 or more likely RAID 1/10.
If the answer is "Nobody does any work while I recreate it and make sure it's bit-perfect"  you want ZFS/Raid-Z
Note that you're always able to recreate it. RAID isn't a backup.
Comment: I was going for the importance of the data more than the relative performance characteristics. The degradation during rebuild is also important of course but not what I was addressing.
Comment: How does RAID-Z or RAIDZ2 provide better redundancy than RAID6? Both handle any 2 failing disks in an array at most. Also RAID10 handles a second failing disk not as good as RAID6 because you need the right disk to fail, not any of the remaining. Performance is way better with RAID10 than with RAID6. Side Note: Linux 2.6.30 is out and allows you to migrate from RAID1 -> RAID5 <-> RAID6 == awesomeness!
Comment: I've heard RaidZ2 eliminates the write-hole. Basically what mdadm + write journaling do. However, I don't have personal experience with RaidZ, so I'm just repeating what I've heard.
Answer: To connect a lot of drives in the same chassis, a hardware RAID controller is the best tool. It will provide lots of SATA connectors for your drives, redondancy via RAID-5 or preferably RAID-6, and may provide better performance too.
Software RAID performance is often better than hardware RAID in benchmarks, however file serving and software RAID are both CPU intensive and compete for your processors while working. My experience shows that unless you use dual quad-core systems, properly configured hardware RAID will beat software RAID hands down.
Good hardware controllers with good linux support :

Areca
3Ware
the new Adaptec series (the old are slooooow)
LSI MegaRAID
Comment: i am gonna chime in on the 3ware cards, they are wicked especially teh 9650se and the 9690se, used both types of cards with up to 16 drives on the 9650se, no real issue and good stable product.
Answer: RAID is NOT like LVM. You can use RAID to make fault-tolerance partitions, but LVM is used to easy disk partitioning and filesystem edition.
You can use RAID over LVM or ZFS (ZFS is can work both RAID and LVM).
In my opinion, ZFS works better than LVM, but:

on Solaris 10/11/OpenSOlaris only, you can't use it from linux
ZFS is disk management and filesystem, LVM allow to use any filesystem you need

On Ubuntu i prefer to use RAID5 MD with LVM.
Comment: ZFS is available on FreeBSD 7.x as well as Nexenta.
Comment: Can you use ZFS as a disk management/raid, while skipping the filesystem portion? So it would be a direct replacement for mdadm and LVM? If so, having a combination of ZFS and SCST for iSCSI might be an interesting solution. However, if you are forced to use the ZFS file system, then that goes out the window.
Answer: Take a look at what Nexenta and OpenSolaris are offering and I think you'll be very pleased with that you can get for nothing.  It's rumoured that the next releases of OpenFiler will use the FreeBSD ZFS port as well (though, they're quite behind from a feature perspective).
That being said, I try to avoid doing RAID5, RAID6 or RAID50 in software and prefer to use hardware controllers to offload all the XOR work.  RAID1 and RAID10 in Linux software work pretty well, and from there I put LVM on top of them to allow more flexibility in what's done with the blocks I have after the redundancy in place.  RAID+LVM+XFS is my favorite Linux config., but I'd take ZFS over it anyday.
Comment: Traditionally hardware RAID has not performed as well software RAID -- typically it has an advantage only when there's multiple writes that the dedicated controller can duplicate (i.e. don't have to pass over the PCI bus), namely RAID 1. There are other concerns with hardware RAID, for example the firmware's quality and inability to be (easily) updated. Finally, it adds another point of failure. For these reasons, I tend to avoid hardware RAID. That being said, for these same reasons, I haven't played with the new hardware RAID options! :)
Answer: RAID vs LVM isn't really a good comparison they perform separate roles, and are frequently used together.  RAID is used for drive redundancy, LVM can be used to break up your RAID device into logical volumes, it is used for easy resizing, and for taking snapshots.
Answer: I ran the file server for a very similar company/situation.  Basically a 3 person graphics department with 30TB of storage and the shoestring budget of a small company.  Our typical projects ran from a 0.5TB to 6TB.  And the file server was serving a sizable rendering farm which could really pound on it.
In my setup I ran a 3U server running Linux with external hardware RAID6 arrays attached to it.  I managed the physical and logical volumes with LVM and ran the XFS file system.  What I would do is create a logical volume for each project and then expand it as the project grew.  When the project was done I could archive the job to tape and blow away the logical volume.  This would return that space back to the volume group where it would get reallocated to the next project(s).
This was a very clean way to utilize our storage but there are two drawbacks to this approach.  You end up having to micromanage the sizes of the logical volumes trying to balance the amount of space allocated to a logical volume so that you had enough space to do your job but not over allocate it and end up wasting space.  Our rendering farm was capable of generating many TB's of data a day and if you didn't pay close attention to this you would run out of space in a hurry.  I eventually setup some scripts that monitored the trends in the available space on the logical volumes and would auto grow them.  Even with that in place with 80 or so Logical Volumes there was a lot of unused space tied up in all the logical volumes.  I've already hinted at the 2nd problem....LVM doesn't really do thin provisioning and XFS only allows you to grow a file system.  So over allocation of space to a logical volume can add up to a lot of unusable space.
This was all setup about 5 years ago and if I were setting it up today I would use OpenSolaris and ZFS.  The main reason is ZFS pooled storage approach means less volume management.  You can still separate each project into its own file system but without having to micromanage the sizes of the individual volumes.  ZFS has some other very nice features that make it a better choice but there are other questions on serverfault that go into that.
In my opinion ZFS simply is the best free solution available today.
Answer: Some things to consider if you stay with Linux:

Think about the filesystem, too. Your 4x 500GB example is about the largest capacity I would recommend with good conscience for ext3. I do not recommend to create much larger ext3 filesystems because e.g. fsck time can be enormous. Create several smaller instead of one large filesystem.
As you mentioned video data: ext3 handles large files inefficiently because it'll have to create indirect, double-indirect and triple-indirect metadata blocks to store the data of large files and you'll pay the price. Nowadays, ext4 supports extents and handles this much better. But then, it is rather new and e.g. Red Hat Enterprise Linux 5 does not support it yet. (Some Enterprise distros will support alternatives like XFS).
If there is data corruption on any data block you'll have a hard time to even notice this with Linux filesystems. ZFS on the other hand checksums all metadata and data and also verifies the checksum every time data is read from disk. (There is also background scrubbing)
RAID rebuild time on Linux is proportional to disk size because the RAID layer does not know the contents of the filesystem (layer). ZFS's RAID-Z rebuild time depends on the  amount of actual data on the failed disk because only used blocks will be copied/rebuilt on a replacement disk.
Do you want to snapshot your filesystems? LVM snapshots don't even compare with ZFS's instantaneous snapshots. The latter can also easily exposed to the end-users e.g. for easy restores.
Use RAID6 (RAID-Z2) and not only RAID5 (RAID-Z) with large disks (>500GB) because chances are that another disk will fail during rebuilt.
Comment: Excellent points I had not considered about ext3.  Ext4 is still a bit new for my blood, but XFS should be supported by the Ubuntu Server I am using, do you recommend it for this?
Answer: Use the "mdadm" utility to create a RAID-5 array out of your drives.
This provides the redundancy you need, so if a drive goes dead you can replace it with no data loss, and also gives you usage of 3 out of the 4 drives.
I'd also recommend you create an LVM volume on top of the RAID, so you can partition the space out as needed.
Answer: You may want to give a look at AFS. This will give you some measure of both availability (you can access these files both on and off your network) and redundancy (files can be replicated). For a workflow where you open a file, work on it for some time and then save it, this would be better (from a network standpoint) than NFS, at least older NFS.
Answer: As the other reply says, LVM is widely used, and can combine several disks into a single "volume group" that looks like one huge block device. It's worth remembering, though, that doing this increases your probability of failure -- it only takes one disk to fail in a volume group to take out the entire filesystem, and if you have four disks joined together, this is four times more likely. Best to use LVM on top of a RAID1 or similar to mitigate this. Linux software RAID is quite adequate for this, although hardware RAID may be more convenient.
Comment: Your statement "it only takes one disk to fail in a volume group to take out the entire filesystem" is highly dependant of how you create and use the logical volumes within the volume group.  If you only create a single logical volume filling the entire volume group them what you say is true.  It is entirely possible, and depending on filesystem requirements, even recommended, to create multiple logical volumes in a single volume group.
Answer: Sorry this would be a comment but I don't have the rep...

How does RAID-Z or RAIDZ2 provide better redundancy than RAID6?

ZFS has checksumming everywhere
About the original question. Whatever the data I would use 2 active parity per 10 discs. I would use good quality RAID card the 3ware ones are excellent. Personally I use hardware RAID with battery backup. LVM  just so you can migrate the data easily at the end of the hardware's life. XFS as the file system.
Answer: Why you don't use a disk or SSD card to have the system server to bootup and the 500 GB as only storage. Use one 500GB disk and when it becomes full exchange it manually. You can do the backup later in another computer with calm.
Because while the harddisk is turning (spinning) it can be damaged. Anyway if you connect all disks at the same time they all are turning and can take damage if you use it or not.
The probability of failure raise when you have more disks turned on. Use one per time and exchange it when are full or in a period of time anticipating a failure (use too the SMART capability to get rid of that). Use a carry disk or use some external SCSI/SATA disk adapter so you don't need to dissasemble the computer server every time you exchange a disk.
That is the most secure and reliable form.
Using RAID is more expensive and you just waste some disks (because you let it turned on in risk of become damaged for only letting it turned on? stupid, or not?).
If you want more datatroughtput then using a RAID configuration for that I guess is a good choice but never trust in a computer configuration. The backup must be done always manually with a person (the network or server administrator). That is one of the works of an administrator.
You can use tapes, DVD, BlueRay, or other disks to do the backup. But you always will need a reliable storage medium and a running disk is not one.
A turned off disk and well saved (in a fresh and free of humidity place) is a reliable storage medium.