Why does the chord progression Gmaj - F#maj - Amaj sound the way it does?

Question: I really like the chord progression Gmaj - F#maj - Amaj ... (I think it can be written I, VII, II)?
While all the chords are major, there is some sadness about it.
What is the story behind this progression, is it in another mode other than the standard major or minor?
Comment: It could also be IV - III - V in the key of D major, with the III being a borrowed chord from the parallel minor (D minor).
Comment: Just to compare notes - just quickly strumming it on the guitar, I'm not really feeling the sadness :) do you have a link to a sound file? These things can be very arrangement-specific.
Answer: It's actually can be looked at modally as a chords from the Phrygian/Phrygian Dominant scales. The Phrygian scale due to its lowered third is viewed as a minor scale and thus contributes to the "sadness" you hear especially since the A would be the 3rd of the Phygian scale giving the progression a slightly more minor sound even using just major chords.
With the root of F♯, you have the following notes of the Phrygian scale:

F# G A B C# D E F#

and from the Phrygian Dominant scale you have the following notes:

F# G A# B C# D E F#

The notes in each of the chords above are:

G  major - G,  B,  D
F♯ major - F♯, A♯, C♯
A  major - A,  C♯, E

From the two of these scale, you have all the notes of the chords in the progressions. The progression is simply a II I III in F♯ Phrygian with the I chord coming from Phrygian Dominant, or bII I bIII if you prefer to look at analysis from the perspective of the major scale.
Comment: @seanreads Phygian is a very distinct mode where the I, II, and III chords are very important to the mode and really defines and establishes it. The II chord (in this case G major) leads to the I chord very well. So strong in fact there's [a cadence named for it](http://dictionary.onmusic.org/terms/2586-phrygian_cadence). Even the F# being major is very distinctive to the commonly associated Phygian Dominant and this chord wouldn't make sense in G Lydian or A Mixolydian  nor does the progression in general fit it.
Comment: I see how you identified the Phrygian scale based on the notes in the chords. But, using your logic, couldn't one also make an argument for the G Lydian or A Myxoldian scales, which also encompass the same notes? How did you decide that F#maj should function as the I chord in this progression and therefore establish the Phrygian mode?
Answer: I believe the sad impression is most of all due to the chromatic descent B - A♯ - A embedded in these chords. It has a kind of disillusioning effect: you start out on a nice major third of the G chord. But then you drop down to F♯, whose A♯ third is enharmonic equivalent to the G chord's minor third. Normally this wouldn't be perceived as bluesy, because the F♯ would then be clearly a dominant to b minor. In your case, this resolution does not happen though, instead the supposed leading voice goes yet another semitone down, to the fundamental of A.
That in turn could be heard as a dominant to D. Or, alternatively, the chromatic descent could go on in the familiar way à la Hotel California.
Neither expectation is fulfilled, instead we go back to G which has now a sort of anticlimactic subdominant character to it.
Answer: All three chords are major, consonant chords. But, there is no strong resolution that identifies a tonic chord. If in the key of G Major, it could be written I - VII - II. But the VII and II are non-diatonic to the G Major key and so do not set up a strong tonality with G Major chord as Imaj. (In contrast, the diatonic versions of these chords, VIIdim and IImin, would be dissonant and could be resolved to Gmaj functioning as the tonic (I) chord.)
So - to my ears the sound is "unresolved consonance," a progression of major chords troubled by the uncertainty of "where is home?".
Comment: You would never find II or VII in a major key as it is much outside the functional harmony of a major key. Even if you see let's just say a D major chord in the key of C major, it's not functioning as a II, but instead a V/V (the dominant chord of the dominant.)
Comment: @Dom: well, Pythagoreically speaking, the `ii` degree is basically _defined_ as the secondary dominant. Only if you stay in a single diatonic scale, the `ii` chord is rendered as minor and thus doesn't function as `V/V`, but using the secondary dominant and labelling it `II` is fine and common.


chrome doesn't show up css images

Question: I have a menu bar which is included in an ascx file, which I've styled with the following css:
.Menu
{
    background:transparent url(../images/blueslate_background.gif) repeat-x;
    text-align:center;
    font-family : "lucida grande", tahoma, verdana, arial, sans-serif;
    font-size:12px;
    font-weight:bold;
    border: None 0px #fff !important;
}

.menuhover
{
     color:#fff;background:transparent url(../images/blueslate_backgroundOVER.gif) repeat-x left center;
}

This is my control MenuControl.ascx design source:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl" %>
<link rel="stylesheet" href="css/Menu3.css" type="text/css" />

    <asp:Menu ID="Menu1" runat="server" Orientation ="Horizontal"  CssClass="Menu"
        ForeColor ="Black" Width="100%" ScrollDownText="">
     <StaticMenuItemStyle Height ="40px"/>
    <DynamicMenuItemStyle CssClass ="Menu" Height="30px" HorizontalPadding="10px"  />
    <dynamichoverstyle  CssClass ="menuhover"/>
    <StaticHoverStyle CssClass ="menuhover"/>
   <%--<Items>
            <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" Value="Home">
            </asp:MenuItem>
            <asp:MenuItem NavigateUrl="~/Register.aspx" Text="Register" Value="Register">
            </asp:MenuItem>
<asp:MenuItem Text="Services" Value="Services" NavigateUrl="#">
    <asp:MenuItem Text="Corporate Services"
        Value="Corporate Services"  NavigateUrl="#"></asp:MenuItem>
    <asp:MenuItem Text="New Item"
        Value="New Item"></asp:MenuItem>
</asp:MenuItem>
            <asp:MenuItem NavigateUrl="#" Text="Tools" Value="New Item">
                <asp:MenuItem NavigateUrl="#" Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet"></asp:MenuItem>
                <asp:MenuItem NavigateUrl="#" Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet"></asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#">
                </asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#"></asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#"></asp:MenuItem>
            </asp:MenuItem>
            <asp:MenuItem NavigateUrl="#" Text="Important Links" Value="New Item">
                <asp:MenuItem NavigateUrl="#" Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet"></asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#"></asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#"></asp:MenuItem>
            </asp:MenuItem>
            <asp:MenuItem NavigateUrl="#" Text="Acts" Value="New Item">
                <asp:MenuItem NavigateUrl="#" Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet"></asp:MenuItem>
                <asp:MenuItem Text="Lorem ipsum dolor sit amet"
                    Value="Lorem ipsum dolor sit amet" NavigateUrl="#"></asp:MenuItem>
            </asp:MenuItem>
            <asp:MenuItem Text="Rules" Value="Rules" NavigateUrl="#"></asp:MenuItem>
            <asp:MenuItem Text="Circulars" Value="Circulars" NavigateUrl="#"></asp:MenuItem>
            <asp:MenuItem Text="Notification" Value="Notification" NavigateUrl="#"></asp:MenuItem>
            <asp:MenuItem Text="Forms" Value="Forms" NavigateUrl="#"></asp:MenuItem>
        </Items>--%>
    </asp:Menu>

The menu display differently dependnent on which browser I use.
1) Chrome:

2) Internet Explorer:

3) Mozilla:

Only Mozilla displays the menu correctly. What am I doing wrong?
Comment: what about Internet explorer?
Comment: it's display correctly after publishing web site. but at visual studio run time localhost it's not displays sub menus.
Comment: @Ravimallya - ya i found one post on http://productforums.google.com/forum/#!topic/chrome/swvyErUBfzY
Comment: glad to know that you found the solution for your issue.
Answer: ya found solution here link
here i have to include this code for chrome
 protected void Page_PreInit(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if ((Request.UserAgent.IndexOf("AppleWebKit") > 0) || (Request.UserAgent.IndexOf("Unknown") > 0) || (Request.UserAgent.IndexOf("Chrome") > 0))
            {
                Request.Browser.Adapters.Clear();
            }
        }
    }

and For IE8 there is a special hotfix for ASP.NET 2.0. Here is it: http://support.microsoft.com/kb/962351

chrome doesn't show up css images


What are the available image sliders?

Question: I want to know what sliders are available for Drupal 7, and which ones can be used in blocks.
Answer: See handbook page Comparison of Rotator / Slider modules.

What are the available image sliders?


If $f,g: R^n \to R^3$, what is the derivative of the cross product $(f \times g)(\vec{a})$ where $\vec{a} \in R^n$?

Question:
If $f,g: R^n \to R^3$ are differentiable functions at $\vec{a}$, what is the derivative of the cross product $(f \times g)(\vec{a})$ where $\vec{a} \in E$ and $E$ is open in $R^n$?

I have deduced that for the case $n=1$, we have
$$ (f \times g)'(\vec{a}) = f'(\vec{a}) \times g(\vec{a}) + f(\vec{a}) \times g'(\vec{a}).$$
Does the case $n > 1$ need to be evaluated separately or does the above result hold for all $n$?
Comment: Do you mean $(f \times g)'(\vec{a}) = f'(\vec{a}) \times g(\vec{a}) + f(\vec{a})\times g'(\vec{a})?$. For $n>1$ what do you mean by $f'?$
Comment: Yes, corrected. For $n > 1$, I'm wondering if there is an analogous statement for functions of several variables.
Answer: $\newcommand{\Reals}{\mathbf{R}}$In general, if $B$ is a bilinear function on $\Reals^{m}$, and if $f$, $g:\Reals^{n} \to \Reals^{m}$ are continuously-differentiable, then for all points $a$, $b$ in $\Reals^{n}$ and all vectors $u$ and $v$ in $\Reals^{n}$, there is a "Leibniz rule"
$$
\bigl[D\bigl(B(f, g)\bigr)(a, b)\bigr](u, v)
  = B\bigl(Df(a)(u), g(b)\bigr) + B\bigl(f(a), Dg(b)(v)\bigr).
$$
Indeed, $f(a + tu) = f(a) + tDf(a)(u) + o(t)$ and $g(b + tv) = g(b) + tDg(b)(v) + o(t)$, so
\begin{align*}
\bigl[D\bigl(B(f, g)\bigr)(a, b)\bigr](u, v)
  &= \frac{d}{dt}\bigg|_{t=0} B\bigl(f(a + tu), g(b + tv)\bigr) \\
  &= \frac{d}{dt}\bigg|_{t=0} B\bigl(f(a) + tDf(a)(u) + o(t), g(b) + tDg(b)(v) + o(t)\bigr) \\
  &= B\bigl(Df(a)(u), g(b)\bigr) + B\bigl(f(a), Dg(b)(v)\bigr),
\end{align*}
the final equality being a straightforward consequence of bilinearity.


Como corrigir imagem com "baixa qualidade" no Listview

Question: Galera eu estava usando o código abaixo para criar thumbnail de vídeo e mostrar em um ListView:
Dim cont As Integer = 0
    Dim thumbnail As New ImageList With {.ImageSize = New Size(200, 200)}
    Dim caminho_saida As String = "C:\..."
    Dim caminho_thumb As String
    Dim name_arquivos As String
    Dim xx As Image

    For Each zz In FileIO.FileSystem.GetFiles(caminho_saida)
        My.Computer.FileSystem.DeleteFile(zz)
    Next

    FolderBrowserDialog1.ShowDialog()

    Try
        For Each caminho_videos In FileIO.FileSystem.GetFiles(FolderBrowserDialog1.SelectedPath, FileIO.SearchOption.SearchAllSubDirectories, "*.mp4")
            name_arquivos = System.IO.Path.GetFileNameWithoutExtension(caminho_videos)
            caminho_thumb = caminho_saida + name_arquivos + ".png"

            Try
                Dim ffMpeg = New NReco.VideoConverter.FFMpegConverter()
                ffMpeg.GetVideoThumbnail(caminho_videos, caminho_thumb, 20)
            Catch ex As Exception
                MsgBox(caminho_videos)
            End Try

            Using str As Stream = File.OpenRead(caminho_thumb)
                xx = Image.FromStream(str)
                thumbnail.Images.Add(xx)
            End Using

            ListView1.LargeImageList = thumbnail
            ListView1.Items.Add(name_arquivos, cont)

            cont += 1
        Next
    Finally
    End Try

O problema é que o resultado no ListView é uma imagem "ruim", sendo que a original tem a qualidade do arquivo original.

O que eu gostaria e de saber como eu concerto isso.
Comment: Não será o método `GetVideoThumbnail` que está a trazer uma imagem de fraca qualidade? Ou se abrir a imagem manualmente ela tem boa qualidade mas só quando coloca na `ListView` é que passa a ficar fraca?
Comment: Exatamente! Apenas quando coloco no listview que perde qualidade. Ex: Ná imagem acima à esquerda está o listview e olha como a última imagem da Paramount está ruim, já ná direita está a versão original da imagem que é jogada no listview (a imagem que sai do GetVideoThumbnail).
Comment: No PictureBox a imagem fica normal, mas no Listview não.
Answer: Tente criar a imagem com a gestão de cores original:
Dim imagem As Image = Image.FromFile(strImagem, True)

Se mesmo assim não ficar como pretende, implemente o seguinte método:
Private Function RetornaImagemComQualidade(ByVal strImagem As String) As Image
    Dim imagem As Image = Image.FromFile(strImagem, True)
    Dim objBitmapImagem As Bitmap = New Bitmap(imagem.Width, imagem.Height, PixelFormat.Format24bppRgb)

    objBitmapImagem.SetResolution(imagem.HorizontalResolution, imagem.VerticalResolution)

    Dim objGraphicsImagem As Graphics = Graphics.FromImage(objBitmapImagem)

    objGraphicsImagem.Clear(SystemColors.Control)
    objGraphicsImagem.CompositingQuality = CompositingQuality.HighQuality
    objGraphicsImagem.InterpolationMode = InterpolationMode.HighQualityBilinear
    objGraphicsImagem.SmoothingMode = SmoothingMode.HighQuality

    objGraphicsImagem.Dispose()

    Return objBitmapImagem
End Function

Passando o caminho da sua imagem por parâmetro.
Edit
Só reparei agora que está a utilizar uma ImageList para guardar as imagens antes de as colocar na ListView. Experimente fazer o seguinte:
thumbnail.ColorDepth = ColorDepth.Depth32Bit

Outra solução passa por não fazer o resize das imagens na ImageList e mantê-las do mesmo tamanho, fazendo isso depois apenas na ListView.
Comment: Ambos não funcionam. O primeiro tem o mesmo resultado e o segundo retorna todas as imagens em um tom claro de cinza.
Comment: Com a primeira opção no PictureBox a imagem fica normal, mas no listview não.
Comment: Na segunda opção altere o "SystemColors.Control" para "Color.Transparent".
Comment: Imagens agora estão todas pretas.
Comment: Está difícil... e se retirar essa linha do Clear()?
Comment: quando mudei eu fiz esse teste também e continuou tudo preto. Eu fiz um redimensionamento da imagem para um tamanho (256, 256) e mostrei a mesma
imagem no Listview e no Picturebox, mas a imagem ficou boa no picturebox e ruim no Listview. Não teria alguma ideia do que poderia ser?
Comment: Edição feita na resposta. O facto de estar a utilizar uma `ImageList` pode ser o problema.


How to send arrays between threads using pipes?

Question: I have three threads - the first one reads sentences until ";" is given, the second counts the characters in those sentences, and the third shows the result.
Well, I've done this for only one sentence, but sending arrays through pipes seems to generate some problems (as well as reading multiple strings from a thread).
For reading, I can put the string only once, and no more. Even mutex on the whole function doesn't work. Why is that so?
Also, after writing the string I get "write: Success" message.
What's wrong here?
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#include <pthread.h>
#include <string.h>

int first[2];
int second[2];

void *input(void *ptr)
{
   char str[100], ch = '0';
   int length, i = 0;

   while(1)
   {
      while(ch != ';')
      {
         printf("Enter the %d message: ", i + 1);
         fflush(stdout);
         length = read(STDIN_FILENO, str, sizeof(str));

         if(write(first[1], str, sizeof(str)) != length)
         {
            perror("write");
            exit(2);
         }

     if(length <= 0)
         {
            if(length == -1)
               perror("read");
            close(first[1]);
            exit(2);
         }

         i++;
      }
   }
}

void *countChars(void *ptr)
{
   char str[100];
   int length, count = 0, i = 0;

   while(1)
   {
      length = read(first[0], str, sizeof(str));

      if(length <= 0)
      {
         if(length == -1)
            perror("read");
         close(first[0]);
         close(second[1]);
         exit(2);
      }
      if(write(STDOUT_FILENO, str, length) != length)
      {
         perror("write");
         exit(2);
      }

      while(str[count] != '\n') count++;

      write(second[1], &count, sizeof(count));

      count = 0;
   }
}

void *output(void *ptr)
{
   int length, count = 0, i = 0;

   while(1)
   {
      length = read(second[0], &count, sizeof(count));
      if(length < sizeof(count))
      {
         close(second[0]);
         exit(2);
      }

      printf("Number of characters: %d\n", count);
   }
}

int main()
{
   pthread_t t1, t2, t3;

   if(pipe(first) == -1)
   {
      printf("First pipe error");
      exit(1);
   }

   if(pipe(second) == -1)
   {
      printf("Second pipe error");
      exit(1);
   }

   pthread_create(&t1, NULL, input, NULL);
   pthread_create(&t2, NULL, countChars, NULL);
   pthread_create(&t3, NULL, output, NULL);

   pthread_join(t1, NULL);
   pthread_join(t2, NULL);
   pthread_join(t3, NULL);

   return 0;
}

EDIT.
I think the question would be - how to logically solve this? I see it that way:
Thread1 -> (string) -> Thread2 -> (number of chars) -> Thread3 - save elements somewhere
...
Thread1 -> (ending string) -> Thread2 -> (number of chars removed later) -> Thread3 - display all elements

BUT if so then - how to make threads run one by one like this? How to stop the application on ending string? Where to save those integer values in thread 3?
Comment: off topic: Why is everything downvoted?
Comment: good question, no idea
Comment: Please edit you question clearly stating your problem. Do you want to fix the logic or the "Write: Success"? Because the way you send data through pipe is correct.
Answer: In the input thread, after the read call length = read(STDIN_FILENO, str, sizeof(str));, you are writing sizeof(str) and not of size length.
It should be
if(write(first[1], str, length) != length)

Another issue is your code is not matching your specification.
You say that input thread is reading until ';', but ch is never modified in the loop. Fix your code.
Comment: Oh, right, I didn't see that one, thanks. But if so, the loop should be going forever, yet it stops after the first run.
Comment: It stops after first run, because you have exit on failure. But because of incorrect length matching, even succeess case entered the failure path and printed 'write: Success"!
Answer: Pipes are used to communicate data between processes, not threads. Threads run in the same process and have access to the same memory so it is pointless to use pipes in that case.
An example of a pipeline with three processes. Parent sends "hello world" to child, who prepends the string length and sends that new string to the grandchild who prints it to stdout.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void parent(int fd_write) {
    char *msg = "hello world";
    ssize_t len = strlen(msg);
    if (write(fd_write, msg, len) != len) {perror("parent write"); exit(1);}
}

void child(int fd_read, int fd_write) {
    char msg_in[100], msg_out[150];
    ssize_t len = read(fd_read, msg_in, sizeof msg_in);
    if (len == -1) {perror("child read"); exit(1);}
    msg_in[len] = '\0';
    len = sprintf(msg_out, "%d: %s", (int)len, msg_in);
    if (write(fd_write, msg_out, len) != len) {perror("child write"); exit(1);}
}

void grandchild(int fd_read) {
    char msg[256];
    ssize_t len = read(fd_read, msg, sizeof msg);
    if (len == -1) {perror("grandchild read"); exit(1);}
    msg[len] = '\0';
    printf("Msg: %s\n", msg);
}

int main() {
    enum {READ, WRITE};
    pid_t pid;

    int fd[2];
    if (pipe(fd) == -1) {perror("first pipe"); exit(1);}

    pid = fork();
    if (pid == -1) {perror("first fork"); exit(1);}

    if (pid == 0) {
        int fd2[2];
        if (pipe(fd2) == -1) {perror("second pipe"); exit(1);}

        pid = fork();
        if (pid == -1) {perror("second fork"); exit(1);}

        if (pid == 0) {
            close(fd2[WRITE]);
            grandchild(fd2[READ]);
            close(fd2[READ]);
            exit(0);
        }

        close(fd[WRITE]); close(fd2[READ]);
        child(fd[READ], fd2[WRITE]);
        close(fd[READ]); close(fd2[WRITE]);
        wait(NULL);
        exit(0);
    }

    close(fd[READ]);
    parent(fd[WRITE]);
    close(fd[WRITE]);
    wait(NULL);

    return 0;
}

Comment: IMO you did not answer the question you just changed OP's program to suit your opinion on the use of pipes, an opinion I think wrong for many applications.
Comment: Very true. If anything, you might pass a pointer to the array via a pipe (which will be valid in another thread of the same process), not the actual array. But even that can be done more efficiently without pipes. You really only want pipes for process-process, not thread-thread.
Comment: The downvoters aren't expressing the reason for their disagreement.
Comment: @TranslucentPain Fair enough. Thank you for commenting. I just didn't see the sense of pipes in the OP's case. I thought maybe he meant to create a normal pipeline. But he could just be playing with threads and pipes.


problemas em pega um ID especifico e checar se na outra tabela existe

Question: estou criando um sistema de controle, onde tenho 3 níveis de usuario, sendo: admin, aluno e diretor.
no sistema o usuario adiciona links e consegue acompanha o progresso da mesma, como: views,curtidas,comentarios e etc.. estou criando a view do admin para ta listando os dados do usuario como escrito acima, mais pode acontecer do usuario ter mais de um link e sera necessario mostra todos eles, minha dificuldade é trazer todos esses links, no momento so estou conseguindo trazer apenas uma.
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Bom dia, pelo o que entendi, a questão pode estar no where, ao invés de:
pessoas_has_links.id

deveria ser
pessoas_has_links.links_id

ficando assim:
links.id = pessoas_has_links.links_id

Desse modo, deverá ser retornado todos os registros que contenha o mesmo link. Ou então, mude links.id para links.pessoa_id ficando:
links.pessoa_id = pessoas_has_links.pessoas_id

Para que retorne todos os dados referente ao usuário especificado.
Verifique também se o join usado não pode estar interferindo nos resultados.
Comment: Bom dia, certo. na tabela "pessoas_has_links" na coluna "pessoa_id" o id se repete isso mostra que aquele usuario em especifico possui mais de um link, é isso que gostaria de checar pega o usuario(5) e visualizar quantos links ele possui. tentei da maneira que você mostrou acima mais trouxe todos os links de todos os usuarios.
Comment: @willianpereira você testou os dois? Verifique tbm se não seria outro tipo de join, talvez, o right
Comment: apenas o primeiro, mas fiquei na duvida, não seria necessário  especifica o id(5) para fazer essa ação? pra ele trazer somente esse usuario.
Comment: Tente o segundo tbm. Aí em pessoas_has_links.pessoas_id coloque o id do usuário.
Comment: na tabela "links" tenho a coluna "id" posso alterar ela pra "pessoa_id" sem problemas? e ao fazer isso a tabelas "pessoas_has_link" ja entende a conexão? ou terei que fazer manualmente ? sou novo em php haha
Comment: @willianpereira não indicaria, pois, a coluna id dessa tabela é o identificador dos registros dessa tabela e a tabela pessoas_has_links é quem faz a relação entre os registros da tabela link com a tabela pessoas. Indicaria estudar um pouco sobre relacionamentos SQL.
Comment: certo, muito obrigada


$P(X > Y) = ?$ when $X,Y \stackrel{iid}{\sim} \text{Bin} \left(n, \frac{1}{2} \right)$

Question: If $X,Y \stackrel{iid}{\sim} \text{Bin} \left(n, \frac{1}{2} \right)$, how do I calculate $P(X^2 > Y^2)$ or $P(X^2 = Y^2)$?
Attempt:
$\begin{aligned}
P(X^2 > Y^2) &= P((X-Y)(X+Y) > 0) = P((X-Y) > 0) \cdot P((X+Y) > 0) + P((X-Y) < 0) \cdot P((X-Y) < 0) \\
&= [ \cdots ]
\end{aligned}$
How do I calculate $P(X > Y)$? I think if I know this, I'll be able to do the rest of it.
[This is not a homework problem. I was doing a longer question and this part is bothering me for sometime.]
Comment: Your first computation is wrong : you do as id the random variables $X-Y$ and $X+Y$ were independent. Since $X$ and $Y$ are non-negative, the event $[X^2>Y^2]$ is the same as the event $[X>Y]$.
Answer: The random variable $n-Y$ has the same law as $Y$, and is independent of $X$ (like $Y$). Hence $(X,n-Y)$ has the same distribution as $(X,Y)$. Moreover, $X+Y$ is Binomial with parameters $2n$ and $1/2$. As a result
$$P[X=Y] = P[X=n-Y] = P[X+Y=n] = \frac{{2n \choose n}}{2^{2n}}.$$
Moreover, $(X,Y)$ has the same distribution as $(Y,X)$, so
$$2P[X>Y] = P[X>Y] + P[X<Y] = 1-P[X=Y] = 1-\frac{{2n \choose n}}{2^{2n}}.$$
Comment: For those reading too fast, you have to divide the final line by $2$ to answer the question
Answer: Another approach without complementary probability is simply summing all cases: iterating through all possibilities of $X$ and summing the probability that $Y$ is any number less than each value of $X$. In other words, by independence of $X$ and $Y$,
\begin{align*}
  P(X > Y) &= \sum_{i = 0}^n P(X = i) \cdot P(Y < i) \\
  &= \sum_{i = 0}^n P(X = i) \sum_{j = 0}^{i - 1} P(Y = j) \\
  &= \sum_{i = 0}^n \binom{n}{i} \frac{1}{2^n} \sum_{j = 0}^{i - 1} \binom{n}{j} \frac{1}{2^n} \\
  &= \frac{1}{2^{2n}} \sum_{i = 0}^n \binom{n}{i} \sum_{j = 0}^{i - 1} \binom{n}{j}
.\end{align*}
By binomial identities, the double sum is $2^{2n - 1} - \binom{2n - 1}{n}$, giving us
$$ P(X > Y) = \frac{1}{2} - \frac{1}{2^{2n}} \binom{2n - 1}{n} = \frac{1}{2} - \frac{1}{2^{2n + 1}} \binom{2n}{n}. $$
As Christophe Leuridan points out in the comments, this is also $P(X^2 > Y^2)$ because $X$ and $Y$ are non-negative.


Check if the user has read a node, if so give access to the next

Question: Is there a module which can check if an user has read a node? For example, I have this node:

Node order 1
Node order 2 (locked)
Node order 3 (locked)
Node order 4 (locked)

If the user read 'node order 1' or marked as read with a button, he has access to 'node order 2'. If 'node order 2' has marked as read, he has access to 'node order 3'.
It's all user based. It's similar to an e-learning structure, but I don't like heavy modules like: course or opigno for just this functionality.
Can I do something like this with rules or an other lightweight module? I saw the flag module, but I don't know if it possible to do something like this with that module?
Comment: Rules isnt exactly lightweight. I think you need at a minimum a table to hold nid/uid/read values, and create an entry when the node is viewed. On each node, add a reference field to hold the required node to read, and evaluate that too when viewing a node. It's probably not too hard to pull off.
Comment: What about the size of the table? If 1000 users each viewing 500 nodes I've a table with: 500.000 entries? Any ideas?
Comment: May be , Once the user has read all the nodes, deleted the entries in the table and set a new field with value stating user has read all nodes ?
So that you have only one entry per user if user has read all.
Comment: Yes, that could be one solution. Doing multiple writes shouldn't be too big of a deal. You'd have the same issue if 1000 users clicked a button that inserted records too. The size of the table doesn't necessarily matter, use good indices. There's probably a few ways to mitigate that, the scope of the question would need more focus to answer any one part in depth.
Comment: Is it a hard requirement that they've viewed node 1 before viewing node 2? or is it more like a recommendation?
Comment: It's an hard requirement.
Answer: I'd say you can use hook_ENTITY_TYPE_view to store the uid and the nid of the user into a custom table. That would solve the easy part, I believe.
You'd may start by something similar to
<code>function yourmodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity,
        \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $bundle = $entity->bundle();
  if($bundle == 'your_content_type') {
    $uid = \Drupal::currentUser()->id(); // get current user's ID
    $nid = $entity->get('nid');
    [...] // insert into custom table, etc
  }
}
</code>
For the long-term, complex solution regarding performance, that's a huge discussion. If your node list is just a simple queue that unlocks next node if previous has been read, then maybe storing just the current nid would work for you. If you need the history per user, then, as mentioned, some different solutions could do the trick. Other approach could be to do database sharding, for instance creating 1 table per node so table_read_nid_1 would just contain the users who actually have read this node and can unlock the second. table_read_nid_2 would contain the next and so on. Don't be afraid of sharding, lots of big companies use it daily! :)
Comment: Could you give me an example of the code: `hook_entity_type_view`?
Comment: Edited to add an initial snippet you could look at to start using the hook.


MS Access Query Command (NOT) vs (<>)

Question: Please educate me. What is the difference between using NOT rather than (<>)
<code>(NOT ([tblTitles].[locTitle])="xxx Avenue")
</code>
versus
<code>([tblTitles].[locTitle])<>"xxx Avenue")
</code>
Both examples seem to work fine I just don't know the "proper" thing to do or whatever is the acceptable practice.
Thank you,
Fred
Comment: they are the same thing. Use whichever expresses intent best.
Answer: In your example they are both equivalent and you can use the expression you prefer without any effects on the result.
But keep in mind that the NOT-operator is much more powerful as you can invert any expression with it. E.g. expressions using LIKE or IN, which result in criteria that can usually not be expressed any other way.
<code>... WHERE ProductCode NOT LIKE 'A*'

... WHERE ProductCode NOT IN ('A','B','C')
</code>
or you can apply it to the results of a sub-query:
<code>... WHERE ProductCode NOT IN (SELECT code FROM otherTable)
</code>

MS Access Query Command (NOT) vs (<>)


Finding the Eclipse Project file location

Question: I have an android project running in Eclipse IDE. Lets say it is 'ABC Project'. Some of my collieges have made number of copies of this project, so the project files can be seen in desktop, C://, D:// and even in eclipse work space. Now I don't know project in which location I am running because they have deleted and imported the project folder to eclipse using this copies and they can't remember whether they selected the option 'make a copy to the workspace'.. How can I get this location? I tried to right click on the project and see any option is there but no. Manually finding it using java code (getAbsolutePath()) will return no good, it will return the path in the phone.
Please help.
Comment: Did you try right click on project ->Properties->Resources ? You will be able to see the path there.
Comment: @AdityaKamath: Perfect! It shows the location as workspace, so this is the location of the project right?
Answer: Did you try right click on project ->Properties->Resources ? You will be able to see the Project path there.
Answer: Right Click on project and click on Resources.
In that it shows the location where it is .
Find it out dude :)
Answer: Properties -> Resource -> Linked Resources -> PROJECT_LOC
Answer: Use Alt+Enter on the project Name in Eclipse to see the complete path of the project directory where it resides.


Sum values of same Id in a Json Array using JS

Question: I have a json array with Id and age as follows
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

I want to get sum of age which belong to same id which will be as follows
1 = 20
2 = 50
3 = 20
5 = 10

Please find the below code
$scope.TestFunc = function()
{
var tot = 0;
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
for(var i=0; i <arrayVal.length; i++ )
{
  for(var j=1; j<arrayVal.length - i; j++ )
  {
    if(arrayVal[i].id == arrayVal[j].id)
    {
      tot = arrayVal[i].age.valueOf() + arrayVal[j].age.valueOf();
    }
    else{
      tot = tot + arrayVal[i].age;
    }
  }
}
console.log("-----total----"+tot);
}

I don't receive the expected output. the console shows the output as 202020. What has gone wrong in the above code?
Comment: I've rolled back your edit. Please don't invalidate your question after it has been answered by fixing the code in the question.
Answer: With a simple reduce() operation:

const array = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

const ages = array.reduce((a, {id, age}) => (a[id] = (a[id] || 0) + +age, a), {});

console.log(ages);

Besides the reduce solution being more compact and declarative, the main problem with the code provided is due to coercion. One of the age values has the string "20", forcing the subsequent + operations to be interpreted as string concatenation.
This answer avoids this unexpected side-effect using the +age, forcing age to be a Number (this could be made explicit by doing Number(age) instead).
Comment: var arrayVal = [{id:"1", sAge: 20, eAge:30},{id:"2", sAge: 30, eAge:50},{id:"2", sAge: 20, eAge:40},{id:"3", Aage: 20, eAge:50},{id:"5", sAge: 10, eAge:30}]; If I have an array like this how can get the diff between each sAge and eAge of each id and sum them seperately?
Comment: That should be asked as a new question, but the same principles apply.
Answer: The age must be number. It should not be as a string. In your code, id:2 has 20 as string. Kindly check with datatype in arrayVal.
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: 20},{id:"3", age: 20},{id:"5", age: 10}];
$scope.TestFunc = function()
{
var tot = 0;
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: 20},{id:"3", age: 20},{id:"5", age: 10}];
for(var i=0; i <arrayVal.length; i++ )
{
  for(var j=1; j<arrayVal.length - i; j++ )
  {
    if(arrayVal[i].id == arrayVal[j].id)
    {
      tot = arrayVal[i].age.valueOf() + arrayVal[j].age.valueOf();
    }
    else{
      tot = tot + arrayVal[i].age;
    }
  }
}
console.log("-----total----"+tot);
}

Answer: I've prepared another answer using Array#reduce method which returns array of objects instead of simple array:

const arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

let summedAges = arrayVal.reduce((a, c) => {
 let filtered = a.filter(el => el.id === c.id);
 if(filtered.length > 0){
  a[a.indexOf(filtered[0])].age += +c.age;
 }else{
  a.push(c);
 }
 return a;
}, []);

console.log(JSON.stringify(summedAges));


Drag and Drop Image in Layout

Question: I have 10X4 table with in that some cell have image, need to drag and drop image in side table in cells. how to find already cell has image or not?
My Code: for creating cells, drag and drop.
public class WhiteFragment extends Fragment {
    View mView;
    private TableLayout Table1;
    ImageView img;

    int[] imageArray = {R.drawable.a, R.drawable.a, R.drawable.a, R.drawable.a};

    LinearLayout layout;
    View parentView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_white, container, false);

        Table1 = (TableLayout) mView.findViewById(R.id.table);
        for (int i = 0; i < 4; i++) {
            TableRow TR = new TableRow(getActivity());

            for (int j = 0; j < 10; j++) {
                LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View row = layoutInflater.inflate(R.layout.table_image, null, false);
                img = (ImageView) row.findViewById(R.id.ivImage);
                layout=(LinearLayout) row.findViewById(R.id.layout);

                if(j%2==0)
                img.setImageResource(imageArray[i]);
                layout.setOnTouchListener(new MyTouchListener());
                layout.setOnDragListener(new MyDragListener());

                TR.addView(row);

            }
            Table1.addView(TR);
        }
        return mView;
    }

    float x, y = 0.0f;
    boolean ismoving;

    private final class MyTouchListener implements View.OnTouchListener {
        public boolean onTouch(View view, MotionEvent motionEvent) {

           switch (motionEvent.getAction()){
               case MotionEvent.ACTION_DOWN:
                   Log.e("owner status","down");
                   break;
               case MotionEvent.ACTION_MOVE:
                   Log.e("owner status","move");
                   ClipData data = ClipData.newPlainText("", "");
                   View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
                   view.startDrag(data, shadowBuilder, view, 0);
                   view.setVisibility(View.INVISIBLE);

                   break;
               case MotionEvent.ACTION_UP:
                   Log.e("owner status","up");
                   break;
           }
           return true;
        }
    }

    class MyDragListener implements View.OnDragListener {

        @Override
        public boolean onDrag(View v, DragEvent event) {
            int action = event.getAction();
            switch (event.getAction()) {
                case DragEvent.ACTION_DRAG_STARTED:
                    break;
                case DragEvent.ACTION_DRAG_ENTERED:
                    break;
                case DragEvent.ACTION_DRAG_EXITED:
                    break;
                case DragEvent.ACTION_DROP:
                    // Dropped, reassign View to ViewGroup
                    View view = (View) event.getLocalState();
                    ViewGroup owner = (ViewGroup) view.getParent();
                    owner.removeView(view);
                    LinearLayout container = (LinearLayout) v;

                    if(owner.getChildCount()==0)
                        container.addView(view);
                   else owner.addView(view);
                    view.setVisibility(View.VISIBLE);
                    break;
                case DragEvent.ACTION_DRAG_ENDED:
                default:
                    break;
            }
            return true;
        }
    }
}

xml code:
 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/table_border">
       <LinearLayout
           android:id="@+id/layout"
           android:layout_width="120dp"
           android:layout_height="120dp">
        <ImageView
            android:id="@+id/ivImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp" />
       </LinearLayout>
    </LinearLayout>

suggest your logics..thanks
Answer: Yes, I solved this using setTag for elements and while drag checking status of that tag in Saved List.
Answer: use this code
in Activity
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();

tv1 = (ImageView)findViewById(R.id.image);
tv1.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        layoutParams1 = (RelativeLayout.LayoutParams) tv1.getLayoutParams();
        switch(event.getActionMasked())
        {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int x_cord = (int) event.getRawX();
                int y_cord = (int) event.getRawY();
                if (x_cord > windowwidth) {
                    x_cord = windowwidth;
                }
                if (y_cord > windowheight) {
                    y_cord = windowheight;
                }
                layoutParams1.leftMargin = x_cord - 25;
                layoutParams1.topMargin = y_cord - 75;
                tv1.setLayoutParams(layoutParams1);
                break;
            default:
                break;
        }
        return true;
    }
});

tv2 = (ImageView)findViewById(R.id.image1);
tv2.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        layoutParams2 = (RelativeLayout.LayoutParams) tv2.getLayoutParams();
        switch(event.getActionMasked())
        {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int x_cord = (int) event.getRawX();
                int y_cord = (int) event.getRawY();
                if (x_cord > windowwidth) {
                    x_cord = windowwidth;
                }
                if (y_cord > windowheight) {
                    y_cord = windowheight;
                }
                layoutParams2.leftMargin = x_cord - 25;
                layoutParams2.topMargin = y_cord - 75;
                tv2.setLayoutParams(layoutParams2);
                break;
            default:
                break;
        }
        return true;
    }
});

XML File:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView android:layout_width="50sp" android:layout_height="50sp"
        android:id="@+id/image" android:src="@drawable/image">
    </ImageView>
    <ImageView android:layout_y="30dip" android:layout_x="118dip"
        android:layout_width="50sp" android:layout_height="50sp" android:id="@+id/image1"
        android:src="@drawable/image1">
    </ImageView>
</RelativeLayout>

Answer: i would do it like this.
   int[] newLocation = new int[2];
    button.getLocationOnScreen(newLocation);
    int x = newLocation[0];
    int y = newLocation[1];
    imageView.setX(x);
    imageView.setY(y);

Also you can override onTouch listener and get position . but use setX() and setY()
Comment: posted updated code its working drag and drop into other cells but how to check destination cell has image or not?
Comment: you can use getChildCount() and getChildAt(int location) on your linear layout

Drag and Drop Image in Layout


Moment generating functions and distribution: the sum of two poisson variables

Question: We have two random variables $Y_1\sim Poisson(\lambda_1)$ and $Y_2\sim Poisson(\lambda_2)$.
And I know that the moment-generating function $m(t)$ for a random variable with parameter $\lambda$ is $$m(t)=e^{\lambda(e^t -1)}$$
How may I use the moment-generating functions to determine the distribution of $Y_1+Y_2$? Thank you very much.
Answer: The moment-generating function $m_X(t)$ of the random variable $X$ is actually $\mathbb{E} [e^{tX}]$.
This means: The moment-generating function of $Y_1 + Y_2$ is
$\mathbb{E} [e^{t(Y_1 + Y_2)}] = \mathbb{E} [e^{tY_1} e^{tY_2}]$.
If $Y_1$ and $Y_2$ are independent , then $\mathbb{E} [e^{tY_1} e^{tY_2}] = \mathbb{E} [e^{tY_1}]\mathbb{E} [e^{tY_2}]$.
Now you plug the moment-generating functions of $Y_1$ and $Y_2$ (which you already know) into this and you get the moment-generating function of $Y_1 + Y_2$. What is left is to deduce the actual distribution of $Y_1 + Y_2$.
Comment: "or uncorrelated, resp." No.
Comment: Ok, thanks. I edited my answer. I thought that since for $\mathbb{E}[Y_1 Y_2] = \mathbb{E}[Y_1] \mathbb{E}[Y_2]$ it suffices for the two variables to be uncorrelated, it also suffices here. I guess, that was wrong.
Comment: Independence implies uncorrelated, but sadly the converse is not true in general. Another note: of course you showed this, but it might be useful to explicitly state: $M_{X+Y}(t) = M_X(t)M_Y(t)$.


What's the benefit of using multiple measurement threads?

Question: I just noticed that JMH allows us to use multiple measurement threads (by default, only one thread is used).
What's the point of using multiple measurement threads? Is it only meant to test thread contention in the code being benchmarked? Or will the benchmarks complete any sooner?
Answer: Threads in JMH are about testing concurrent code on a microbenchmark-level, for example if you want to compare a lock to using compare-and-swap against a shared resource.
In general, JMH needs to run code sufficiently often to for example trigger JIT compilation but in my understanding this would rather be a side-effect. If your application is single-threaded and you run a multithreaded benchmark, it would not be representative of your application even if it ran faster.


iptables rule order

Question: I have noticed the following iptables rule order executed by a program:
iptables -A INPUT -p all -j ACCEPT

iptables -A INPUT -p all -s ip_address -j REJECT

I thought that based on the ordering principle of iptables, this would lead to the second line being ignored (ie. the ip_address will not be rejected because all connections are already accepted by the first line). Does it mean that this program is misconfigured?
Thanks in advance
Comment: yup, you're right! test it to verify.
Comment: Ya i tested it but i wasn't sure if I missed something. It confuses me when a reputable program does something unexpected. thanks for your confirmation!
Answer: Yes, the rules will be executed in that order. Assuming there are no other interrelated rules not displayed in your question, this won't deny the host with -s ip_address ip address. If you want that ip address to be rejected, replace -A (Append) with -I (Insert).
/sbin/iptables -I -p all -s ip_address -j REJECT

iptables rule order


Spring Boot "schema.sql" When Using JPA

Question: When utilizing 'Spring Data JPA' the schema is created automatically if you have '@Repository' and '@Entity' annotated classes. Is there any reason why I may want to have the addition of a 'schema.sql' file in the resources folder? There does not seem to have any conflict if you happen to have it present. If so, which takes precedence in creating the structure of the database (tables, columns, etc)? JPA or the 'schema.sql' file when present?
Comment: squema? do you mean schema?
Comment: Correct... typo. Thanks.
Answer: I found an answer according to the link below:
Database Initialization on Spring Boot
" In a JPA-based app, you can choose to let Hibernate create the schema or use schema.sql, but you cannot do both. Make sure to disable spring.jpa.hibernate.ddl-auto if you use schema.sql."

Spring Boot "schema.sql" When Using JPA


what is the criteria to chose the squad of PSL teams and how this is different from IPL

Question: I am a cricket fan but I have little bit confusion that how Pakistani franchises select the players in psl and how Indian franchises select the player basically I want to know that how ipl selection criteria is different from psl selection criteria in draft.
Answer: These all things are based on your cricket management system. what criteria the player should have depend upon your team cricketing staff. Here is the reference of the site that will help u and make your confusion clear..
http://sportsmaza.com/cricket/pakistan-super-league-psl-vs-ipl-indian-premier-league/


Get entries stored in database from yesterday

Question: I have an SQL statement that gets me some data based on today's date and it fills it in linkbutton.Text. If there is not enough data for today, it should fill it with the data from yesterday. Here is the SQL statement I've written so far:
"SELECT * FROM table1 WHERE cat = 1 and datee = @dt ORDER BY datee DESC ";

Comment: Would be best to drop the `datee` where clause and just add a `TOP(x)` selection to get how many results you deem to be acceptable
Answer: I would suggest rather than limiting the date, just decide how many results you want and select the TOP(x) number of them:
For example, if you want the 20 most recent results starting today and going back to tomorrow (and further) if needed, you can do this:
"SELECT TOP(20) * FROM table1 WHERE cat = 1 ORDER BY datee DESC ";

If you pottentially have dates in the future you can limit them by adding the following where clause:
"SELECT TOP(20) * FROM table1 WHERE cat = 1 AND datee <= @dt  ORDER BY datee DESC ";

Where @dt is Today's date

Of course if you rules are more specific, i.e you should return 24 results if Today has 24 entries, or you don't want the total restricted in such a way, then I would suggest doing two queries, for example:
var results = GetResultsForToday();

if(results.Count() < 20)//not enough!
    result.Add(GetResultsForYesterday());

Answer: Or you could use BETWEEN aside from TOP statement like:
SELECT TOP(10) * FROM table1 WHERE cat = 1 and
datee BETWEEN DATEADD(day, -1, @dt) AND @dt
ORDER BY datee DESC


React Hooks SetState Method isn't updating the state at all

Question: I am using a Material UI Select Component to render a simple drop down menu, with its value as a state declares using the useState method.
    const [collaboratingTeams, setCollaboratingTeams] = useState([])

The below code is of the Select Component, with its value and the corresponsing handler function in its onChange prop.
                 <Select
                    validators={["required"]}
                    errorMessages={["this field is required"]}
                    select
                    multiple
                    variant="outlined"
                    value={collaboratingTeams}
                    name="collaboratingTeams"
                    onChange={(e) => handleSelectCollaboratingTeams(e)}
                    helperText="Select Collaborating Teams    "

                >
                    {arrTeams.map((option, index) => (
                    <MenuItem
                   key={option.teamId}
                  value={option.teamId}
                 variant="outlined"
                 >
               <Checkbox
              checked={collaboratingTeams.indexOf(option.teamId) !== -1}
            />
           <ListItemText primary={option.teamValue} />
        </MenuItem>
        ))}
      </Select>

The below code is the function that triggers when a drop down data is changed.
This function sets the state, which should then technically update the Select's selected options.
const handleSelectCollaboratingTeams =(e)=>{
        setCollaboratingTeams(e.target.value)
 }

The issue is, the setCollaboratingTeams method isn't updating the state only. I understand that the setstate method in hooks works so coz of its asynchronous nature but at some point it should display up right. Don't understand where I'm going wrong.
I expect the collaboratingTeams array to be updated with a new value when a new value is selected by the user.
Comment: i have a guts feeling that the interface of this Select isn't `e`. Can you put a console.log inside `handleSelectCollaboratingTeams`?
Answer: dont use arrow function with onchange it often used when we need to pass id or some other data
Answer: you should define the new state for storing the selected item.
Example for class component:
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

Example for functional component(using React-hook):
const [selectedOption, setSelectedOption] = useState(null);
  handleChange = selectedOption => {
    setSelectedOption(selectedOption);
  };

Comment: Thanks a lot for the answer. I fixed it by changing the state declaration to null. Moreover,  the state was getting updated, but I wasn't using the correct state to get the display on the output screen. Apologies for the late response.


How to calculate real probability with multiple scenarios?

Question: I would like to know how to calculate the probability of being profitable on an event where there are multiple scenarios. For example paying 5 dollars to grab a bill from a box box full of bills where there is a 1% chance of grabbing a 100 dollar bill, a 5% chance of grabbing a 20 dollar bill, a 10% of grabbing a 10 dollar bill and a 84% chance of grabbing a 1$ bill.
The first 3 scenarios would be profitable but the last one wouldn't. My question is, how do I calculate the real probability of being profitable? I thought about just adding the probabilities and that would give a 16% chance of being profitable but I don't know if I should apply some additional logic to it.
Answer: You need to calculate the payout ratio.
From this case you 1 in 100 chance of drawing the \$100 bill so that average payout ratio is \$1. (win once, lose 99 times).
So in this case with multiple different payouts:
\$100 * 1% = \$1
\$20 * 5% = \$1
\$10 * 10% = \$1
\$1 * 84% = \$0.84
So summing up all of these values equals \$3.84. This is the predictive long term average of every play.  Since the payout is less than the investment, it is not a very good game.
Note this payout ratio is better than most lotteries.
Comment: Thank you for you answer, never thought about calculating payout ratio for long term average return but, if I wanted to do the experiment only one time, is 16% chance a correct approach?
Comment: Yes, for a single play, a 16% chance of drawing a 10, 20 or 100 dollar bill


Simplify $G(t) = \sum_\limits{n=1}^{\infty} (\cos\frac{n\pi}{2}-1) \cos(\frac{nt\pi}{3}) $

Question: Simplify $G(t) = \sum_\limits{n=1}^{\infty} (\cos\frac{n\pi}{2}-1) \cos(\frac{n\pi t}{3}) $
I am unsure how to simplify this in the best form, anyone have any ideas?
Comment: is  the first $\cos$ argument $\frac{n \pi}{2}$ or $\frac{n \pi t}{2}$ ?
Comment: it is $\frac{n\pi}{2}$
Answer: $$ (\cos\frac{n\pi}{2}-1) \cos(\frac{nt\pi}{3}) = \\ \frac{1}{2} \cos\left( n \left(\frac{\pi t}{3} - \frac{\pi}{2}\right)\right)+\frac{1}{2} \cos\left( n \left(\frac{\pi t}{3} + \frac{\pi}{2}\right)\right) -\cos \left( \frac{n \pi t}{3} \right) $$
So all terms are cosines.
Comment: It uses $\cos(a) \cos(b) \equiv \frac{1}{2} \cos(a-b) + \frac{1}{2} \cos(a+b)$
Answer: Here is an alternate representation using the fact that
\begin{equation}
\cos\left(\dfrac{n\pi}{2}\right)-1=\begin{cases}
-1&\text{ for }n=4k-3,\,n=4k-1\\
-2&\text{ for }n=4k-2\\
\phantom{-}0&\text{ for }n=4k\\
\end{cases}
\end{equation}
\begin{eqnarray*}
G(t)&=&-\sum_{k=1}^{\infty}\left[\cos\left(\frac{4k-3}{3}\pi t\right)
+2\cos\left(\frac{4k-2}{3}\pi t\right)
+\left.\cos\left(\frac{4k-1}{3}\pi t\right)\right]\right.
\end{eqnarray*}


Example of increasing function such that $f(x+y)=f(x)+f(y)$

Question: Is there a strictly increasing continuous function $f:[0,m]\rightarrow [0,2000]$ such that $f(0)=0$, $f(m)=2000$ (where $m>2000$) and $f(x+y)=f(x)+f(y)$? If so, can someone give me an example?
What I'm trying to do is to apply a function to a bar chart that has values like 300, 40000, 10000, 30000, 12345 etc in order to 'normalize' the chart (make the chart look more friendly, without seeing a very big bar, then a tiny one). I applied the function $f(x)=\frac{x}{300/40000*x + 1}$, but the chart started to look weird because $f(40000)  \ne f(10000)+f(30000)$. This is why I'm searching for a function that satisfies $f(x+y)=f(x)+f(y)$.
Comment: like $f(x)=\frac12 x$?
Comment: You don't mean $f(m)=2000 $ for all $m>2000$, do you?  That would not be strictly increasing.
Comment: That is what I was showing.  $f(ax)=af(x) \Rightarrow f(x)= f(1) x = \text{const.} \cdot x.$
Comment: $f(x) = \frac{2000}{m}x$ ?
Comment: @MTZ, assuming only $f(x+y)=f(x)+f(y)$:  For any integer $k$, it should be clear that $f(kx) = kf(x)$.  We can show this, for example by induction.  Also, $f(x/2)+f(x/2) = f(x)$, so $f(x/2)=f(x)/2$.  Similarly $f(x/k)=f(x)/k$.  We can show the function is continous, and reason that $f(ax)=af(x).$ $\cdots$.
Comment: We also get from the above that  $f(x) = xf(1)$, so$ f(x) =x\cdot a$ for some $a$.
Comment: @MTW what defines a linear function. How about this: Iff a function $f$ satisfying $f(0)=0$ is not linear then there are $a_x,a_y$; $a_x \not = a_y$, such that $f(x)=a_xx$ and $f(y)=a_yy$.
Comment: @mjw Got it! Thank you!
Comment: @Mike  Got it! Thank you!
Comment: That's all of them ($f(x)=ax$), yes?
Comment: Same thing, yes?
Comment: the simplest would simply be $f: 0 \mapsto 0$ and $f: m\mapsto 2000$ and everything between maps proportionally.  It's straightforward to manipulate that to $f(x) = \frac {2000}m x$.  The issue is is that the *only* such function? What do you think?
Comment: @Mike said that there are no non-linear function that satisfy this condition? Can someone give me an explanation why?
Comment: @mjw I meant how do we know that there are no other functions except the linear ones? How do I know that the linear functions are the only ones that satisfy my conditions?
Answer: When @J.W.Tanner gave an example, he basically gave the prototype for all such functions.  $$f(x+y)=f(x)+f(y)$$ is linear, and with your other conditions $$f(x)=ax, \quad \text{with }0<a<1.$$
UPDATE
Why is the function necessarily linear?  We reasoned in a comment above that $f(kx)=kf(x)$ and $f(x/k)=f(x)/k$ when $k$ is an integer.  Combining these, we have $f(px/q) = pf(x)/q,$ so it holds for rationals.  A continuity argument gives $f(a x)=af(x)$ for $a \in \text{Reals},$ which implies $f(x) = ax.$
Comment: Why "-1"?  Check again.
Comment: $f(x+y)=f(x)+f(y)$ is a very strong condition.  I think it implies continuity.
Comment: @Mike, thank you!  Appreciate your vote.
Comment: This answer is correct. I just upvoted
Comment: Okay, if you interpret the question to be for a specific $m$, then yes, $a=2000/m$.  I read it as "for some $m>2000$", so yes, that answer (originally given in the comment) would answer for a specific $m$.
Comment: correct me if I'm wrong.  If we remove the condition that $f$ is increasing and allow $f$ to not be continuous it need not hold.  I think?  ..... Counter example is tedious and if $f(x) \ne f(1)x$, we would have to $f(x)=c$ and $f(qx) =qc$ for all rationals but this we have an irrational of the form $r + qx$ for some rational $r$ we must have $f(r+qx) = ar +qc$ and... well, it gets tedious to show we can partion the reals... I think.  I'm too lazy and tired....
Comment: @mjw of course, your answer was correct, it deserved the upvote. Now you do need to explicitly state continuity or strictly increasing a priori, otherwise why wouldn't $f(x) = ax$ for the rationals and $f(x)=bx$ for the irrationals work. The strictly increasing or even nondecreasing would force the continuity condition however.
Comment: $f(x+y)=f(x)+f(y)$.  What if $x \in \mathbb{Q}$ and $y \in \mathbb{R} \setminus \mathbb{Q}$?
Comment: What about $x=5-\sqrt{2}$ and $y=5+\sqrt{2}$?
Comment: You are right, there are exceptional cases where continuity is not guaranteed.  Looks like it is known that additive functions are linear for rationals, but by not assuming the axiom of choice, other constructions are possible for the irrationals:  https://math.stackexchange.com/questions/3968648/does-all-additive-functions-are-linear-imply-every-set-of-reals-is-measurable
Comment: @mjw good point. Constructing a counterexample does seem to be rather deep and the example I gave would not suffice. I will look over that link
Answer: The function $f(x) = \frac{2000x}{m}$ will do, as SenJen noted in the comments.
Comment: @MTZ if you want $f(x)+f(y)=f(x+y)$ to hold for all $x,y$ in the interval $[0,m]$ then the only functions that satisfy this are linear functions.
Comment: This is of the form $f(x) = ax$.  Here $a=2000/m$.
Comment: Thanks to @SenZen, who wrote this answer in a comment before Mike posted it as an answer.
Comment: @mjw  Mike and SenZen both wrote correct comments, one though, before the other.  Some of us give credit to commenters, who post before one posts one's answer.
Comment: Actually, they are the same exact example (Mike's and SZ's).  What's so great about this example.  J. W.'s answer is just as nice.  I actually like this answer!
Comment: I'm just not fond of users taking someone else's idea from a comment, and posting it as their own answer, without acknowledging the suggestion from the original user. Note, @mjw, you included this courtesy in your answer.  That's all I'm suggesting, and thanks for doing that.
Comment: Yes... I forgot to mention in the question that the plot of the graph must be a curve. However, I will accept the answer since it is bad. But I will really appreciate if you guys give me other examples, rather than $f(x)=ax$
Comment: I'm not a fan of answering questions in the comments nor am I a fan of downvoting answers to "easy" questions just because it may have been answered already in the comments. Answers to questions IMO should be posted as answers, and correct answers should not be downvoted. Many times when there is a question, multiple answers that really are just repeating the same line of reasoning, are posted, with no downvotes to the posters who were not first in posting their answer.
Comment: Keep in mind too @amWhy that people cross-post
Comment: @Mike with that in mind, I still do not understand why you did not acknowledge SenZen's comment.  Sounds like you're makiing an excuse.
Comment: @amWhy, okay, sorry for my question on your question.  Read it too quickly.  Now makes sense.
Comment: @Mike  is there a theorem that says so? (sorry for the dummy question)
Comment: @MTZ I don't know any theorem off the top of my head. The proof of this is somewhat involved. You would first show $f(0)$ must be $0$, and then show that there is an $a$ such that $f(x)=ax$ for all *rational* $x$. Then use continuity of $f$ to extend this to the irrationals.
Comment: I cross-posted...just saw that @mjw already said this!
Answer: First of all note that any function with given condition must be $f(x)=ax$, $a\in\mathbb R$ (real numbers).
In our case $a=2000/m$.
So required function is $f(x)=2000x/m$.
Please verify this function follow all your given conditions.
Comment: This question has already been asnwered (in comments, in answers, and one answer was even accepted).  Why post a repeat answer?


Show other view on slide up android

Question: I am starting a new project in android.I have to make it like google maps.For example see the image below

The screen will be like this with 2 views.1st mark with red and other with yellow.
Now what i want is that when user drags view 2 from bottom to top it should be like this

How can i achieve this.Please do help me out as i new to andriod development
Thanks
Comment: Have you tried anything yet?
Comment: Sorry but i dnot know where to start from
Answer: There's a similar implementation in this library. Download the sample app here and see the

SlidingUpGridView
SlidingUpListView
SlidingUpRecyclerView
SlidingUpScrollView
SlidingUpWebView

options.
EDIT
Looks like AndroidSlidingUpPanel is a better solution.
EDIT 2
If you don't want to use that library, I suggest use the codes of that library. It's really not that much work.

Create a new package sliderlib or something in your project
Create two classes named ViewDragHelper.java and SlidingUpPanelLayout.java
Copy the contents of the two named classes here
Download these drawables to your drawable directory of your app
Add these values to your attrs.xml (create one if there isn't one)
And in your XML, use your new widget like this.

your_layout.xml
<your.app.package.sliderlib.SlidingUpPanelLayout>
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:panelHeight="68dp"
    sothree:shadowHeight="4dp">

</your.app.package.sliderlib.SlidingUpPanelLayout>

NOTE : The answer may not be exactly right. But it will be a start.
Comment: Thanks for the help Sir but i wanted to do it without library.Is there any way or code which can help me out
Answer: Checkout AndroidSlidingUpPanel library, probably this is what you want to achieve.

Show other view on slide up android


Finding the $y$-intercept of a parametric equation

Question: Find the $y$-intercept of a given parametric curve.
$$x=t(t^2-3)$$
$$y=3(t^2-3)$$
My attempt: $x'_t=3t^2-3$, and $y'_t=6t$
$y'/x'=6t/3t^2-3=2t/t^2-1=?$
And that's where I'm stuck, I tried the other method of substitution but couldn't find a method to isolate $t$. I derived $x$ and $y$ because I'm trying to find $mx+b$ to find its y-intercept.
Answer: The $y$ intercept is when $x=0$, so solve the $x$ equation to get the $t$ that makes that true.  You should find three of them.  Each creates a $y$ intercept, but two are the same.
Here is the plot from Alpha:

You can see it crosses the $y$ axis once at $-9$ and twice at $0$.  These correspond to $t=0$ and $t=\pm \sqrt 3$
Comment: that means there's no vertical tangent?What would the graph look like?
Comment: There might be a vertical tangent, though there is not one here.
Answer: The $y$ intercepts of a curve are the points at which the curve intersects the $y$-axis (i.e. the curve may be a line and may be not, so the $y$-intercept is not only the $b$ in the equation $y=mx+b$)
Also when the curve intersects the $y$-axis, it means that the $x=0$ so $t(t^2-3)=0 \implies t=0$ or $t=\pm \sqrt{3}$
Your graph will look like this
Answer: We have x=t(t^2-3) and y=3(t^2-3)
So x/y = t/3 => t=3x/y
So substituting this value of t in any of the parametric expression in t for x or y we get an equation in x and y. Further we can put x=0 to get the y intercept.


"Fatal error: Cannot use string offset as an array in theme.inc"

Question: i am adding custom modules in drupal 7. while creating a custom table i got the error like this
"Fatal error: Cannot use string offset as an array in /srv/bindings/code/includes/theme.inc on line 2002"
            $form = array();
            $headers = array(t('Teacher Name'), t('Paypal Id '),  t('Status'), t('Action'));
            $query = "SELECT * FROM `users_roles` ur JOIN `users` u ON u.uid=ur.uid WHERE rid=4";
            $rs = db_query($query);
            $row = array();
            if ($rs) {
                  foreach($rs as $data) {
                    $name = $data->name;
                    $mail = $data->mail;
                    $status = $data->status ;
                    $row[] = array(stripslashes(ucwords($data->name)), $mail, $status,
                    "" . t('Pay Now') . "  " );
                }}
                echo "
";
                print_r($headers);
                print_r($row);
            return theme_table('table', array('header' => $headers, 'rows' => $row));

I dont know where i done mistake. Please give some ideas.
Comment: This error happens when you try to access a variable like an array when
the variable was initialised with a different type than array.
That was clear as the PHP Error discribes the problem.
Answer: You're calling theme_table directly instead of theme, but still passing the name in.
Use this instead:
return theme('table', array('header' => $headers, 'rows' => $row));

Or even better (depending on context), a render array.
Answer:         $form = array();
        $headers = array(t('Teacher Name'), t('Paypal Id '),  t('Status'), t('Action'));
        $query = "SELECT * FROM `users_roles` ur JOIN `users` u ON u.uid=ur.uid WHERE rid=4";
        $rs = db_query($query);
        $row = array();
        if ($rs) {
              $result = $rs->fetchAll();
              foreach($result as $data) {
                $name = $data->name;
                $mail = $data->mail;
                $status = $data->status ;
                $row[] = array(stripslashes(ucwords($data->name)), $mail, $status,
                "" . t('Pay Now') . "  " );
            }}
            echo "
";
            print_r($headers);
            print_r($row);
        return theme_table('table', array('header' => $headers, 'rows' => $row));

Now, it will work correctly for you.
Comment: Hi ashish,
thanks for your comment. But still i got error like this
"atal error: Cannot use string offset as an array in /srv/bindings/c90e433b09414ab9a209102a3246bcae/code/includes/theme.inc on line 2002"
Comment: please verify the code now. I have edited my code.
Comment: yes i changed  "foreach($result as $data) {" this
Comment: Are you still getting that error?
Comment: yes ashish still error is coming
Answer: You don't report exactly which line is causing the error, but if it is between the lines you shown, then the line causing the error is the following one.
return theme_table('table', array('header' => $headers, 'rows' => $row));

It happens because theme_table(), as any other theme function, is expecting an array as first argument, not a string.
The correct line would be the following one.
return theme('table', array('header' => $headers, 'rows' => $row));

Keep in mind that on Drupal you never directly call a theme function like theme_table() because the theme function for generating a table could not be that. In fact, modules can change the theme function called from theme() by implementing hook_theme_registry_alter().
Then, in Drupal 7 is possibile to return a render array, instead of a string. Instead of  return theme_table('table', array('header' => $headers, 'rows' => $row)); you can use return array('#theme' => 'table', '#header' => $headers, '#rows' => $row); in most of the cases.


My Python code has logic errors, but not sure exactly how to fix

Question: I am using Python 3.5 with the openpyxl module.
I have a small excel spreadsheet where it has 5 columns, each has 5 movies in a specific genre.
My Python program is designed to, based on user input, display the movies of a certain genre, add a movie to the spreadsheet, delete a movie,  or just exit.
Now, I have got it to display the movies in a category the user chooses, however, I cannot get it to delete correctly.
It will show the list of movies in the genre and regardless of what number the user enters, it automatically chooses option #5. I do not know how to get it to correctly match.
To make matters worse, when given the option to delete (by entering 'Y' or 'N'), sometimes it still deletes anyways.
And, even though the excel workbook is supposed to "save" - once you restart the program, the deleted file shows up again.
I've been looking at this code for hours and I don't know what to change.
Can you guys please take a look and give me some suggestions?
I know you can't access the spreadsheet, but here isn image of the spreadsheet layout:

and here is the code from the beginning :
import openpyxl
wb = openpyxl.load_workbook("Movies.xlsx")
sheet = wb.active
sheetname = wb.get_sheet_by_name("Movies")

thrillers = list(sheet['A2' : 'A6'])
comedies = list(sheet['B2' : 'B6'])
action = list(sheet['C2' : 'C6'])
dramas = list(sheet['D2' : 'D6'])
family = list(sheet['E2' : 'E6'])

def greeting():
    print("\tWELCOME TO YOUR MOVIE DATABASE!\n")
    print("Please select an option from the menu:\n")

def menu_selection():
    print("\n")
    print("\t ** MENU **")
    print("1. Search the movie database\n" \
          "2. Add a movie to the database\n" \
          "3. Delete a movie from the database\n" \
          "4. Exit the program\n")

And here is the code from the function that displays the movies in the database it, depending on the genre entered by user:
def movie_selector():
print("1. Thriller\n" \
      "2. Comedy\n" \
      "3. Action\n" \
      "4. Drama\n" \
      "5. Family\n" \
      "6. Exit to main menu")

print("\n")
selection = int(input("Enter your selection: "))
print("\n")

if selection == 1:
    print("\t ** " + sheet['A1'].value + " **")
    for m in thrillers:
        print(m[0].value)
elif selection == 2:
    print("\t ** " + sheet['B1'].value + " **")
    for m in comedies:
        print(m[0].value)
elif selection == 3:
    print("\t ** " + sheet['C1'].value + " **")
    for m in action:
        print(m[0].value)
elif selection == 4:
    print("\t ** " + sheet['D1'].value + " **")
    for m in dramas:
        print(m[0].value)
elif selection == 5:
    print("\t ** " + sheet['E1'].value + " **")
    for m in family:
        print(m[0].value)
elif selection == 6:
    menu_selection()
else:
    print("Invalid selection. Try again.")
    movie_selector()

And here is the function to delete a movie, and nothing works right:
def delete_movies():
print("\t ** CATEGORIES **\n")
print("1. Thriller\n" \
      "2. Comedy\n" \
      "3. Action\n" \
      "4. Drama\n" \
      "5. Family\n" \
      "6. Exit to main menu")

selection = int(input("\nSelect the category of the movie you want to delete: "))
n = 0

print("\n")

if selection == 1:
    print("\t ** " + sheet['A1'].value + " **")
    for m in thrillers:
        n += 1
        print(str(n) + '. ' + m[0].value)
elif selection == 2:
    print("\t ** " + sheet['B1'].value + " **")
    for m in comedies:
        n += 1
        print(str(n) + '. ' + m[0].value)
elif selection == 3:
    print("\t ** " + sheet['C1'].value + " **")
    for m in action:
        n += 1
        print(str(n) + '. ' + m[0].value)
elif selection == 4:
    print("\t ** " + sheet['D1'].value + " **")
    for m in dramas:
        n += 1
        print(str(n) + '. ' + m[0].value)
elif selection == 5:
    print("\t ** " + sheet['E1'].value + " **")
    for m in family:
        n += 1
        print(str(n) + '. ' + m[0].value)
elif selection == 6:
    menu_selection()
else:
    print("Invalid selection. Try again.")
    movie_selector()

delete_num = int(input("\nEnter the number of the movie to delete: "))

if delete_num == 1:
    confirm = input("Delete " + m[0].value + " (Y or N)?  ")    # it outputs #5 value no matter what

    if confirm == 'y' or 'Y':
        print("Ok, deleted.")
        m[0].value = ""
        wb.save("Movies.xlsx")

    elif confirm == 'n' or 'N':
        print("Not deleted")

elif delete_num == 2:
    confirm = input("Delete " + m[0].value + " (Y or N)?  ")

    if confirm == 'y' or 'Y':
        print("Ok, deleted.")
        m[0].value = ""
        wb.save("Movies.xlsx")

    elif confirm == 'n' or 'N':
        print("Not deleted.")

elif delete_num == 3:
    confirm = input("Delete " + m[0].value + " (Y or N)?  ")

    if confirm == 'y' or 'Y':
        print("Ok, deleted.")
        m[0].value = ""
        wb.save("Movies.xlsx")

    elif confirm == 'n' or 'N':
        print("Not deleted.")

elif delete_num == 4:
    confirm = input("Delete " + m[0].value + " (Y or N)?  ")

    if confirm == 'y' or 'Y':
        print("Ok, deleted.")
        m[0].value = ""
        wb.save("Movies.xlsx")

    elif confirm == 'n' or 'N':
        print("Not deleted.")

elif delete_num == 5:
    confirm = input("Delete " + m[0].value + " (Y or N)?  ")

    if confirm == 'y' or 'Y':
        print("Ok, deleted.")
        m[0].value = ""
        wb.save("Movies.xlsx")

    elif confirm == 'n' or 'N':
        print("Not deleted.")

else:
    print("Invalid selection. Try again.")

I hope someone can tell me what is going wrong. I will greatly appreciate it.
Comment: It seems that you did not manipulate the excel object directly, you were just  making some changes to the `list` object when you executed the delete function.
Comment: Thank you for your response.
How would I manipulate it directly?
Comment: my suggestion would be using `xlrd` module, because it's easy to learn, and the operations provided can be easily performed.
Comment: xlrd cannot save existing files so won't be any use here.
Answer: In your delete you are modifying M:
m[0].value = ""

M however is just the value inside your program. You need to modify the Cell of the Worksheet:
sheetname['A2'] = ""

You can build up the cell string ('A2', like 'A' + str(i)) to delete the right cell
Comment: THANK YOU! This is working!!
I'm sure I'll run into some more questions at some point, but this gets me over the current big hump I've been stuck on.
Answer: Whit this if delete_num == 1:
        confirm = input("Delete " + m[0].value + " (Y or N)?  ")    # it outputs #5 value no matter what
You are trying to access a variable that you have declared in an IF statement. You should declare it right after the start of your function like this
def delete_movies():
    m = ""
    print("\t ** CATEGORIES **\n")
    print("1. Thriller\n"
          "2. Comedy\n"
          "3. Action\n"
          "4. Drama\n"
          "5. Family\n"
          "6. Exit to main menu")


Meaning of **Canonical metric** on complex manifolds

Question: What is the meaning of Canonical metric on complex manifolds ?
Comment: See [this presentation](http://www.math.lsa.umich.edu/seminars/lecturesmath/file_uploads/canonical_metrics.pdf) by Yau.
Comment: In general there is no such thing in the obvious interpretation of the words. For example multiplication with $\lambda\ne 0$ is a homeomorphism $\mathbb C\to \mathbb C$, hence the set of points at canonical distance $1$ from the origin should be scale-invariant, which is impossible
Comment: it would be better, if you show the context...
Answer: For a compact Kahler manifold $M$, canonical metric can mean:
(i) Kahler-Enstein metric or (ii) metric with constant scalar curvature which is the extremal metric of the Calabi functional $\displaystyle\int_M R^2$.
You can find more details from the book Canonical Metrics in Kahler Geometry by by Gang Tian.


If I want to adjust survival analysis for a covariate, like age, should I add it "smth+age" or add an interaction with it "smth*age"?

Question: I have a survival analysis with a categorical predictor called "smth". I want to adjust it for age. I don't have any idea if they can interact or not but I guess they can. Now, about the the terminology: is the "adjustment" more about adding two main effects, in R: ~smth + age, or interacting them: ~smth * age?
Of course, if there is no interaction, the two will be equivalent. But I just wanted to make sure about the terminology and traditions.
In most articles I saw the Cox analysis like ~something + controlled_covariate_A + controlled_covariate_B rather than ~something * controlled_covariate_A * ....
Which one is more "common"? Should I even care about the "+" (main effects only) or by default check the interaction (*) between them, since it's not impossible to have it?
The final outcome will be explored and judged by domain experts anyway. They will decide how to treat the the calculated output.
Sure, I know using the interaction will create a long output, the interpretation will be more challenging, but - well - if I guess something may vary on the level of something else, why ignoring it?
But is such interaction still "controlling for a confounder" or "adjusting for a covariate" according to the "nomenclature"?
Comment: How many cases, events, predictors, and potential interactions are you talking about? The answer depends in part on that. Are there particular interactions that the domain experts think are important to evaluate?
Comment: There will be abouft 100 subjects and this gives about 80 events in total. There are no specific interaction of interest, rather expectations it will occur. There will be 4 categorical covariates: 1 will differentiate the curves, 3 will render the groups. I think I found partially my answer - the effects will likely vary across all groups, so interactions sound legit. But is this what is called "adjustment", or "adjusted" means usually "same effect on all levels of the covariate, thus A+B rather than A*B"?
Comment: Also, hazards are likely non-proportional, baseline hazards also not equal.
Answer: You would simply need to have $age$ and $smth$ in the model, as well as the interaction term $age*smth$ in order to adjust $smth$ by $age$.  A trick would be to regress $smth$ on $age$ in a simple regression model, then pull back (obtain) the residuals, i.e. $\hat{y}_i$, rename them to a new variable like $smthage$ and employ those in the Cox PH model.
Answer: "Adjusting for a covariate" can mean many things. I suspect that additive corrections might be most common, but that doesn't mean that limiting yourself to them is best. If an interaction is important and isn't included, you are likely to get biased results, lower power, and less of an ability to extend results to a population that has different prevalences of the values of the interacting predictors that are associated with outcome.
A good overall strategy in regression modeling, particularly with survival modeling, is thus to work with as complex a model as is reasonable. Frank Harrell's class notes and book, particularly Chapter 4, present useful introductions to multivariable regression modeling strategies.
The problem you face is the relatively small number of cases relative to the number of predictors. Survival modeling is at risk of overfitting if you evaluate more than 1 unpenalized predictor per 10-20 events, with each level of a categorical predictor beyond the first and each interaction term counting as a separate predictor. So unless you do some type of penalization, you are limited to about 6 predictors including interactions.
If you have one binary predictor of primary interest and 3 categorical predictors as covariates, you might be able to get away with each of those as additive terms plus interactions of the primary predictor with each of the covariates separately (total of 7 predictors including interactions). It would be wise to evaluate that model for overfitting with the "optimism bootstrap" explained in Chapter 5 of Harrell and implemented in the validate() function of his rms package in R.
If some of your categorical predictors have more than 2 levels, you need to examine interactions among the covariates not of primary interest, or you have additional covariates to control for, then adding the corresponding extra terms is likely to overfit. You can cut down on the effective number of covariates by combining them usefully first without regard to outcome (Chapter 4 of Harrell) or by using ridge regression to penalize the covariates that aren't of primary interest. See for example the discussion of penalization by Pavlou et al and the comparison by Chen et al of different ways to deal with "too many covariates and too few cases." Penalization reduces the magnitudes of covariates, minimizing overfitting while allowing evaluation of more covariates than otherwise would be possible.
Finally, note that this type of control for covariates can fail if there is confounding (a "treatment," your primary predictor of interest here, and outcome having a common cause), selection bias, or measurement bias. Hernán and Robins discuss those types of complications and ways to deal with them.


Confusion regarding correlation and correlation coefficient

Question: Can somebody provide an intuitive difference between correlation and correlation coefficient? During learning of weights of neural network, I want to show how closely the estimated weights are to the known true weights. For this, I was thinking of using the correlation measure. If they are correlated then the value will be close to one. But I am not sure, if it should be the correlation or the correlation coefficient.
Also, what is the difference between the two formula wise and physical meaning wise. Thank you
Comment: No difference, unless you have some strange textbook that tries to make some sort of distinction.
Comment: I'm not sure what distinction you have in mind when you contrast "Correlation" with "Correlation coefficient"...
Comment: Which "two formulas" are you referring to?
Comment: Correlation in the context of 2 random variables to be independent. Do we say correlation coefficient = 0 or correlation = 0. In other case, in cryptography, when we want to check how good the decryption is, then we measure the correlation. When the decryption is perfect then correlation is high between the original plaintext and the decrypted recovered message. So, what is a correlation coefficient and only correlation? Or are they the same?
Answer:
Can somebody provide an intuitive difference between correlation and correlation coefficient?

The word 'correlation' has (i) several specific technical senses (most usually the Pearson product-moment correlation, plus many other measures that get labelled as one or another kind of 'correlation' in different contexts), as well as (ii) a more general sense (implying some kind of association, usually monotonic, but without needing any specific 'formulaic' sense of the word).
In the most common usages of the terms, "correlation" and "correlation coefficient" mean the same thing - the Pearson product-moment correlation.
However, it is certainly possible for a single source using both terms to be attempting to draw a distinction, and in that case, for example, it might be that the second form (correlation coefficient) implies one of the mathematically defined technical senses I mentioned in (i), while the first might only refer to the more abstract/general sense of association.
Both senses are discussed here.
If you're referring to a particular use or uses of the terms, you'll need to provide some context, such as a direct quote (with source(s)).
Comment: By context I don't mean "application area" - I mean "within a particular piece of writing" - if a particular author uses a term one way or another, which will generally be clear from the surrounding text. As with "*when we say the correlation between 2 variables is 0.8, are referring to the value of the correlation coeff?*" -- yes, in that situation, 'correlation' is referring to a correlation coefficient, likely the Pearson one. If, on the other hand, someone said 'there's some correlation between experience and income' they may mean nothing more than some association exists -likely monotonic
Comment: What is then the difference between correlation and mutual information if both of them mean how closely 2 random variables are related or how closely 2 signals are related to each other?
Comment: @SKM correlation measures the degree of linear association. Mutual information can identify much more general forms of dependence. You can have highly dependent variables for which the correlation is 0. Consider $X$ being symmetric with mean 0, and $Y=X^2$. They're perfectly functionally dependent but uncorrelated.
Comment: @SKM you might benefit from reading the comments - including links - and Aaron's answer [here](http://stats.stackexchange.com/questions/109567/implication-of-mutual-information)
Comment: Thank you for the link. So, correlation and correlation coefficient is the same thing. When we say that weights after training and the actual weights of the system Or when decryption and original message correlation = 1, then it means that the algorithm performed well. We do not say that the correlation coefficient =1. Is my understanding correct?
Comment: "*So, correlation and correlation coefficient is the same thing.*" -- actually, that's not really what I said, perhaps you should reread my answer; it's usually the case that people mean the same thing, but it depends on the context, as I explained.
Comment: The context to what I referred to, which is the area of cryptography or image processing where we want to check how close the variables(images) are dependent or if there is any relationship, in this context is corr coeff and corr the same thing?Also, I found no separate mathematical representation for correlation and correlation coeff. They seem to be pointing to corr coeff(http://mathworld.wolfram.com/CorrelationCoefficient.html)Eq 15. So, when we say the correlation between 2 variables is 0.8, are referring to the value of the correlation coeff?I am sorry but your answer seems too high level
Comment: Commenting again since I found out that there are 2 measures correlation and correlation coefficient in image processing: $Correlation(\alpha,\beta) = \sum \sum f(m,n)g(m+\alpha,n+\beta)$ where alpha beta are the spatial shift
Comment: CorrCoeff = $\frac{\sum sum f(m,n)g(m,n)}{\sqrt(\sum sum f^2(m,n) \sum \sum g^2(m,n))}$  Eq 3.14 and 3.18 in lecture notes http://www2.enel.ucalgary.ca/People/Ranga/enel563/LecturesCh1-2-3.pdf
Comment: Now I am really confused based on your answer. Can you please let me know?
Comment: Let you know what? I don't understand what you're asking for. If it's to do with the formulas in your comments that looks like an entirely new question that needs a deal more context.


Group Policy Settings Not Applying

Question: I have Microsoft Small Business Server 2011 and when creating a GPO for my SBSComputers the settings do not apply.
For instance I have enabled Verbose vs normal status messages in the Group Policy Management Editor in the Windows SBS Client Policy.
However, when logging onto one of my client computers and looking at the local group policy this setting is not enabled.
Why would that be?
EDIT:
Ah it looks like I just had the basic concept wrong, running gpresult /H did indeed show that the policy's are in effect on these machines.
Thanks!
Answer: We've had situations where policies weren't "taking" properly; usually running (as administrator at the prompt on the client) "gpupdate /force" would refresh the policy.
It can also depend on how long your refresh period is as to when the client got the updated policy off the server.
Answer: Group Policy may not have refreshed yet. It is not an instantaneous process, the clients have to actually check for new policies, which happens at an interval that is defined in the Default Domain Policy.
Even if the interval period has passed, some settings are not applied until the computer starts up, or a user logs in. You can check the policies that are applied to a machine by running gpresult /H. This should give you some hints about whether or not the policy is applied and the machine just needs a reboot, or if it isn't applying and you need to either run gpupdate /force or look at the event logs for errors.
Comment: I'll mark your answer cause it's what eventually led me to solve the problem. Thanks!
Answer: You can use the gpresult command to output the policies that are being applied to a user/computer. One of the sections lists the policies that were either successfully or unsuccessfully applied. Generally it will have a brief error message (i.e. Permission Denied) next to the policies not applied. Try that and see if it sheds any light. It's also useful because it drills down and tells you every rule that is currently in place, so it's easy to see what's working and what's not.  Good luck!
Answer: I had the same issue at first.  It was because DNS was not properly set up.  Config your DNS Server, point the client DNS to the DNS Server's Static IP Address... Make sure the client pc's have the internal DNS server, NOT an internet DNS service or ISP. Once you've done that, do a "gpupdate /force" to update the local policy.

Group Policy Settings Not Applying


Generics: Compiler seems incapable of recognizing that the type passed to an argument is the same as what is returned - why?

Question: Let's say I have several POJOs which all extend a common supertype, BaseObject.
I have a GenericDao which is declared as public interface GenericDao<T>.
For each type-specific DAO, I have an interface which extends the generic type and restricts it to a concrete type (public interface UserDao extends GenericDao<User>) and then an implementation of the type-specific DAO.
In a class that attempts to use a number of GenericDao implementations, I have a method that looks like
public <T extends BaseObject> long create(T object) {
    return getDao(object.getClass()).save(object);
}

If I implement getDao() so that it's parameter is a Class object, such as
private <T extends BaseObject> GenericDao<T> getDao(Class<T> clazz) { ... }

Then the call to getDao(object.getClass() in the create() method fails to compile - the compiler appears to interpret the return type of getDao() as
GenericDao<? extends BaseContractObject>

rather than recognizing that getDao(Class<T>) is going to return me a GenericDao of the same type T.
Can someone explain why this is? I understand that repeated appearances of the same type bound or wildcard don't necessary refer to the same type; however it seems like the compiler should recognize from the signature of getDao(Class<T>) that the T passed in should be the same T returned (but obviously it isn't capable of recognizing this, the why is the part I fail to grasp).
If I instead define getDao's signature to be
private <T extends BaseContractObject> GenericDao<T> getDao(T obj) { ... }

Then there is no issue in compiling a create() implementation which looks like
public <T extends BaseContractObject> long create(T object) {
    return getDao(object).save(object);
}

So why is the compiler capable of recognizing in this case that the T argument passed to getDao(T) is the same T in the return type, whereas it couldn't recognize this when the argument was Class<T>?
Answer: The expression object.getClass(), where object is of type T extends BaseObject, returns a Class<? extends BaseObject>, not a Class<T> as one might expect. So, getDao() is returning a DAO of the same type it receives; it's just not receiving the expected type.
Comment: This makes perfect sense, thanks. I forgot that getClass() will return a wildcard type
Answer: This is a classic type erasure issue.  getClass() has the following signature:
public final native Class<? extends Object> getClass();

If you have a String and do a getClass() on it, the class you get is Class<? extends String>.  The javadocs read:
 * @return The java.lang.Class object that represents
 *         the runtime class of the object.  The result is of type
 *         {@code Class<? extends X>} where X is the
 *         erasure of the static type of the expression on which
 *         getClass is called.

You will need to force the following cast to get it to work:
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>)object.getClass();
return getDao(clazz).save(object);

That works for me.
Answer: I think this should explain why the constraint is not doing what you expect:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ206
Comment: I'm afraid it doesn't answer the question. I'm not attempting to access `T.class`; my question is why the compiler doesn't recognize that the type bound `` means that the `T` in my input parameter `Class` will refer to the same type as the `T` in the return type `GenericDao`.